@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.
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
Promptmodel; 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-workspacePeer dependency: @google/genai (when using the bundled Google adapter).
Requirements
- Node.js (or a browser with
IndexedDBBlobStoragefor blob persistence) - A store factory for persistence — e.g.
createEphemeralStorefrom@asaidimu/utils-database, or your ownDatabaseConfig.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 withSystemErrorcodeINVALID_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 aHead(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:
blob:register— hash, store bytes, create record, ref-count = 1blob:retain/blob:release— adjust ref-countblob: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):
- Record the user turn (
recordUserTurn). - Snapshot the session (
session.snapshot()→Result<SessionSnapshot>). - Assemble a provider-agnostic prompt (
PromptAssembler/ prompt builder over the snapshot). - Resolve an adapter (
workspace.llm.resolve({ prompt })) andexecute(). - Record the assistant turn; run effects (
runAssistantEffects). - 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 modeIntegration tests exercise the full kernel: module aggregation, store instantiation, dispatch / transact, and index rebuilds.
License
MIT © Saidimu
