npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@asaidimu/utils-workspace

v9.1.0

Published

Content-addressed workspace and conversation management for AI applications.

Readme

@asaidimu/utils-workspace

Content-addressed workspace and conversation management for AI applications — DAG-based history, CQRS command pipeline, and provider-agnostic prompting.

version license


Overview

@asaidimu/utils-workspace is a state engine for production AI workspaces. It replaces the disposable Array<Message> chat model with a persistent, branching conversation graph and a command-driven mutation pipeline.

It is designed for IDEs, research tools, and agent platforms that need:

  • Non-destructive conversation editing — turns are immutable versions in a DAG; editing or forking never rewrites history.
  • Deduplicated multi-modal assets — blobs are content-addressed by SHA-256 with reference counting.
  • Reactive, in-memory read models — commands patch an index; subscribers get updates over an event bus.
  • Provider-agnostic prompting — the workspace speaks an abstract Prompt model; LLM providers are swapped via adapters (GoogleAdapter, VercelAdapter, or your own).

Key features

| Feature | Description | | :-------------------------- | :-------------------------------------------------------------------------------------------------------------- | | Turn DAG | TurnNode (stable slot) + Turn (immutable versioned content). Branch, edit, and A/B test timelines cheaply. | | CQRS pipeline | Every mutation is a command (session:create, turn:edit, …) dispatched through middleware to reducers. | | Content-addressed blobs | SHA-256 identity, ref-counting (blob:register / retain / release / purge), memory & IndexedDB backends. | | Modular extensions | Package domain logic as Modules (schemas, actions, middleware, stores, registries). | | Agent loop primitives | Snapshot → assemble prompt → resolve LLM adapter → record assistant turn → run tool effects. |


Installation

npm install @asaidimu/utils-workspace

Peer dependency: @google/genai (when using the bundled Google adapter).

Requirements

  • Node.js (or a browser with IndexedDBBlobStorage for blob persistence)
  • A store factory for persistence — e.g. createEphemeralStore from @asaidimu/utils-database, or your own DatabaseConfig.factory

Quick start

The Bootstrapper wires the kernel, stores, registries, and LLM adapters in one call:

import { Bootstrapper } from "@asaidimu/utils-workspace";
import { createEphemeralStore } from "@asaidimu/utils-database";
import { ReactiveDataStore } from "@asaidimu/utils-store";

const workspace = await Bootstrapper.workspace({
  database: {
    database: "my-db",
    validate: true,
    predicates: {},
    factory: createEphemeralStore,
  },
  state: new ReactiveDataStore({}),
  // storage defaults to MemoryBlobStorage
  // authorizer defaults to open access
});

// Define a persona
await workspace.workspace.createRole({
  name: "assistant",
  label: "Assistant",
  persona: "You are a helpful assistant.",
  preferences: [],
  topics: [],
});

// Open a session
const session = await workspace.sessions.create("user-123", {
  label: "Getting started",
  role: "assistant",
  model: "gemini-3.1-flash-lite",
});

// Record a user turn
const turn = workspace.turns
  .new("user", session.id)
  .addText("Hello there")
  .build();
await session.recordUserTurn(turn);

// Snapshot history for the LLM
const snapshot = await session.snapshot();
if (!snapshot.ok) throw snapshot.error;
// snapshot.value → SessionSnapshot (feed to PromptAssembler / adapter)

Runnable examples live in example/simple — including a full agent pipeline (record user turn → snapshot → infer → record assistant turn → execute tools).


Architecture

┌─────────────────────────────────────────────────────────┐
│                        Kernel                           │
│  coordinator.dispatch(ctx, cmd)  ·  state  ·  actions   │
├───────────────┬─────────────────────────┬───────────────┤
│    Modules    │        Middleware       │    Stores     │
│ session, turn │   intercept / abort /   │ sessions,     │
│ content, blob │   observe commands      │ turns, ...    │
│ role, tool    │                         │ (per module)  │
├───────────────┴─────────────────────────┴───────────────┤
│  Read model: reactive Index (StateManager) + events     │
│  BlobStorage: MemoryBlobStorage / IndexedDBBlobStorage  │
└─────────────────────────────────────────────────────────┘
  • Write path — kernel.coordinator.dispatch(authCtx, command) runs registered middleware, then the reducer for the command type. Unknown types fail with SystemError code INVALID_COMMAND. transact() wraps steps in a saga with undo for multi-command atomicity.
  • Read path — reducers update stores; the in-memory index/state is patched and subscribers are notified. kernel.rebuildIndex() re-derives projections from all registered indexers.
  • Concurrency — mutations flow through the coordinator’s sequential pipeline to avoid phantom branches and corrupt heads.

Mental model: conversation as a DAG

  • TurnNode — a stable logical slot in the conversation timeline.
  • Turn — immutable content (blocks) at a node, versioned.
  • Session — a pointer to a Head (TurnRef { id, version }) plus metadata (label, role, model, topics).

Editing a turn creates a new version rather than mutating history; forking a session is a metadata-only operation that can share arbitrarily deep history. switchVersionLeft / switchVersionRight and branch() navigate divergent timelines.

Content-addressed blobs

Binary assets are keyed by SHA-256 checksum:

  1. blob:register — hash, store bytes, create record, ref-count = 1
  2. blob:retain / blob:release — adjust ref-count
  3. blob:purge — delete physical bytes when appropriate

Implement BlobStorage (storeBytes, loadBytes, hasBytes, deleteBytes, exportAllBytes) or use the bundled MemoryBlobStorage / IndexedDBBlobStorage.


Commands

Commands are dispatched via kernel.coordinator.dispatch(ctx, { type, payload, timestamp }). The high-level Session API records turns and updates metadata for you.

Workspace

| Command | Description | | :----------------- | :----------------------------------- | | workspace:create | Initialize root workspace metadata. | | workspace:sync | Force a full re-index of all stores. |

Session & turn

| Command | Payload (shape) | Description | | :--------------- | :------------------------------------------------- | :------------------------------------------- | | session:create | session fields (id, label, role, model, …) | Create session record + index entry. | | session:update | { id, updates } | Patch session metadata. | | session:fork | { id, newId, label, role?, topics? } | Metadata-only clone of history. | | session:delete | { id } | Delete a session. | | turn:add | Turn (without timestamps) | Append an immutable turn. | | turn:update | turn fields | Update turn metadata. | | turn:edit | { id, session, version, content, role?, model? } | New version under the same node; moves head. | | turn:branch | turn payload | Diverge from a non-head node. | | turn:delete | { session, id, version, newHead? } | Remove a version. |

Content & blob

| Command | Description | | :-------------------------------------------------- | :----------------------------------------------------------------------------------- | | content:add / content:update / content:delete | Manage RAG/context content entries. | | blob:register | { id, checksum, size, mime, data, filename?, metadata? } — hash, store, ref-count. | | blob:retain / blob:release | Adjust ref-count. | | blob:purge | Delete blob bytes. | | blob:record_remote_id | Map local hash to a remote provider file ID. |

Role & tools

| Command | Description | | :----------------------------------------- | :------------------------------------------------------- | | role:add / role:update / role:delete | Manage AI personas. | | tool:execute | { name, parameters, key } — execute a registered tool. |

Persistence collections

| Collection | Purpose | | :--------- | :----------------------------------------- | | sessions | Session metadata + head pointer. | | turns | Immutable turn records (id + version). | | content | Context / RAG snippets. | | blob | Blob metadata + ref-counts. | | role | Persona instructions & constraints. |


Content blocks

Turns hold typed blocks. Defaults registered by the content registry:

| Block | Role | | :---------------------------- | :---------------------------------------------- | | text | Plain text communication. | | thinking | Internal chain-of-thought (hide/show in UI). | | preference | Preference-setting content. | | json | Structured JSON payload. | | blob | Reference to a content-addressed asset. | | image / document | Multi-modal assets (via blob refs). | | tool:call | Tool invocation request (callId, name, args). | | tool:result / tool:report | Tool output / report linked by callId. | | unknown | Fallback for unrecognized block types. |

Register custom block types through ContentRegistry / a ContentModule.


Sessions API

const session = await workspace.sessions.create(user, {
  label, role, model, topics?, preferences?, metadata?,
});

await session.open(user, sessionId);          // via SessionManager
session.rename(...); session.setTopics(...); session.switchRole(...);
session.setModel(...); session.setPreferences(...);
session.linkContent(...); session.unlinkContent(...);

await session.recordUserTurn(turn);
await session.recordAssistantTurn(turn);
await session.recordSystemTurn(turn);
await session.editTurn(turnId, newBlocks, role?, model?);
await session.branch(turn);
session.switchVersionLeft(turnId);
session.switchVersionRight(turnId);

const snap = await session.snapshot();   // Result<SessionSnapshot>
await session.runAssistantEffects(effects); // apply tool side-effects
session.turns(); session.head(); session.branchInfo(turnId);

Build turns with TurnBuilderFactory:

const turn = workspace.turns
  .new("user", session.id)
  .addText("Hello")
  .addToolReport(...)   // optional
  .build();

Prompt pipeline

Typical agent loop (see example/simple/pipeline.ts):

  1. Record the user turn (recordUserTurn).
  2. Snapshot the session (session.snapshot() → Result<SessionSnapshot>).
  3. Assemble a provider-agnostic prompt (PromptAssembler / prompt builder over the snapshot).
  4. Resolve an adapter (workspace.llm.resolve({ prompt })) and execute().
  5. Record the assistant turn; run effects (runAssistantEffects).
  6. Execute tools and record system/tool-report turns; loop or wait for input.

Extending with modules

Package custom schemas, commands, middleware, and stores as a Module and pass it to Bootstrapper.workspace({ extensions: [...] }) or register it on the kernel:

import type { Module } from "@asaidimu/utils-workspace";

const MyModule: Module = {
  name: "my-module",
  schemas: [
    /* collection schemas */
  ],
  actions: { "custom:cmd": myReducer }, // command → reducer
  middleware: [myMiddleware], // abort / augment / observe
  stores: {
    /* per-collection stores */
  },
  registries: {
    /* content/tool registries */
  },
};
  • Middleware intercepts the command stream (auth, validation, logging, shadow turns).
  • TurnProcessors scan assistant turns for side effects (auto-save memory, enqueue tasks) and return follow-up commands.
  • Custom indexers extend the read model; rebuild with workspace:sync / kernel.rebuildIndex().

Low-level bootstrap

For full control, compose the pieces yourself (as in integration.test.ts):

const aggregator = new ModuleAggregator();
aggregator.use(sessionModule, contentModule /* ... */);

const db = new WorkspaceDatabase({ factory, database: "app" /* ... */ });
await aggregator.instantiateStores(db);

const kernel = new Kernel({ state, authorizer, registries, logger });
kernel.actions.register(module, type, reducer);
kernel.actions.use(middleware);

await kernel.rebuildIndex();

const result = await kernel.coordinator.dispatch(authCtx, {
  type: "session:create",
  payload: {
    /* ... */
  },
  timestamp: Date.now(),
});

// Multi-step atomic saga:
await kernel.coordinator.transact(authCtx, {
  do: [
    /* steps */
  ],
  undo: [
    /* compensations */
  ],
});

createWorkspace() is the middle ground: pass { state, database, storage, authorizer, extensions?, logger? } and get back { kernel, stores, aggregator }.


Errors

Operational failures use SystemError with machine-readable codes (re-exported from the package root):

import { SystemError, CommonErrors } from "@asaidimu/utils-workspace";

throw new SystemError({
  code: CommonErrors.VALIDATION_FAILED,
  message: "Invalid input",
});

Dispatching an unregistered command type yields INVALID_COMMAND. Session APIs return Result<T, SystemError> ({ ok, value } / { ok: false, error }) rather than throwing for expected failures.

Troubleshooting

| Issue | Fix | | :-------------------------------- | :------------------------------------------------------------------------------------------------------------------ | | INVALID_COMMAND on dispatch | No reducer registered for that type — check module registration. | | Stale index after external writes | Dispatch workspace:sync or call kernel.rebuildIndex(). | | Blob storage growth | Ensure blob:release runs when turns/sessions that referenced assets are removed; purge at ref-count 0. | | LLM adapter mismatch | Verify workspace.llm.use(provider, adapter) and that the session’s model resolves through the adapter registry. |


API surface (package root)

| Export | Kind | | :----------------------------------------------------------------------------------------------- | :-------------------------- | | createWorkspace, CreateWorkspaceParams | Factory | | Bootstrapper, BootstrapParams, BootstrappedWorkspace | High-level bootstrap | | Kernel, KernelConfig | Command coordinator + state | | SessionManager, Session, SessionSnapshot, TurnTree, TurnBuilderFactory | Conversation model | | PromptAssembler + prompt types | Prompt building | | LLM, LLMAdapter, GoogleAdapter, VercelAdapter | Provider adapters | | BlobStorage, MemoryBlobStorage, IndexedDBBlobStorage | Blob boundary | | WorkspaceDatabase, IWorkspaceDatabase, DatabaseConfig | Persistence boundary | | ModuleAggregator, Module, AgentModule, ContentModule, SessionModule, WorkspaceModule | Extension system | | ContentRegistry, tool definition types | Content/tool registries | | SystemError, CommonErrors, Result, Authorizer, StateManager, Logger, createLogger | Kernel utilities |

Only the package root is exported (exports map exposes "." only) — deep imports into internals are not supported.


Development

npm test           # vitest run
npm run test:watch # watch mode

Integration tests exercise the full kernel: module aggregation, store instantiation, dispatch / transact, and index rebuilds.


License

MIT © Saidimu