@asaidimu/utils-workspace 3.0.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (6) hide show
  1. package/README.md +297 -277
  2. package/index.d.mts +600 -137
  3. package/index.d.ts +600 -137
  4. package/index.js +288 -1
  5. package/index.mjs +287 -1
  6. package/package.json +1 -1
package/index.d.mts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { QueryFilter, PaginationOptions } from '@asaidimu/query';
2
2
  import { IndexDefinition, SchemaDefinition, SchemaChange, DataTransform } from '@asaidimu/anansi';
3
3
  import { EventBus } from '@asaidimu/events';
4
+ import * as _google_genai from '@google/genai';
5
+ import { GenerateContentParameters, GenerateContentResponse, GoogleGenAI } from '@google/genai';
4
6
 
5
7
  /**
6
8
  * Utility type for representing partial updates to the state, allowing deep nesting.
@@ -13,10 +15,26 @@ type DeepPartial<T> = T extends object ? T extends readonly (infer U)[] ? readon
13
15
  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> | undefined : T[K] | undefined;
14
16
  } | undefined | T : T | undefined;
15
17
 
18
+ /**
19
+ * core/types.ts
20
+ * * This file contains the primary domain models, data structures, and command types
21
+ * for the AI Workspace. It acts as the "Source of Truth" for all modules.
22
+ */
23
+
24
+ /** RFC 4122 compliant Universally Unique Identifier. */
16
25
  type UUID = string;
26
+ /** ISO-8601 formatted UTC timestamp string. */
17
27
  type Timestamp = string;
28
+ /** Uniform Resource Identifier string. */
18
29
  type URI = string;
30
+ /** Hexadecimal representation of a SHA-256 hash. */
19
31
  type SHA256 = string;
32
+ /** Special marker used to denote a role with no specific instructions or identity. */
33
+ declare const EMPTY_SYSTEM_ROLE = "__system__";
34
+ /**
35
+ * A functional wrapper for operations that can fail.
36
+ * Encourages explicit error handling over try/catch blocks.
37
+ */
20
38
  type Result<T, E = WorkspaceError> = {
21
39
  ok: true;
22
40
  value: T;
@@ -24,47 +42,72 @@ type Result<T, E = WorkspaceError> = {
24
42
  ok: false;
25
43
  error: E;
26
44
  };
45
+ /** Occurs when attempting to create a resource with a key that already exists. */
27
46
  type DuplicateKeyError = {
28
47
  code: 'DUPLICATE_KEY';
29
48
  resource: string;
30
49
  key: string;
31
50
  };
51
+ /** Occurs when a requested resource cannot be found by its unique identifier. */
32
52
  type NotFoundError = {
33
53
  code: 'NOT_FOUND';
34
54
  resource: string;
35
55
  id: string;
36
56
  };
57
+ /** Triggered when a command payload fails validation or is logically inconsistent. */
37
58
  type InvalidCommandError = {
38
59
  code: 'INVALID_COMMAND';
39
60
  reason: string;
40
61
  };
62
+ /** Generic wrapper for unexpected infrastructure or downstream service failures. */
41
63
  type BackendError = {
42
64
  code: 'BACKEND_ERROR';
43
65
  reason: string;
44
66
  };
67
+ /** Specific errors related to blob storage, retrieval, or corruption. */
45
68
  type BlobError = {
46
69
  code: 'BLOB_ERROR';
47
70
  reason: string;
48
71
  };
49
- type WorkspaceError = DuplicateKeyError | NotFoundError | InvalidCommandError | BackendError | BlobError;
72
+ /** Triggered when the current actor lacks sufficient privileges for a command. */
73
+ type PermissionDeniedError = {
74
+ code: 'PERMISSION_DENIED';
75
+ command: Command;
76
+ reason: string;
77
+ };
78
+ /** Union of all possible error types within the Workspace domain. */
79
+ type WorkspaceError = DuplicateKeyError | NotFoundError | InvalidCommandError | BackendError | PermissionDeniedError | BlobError;
80
+ /** Global user preferences and defaults for the workspace. */
50
81
  interface Settings {
82
+ /** Default language code (e.g., 'en-US'). */
51
83
  language: string;
84
+ /** The name of the role used when starting a new session. */
52
85
  defaultRole?: string;
86
+ /** Global instructions appended to all system prompts. */
53
87
  prompt?: string;
54
88
  }
89
+ /** * Represents the project-level metadata.
90
+ * Allows for extensible metadata fields via the generic Metadata type.
91
+ */
55
92
  type Project<Metadata extends Record<string, any> = Record<string, any>> = Metadata & {
56
93
  id: UUID;
57
94
  name: string;
58
95
  };
96
+ /** Supported mime-types for image assets. */
59
97
  type ImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
98
+ /** Supported mime-types for text-based or structured documents. */
60
99
  type DocumentMediaType = 'application/pdf' | 'application/json' | 'text/plain' | 'text/html' | 'text/markdown' | 'text/csv' | 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' | 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
100
+ /** Union of all media types handled by the blob system. */
61
101
  type BlobMediaType = ImageMediaType | DocumentMediaType;
62
102
  /**
63
- * Lightweight pointer to a blob — the subset of BlobRecord that content
64
- * blocks and context entries carry. Use this at call sites that only need
65
- * to reference a blob, not inspect its registry metadata.
103
+ * A lightweight reference to a blob.
104
+ * Used in content blocks to avoid passing heavy metadata or binary data.
66
105
  */
67
106
  type BlobRef = Pick<BlobRecord, 'sha256' | 'mediaType' | 'sizeBytes' | 'filename' | 'previewUrl'>;
107
+ /**
108
+ * Represents a blob that has been fetched into memory.
109
+ * Can be 'inline' (binary data present) or 'remote' (stored in an external provider).
110
+ */
68
111
  type ResolvedBlob = {
69
112
  kind: 'inline';
70
113
  sha256: SHA256;
@@ -76,10 +119,11 @@ type ResolvedBlob = {
76
119
  mediaType: BlobMediaType;
77
120
  fileId: string;
78
121
  providerId: string;
122
+ timestamp: Timestamp;
79
123
  };
80
124
  /**
81
- * Full registry entry for a blob. BlobRef is a Pick of this type, so
82
- * a BlobRecord is always assignable to BlobRef.
125
+ * The authoritative registry entry for a file in the system.
126
+ * Includes reference counting for garbage collection and remote mappings.
83
127
  */
84
128
  interface BlobRecord {
85
129
  sha256: SHA256;
@@ -87,16 +131,23 @@ interface BlobRecord {
87
131
  sizeBytes: number;
88
132
  filename?: string;
89
133
  previewUrl?: string;
134
+ /** Number of content blocks currently referencing this blob. */
90
135
  refCount: number;
91
- remoteIds: Record<string, string>;
136
+ /** Map of provider IDs to their specific external file identifiers. */
137
+ remoteIds: Record<string, {
138
+ id: string;
139
+ timestamp: Timestamp;
140
+ }>;
92
141
  createdAt: Timestamp;
93
142
  lastUsedAt: Timestamp;
94
143
  }
144
+ /** Standard text content within a turn. */
95
145
  interface TextBlock {
96
146
  id: UUID;
97
147
  type: 'text';
98
148
  text: string;
99
149
  }
150
+ /** An image asset within a turn, optionally containing the resolved binary data. */
100
151
  interface ImageBlock {
101
152
  id: UUID;
102
153
  type: 'image';
@@ -104,6 +155,7 @@ interface ImageBlock {
104
155
  blob?: ResolvedBlob;
105
156
  altText?: string;
106
157
  }
158
+ /** A document asset within a turn. */
107
159
  interface DocumentBlock {
108
160
  id: UUID;
109
161
  type: 'document';
@@ -111,67 +163,76 @@ interface DocumentBlock {
111
163
  blob?: ResolvedBlob;
112
164
  title?: string;
113
165
  }
166
+ /** Represents a structured proposal to create or modify a task. */
114
167
  interface TaskProposalBlock {
115
- id: UUID;
116
- taskId?: UUID;
168
+ id?: UUID;
169
+ ref?: string;
117
170
  type: 'task:proposal';
118
171
  title: string;
119
172
  steps: {
120
- id?: UUID;
173
+ ref?: string;
121
174
  text: string;
122
175
  status: 'todo' | 'done';
123
176
  }[];
124
177
  action: 'create' | 'update' | 'complete';
125
178
  }
179
+ /** Captured request from the AI to execute a specific tool. */
126
180
  interface ToolUseBlock {
127
181
  id: UUID;
128
182
  type: 'tool:use';
129
183
  name: string;
130
184
  input: Record<string, unknown>;
131
185
  }
186
+ /** The resulting output (or error) from a tool execution. */
132
187
  interface ToolResultBlock {
133
188
  id: UUID;
134
189
  type: 'tool:result';
190
+ /** References the ToolUseBlock ID that generated this result. */
135
191
  useId: UUID;
136
192
  content: string | Record<string, unknown>;
137
193
  isError?: boolean;
138
194
  }
195
+ /** Internal "Chain of Thought" or reasoning generated by the model. */
139
196
  interface ThinkingBlock {
140
197
  id: UUID;
141
198
  type: 'thinking';
142
199
  thinking: string;
143
200
  }
201
+ /** A condensed summary of previous conversation history. */
144
202
  interface SummaryBlock {
145
203
  id: UUID;
146
204
  type: 'summary';
147
205
  text: string;
148
206
  }
207
+ /** Notates that the session has switched from one Role persona to another. */
149
208
  interface RoleTransitionBlock {
150
209
  id: UUID;
151
210
  type: 'role:transition';
152
211
  previousRole: string | null;
153
212
  newRole: string;
154
213
  }
214
+ /** Union of all possible content types that can exist within a conversation Turn. */
155
215
  type ContentBlock = TextBlock | ImageBlock | DocumentBlock | ToolUseBlock | ToolResultBlock | SummaryBlock | RoleTransitionBlock | ThinkingBlock | TaskProposalBlock;
216
+ /** Definition of a tool available to the AI. */
156
217
  interface ToolSummary {
157
218
  name: string;
158
219
  description: string;
220
+ /** JSON Schema defining the required input arguments. */
159
221
  parameters: {
160
222
  type: 'object';
161
223
  properties: Record<string, any>;
162
224
  required: string[];
163
225
  };
164
- /**
165
- * The semantic tags for this tool.
166
- * Used by the ContextRetriever to filter relevance.
167
- */
226
+ /** Semantic tags used to help the model find relevant tools. */
168
227
  topics: string[];
169
228
  }
229
+ /** An instance of a tool being called with specific arguments. */
170
230
  interface ToolCall {
171
231
  id: UUID;
172
232
  tool: UUID;
173
233
  arguments: Record<string, any>;
174
234
  }
235
+ /** A request for authorization before executing a command or tool. */
175
236
  type AuthRequest = {
176
237
  type: 'command';
177
238
  payload: Command;
@@ -179,39 +240,38 @@ type AuthRequest = {
179
240
  type: 'tool';
180
241
  payload: ToolCall;
181
242
  };
182
- type TurnRole = 'user' | 'assistant' | 'tool';
243
+ /** Identifies whether a turn originated from the user, the AI, a tool, or the system. */
244
+ type TurnActor = 'user' | 'assistant' | 'tool' | 'system';
245
+ /** * The flat storage format for a conversation turn.
246
+ * Supports versioning and parent-pointers for branching conversation trees (DAG).
247
+ */
183
248
  interface Turn {
184
249
  id: UUID;
250
+ /** Incrementing number for edits to the same turn ID. */
185
251
  version: number;
186
- owner: TurnRole;
252
+ actor: TurnActor;
187
253
  blocks: ContentBlock[];
188
254
  timestamp: Timestamp;
189
- /**
190
- * The name of the role active when this turn was recorded.
191
- * Snapshot so history is stable even if the role is later renamed.
192
- */
255
+ /** Name of the role active at the time of this turn. */
193
256
  role?: string;
194
- /**
195
- * Parent pointer. Null for root turns.
196
- * This is plain data stored on the document — the DAG is reconstructed
197
- * in memory by TurnTree.buildNodeGraph() at session open time.
198
- */
257
+ /** Link to the preceding turn in the conversation tree. */
199
258
  parent: {
200
259
  id: UUID;
201
260
  version: number;
202
261
  } | null;
203
- /**
204
- * Partition key. Stored on the Turn document so Collection.filter
205
- * can retrieve all turns for a session in a single query.
206
- * Not present on Turn objects used purely in memory (e.g. dirty buffer).
207
- */
262
+ /** Used for fast filtering within a specific chat session. */
208
263
  sessionId?: UUID;
209
264
  }
265
+ /**
266
+ * An in-memory representation of a turn, including all its versions and children.
267
+ * This is used for rendering threaded/branching conversations.
268
+ */
210
269
  interface TurnNode {
211
270
  id: UUID;
271
+ /** Map of version numbers to the Turn data. */
212
272
  versions: Record<number, Turn>;
213
273
  activeVersion: number;
214
- role: TurnRole;
274
+ role: TurnActor;
215
275
  blocks: ContentBlock[];
216
276
  timestamp: Timestamp;
217
277
  roleSnapshot?: string;
@@ -219,8 +279,10 @@ interface TurnNode {
219
279
  id: UUID;
220
280
  version: number;
221
281
  } | null;
282
+ /** Map of version numbers to an array of child turn IDs. */
222
283
  children: Record<number, UUID[]>;
223
284
  }
285
+ /** UI helper for navigating between different versions of a turn (e.g. "2 of 5"). */
224
286
  interface BranchInfo {
225
287
  versions: number[];
226
288
  currentIndex: number;
@@ -228,19 +290,27 @@ interface BranchInfo {
228
290
  hasPrev: boolean;
229
291
  hasNext: boolean;
230
292
  }
293
+ /** A system persona containing specific instructions and associated preferences. */
231
294
  interface Role {
295
+ /** Unique identifier name (e.g. "software-architect"). */
232
296
  name: string;
297
+ /** Human-readable display label. */
233
298
  label: string;
234
299
  description?: string;
300
+ /** The core instructions (system prompt) for this persona. */
235
301
  persona: string;
302
+ /** Array of Preference IDs associated with this role. */
236
303
  preferences: UUID[];
237
304
  }
305
+ /** A specific user preference or "memory" that informs model behavior. */
238
306
  interface Preference {
239
307
  id: UUID;
240
308
  content: string;
309
+ /** Topics used for retrieval-augmented generation (RAG). */
241
310
  topics: string[];
242
311
  timestamp: Timestamp;
243
312
  }
313
+ /** Discriminated union of types that can be injected into the AI context. */
244
314
  type ContextContent = {
245
315
  kind: 'text';
246
316
  value: string;
@@ -258,20 +328,20 @@ type ContextContent = {
258
328
  uri: URI;
259
329
  mediaType?: BlobMediaType;
260
330
  };
331
+ /** A contextual item (file, snippet, or data) attached to a session or prompt. */
261
332
  interface Context {
333
+ /** Unique lookup key. */
262
334
  key: string;
263
335
  topics: string[];
264
336
  content: ContextContent;
265
337
  timestamp: Timestamp;
266
338
  metadata?: Record<string, any>;
267
339
  }
268
- /**
269
- * SessionMeta is stored as a document in the 'session' collection.
270
- * The head pointer lives here — no separate session_heads store needed.
271
- */
340
+ /** Metadata for a conversation session, stored in the persistent collection. */
272
341
  interface SessionMeta {
273
342
  id: UUID;
274
343
  label: string;
344
+ /** The active Role name for this session. */
275
345
  role: string;
276
346
  topics: string[];
277
347
  preferences: UUID[];
@@ -279,21 +349,27 @@ interface SessionMeta {
279
349
  created?: Timestamp;
280
350
  updated?: Timestamp;
281
351
  };
352
+ /** Tracks how many turns have been persisted to the database. */
282
353
  flushedTurnCount: number;
354
+ /** The current leaf-node of the conversation. */
283
355
  head: {
284
356
  id: UUID;
285
357
  version: number;
286
358
  } | null;
359
+ /** Optional link to a specific Task being worked on. */
287
360
  task: UUID | null;
288
361
  }
289
362
  type TaskStatus = 'todo' | 'active' | 'done' | 'blocked' | 'defered';
363
+ /** A single item within a Task's checklist. */
290
364
  interface TaskStep {
291
- id: UUID;
365
+ ref: string;
292
366
  text: string;
293
367
  completed?: Timestamp;
294
368
  }
369
+ /** A high-level objective with nested steps, used for tracking AI progress. */
295
370
  interface Task {
296
371
  id: UUID;
372
+ ref?: string;
297
373
  title: string;
298
374
  description?: string;
299
375
  status: TaskStatus;
@@ -307,7 +383,6 @@ interface RoleSummary {
307
383
  name: string;
308
384
  label: string;
309
385
  description?: string;
310
- /** Number of preference IDs listed on the role. */
311
386
  preferences: number;
312
387
  }
313
388
  interface PreferenceSummary {
@@ -328,6 +403,8 @@ interface ContextSummary {
328
403
  }
329
404
  interface TaskSummary {
330
405
  id: UUID;
406
+ ref?: string;
407
+ description: string;
331
408
  title: string;
332
409
  status: TaskStatus;
333
410
  steps: {
@@ -336,6 +413,7 @@ interface TaskSummary {
336
413
  };
337
414
  topics: string[];
338
415
  }
416
+ /** Maps topics to the various entities that reference them. */
339
417
  interface TopicIndex {
340
418
  topic: string;
341
419
  contextKeys: string[];
@@ -347,6 +425,7 @@ interface TopicIndex {
347
425
  entries?: number;
348
426
  };
349
427
  }
428
+ /** The complete in-memory read-model of the Workspace state. */
350
429
  interface Index {
351
430
  roles: Record<string, RoleSummary>;
352
431
  preferences: Record<UUID, PreferenceSummary>;
@@ -357,12 +436,16 @@ interface Index {
357
436
  blobs: Record<SHA256, BlobRecord>;
358
437
  tools: Record<string, ToolSummary>;
359
438
  }
439
+ /** The root container for a user's workspace. */
360
440
  interface Workspace<ProjectMetadata extends Record<string, any> = Record<string, any>> {
361
441
  id: UUID;
362
442
  settings: Settings;
363
443
  project: Project<ProjectMetadata>;
364
444
  index: Index;
365
445
  }
446
+ /** * Format used for exporting/importing a complete workspace state,
447
+ * including all historical turns and binary records.
448
+ */
366
449
  interface WorkspaceBundle {
367
450
  format: 'aiworkspace/4.0';
368
451
  workspace: Workspace;
@@ -375,6 +458,7 @@ interface WorkspaceBundle {
375
458
  tasks: Record<UUID, Task>;
376
459
  blobs: Record<SHA256, BlobRecord>;
377
460
  }
461
+ /** A fully hydrated view of a session, including resolved objects for the prompt builder. */
378
462
  interface EffectiveSession {
379
463
  session: SessionMeta;
380
464
  role: Role;
@@ -384,24 +468,14 @@ interface EffectiveSession {
384
468
  task: Task | null;
385
469
  instructions?: string;
386
470
  }
387
- interface CacheConfig {
388
- roles?: number;
389
- preferences?: number;
390
- context?: number;
391
- tasks?: number;
392
- }
393
- interface FlushConfig {
394
- maxBufferSize: number;
395
- flushIntervalMs: number;
396
- }
397
- interface ContentStoreConfig {
398
- cache?: CacheConfig;
399
- flush?: FlushConfig;
400
- }
401
471
  interface BaseCommand {
472
+ /** Discriminator for the command type. */
402
473
  type: string;
403
474
  timestamp: Timestamp;
475
+ /** The ID of the user or system component that initiated the command. */
404
476
  actor?: string;
477
+ description?: string;
478
+ synthetic?: boolean;
405
479
  }
406
480
  interface CreateWorkspace extends BaseCommand {
407
481
  type: 'workspace:create';
@@ -469,15 +543,18 @@ interface DeleteContext extends BaseCommand {
469
543
  key: string;
470
544
  };
471
545
  }
546
+ type TaskRef = UUID | string;
472
547
  interface AddTask extends BaseCommand {
473
548
  type: 'task:add';
474
549
  payload: Task;
475
550
  }
476
551
  interface UpdateTask extends BaseCommand {
477
552
  type: 'task:update';
478
- payload: Partial<Task> & {
553
+ payload: Partial<Task> & ({
479
554
  id: UUID;
480
- };
555
+ } | {
556
+ ref: string;
557
+ });
481
558
  }
482
559
  interface DeleteTask extends BaseCommand {
483
560
  type: 'task:delete';
@@ -485,6 +562,7 @@ interface DeleteTask extends BaseCommand {
485
562
  id: UUID;
486
563
  };
487
564
  }
565
+ /** Updates an existing turn record in storage. */
488
566
  interface SaveTurn extends BaseCommand {
489
567
  type: 'turn:save';
490
568
  payload: {
@@ -492,6 +570,7 @@ interface SaveTurn extends BaseCommand {
492
570
  turn: Turn;
493
571
  };
494
572
  }
573
+ /** Appends a new turn to a session. */
495
574
  interface AddTurn extends BaseCommand {
496
575
  type: 'turn:add';
497
576
  payload: {
@@ -499,6 +578,7 @@ interface AddTurn extends BaseCommand {
499
578
  turn: Turn;
500
579
  };
501
580
  }
581
+ /** Creates a new version of an existing turn. */
502
582
  interface EditTurn extends BaseCommand {
503
583
  type: 'turn:edit';
504
584
  payload: {
@@ -509,6 +589,7 @@ interface EditTurn extends BaseCommand {
509
589
  roleSnapshot?: string;
510
590
  };
511
591
  }
592
+ /** Creates a new branch in the conversation history from a specific turn. */
512
593
  interface BranchTurn extends BaseCommand {
513
594
  type: 'turn:branch';
514
595
  payload: {
@@ -520,6 +601,7 @@ interface TurnRef {
520
601
  id: UUID;
521
602
  version: number;
522
603
  }
604
+ /** Removes a specific version of a turn and updates the session head if necessary. */
523
605
  interface DeleteTurn extends BaseCommand {
524
606
  type: 'turn:delete';
525
607
  payload: {
@@ -550,6 +632,7 @@ interface OverrideSessionPreferences extends BaseCommand {
550
632
  preferences: UUID[];
551
633
  };
552
634
  }
635
+ /** Creates a new session starting from the state of an existing one. */
553
636
  interface ForkSession extends BaseCommand {
554
637
  type: 'session:fork';
555
638
  payload: {
@@ -560,6 +643,17 @@ interface ForkSession extends BaseCommand {
560
643
  topics?: string[];
561
644
  };
562
645
  }
646
+ interface UpdateSession extends BaseCommand {
647
+ type: 'session:update';
648
+ payload: {
649
+ sessionId: UUID;
650
+ label?: string;
651
+ role?: string;
652
+ topics?: string[];
653
+ preferences?: UUID[];
654
+ task?: UUID | null;
655
+ };
656
+ }
563
657
  interface DeleteSession extends BaseCommand {
564
658
  type: 'session:delete';
565
659
  payload: {
@@ -574,30 +668,35 @@ interface RegisterBlob extends BaseCommand {
574
668
  filename?: string;
575
669
  };
576
670
  }
671
+ /** Increases reference count to prevent garbage collection. */
577
672
  interface RetainBlob extends BaseCommand {
578
673
  type: 'blob:retain';
579
674
  payload: {
580
675
  sha256: SHA256;
581
676
  };
582
677
  }
678
+ /** Decreases reference count. */
583
679
  interface ReleaseBlob extends BaseCommand {
584
680
  type: 'blob:release';
585
681
  payload: {
586
682
  sha256: SHA256;
587
683
  };
588
684
  }
685
+ /** Immediately removes a blob regardless of reference count. */
589
686
  interface PurgeBlob extends BaseCommand {
590
687
  type: 'blob:purge';
591
688
  payload: {
592
689
  sha256: SHA256;
593
690
  };
594
691
  }
692
+ /** Maps a local blob to an external provider's file ID. */
595
693
  interface RecordBlobRemoteId extends BaseCommand {
596
694
  type: 'blob:record_remote_id';
597
695
  payload: {
598
696
  sha256: SHA256;
599
697
  providerId: string;
600
698
  fileId: string;
699
+ timestamp?: Timestamp;
601
700
  };
602
701
  }
603
702
  type BlobCommand = RegisterBlob | RetainBlob | ReleaseBlob | PurgeBlob | RecordBlobRemoteId;
@@ -605,30 +704,27 @@ interface CallTool extends BaseCommand {
605
704
  type: 'tool:call';
606
705
  payload: ToolCall;
607
706
  }
608
- type Command = CreateWorkspace | AddRole | UpdateRole | DeleteRole | AddPreference | UpdatePreference | DeletePreference | CreateSession | AddContext | UpdateContext | DeleteContext | AddTask | UpdateTask | DeleteTask | AddTurn | SaveTurn | EditTurn | BranchTurn | DeleteTurn | SwitchRole | AddSessionTopics | OverrideSessionPreferences | ForkSession | DeleteSession | BlobCommand | CallTool;
707
+ /** Union of all possible commands that can be dispatched to the Workspace Manager. */
708
+ type Command = CreateWorkspace | AddRole | UpdateRole | DeleteRole | AddPreference | UpdatePreference | DeletePreference | CreateSession | UpdateSession | AddContext | UpdateContext | DeleteContext | AddTask | UpdateTask | DeleteTask | AddTurn | SaveTurn | EditTurn | BranchTurn | DeleteTurn | SwitchRole | AddSessionTopics | OverrideSessionPreferences | ForkSession | DeleteSession | BlobCommand | CallTool;
709
+ /** Configuration for token counting and management during prompt generation. */
609
710
  interface TokenBudget {
610
711
  total: number;
611
712
  estimator?: (text: string) => number;
612
713
  blobTokensPerKB?: number;
613
714
  }
715
+ /** Details regarding why a specific preference was excluded from a prompt. */
614
716
  interface PreferenceConflict {
615
717
  topic: string;
616
718
  kept: UUID;
617
719
  dropped: UUID;
618
720
  reason: 'superseded_by_newer';
619
721
  }
620
- interface ContextRelevanceConfig {
621
- recentMessageWindow?: number;
622
- minScore?: number;
623
- freshnessHalfLifeDays?: number;
624
- }
625
722
  /**
626
- * Prompt.transcript.turns is Turn[].
627
- * Synthetic turns produced by PromptAssembler (summary blocks, truncation
628
- * notices, referential attachments) carry generated UUIDs and version 0,
629
- * with parent: null. They are ephemeral — never stored, never patched.
723
+ * The final structure sent to an LLM provider.
724
+ * Assembled by the PromptAssembler by resolving roles, context, and history.
630
725
  */
631
726
  interface Prompt {
727
+ /** Information destined for the System Message. */
632
728
  system: {
633
729
  instructions?: string;
634
730
  persona: string;
@@ -636,7 +732,9 @@ interface Prompt {
636
732
  context: Context[];
637
733
  task: Task | null;
638
734
  };
735
+ /** Additional context items injected separately. */
639
736
  context: Context[];
737
+ /** The conversation history. */
640
738
  transcript: {
641
739
  turns: Turn[];
642
740
  };
@@ -645,6 +743,7 @@ interface Prompt {
645
743
  used: number;
646
744
  breakdown: Record<string, number>;
647
745
  };
746
+ /** Statistics on what was removed to fit within the token limit. */
648
747
  truncated: {
649
748
  preferences: number;
650
749
  interactions: number;
@@ -653,20 +752,118 @@ interface Prompt {
653
752
  warnings: string[];
654
753
  conflicts: PreferenceConflict[];
655
754
  }
656
- interface TranscriptWindow {
657
- sessionId: UUID;
658
- turns: Turn[];
659
- flushedCount: number;
660
- hasMore: boolean;
661
- }
755
+ /** Typed events emitted by the Workspace when data changes. */
662
756
  interface WorkspaceEvents {
757
+ /** Emitted when the index or core settings change. */
663
758
  'workspace:changed': DeepPartial<Workspace>;
759
+ /** Emitted when a blob is registered, updated, or removed. */
664
760
  'blobs:changed': {
665
761
  sha256: SHA256;
666
762
  record: BlobRecord | null;
667
763
  };
668
764
  }
669
765
 
766
+ /**
767
+ * Handles transcript compression and history management.
768
+ * When a conversation exceeds the model's context window, the Summarizer
769
+ * condenses older turns into a single summary string to reclaim tokens.
770
+ */
771
+ interface Summarizer {
772
+ /**
773
+ * Compresses the provided transcript.
774
+ * * @param transcript - The current list of conversation turns.
775
+ * @param tokenBudget - The maximum allowed tokens for the history.
776
+ * @returns A promise resolving to the summary and the remaining uncompressed turns.
777
+ */
778
+ summarize(transcript: Turn[], tokenBudget: number): Promise<{
779
+ summary: string;
780
+ remaining: Turn[];
781
+ }>;
782
+ }
783
+ /**
784
+ * Analyzes model outputs for side effects and workspace actions.
785
+ * The TurnProcessor scans the assistant's response (Turn) for specific
786
+ * triggers, such as file edits, UI updates, or state changes.
787
+ */
788
+ interface TurnProcessor {
789
+ /**
790
+ * Scans a turn for actionable blocks and returns workspace commands.
791
+ * @param turn - The assistant turn to be processed.
792
+ * @param sessionId - The session in which the turn was generated.
793
+ * @returns An array of Commands to synchronize the Workspace state.
794
+ */
795
+ process(turn: Turn, sessionId?: UUID): Command[];
796
+ }
797
+ /**
798
+ * Manages the lifecycle and execution of external tools.
799
+ * Acts as a central hub for discovering available capabilities and
800
+ * routing tool calls to their respective executors.
801
+ */
802
+ interface ToolRegistry {
803
+ /**
804
+ * Subscribes to changes in the tool ecosystem.
805
+ * @param callback - Invoked whenever tools are added, removed, or updated.
806
+ */
807
+ onRegistryChanged(callback: (tools: ToolSummary[]) => void): void;
808
+ /**
809
+ * Retrieves a list of all currently registered and available tools.
810
+ * @returns An array of summaries describing tool capabilities and schemas.
811
+ */
812
+ list(): ToolSummary[];
813
+ /**
814
+ * Executes a tool call in a stateless manner.
815
+ * * @template T - The expected return type of the tool execution.
816
+ * @param call - The specific tool call requested by the model.
817
+ * @returns A promise resolving to a Result wrapper containing the tool output.
818
+ */
819
+ execute<T = any>(call: ToolCall): Promise<Result<T>>;
820
+ }
821
+ /**
822
+ * Enforces security and authorization policies.
823
+ * * The PermissionGuard ensures that the current execution context (User/Session)
824
+ * has the necessary privileges to perform a requested action or tool call.
825
+ */
826
+ interface PermissionGuard {
827
+ /**
828
+ * Validates if the current context has the right to execute the request.
829
+ * * @param request - The authentication payload and target action.
830
+ * @returns A Result containing the authorized payload or an error.
831
+ */
832
+ authenticate(request: AuthRequest): Promise<Result<AuthRequest["payload"] | null>>;
833
+ }
834
+ /**
835
+ * Bridge between the internal Workspace types and external LLM APIs.
836
+ * This generic adapter allows the system to remain vendor-agnostic by
837
+ * centralizing the translation logic for different providers (Google, OpenAI, etc.).
838
+ * @template TRequest - The specific request shape expected by the provider SDK.
839
+ * @template TRequestParams - Extra parameters for the request (e.g., model name, temperature).
840
+ * @template TResponse - The raw response shape returned by the provider SDK.
841
+ */
842
+ interface LLMAdapter<TRequest, TRequestParams, TResponse> {
843
+ /**
844
+ * Maps the internal `Prompt` to the vendor-specific request format.
845
+ * * @param params - The prompt and provider-specific configuration.
846
+ * @returns The formatted request object ready for the SDK.
847
+ */
848
+ /**
849
+ * Prepares the request and identifies necessary side-effects (like uploads).
850
+ */
851
+ prepare(params: {
852
+ prompt: Prompt;
853
+ } & TRequestParams): Promise<{
854
+ request: TRequest;
855
+ effects?: Command[];
856
+ }>;
857
+ /**
858
+ * Maps the vendor-specific response back to an internal `Turn`.
859
+ * * @param params - The raw response received from the model API.
860
+ * @returns A Result containing standardized Turn object or an error.
861
+ */
862
+ parse(params: {
863
+ response: TResponse;
864
+ }): Result<Turn, WorkspaceError>;
865
+ }
866
+
670
867
  /**
671
868
  * Buffers write operations across one or more stores and commits them atomically.
672
869
  *
@@ -1105,20 +1302,50 @@ type CollectionName = typeof COLLECTIONS[keyof typeof COLLECTIONS];
1105
1302
 
1106
1303
  declare function del<T>(): T;
1107
1304
  declare const merge: <T extends object>(original: T, changes: DeepPartial<T> | symbol) => T;
1108
- declare function ok<T>(value: T): Result<T, never>;
1109
- declare function err<E = WorkspaceError>(error: E): Result<never, E>;
1305
+ declare function success<T>(value: T): Result<T, never>;
1306
+ declare function error<E = WorkspaceError>(error: E): Result<never, E>;
1110
1307
  declare function omitNullUndefined<T extends Record<string, any>>(obj: T): Partial<T>;
1111
1308
  declare function createProjectWorkspace<ProjectMetadata extends Record<string, any> = Record<string, any>>({ project, language }: {
1112
1309
  language: string;
1113
1310
  project: Omit<Project<ProjectMetadata>, "id">;
1114
1311
  }): Workspace<ProjectMetadata>;
1115
- declare function createSimpleWorkspace({ name, owner, language }: {
1312
+ declare function createSimpleWorkspace({ name, actor, language }: {
1116
1313
  name: string;
1117
1314
  language: string;
1118
- owner: string;
1315
+ actor: string;
1119
1316
  }): Workspace;
1120
1317
  declare function extractBlobRecord(patch: DeepPartial<Workspace>): BlobRecord | null;
1121
1318
  declare function extractBlobRef(record: BlobRecord): BlobRef;
1319
+ declare function computeSHA256(data: Uint8Array): Promise<SHA256>;
1320
+ /**
1321
+ * Creates a skeleton Role object with empty defaults.
1322
+ */
1323
+ declare const createEmptyRole: (name: string, label: string) => Role;
1324
+ /**
1325
+ * Isomorphic Base64 converter (Node.js / browser).
1326
+ */
1327
+ declare function bufferToBase64(data: ArrayBuffer | Uint8Array | number[]): string;
1328
+
1329
+ /**
1330
+ * Short, deterministic hash of a string (4 chars in base36).
1331
+ * Suitable for AI-friendly reference tokens.
1332
+ */
1333
+ declare function shortHash(s: string, length?: number): string;
1334
+ /**
1335
+ * Generates a short, memorable reference for a task.
1336
+ * - Returns the proposal's own `ref` if provided.
1337
+ * - Otherwise returns a 4‑character hash of the proposal's `id` or `title`.
1338
+ */
1339
+ declare function generateTaskRef(proposal: TaskProposalBlock): string;
1340
+ /**
1341
+ * Generates a short step reference.
1342
+ * - Returns the step's own `ref` if provided.
1343
+ * - Otherwise returns `${taskRef}_${index+1}` (e.g., "a3f9_2").
1344
+ *
1345
+ * The underscore separator avoids confusion with colons, slashes, or
1346
+ * numeric suffixes that could be misinterpreted by LLMs.
1347
+ */
1348
+ declare function generateTaskStepRef(index: number, proposal: TaskProposalBlock): string;
1122
1349
 
1123
1350
  /**
1124
1351
  * Persistence contract for binary blob content and blob registry records.
@@ -1197,7 +1424,6 @@ declare class TurnTree {
1197
1424
  copyTranscript(sourceSessionId: UUID, targetSessionId: UUID): Promise<void>;
1198
1425
  }
1199
1426
 
1200
- declare function computeSHA256(data: Uint8Array): Promise<SHA256>;
1201
1427
  interface BlobStoreConfig {
1202
1428
  /**
1203
1429
  * When true, blobs with refCount === 0 are deleted from the backend
@@ -1232,6 +1458,10 @@ declare class BlobStore {
1232
1458
  release(sha256: SHA256): Promise<Result<void, WorkspaceError>>;
1233
1459
  recordRemoteId(sha256: SHA256, providerId: string, fileId: string): Promise<Result<void, WorkspaceError>>;
1234
1460
  getRemoteId(sha256: SHA256, providerId: string): string | null;
1461
+ getRemoteRecord(sha256: SHA256, providerId: string): {
1462
+ id: string;
1463
+ timestamp: Timestamp;
1464
+ } | null;
1235
1465
  resolveRef(ref: BlobRef, providerId: string | null): Promise<Result<ResolvedBlob, WorkspaceError>>;
1236
1466
  resolveRefs(refs: BlobRef[], providerId: string | null): Promise<{
1237
1467
  resolved: Map<SHA256, ResolvedBlob>;
@@ -1250,6 +1480,15 @@ declare class BlobStore {
1250
1480
  getAllRecords(): Record<SHA256, BlobRecord>;
1251
1481
  }
1252
1482
 
1483
+ interface CacheConfig {
1484
+ roles?: number;
1485
+ preferences?: number;
1486
+ context?: number;
1487
+ tasks?: number;
1488
+ }
1489
+ interface ContentStoreConfig {
1490
+ cache?: CacheConfig;
1491
+ }
1253
1492
  declare class ContentStore {
1254
1493
  private readonly db;
1255
1494
  readonly tree: TurnTree;
@@ -1299,64 +1538,41 @@ declare class ContentStore {
1299
1538
  gc(): Promise<number>;
1300
1539
  }
1301
1540
 
1302
- declare function workspaceReducer({ index: state }: Workspace, command: Command): Result<DeepPartial<Workspace>, WorkspaceError>;
1303
-
1304
- interface Summarizer {
1305
- summarize(transcript: Turn[], tokenBudget: number): Promise<{
1306
- summary: string;
1307
- remaining: Turn[];
1308
- }>;
1309
- }
1310
- interface ToolRegistry {
1311
- /**
1312
- * Subscribe to tool registry changes.
1313
- * The callback is executed whenever the set of available tools changes.
1314
- */
1315
- onRegistryChanged(callback: (tools: ToolSummary[]) => void): void;
1316
- /**
1317
- * Returns all tools currently available in the environment.
1318
- */
1319
- list(): ToolSummary[];
1320
- /**
1321
- * The stateless executor.
1322
- * Takes the call, returns the raw result.
1323
- */
1324
- execute<T = any>(call: ToolCall): Promise<Result<T>>;
1325
- }
1326
- interface PermissionGuard {
1327
- /**
1328
- * An async predicate that determines if the current context
1329
- * (user, session, project) has the right to execute the request.
1330
- */
1331
- authenticate(request: AuthRequest): Promise<Result<null>>;
1332
- }
1333
-
1334
1541
  declare class WorkspaceManager {
1335
1542
  private readonly contentStore;
1336
1543
  private readonly permissionGuard?;
1337
1544
  private readonly toolRegistry?;
1545
+ private readonly processor;
1338
1546
  private bus;
1339
- /**
1340
- * Called after any workspace change
1341
- */
1342
- subscribe<TEventName extends keyof WorkspaceEvents>(event: TEventName, callback: (payload: WorkspaceEvents[TEventName]) => void): () => void;
1343
1547
  constructor(options: {
1344
1548
  contentStore: ContentStore;
1345
1549
  permissionGuard?: PermissionGuard;
1346
1550
  toolRegistry?: ToolRegistry;
1347
1551
  eventBus: EventBus<WorkspaceEvents>;
1552
+ turnProcessor?: TurnProcessor;
1348
1553
  });
1554
+ store(): ContentStore;
1555
+ turnProcessor(): TurnProcessor;
1349
1556
  /**
1350
1557
  * Initializes a Workspace's in-memory Index from environment-static
1351
1558
  * sources (like ToolRegistry). Call this when opening a Workspace.
1352
1559
  */
1353
- init(_: Workspace): DeepPartial<Workspace>;
1560
+ initTools(_: Workspace): DeepPartial<Workspace>;
1561
+ /**
1562
+ * Called after any workspace change
1563
+ */
1564
+ subscribe<TEventName extends keyof WorkspaceEvents>(event: TEventName, callback: (payload: WorkspaceEvents[TEventName]) => void): () => void;
1354
1565
  reduce(workspace: Workspace, command: Command): Result<DeepPartial<Workspace>, WorkspaceError>;
1355
1566
  dispatch(workspace: Workspace, command: Command): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1356
1567
  resolveSession(workspace: Workspace, sessionId: UUID, transcript?: Turn[]): Promise<Result<EffectiveSession, WorkspaceError>>;
1357
1568
  private handleContentSideEffects;
1358
1569
  }
1359
1570
 
1571
+ interface ContextRelevanceConfig {
1572
+ recentMessageWindow?: number;
1573
+ minScore?: number;
1574
+ freshnessHalfLifeDays?: number;
1575
+ }
1360
1576
  interface ContextRankingInput {
1361
1577
  entries: Context[];
1362
1578
  recentMessages: string[];
@@ -1434,9 +1650,9 @@ declare class PromptBuilder {
1434
1650
  * This class helps construct a Turn object by adding various content blocks.
1435
1651
  */
1436
1652
  declare class TurnBuilder {
1437
- private readonly _owner;
1653
+ private readonly _actor;
1438
1654
  private _turn;
1439
- constructor(_owner: TurnRole, initialTurn?: Turn);
1655
+ constructor(_actor: TurnActor, initialTurn?: Turn);
1440
1656
  addText(text: string): TurnBuilder;
1441
1657
  addImage(ref?: BlobRef, altText?: string): TurnBuilder;
1442
1658
  addDocument(ref?: BlobRef, title?: string): TurnBuilder;
@@ -1455,8 +1671,8 @@ declare class TurnBuilder {
1455
1671
  addTaskProposal(title: string, steps: {
1456
1672
  text: string;
1457
1673
  status?: 'todo' | 'done';
1458
- id?: UUID;
1459
- }[], action?: 'create' | 'update' | 'complete', taskId?: UUID): TurnBuilder;
1674
+ ref?: string;
1675
+ }[], action?: 'create' | 'update' | 'complete', id?: string): TurnBuilder;
1460
1676
  addBlock(block: ContentBlock): TurnBuilder;
1461
1677
  deleteBlock(blockId: UUID): TurnBuilder;
1462
1678
  editTextBlock(blockId: UUID, newText: string): TurnBuilder;
@@ -1468,51 +1684,245 @@ declare class TurnBuilder {
1468
1684
  build(): Turn;
1469
1685
  }
1470
1686
 
1687
+ declare class DefaultTurnProcessor implements TurnProcessor {
1688
+ private readonly handlers;
1689
+ process(turn: Turn, sessionId?: UUID): Command[];
1690
+ }
1691
+
1471
1692
  declare class Session {
1472
1693
  private readonly sessionId;
1473
1694
  private readonly tree;
1474
1695
  private readonly manager;
1475
1696
  constructor(sessionId: UUID, tree: TurnTree, manager: WorkspaceManager);
1697
+ /** Returns the UUID of this session. */
1698
+ id(): UUID;
1699
+ /**
1700
+ * Retrieves the full metadata record for this session from the workspace index.
1701
+ */
1702
+ meta(workspace: Workspace): SessionMeta | undefined;
1703
+ /** Returns the human-readable label for the session. */
1704
+ label(workspace: Workspace): string | undefined;
1705
+ /** Returns the name of the role currently assigned to this session. */
1706
+ private roleName;
1707
+ /**
1708
+ * Returns the RoleSummary (label, description, etc.) for the session's active role.
1709
+ */
1710
+ role(workspace: Workspace): RoleSummary | undefined;
1711
+ /** Returns the list of topics associated with this session. */
1712
+ topics(workspace: Workspace): string[];
1713
+ /** Returns the list of preference IDs overriding defaults for this session. */
1714
+ preferences(workspace: Workspace): UUID[];
1715
+ /**
1716
+ * Returns the current "head" pointer (turnId and version) of the conversation DAG.
1717
+ */
1718
+ head(workspace: Workspace): TurnRef | null;
1719
+ /**
1720
+ * Returns the full Task object if the session is currently linked to a task.
1721
+ */
1722
+ task(workspace: Workspace): Promise<Task | undefined>;
1723
+ /**
1724
+ * Returns the TaskSummary if the session is currently linked to a task.
1725
+ */
1726
+ taskSummary(workspace: Workspace): TaskSummary | undefined;
1727
+ /**
1728
+ * Checks whether the session is linked to any task.
1729
+ */
1730
+ hasTask(workspace: Workspace): boolean;
1731
+ /**
1732
+ * Builds the active conversation chain (the current linear history) as an array
1733
+ * of TurnNode objects, following the head pointer and parent links.
1734
+ */
1476
1735
  turns(): Promise<TurnNode[]>;
1736
+ /**
1737
+ * Returns all sibling turns of the given turn (other turns that share the same parent).
1738
+ */
1477
1739
  siblings(turnId: UUID): Promise<TurnNode[]>;
1740
+ /**
1741
+ * Returns version‑branching information for a given turn, including available versions,
1742
+ * current index, and navigation capabilities.
1743
+ */
1478
1744
  branchInfo(turnId: UUID): Promise<BranchInfo>;
1479
- id(): string;
1480
1745
  /**
1481
- * Creates a new fluent TurnBuilder for constructing a Turn object.
1482
- * @param owner The role of the owner of the turn (e.g., 'user', 'assistant', 'tool').
1483
- * @returns A new TurnBuilder instance.
1746
+ * Retrieves a single turn node by its ID from the session graph.
1484
1747
  */
1485
- startTurn(owner: TurnRole): TurnBuilder;
1748
+ getTurn(turnId: UUID): Promise<TurnNode | undefined>;
1486
1749
  /**
1487
- * Saves a constructed Turn object to the session. This method handles setting the session ID
1488
- * and automatically determines the parent turn if not explicitly provided in the Turn object.
1489
- * @param workspace The current workspace state.
1490
- * @param turn The Turn object to save. It can be constructed using the TurnBuilder.
1491
- * @param parentRef Optional TurnRef to explicitly set the parent of the turn. If not provided,
1492
- * the current head of the active chain will be used as the parent.
1493
- * @returns A promise resolving to a Result containing a DeepPartial<Workspace> on success,
1494
- * or a WorkspaceError on failure.
1750
+ * Changes the session's display label.
1751
+ * @param workspace Current workspace state.
1752
+ * @param newLabel New human‑readable label.
1753
+ * @returns A patch to merge into the workspace state.
1495
1754
  */
1496
- addTurn(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1755
+ rename(workspace: Workspace, newLabel: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1756
+ /**
1757
+ * Replaces the session's topic list entirely.
1758
+ * @param workspace Current workspace state.
1759
+ * @param topics New array of topics (overwrites existing).
1760
+ * @returns A patch to merge into the workspace state.
1761
+ */
1762
+ setTopics(workspace: Workspace, topics: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1763
+ /**
1764
+ * Adds topics to the session (union, no duplicates).
1765
+ * @param workspace Current workspace state.
1766
+ * @param topics Topics to add.
1767
+ * @returns A patch to merge into the workspace state.
1768
+ */
1769
+ addTopics(workspace: Workspace, topics: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1770
+ /**
1771
+ * Replaces the session's preference override list entirely.
1772
+ * @param workspace Current workspace state.
1773
+ * @param preferenceIds New array of preference IDs.
1774
+ * @returns A patch to merge into the workspace state.
1775
+ */
1776
+ setPreferences(workspace: Workspace, preferenceIds: UUID[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1777
+ /**
1778
+ * Links the session to a task, or removes the link if taskId is null.
1779
+ * @param workspace Current workspace state.
1780
+ * @param taskId ID of the task to link, or null to unlink.
1781
+ * @returns A patch to merge into the workspace state.
1782
+ */
1783
+ setActiveTask(workspace: Workspace, taskId: UUID | null): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1784
+ /**
1785
+ * Removes the link between the session and its current task (if any).
1786
+ * @param workspace Current workspace state.
1787
+ * @returns A patch to merge into the workspace state.
1788
+ */
1789
+ unsetTask(workspace: Workspace): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1790
+ /**
1791
+ * Creates a new session as a fork (copy) of this one.
1792
+ * @param workspace Current workspace state.
1793
+ * @param newSessionId Unique ID for the new session.
1794
+ * @param label Display label for the new session.
1795
+ * @param role Optional role override (defaults to current role).
1796
+ * @param topics Optional topic override (defaults to current topics).
1797
+ * @returns A patch to merge into the workspace state.
1798
+ */
1799
+ fork(workspace: Workspace, newSessionId: UUID, label: string, role?: string, topics?: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1800
+ /**
1801
+ * Permanently deletes this session and all its turns from the workspace.
1802
+ * @param workspace Current workspace state.
1803
+ * @returns A patch to merge into the workspace state.
1804
+ */
1805
+ delete(workspace: Workspace): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1806
+ dispatch(workspace: Workspace, command: Command): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1807
+ /**
1808
+ * Switches the session to a different role.
1809
+ * @param workspace Current workspace state.
1810
+ * @param newRole Name of the target role (must exist in the workspace).
1811
+ * @returns A patch to merge into the workspace state.
1812
+ */
1813
+ switchRole(workspace: Workspace, newRole: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1814
+ /**
1815
+ * Returns all available roles in the workspace.
1816
+ */
1817
+ listRoles(workspace: Workspace): RoleSummary[];
1818
+ /**
1819
+ * Returns a specific role by name, or undefined if not found.
1820
+ */
1821
+ getRole(workspace: Workspace, name: string): RoleSummary | undefined;
1497
1822
  /**
1498
- * Updates an existing turn in the session using a fully constructed Turn object.
1499
- * This method will dispatch a 'turn:edit' command.
1500
- * @param workspace The current workspace state.
1501
- * @param updatedTurn The Turn object containing the updated blocks and other properties.
1502
- * @returns A promise resolving to a Result containing a DeepPartial<Workspace> on success,
1503
- * or a WorkspaceError on failure.
1823
+ * Creates a new role.
1824
+ * @param workspace Current workspace state.
1825
+ * @param name Unique identifier for the role (e.g., "software-architect").
1826
+ * @param label Human-readable display label.
1827
+ * @param persona The system prompt / instructions for this role.
1828
+ * @param description Optional description.
1829
+ * @param preferenceIds Optional array of preference IDs to associate.
1830
+ * @returns A patch to merge into the workspace state.
1831
+ */
1832
+ createRole(workspace: Workspace, name: string, label: string, persona: string, description?: string, preferenceIds?: UUID[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1833
+ /**
1834
+ * Updates an existing role.
1835
+ * @param workspace Current workspace state.
1836
+ * @param name Name of the role to update (must exist).
1837
+ * @param updates Partial updates (label, description, persona, preferences).
1838
+ * @returns A patch to merge into the workspace state.
1839
+ */
1840
+ updateRole(workspace: Workspace, name: string, updates: Partial<Pick<Role, 'label' | 'description' | 'persona' | 'preferences'>>): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1841
+ /**
1842
+ * Deletes a role. Fails if the role is still referenced by any session.
1843
+ * @param workspace Current workspace state.
1844
+ * @param name Name of the role to delete.
1845
+ * @returns A patch to merge into the workspace state.
1846
+ */
1847
+ deleteRole(workspace: Workspace, name: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1848
+ /**
1849
+ * Saves a constructed Turn object to the session. The turn's parent is automatically
1850
+ * set to the current head of the active chain unless overridden in the turn object.
1851
+ * @param workspace Current workspace state.
1852
+ * @param turn The Turn object (can be built with startTurn()).
1853
+ * @returns A patch to merge into the workspace state.
1854
+ */
1855
+ addTurn(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1856
+ recordUserTurn(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1857
+ recordAssistantTurn(workspace: Workspace, turn: Turn, recordDenial?: boolean): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1858
+ private buildDenialTurn;
1859
+ private describeCommand;
1860
+ /**
1861
+ * Creates a new version of an existing turn with updated content.
1862
+ * @param workspace Current workspace state.
1863
+ * @param turnId ID of the turn to edit.
1864
+ * @param newBlocks New content blocks for the turn.
1865
+ * @param roleSnapshot Optional role name to record with this version.
1866
+ * @returns A patch to merge into the workspace state.
1504
1867
  */
1505
1868
  editTurn(workspace: Workspace, turnId: UUID, newBlocks: ContentBlock[], roleSnapshot?: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1869
+ /**
1870
+ * Creates a new branch from a specific turn (the parent must be set on the turn).
1871
+ * @param workspace Current workspace state.
1872
+ * @param turn The new turn that continues from an existing parent.
1873
+ * @returns A patch to merge into the workspace state.
1874
+ */
1506
1875
  branch(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1876
+ /**
1877
+ * Deletes a specific version of a turn and all its descendants.
1878
+ * @param workspace Current workspace state.
1879
+ * @param turnId ID of the turn to delete.
1880
+ * @param version Version number of the turn to delete.
1881
+ * @param newHead Optional new head pointer after deletion.
1882
+ * @returns A patch to merge into the workspace state.
1883
+ */
1507
1884
  deleteTurn(workspace: Workspace, turnId: UUID, version: number, newHead: TurnRef | null): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1885
+ /**
1886
+ * Switch to the previous version of a turn (if available).
1887
+ * This changes the active chain head but does not create new data.
1888
+ * @param workspace Current workspace state.
1889
+ * @param turnId ID of the turn whose version to switch.
1890
+ * @returns A patch to merge into the workspace state.
1891
+ */
1508
1892
  switchVersionLeft(workspace: Workspace, turnId: UUID): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1893
+ /**
1894
+ * Switch to the next version of a turn (if available).
1895
+ * This changes the active chain head but does not create new data.
1896
+ * @param workspace Current workspace state.
1897
+ * @param turnId ID of the turn whose version to switch.
1898
+ * @returns A patch to merge into the workspace state.
1899
+ */
1509
1900
  switchVersionRight(workspace: Workspace, turnId: UUID): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1510
1901
  private switchVersion;
1902
+ addPreference(workspace: Workspace, content: string, topics: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1903
+ listPreferences(workspace: Workspace): Promise<PreferenceSummary[]>;
1904
+ addContext(workspace: Workspace, key: string, content: ContextContent, topics: string[], metadata?: Record<string, any>): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1905
+ listContextSummaries(workspace: Workspace): Promise<ContextSummary[]>;
1906
+ /**
1907
+ * Registers a new blob in the workspace and returns its SHA256 and BlobRef.
1908
+ * This dispatches a blob:register command and extracts the resulting SHA256
1909
+ * from the returned workspace patch.
1910
+ */
1911
+ registerBlob(workspace: Workspace, data: Uint8Array, mediaType: BlobMediaType, filename?: string): Promise<Result<{
1912
+ sha256: SHA256;
1913
+ ref: BlobRef;
1914
+ }, WorkspaceError>>;
1915
+ /**
1916
+ * Resolves the session into an EffectiveSession object, which bundles the
1917
+ * session metadata, role, preferences, context, transcript, and linked task.
1918
+ * @param workspace Current workspace state.
1919
+ * @returns The resolved effective session or an error.
1920
+ */
1511
1921
  resolve(workspace: Workspace): Promise<Result<EffectiveSession, WorkspaceError>>;
1922
+ private findSubtreeTip;
1512
1923
  }
1513
1924
 
1514
1925
  interface SessionManagerConfig {
1515
- flush?: Partial<FlushConfig>;
1516
1926
  }
1517
1927
  interface OpenResult {
1518
1928
  session: Session;
@@ -1522,6 +1932,26 @@ declare class SessionManager {
1522
1932
  private readonly workspaceManager;
1523
1933
  private readonly contentStore;
1524
1934
  constructor(workspaceManager: WorkspaceManager, contentStore: ContentStore);
1935
+ /**
1936
+ * Returns an array of all session metadata entries in the workspace.
1937
+ */
1938
+ list(workspace: Workspace): SessionMeta[];
1939
+ /**
1940
+ * Retrieves the metadata for a specific session without hydrating a Session object.
1941
+ */
1942
+ meta(workspace: Workspace, sessionId: UUID): SessionMeta | undefined;
1943
+ /**
1944
+ * Creates a new session and returns a hydrated Session instance.
1945
+ * This method dispatches a 'session:create' command which is validated by the
1946
+ * reducer (checking for unique IDs and valid roles) and persisted
1947
+ * to the content store.
1948
+ */
1949
+ create(workspace: Workspace, params: {
1950
+ label: string;
1951
+ role?: string;
1952
+ topics?: string[];
1953
+ preferences?: UUID[];
1954
+ }): Promise<Result<OpenResult, WorkspaceError>>;
1525
1955
  open(workspace: Workspace, sessionId: UUID): Promise<Result<OpenResult, WorkspaceError>>;
1526
1956
  get workspace(): WorkspaceManager;
1527
1957
  close(_: Session): Promise<void>;
@@ -1594,4 +2024,37 @@ declare class IndexedDBBlobStorage implements BlobStorage {
1594
2024
  registerBlob(record: BlobRecord, data: Uint8Array): Promise<void>;
1595
2025
  }
1596
2026
 
1597
- export { type AddContext, type AddPreference, type AddRole, type AddSessionTopics, type AddTask, type AddTurn, type AuthRequest, type BackendError, type BaseCommand, type BlobCommand, type BlobError, type BlobMediaType, type BlobRecord, type BlobRef, type BlobStorage, BlobStore, type BlobStoreConfig, type BranchInfo, type BranchTurn, COLLECTIONS, type CacheConfig, type CallTool, type CollectionName, type Command, type ContentBlock, ContentStore, type ContentStoreConfig, type Context, type ContextContent, type ContextRelevanceConfig, type ContextSummary, type CreateSession, type CreateWorkspace, type DeleteContext, type DeletePreference, type DeleteRole, type DeleteSession, type DeleteTask, type DeleteTurn, type DocumentBlock, type DocumentMediaType, type DuplicateKeyError, type EditTurn, type EffectiveSession, type FlushConfig, type ForkSession, type ImageBlock, type ImageMediaType, type Index, type IndexedDBBlobConfig, IndexedDBBlobStorage, type InvalidCommandError, MemoryBlobStorage, type NotFoundError, type OpenResult, type OverrideSessionPreferences, type Preference, type PreferenceConflict, type PreferenceSummary, type Project, type Prompt, PromptBuilder, type PurgeBlob, type RecordBlobRemoteId, type RegisterBlob, type ReleaseBlob, type ResolvedBlob, type Result, type RetainBlob, type Role, type RoleSummary, type RoleTransitionBlock, type SHA256, type SaveTurn, Session, SessionManager, type SessionManagerConfig, type SessionMeta, type Settings, type SummaryBlock, type SwitchRole, type Task, type TaskProposalBlock, type TaskStatus, type TaskStep, type TaskSummary, type TextBlock, type ThinkingBlock, type Timestamp, type TokenBudget, type ToolCall, type ToolResultBlock, type ToolSummary, type ToolUseBlock, type TopicIndex, type TranscriptWindow, type Turn, type TurnNode, type TurnRef, type TurnRole, TurnTree, type URI, type UUID, type UpdateContext, type UpdatePreference, type UpdateRole, type UpdateTask, type Workspace, type WorkspaceBundle, type WorkspaceDatabase, type WorkspaceError, type WorkspaceEvents, WorkspaceManager, computeSHA256, createProjectWorkspace, createSimpleWorkspace, createWorkspaceDatabase, del, err, extractBlobRecord, extractBlobRef, merge, ok, omitNullUndefined, workspaceReducer };
2027
+ declare class GoogleGenAIAdapter implements LLMAdapter<{
2028
+ model: string;
2029
+ }, GenerateContentParameters, GenerateContentResponse> {
2030
+ private _;
2031
+ constructor(_: GoogleGenAI);
2032
+ /**
2033
+ * Converts a Prompt into a GenerateContentRequest for @google/genai.
2034
+ */
2035
+ prepare({ prompt, model }: {
2036
+ prompt: Prompt;
2037
+ model: string;
2038
+ }): Promise<{
2039
+ request: {
2040
+ model: string;
2041
+ contents: _google_genai.Content[];
2042
+ config: {
2043
+ systemInstruction: _google_genai.Content;
2044
+ thinkingConfig: {
2045
+ includeThoughts: boolean;
2046
+ };
2047
+ responseMimeType: string;
2048
+ responseSchema: _google_genai.Schema;
2049
+ };
2050
+ };
2051
+ }>;
2052
+ /**
2053
+ * Parses the GenerateContentResponse into a Turn (assistant turn).
2054
+ */
2055
+ parse({ response }: {
2056
+ response: GenerateContentResponse;
2057
+ }): Result<Turn, WorkspaceError>;
2058
+ }
2059
+
2060
+ export { type AddContext, type AddPreference, type AddRole, type AddSessionTopics, type AddTask, type AddTurn, type AuthRequest, type BackendError, type BaseCommand, type BlobCommand, type BlobError, type BlobMediaType, type BlobRecord, type BlobRef, type BlobStorage, BlobStore, type BlobStoreConfig, type BranchInfo, type BranchTurn, COLLECTIONS, type CallTool, type CollectionName, type Command, type ContentBlock, ContentStore, type Context, type ContextContent, type ContextSummary, type CreateSession, type CreateWorkspace, DefaultTurnProcessor, type DeleteContext, type DeletePreference, type DeleteRole, type DeleteSession, type DeleteTask, type DeleteTurn, type DocumentBlock, type DocumentMediaType, type DuplicateKeyError, EMPTY_SYSTEM_ROLE, type EditTurn, type EffectiveSession, type ForkSession, GoogleGenAIAdapter, type ImageBlock, type ImageMediaType, type Index, type IndexedDBBlobConfig, IndexedDBBlobStorage, type InvalidCommandError, type LLMAdapter, MemoryBlobStorage, type NotFoundError, type OpenResult, type OverrideSessionPreferences, type PermissionDeniedError, type PermissionGuard, type Preference, type PreferenceConflict, type PreferenceSummary, type Project, type Prompt, PromptBuilder, type PurgeBlob, type RecordBlobRemoteId, type RegisterBlob, type ReleaseBlob, type ResolvedBlob, type Result, type RetainBlob, type Role, type RoleSummary, type RoleTransitionBlock, type SHA256, type SaveTurn, Session, SessionManager, type SessionManagerConfig, type SessionMeta, type Settings, type Summarizer, type SummaryBlock, type SwitchRole, type Task, type TaskProposalBlock, type TaskRef, type TaskStatus, type TaskStep, type TaskSummary, type TextBlock, type ThinkingBlock, type Timestamp, type TokenBudget, type ToolCall, type ToolRegistry, type ToolResultBlock, type ToolSummary, type ToolUseBlock, type TopicIndex, type Turn, type TurnActor, TurnBuilder, type TurnNode, type TurnProcessor, type TurnRef, TurnTree, type URI, type UUID, type UpdateContext, type UpdatePreference, type UpdateRole, type UpdateSession, type UpdateTask, type Workspace, type WorkspaceBundle, type WorkspaceDatabase, type WorkspaceError, type WorkspaceEvents, WorkspaceManager, bufferToBase64, computeSHA256, createEmptyRole, createProjectWorkspace, createSimpleWorkspace, createWorkspaceDatabase, del, error, extractBlobRecord, extractBlobRef, generateTaskRef, generateTaskStepRef, merge, omitNullUndefined, shortHash, success };