@asaidimu/utils-workspace 3.0.0 → 3.1.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 +566 -127
  3. package/index.d.ts +566 -127
  4. package/index.js +288 -1
  5. package/index.mjs +287 -1
  6. package/package.json +1 -1
package/index.d.ts 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,6 +163,7 @@ 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
168
  id: UUID;
116
169
  taskId?: UUID;
@@ -123,55 +176,63 @@ interface TaskProposalBlock {
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,19 +349,24 @@ 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
365
  id: UUID;
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;
297
372
  title: string;
@@ -307,7 +382,6 @@ interface RoleSummary {
307
382
  name: string;
308
383
  label: string;
309
384
  description?: string;
310
- /** Number of preference IDs listed on the role. */
311
385
  preferences: number;
312
386
  }
313
387
  interface PreferenceSummary {
@@ -336,6 +410,7 @@ interface TaskSummary {
336
410
  };
337
411
  topics: string[];
338
412
  }
413
+ /** Maps topics to the various entities that reference them. */
339
414
  interface TopicIndex {
340
415
  topic: string;
341
416
  contextKeys: string[];
@@ -347,6 +422,7 @@ interface TopicIndex {
347
422
  entries?: number;
348
423
  };
349
424
  }
425
+ /** The complete in-memory read-model of the Workspace state. */
350
426
  interface Index {
351
427
  roles: Record<string, RoleSummary>;
352
428
  preferences: Record<UUID, PreferenceSummary>;
@@ -357,12 +433,16 @@ interface Index {
357
433
  blobs: Record<SHA256, BlobRecord>;
358
434
  tools: Record<string, ToolSummary>;
359
435
  }
436
+ /** The root container for a user's workspace. */
360
437
  interface Workspace<ProjectMetadata extends Record<string, any> = Record<string, any>> {
361
438
  id: UUID;
362
439
  settings: Settings;
363
440
  project: Project<ProjectMetadata>;
364
441
  index: Index;
365
442
  }
443
+ /** * Format used for exporting/importing a complete workspace state,
444
+ * including all historical turns and binary records.
445
+ */
366
446
  interface WorkspaceBundle {
367
447
  format: 'aiworkspace/4.0';
368
448
  workspace: Workspace;
@@ -375,6 +455,7 @@ interface WorkspaceBundle {
375
455
  tasks: Record<UUID, Task>;
376
456
  blobs: Record<SHA256, BlobRecord>;
377
457
  }
458
+ /** A fully hydrated view of a session, including resolved objects for the prompt builder. */
378
459
  interface EffectiveSession {
379
460
  session: SessionMeta;
380
461
  role: Role;
@@ -384,24 +465,14 @@ interface EffectiveSession {
384
465
  task: Task | null;
385
466
  instructions?: string;
386
467
  }
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
468
  interface BaseCommand {
469
+ /** Discriminator for the command type. */
402
470
  type: string;
403
471
  timestamp: Timestamp;
472
+ /** The ID of the user or system component that initiated the command. */
404
473
  actor?: string;
474
+ description?: string;
475
+ synthetic?: boolean;
405
476
  }
406
477
  interface CreateWorkspace extends BaseCommand {
407
478
  type: 'workspace:create';
@@ -485,6 +556,7 @@ interface DeleteTask extends BaseCommand {
485
556
  id: UUID;
486
557
  };
487
558
  }
559
+ /** Updates an existing turn record in storage. */
488
560
  interface SaveTurn extends BaseCommand {
489
561
  type: 'turn:save';
490
562
  payload: {
@@ -492,6 +564,7 @@ interface SaveTurn extends BaseCommand {
492
564
  turn: Turn;
493
565
  };
494
566
  }
567
+ /** Appends a new turn to a session. */
495
568
  interface AddTurn extends BaseCommand {
496
569
  type: 'turn:add';
497
570
  payload: {
@@ -499,6 +572,7 @@ interface AddTurn extends BaseCommand {
499
572
  turn: Turn;
500
573
  };
501
574
  }
575
+ /** Creates a new version of an existing turn. */
502
576
  interface EditTurn extends BaseCommand {
503
577
  type: 'turn:edit';
504
578
  payload: {
@@ -509,6 +583,7 @@ interface EditTurn extends BaseCommand {
509
583
  roleSnapshot?: string;
510
584
  };
511
585
  }
586
+ /** Creates a new branch in the conversation history from a specific turn. */
512
587
  interface BranchTurn extends BaseCommand {
513
588
  type: 'turn:branch';
514
589
  payload: {
@@ -520,6 +595,7 @@ interface TurnRef {
520
595
  id: UUID;
521
596
  version: number;
522
597
  }
598
+ /** Removes a specific version of a turn and updates the session head if necessary. */
523
599
  interface DeleteTurn extends BaseCommand {
524
600
  type: 'turn:delete';
525
601
  payload: {
@@ -550,6 +626,7 @@ interface OverrideSessionPreferences extends BaseCommand {
550
626
  preferences: UUID[];
551
627
  };
552
628
  }
629
+ /** Creates a new session starting from the state of an existing one. */
553
630
  interface ForkSession extends BaseCommand {
554
631
  type: 'session:fork';
555
632
  payload: {
@@ -560,6 +637,17 @@ interface ForkSession extends BaseCommand {
560
637
  topics?: string[];
561
638
  };
562
639
  }
640
+ interface UpdateSession extends BaseCommand {
641
+ type: 'session:update';
642
+ payload: {
643
+ sessionId: UUID;
644
+ label?: string;
645
+ role?: string;
646
+ topics?: string[];
647
+ preferences?: UUID[];
648
+ task?: UUID | null;
649
+ };
650
+ }
563
651
  interface DeleteSession extends BaseCommand {
564
652
  type: 'session:delete';
565
653
  payload: {
@@ -574,30 +662,35 @@ interface RegisterBlob extends BaseCommand {
574
662
  filename?: string;
575
663
  };
576
664
  }
665
+ /** Increases reference count to prevent garbage collection. */
577
666
  interface RetainBlob extends BaseCommand {
578
667
  type: 'blob:retain';
579
668
  payload: {
580
669
  sha256: SHA256;
581
670
  };
582
671
  }
672
+ /** Decreases reference count. */
583
673
  interface ReleaseBlob extends BaseCommand {
584
674
  type: 'blob:release';
585
675
  payload: {
586
676
  sha256: SHA256;
587
677
  };
588
678
  }
679
+ /** Immediately removes a blob regardless of reference count. */
589
680
  interface PurgeBlob extends BaseCommand {
590
681
  type: 'blob:purge';
591
682
  payload: {
592
683
  sha256: SHA256;
593
684
  };
594
685
  }
686
+ /** Maps a local blob to an external provider's file ID. */
595
687
  interface RecordBlobRemoteId extends BaseCommand {
596
688
  type: 'blob:record_remote_id';
597
689
  payload: {
598
690
  sha256: SHA256;
599
691
  providerId: string;
600
692
  fileId: string;
693
+ timestamp?: Timestamp;
601
694
  };
602
695
  }
603
696
  type BlobCommand = RegisterBlob | RetainBlob | ReleaseBlob | PurgeBlob | RecordBlobRemoteId;
@@ -605,30 +698,27 @@ interface CallTool extends BaseCommand {
605
698
  type: 'tool:call';
606
699
  payload: ToolCall;
607
700
  }
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;
701
+ /** Union of all possible commands that can be dispatched to the Workspace Manager. */
702
+ 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;
703
+ /** Configuration for token counting and management during prompt generation. */
609
704
  interface TokenBudget {
610
705
  total: number;
611
706
  estimator?: (text: string) => number;
612
707
  blobTokensPerKB?: number;
613
708
  }
709
+ /** Details regarding why a specific preference was excluded from a prompt. */
614
710
  interface PreferenceConflict {
615
711
  topic: string;
616
712
  kept: UUID;
617
713
  dropped: UUID;
618
714
  reason: 'superseded_by_newer';
619
715
  }
620
- interface ContextRelevanceConfig {
621
- recentMessageWindow?: number;
622
- minScore?: number;
623
- freshnessHalfLifeDays?: number;
624
- }
625
716
  /**
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.
717
+ * The final structure sent to an LLM provider.
718
+ * Assembled by the PromptAssembler by resolving roles, context, and history.
630
719
  */
631
720
  interface Prompt {
721
+ /** Information destined for the System Message. */
632
722
  system: {
633
723
  instructions?: string;
634
724
  persona: string;
@@ -636,7 +726,9 @@ interface Prompt {
636
726
  context: Context[];
637
727
  task: Task | null;
638
728
  };
729
+ /** Additional context items injected separately. */
639
730
  context: Context[];
731
+ /** The conversation history. */
640
732
  transcript: {
641
733
  turns: Turn[];
642
734
  };
@@ -645,6 +737,7 @@ interface Prompt {
645
737
  used: number;
646
738
  breakdown: Record<string, number>;
647
739
  };
740
+ /** Statistics on what was removed to fit within the token limit. */
648
741
  truncated: {
649
742
  preferences: number;
650
743
  interactions: number;
@@ -653,20 +746,118 @@ interface Prompt {
653
746
  warnings: string[];
654
747
  conflicts: PreferenceConflict[];
655
748
  }
656
- interface TranscriptWindow {
657
- sessionId: UUID;
658
- turns: Turn[];
659
- flushedCount: number;
660
- hasMore: boolean;
661
- }
749
+ /** Typed events emitted by the Workspace when data changes. */
662
750
  interface WorkspaceEvents {
751
+ /** Emitted when the index or core settings change. */
663
752
  'workspace:changed': DeepPartial<Workspace>;
753
+ /** Emitted when a blob is registered, updated, or removed. */
664
754
  'blobs:changed': {
665
755
  sha256: SHA256;
666
756
  record: BlobRecord | null;
667
757
  };
668
758
  }
669
759
 
760
+ /**
761
+ * Handles transcript compression and history management.
762
+ * When a conversation exceeds the model's context window, the Summarizer
763
+ * condenses older turns into a single summary string to reclaim tokens.
764
+ */
765
+ interface Summarizer {
766
+ /**
767
+ * Compresses the provided transcript.
768
+ * * @param transcript - The current list of conversation turns.
769
+ * @param tokenBudget - The maximum allowed tokens for the history.
770
+ * @returns A promise resolving to the summary and the remaining uncompressed turns.
771
+ */
772
+ summarize(transcript: Turn[], tokenBudget: number): Promise<{
773
+ summary: string;
774
+ remaining: Turn[];
775
+ }>;
776
+ }
777
+ /**
778
+ * Analyzes model outputs for side effects and workspace actions.
779
+ * The TurnProcessor scans the assistant's response (Turn) for specific
780
+ * triggers, such as file edits, UI updates, or state changes.
781
+ */
782
+ interface TurnProcessor {
783
+ /**
784
+ * Scans a turn for actionable blocks and returns workspace commands.
785
+ * @param turn - The assistant turn to be processed.
786
+ * @param sessionId - The session in which the turn was generated.
787
+ * @returns An array of Commands to synchronize the Workspace state.
788
+ */
789
+ process(turn: Turn, sessionId?: UUID): Command[];
790
+ }
791
+ /**
792
+ * Manages the lifecycle and execution of external tools.
793
+ * Acts as a central hub for discovering available capabilities and
794
+ * routing tool calls to their respective executors.
795
+ */
796
+ interface ToolRegistry {
797
+ /**
798
+ * Subscribes to changes in the tool ecosystem.
799
+ * @param callback - Invoked whenever tools are added, removed, or updated.
800
+ */
801
+ onRegistryChanged(callback: (tools: ToolSummary[]) => void): void;
802
+ /**
803
+ * Retrieves a list of all currently registered and available tools.
804
+ * @returns An array of summaries describing tool capabilities and schemas.
805
+ */
806
+ list(): ToolSummary[];
807
+ /**
808
+ * Executes a tool call in a stateless manner.
809
+ * * @template T - The expected return type of the tool execution.
810
+ * @param call - The specific tool call requested by the model.
811
+ * @returns A promise resolving to a Result wrapper containing the tool output.
812
+ */
813
+ execute<T = any>(call: ToolCall): Promise<Result<T>>;
814
+ }
815
+ /**
816
+ * Enforces security and authorization policies.
817
+ * * The PermissionGuard ensures that the current execution context (User/Session)
818
+ * has the necessary privileges to perform a requested action or tool call.
819
+ */
820
+ interface PermissionGuard {
821
+ /**
822
+ * Validates if the current context has the right to execute the request.
823
+ * * @param request - The authentication payload and target action.
824
+ * @returns A Result containing the authorized payload or an error.
825
+ */
826
+ authenticate(request: AuthRequest): Promise<Result<AuthRequest["payload"] | null>>;
827
+ }
828
+ /**
829
+ * Bridge between the internal Workspace types and external LLM APIs.
830
+ * This generic adapter allows the system to remain vendor-agnostic by
831
+ * centralizing the translation logic for different providers (Google, OpenAI, etc.).
832
+ * @template TRequest - The specific request shape expected by the provider SDK.
833
+ * @template TRequestParams - Extra parameters for the request (e.g., model name, temperature).
834
+ * @template TResponse - The raw response shape returned by the provider SDK.
835
+ */
836
+ interface LLMAdapter<TRequest, TRequestParams, TResponse> {
837
+ /**
838
+ * Maps the internal `Prompt` to the vendor-specific request format.
839
+ * * @param params - The prompt and provider-specific configuration.
840
+ * @returns The formatted request object ready for the SDK.
841
+ */
842
+ /**
843
+ * Prepares the request and identifies necessary side-effects (like uploads).
844
+ */
845
+ prepare(params: {
846
+ prompt: Prompt;
847
+ } & TRequestParams): Promise<{
848
+ request: TRequest;
849
+ effects?: Command[];
850
+ }>;
851
+ /**
852
+ * Maps the vendor-specific response back to an internal `Turn`.
853
+ * * @param params - The raw response received from the model API.
854
+ * @returns A standardized Turn object for the workspace transcript.
855
+ */
856
+ parse(params: {
857
+ response: TResponse;
858
+ }): Turn;
859
+ }
860
+
670
861
  /**
671
862
  * Buffers write operations across one or more stores and commits them atomically.
672
863
  *
@@ -1112,13 +1303,22 @@ declare function createProjectWorkspace<ProjectMetadata extends Record<string, a
1112
1303
  language: string;
1113
1304
  project: Omit<Project<ProjectMetadata>, "id">;
1114
1305
  }): Workspace<ProjectMetadata>;
1115
- declare function createSimpleWorkspace({ name, owner, language }: {
1306
+ declare function createSimpleWorkspace({ name, actor, language }: {
1116
1307
  name: string;
1117
1308
  language: string;
1118
- owner: string;
1309
+ actor: string;
1119
1310
  }): Workspace;
1120
1311
  declare function extractBlobRecord(patch: DeepPartial<Workspace>): BlobRecord | null;
1121
1312
  declare function extractBlobRef(record: BlobRecord): BlobRef;
1313
+ declare function computeSHA256(data: Uint8Array): Promise<SHA256>;
1314
+ /**
1315
+ * Creates a skeleton Role object with empty defaults.
1316
+ */
1317
+ declare const createEmptyRole: (name: string, label: string) => Role;
1318
+ /**
1319
+ * Isomorphic Base64 converter (Node.js / browser).
1320
+ */
1321
+ declare function bufferToBase64(data: ArrayBuffer | Uint8Array | number[]): string;
1122
1322
 
1123
1323
  /**
1124
1324
  * Persistence contract for binary blob content and blob registry records.
@@ -1197,7 +1397,6 @@ declare class TurnTree {
1197
1397
  copyTranscript(sourceSessionId: UUID, targetSessionId: UUID): Promise<void>;
1198
1398
  }
1199
1399
 
1200
- declare function computeSHA256(data: Uint8Array): Promise<SHA256>;
1201
1400
  interface BlobStoreConfig {
1202
1401
  /**
1203
1402
  * When true, blobs with refCount === 0 are deleted from the backend
@@ -1232,6 +1431,10 @@ declare class BlobStore {
1232
1431
  release(sha256: SHA256): Promise<Result<void, WorkspaceError>>;
1233
1432
  recordRemoteId(sha256: SHA256, providerId: string, fileId: string): Promise<Result<void, WorkspaceError>>;
1234
1433
  getRemoteId(sha256: SHA256, providerId: string): string | null;
1434
+ getRemoteRecord(sha256: SHA256, providerId: string): {
1435
+ id: string;
1436
+ timestamp: Timestamp;
1437
+ } | null;
1235
1438
  resolveRef(ref: BlobRef, providerId: string | null): Promise<Result<ResolvedBlob, WorkspaceError>>;
1236
1439
  resolveRefs(refs: BlobRef[], providerId: string | null): Promise<{
1237
1440
  resolved: Map<SHA256, ResolvedBlob>;
@@ -1250,6 +1453,15 @@ declare class BlobStore {
1250
1453
  getAllRecords(): Record<SHA256, BlobRecord>;
1251
1454
  }
1252
1455
 
1456
+ interface CacheConfig {
1457
+ roles?: number;
1458
+ preferences?: number;
1459
+ context?: number;
1460
+ tasks?: number;
1461
+ }
1462
+ interface ContentStoreConfig {
1463
+ cache?: CacheConfig;
1464
+ }
1253
1465
  declare class ContentStore {
1254
1466
  private readonly db;
1255
1467
  readonly tree: TurnTree;
@@ -1299,64 +1511,41 @@ declare class ContentStore {
1299
1511
  gc(): Promise<number>;
1300
1512
  }
1301
1513
 
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
1514
  declare class WorkspaceManager {
1335
1515
  private readonly contentStore;
1336
1516
  private readonly permissionGuard?;
1337
1517
  private readonly toolRegistry?;
1518
+ private readonly processor;
1338
1519
  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
1520
  constructor(options: {
1344
1521
  contentStore: ContentStore;
1345
1522
  permissionGuard?: PermissionGuard;
1346
1523
  toolRegistry?: ToolRegistry;
1347
1524
  eventBus: EventBus<WorkspaceEvents>;
1525
+ turnProcessor?: TurnProcessor;
1348
1526
  });
1527
+ store(): ContentStore;
1528
+ turnProcessor(): TurnProcessor;
1349
1529
  /**
1350
1530
  * Initializes a Workspace's in-memory Index from environment-static
1351
1531
  * sources (like ToolRegistry). Call this when opening a Workspace.
1352
1532
  */
1353
- init(_: Workspace): DeepPartial<Workspace>;
1533
+ initTools(_: Workspace): DeepPartial<Workspace>;
1534
+ /**
1535
+ * Called after any workspace change
1536
+ */
1537
+ subscribe<TEventName extends keyof WorkspaceEvents>(event: TEventName, callback: (payload: WorkspaceEvents[TEventName]) => void): () => void;
1354
1538
  reduce(workspace: Workspace, command: Command): Result<DeepPartial<Workspace>, WorkspaceError>;
1355
1539
  dispatch(workspace: Workspace, command: Command): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1356
1540
  resolveSession(workspace: Workspace, sessionId: UUID, transcript?: Turn[]): Promise<Result<EffectiveSession, WorkspaceError>>;
1357
1541
  private handleContentSideEffects;
1358
1542
  }
1359
1543
 
1544
+ interface ContextRelevanceConfig {
1545
+ recentMessageWindow?: number;
1546
+ minScore?: number;
1547
+ freshnessHalfLifeDays?: number;
1548
+ }
1360
1549
  interface ContextRankingInput {
1361
1550
  entries: Context[];
1362
1551
  recentMessages: string[];
@@ -1434,9 +1623,9 @@ declare class PromptBuilder {
1434
1623
  * This class helps construct a Turn object by adding various content blocks.
1435
1624
  */
1436
1625
  declare class TurnBuilder {
1437
- private readonly _owner;
1626
+ private readonly _actor;
1438
1627
  private _turn;
1439
- constructor(_owner: TurnRole, initialTurn?: Turn);
1628
+ constructor(_actor: TurnActor, initialTurn?: Turn);
1440
1629
  addText(text: string): TurnBuilder;
1441
1630
  addImage(ref?: BlobRef, altText?: string): TurnBuilder;
1442
1631
  addDocument(ref?: BlobRef, title?: string): TurnBuilder;
@@ -1468,51 +1657,248 @@ declare class TurnBuilder {
1468
1657
  build(): Turn;
1469
1658
  }
1470
1659
 
1660
+ declare class DefaultTurnProcessor implements TurnProcessor {
1661
+ private readonly handlers;
1662
+ process(turn: Turn, sessionId?: UUID): Command[];
1663
+ }
1664
+
1471
1665
  declare class Session {
1472
1666
  private readonly sessionId;
1473
1667
  private readonly tree;
1474
1668
  private readonly manager;
1475
1669
  constructor(sessionId: UUID, tree: TurnTree, manager: WorkspaceManager);
1670
+ /** Returns the UUID of this session. */
1671
+ id(): UUID;
1672
+ /**
1673
+ * Retrieves the full metadata record for this session from the workspace index.
1674
+ */
1675
+ meta(workspace: Workspace): SessionMeta | undefined;
1676
+ /** Returns the human-readable label for the session. */
1677
+ label(workspace: Workspace): string | undefined;
1678
+ /** Returns the name of the role currently assigned to this session. */
1679
+ private roleName;
1680
+ /**
1681
+ * Returns the RoleSummary (label, description, etc.) for the session's active role.
1682
+ */
1683
+ role(workspace: Workspace): RoleSummary | undefined;
1684
+ /** Returns the list of topics associated with this session. */
1685
+ topics(workspace: Workspace): string[];
1686
+ /** Returns the list of preference IDs overriding defaults for this session. */
1687
+ preferences(workspace: Workspace): UUID[];
1688
+ /**
1689
+ * Returns the current "head" pointer (turnId and version) of the conversation DAG.
1690
+ */
1691
+ head(workspace: Workspace): TurnRef | null;
1692
+ /**
1693
+ * Returns the full Task object if the session is currently linked to a task.
1694
+ */
1695
+ task(workspace: Workspace): Promise<Task | undefined>;
1696
+ /**
1697
+ * Returns the TaskSummary if the session is currently linked to a task.
1698
+ */
1699
+ taskSummary(workspace: Workspace): TaskSummary | undefined;
1700
+ /**
1701
+ * Checks whether the session is linked to any task.
1702
+ */
1703
+ hasTask(workspace: Workspace): boolean;
1704
+ /**
1705
+ * Builds the active conversation chain (the current linear history) as an array
1706
+ * of TurnNode objects, following the head pointer and parent links.
1707
+ */
1476
1708
  turns(): Promise<TurnNode[]>;
1709
+ /**
1710
+ * Returns all sibling turns of the given turn (other turns that share the same parent).
1711
+ */
1477
1712
  siblings(turnId: UUID): Promise<TurnNode[]>;
1713
+ /**
1714
+ * Returns version‑branching information for a given turn, including available versions,
1715
+ * current index, and navigation capabilities.
1716
+ */
1478
1717
  branchInfo(turnId: UUID): Promise<BranchInfo>;
1479
- id(): string;
1480
1718
  /**
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.
1719
+ * Retrieves a single turn node by its ID from the session graph.
1484
1720
  */
1485
- startTurn(owner: TurnRole): TurnBuilder;
1721
+ getTurn(turnId: UUID): Promise<TurnNode | undefined>;
1486
1722
  /**
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.
1723
+ * Changes the session's display label.
1724
+ * @param workspace Current workspace state.
1725
+ * @param newLabel New human‑readable label.
1726
+ * @returns A patch to merge into the workspace state.
1495
1727
  */
1496
- addTurn(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1728
+ rename(workspace: Workspace, newLabel: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1729
+ /**
1730
+ * Replaces the session's topic list entirely.
1731
+ * @param workspace Current workspace state.
1732
+ * @param topics New array of topics (overwrites existing).
1733
+ * @returns A patch to merge into the workspace state.
1734
+ */
1735
+ setTopics(workspace: Workspace, topics: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1497
1736
  /**
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.
1737
+ * Adds topics to the session (union, no duplicates).
1738
+ * @param workspace Current workspace state.
1739
+ * @param topics Topics to add.
1740
+ * @returns A patch to merge into the workspace state.
1741
+ */
1742
+ addTopics(workspace: Workspace, topics: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1743
+ /**
1744
+ * Replaces the session's preference override list entirely.
1745
+ * @param workspace Current workspace state.
1746
+ * @param preferenceIds New array of preference IDs.
1747
+ * @returns A patch to merge into the workspace state.
1748
+ */
1749
+ setPreferences(workspace: Workspace, preferenceIds: UUID[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1750
+ /**
1751
+ * Links the session to a task, or removes the link if taskId is null.
1752
+ * @param workspace Current workspace state.
1753
+ * @param taskId ID of the task to link, or null to unlink.
1754
+ * @returns A patch to merge into the workspace state.
1755
+ */
1756
+ setActiveTask(workspace: Workspace, taskId: UUID | null): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1757
+ /**
1758
+ * Removes the link between the session and its current task (if any).
1759
+ * @param workspace Current workspace state.
1760
+ * @returns A patch to merge into the workspace state.
1761
+ */
1762
+ unsetTask(workspace: Workspace): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1763
+ createTask(workspace: Workspace, title: string, description: string | undefined, steps: {
1764
+ text: string;
1765
+ }[], topics: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1766
+ /**
1767
+ * Creates a new session as a fork (copy) of this one.
1768
+ * @param workspace Current workspace state.
1769
+ * @param newSessionId Unique ID for the new session.
1770
+ * @param label Display label for the new session.
1771
+ * @param role Optional role override (defaults to current role).
1772
+ * @param topics Optional topic override (defaults to current topics).
1773
+ * @returns A patch to merge into the workspace state.
1774
+ */
1775
+ fork(workspace: Workspace, newSessionId: UUID, label: string, role?: string, topics?: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1776
+ /**
1777
+ * Permanently deletes this session and all its turns from the workspace.
1778
+ * @param workspace Current workspace state.
1779
+ * @returns A patch to merge into the workspace state.
1780
+ */
1781
+ delete(workspace: Workspace): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1782
+ dispatch(workspace: Workspace, command: Command): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1783
+ /**
1784
+ * Switches the session to a different role.
1785
+ * @param workspace Current workspace state.
1786
+ * @param newRole Name of the target role (must exist in the workspace).
1787
+ * @returns A patch to merge into the workspace state.
1788
+ */
1789
+ switchRole(workspace: Workspace, newRole: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1790
+ /**
1791
+ * Returns all available roles in the workspace.
1792
+ */
1793
+ listRoles(workspace: Workspace): RoleSummary[];
1794
+ /**
1795
+ * Returns a specific role by name, or undefined if not found.
1796
+ */
1797
+ getRole(workspace: Workspace, name: string): RoleSummary | undefined;
1798
+ /**
1799
+ * Creates a new role.
1800
+ * @param workspace Current workspace state.
1801
+ * @param name Unique identifier for the role (e.g., "software-architect").
1802
+ * @param label Human-readable display label.
1803
+ * @param persona The system prompt / instructions for this role.
1804
+ * @param description Optional description.
1805
+ * @param preferenceIds Optional array of preference IDs to associate.
1806
+ * @returns A patch to merge into the workspace state.
1807
+ */
1808
+ createRole(workspace: Workspace, name: string, label: string, persona: string, description?: string, preferenceIds?: UUID[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1809
+ /**
1810
+ * Updates an existing role.
1811
+ * @param workspace Current workspace state.
1812
+ * @param name Name of the role to update (must exist).
1813
+ * @param updates Partial updates (label, description, persona, preferences).
1814
+ * @returns A patch to merge into the workspace state.
1815
+ */
1816
+ updateRole(workspace: Workspace, name: string, updates: Partial<Pick<Role, 'label' | 'description' | 'persona' | 'preferences'>>): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1817
+ /**
1818
+ * Deletes a role. Fails if the role is still referenced by any session.
1819
+ * @param workspace Current workspace state.
1820
+ * @param name Name of the role to delete.
1821
+ * @returns A patch to merge into the workspace state.
1822
+ */
1823
+ deleteRole(workspace: Workspace, name: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1824
+ /**
1825
+ * Saves a constructed Turn object to the session. The turn's parent is automatically
1826
+ * set to the current head of the active chain unless overridden in the turn object.
1827
+ * @param workspace Current workspace state.
1828
+ * @param turn The Turn object (can be built with startTurn()).
1829
+ * @returns A patch to merge into the workspace state.
1830
+ */
1831
+ addTurn(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1832
+ recordUserTurn(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1833
+ recordAssistantTurn(workspace: Workspace, turn: Turn, recordDenial?: boolean): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1834
+ private buildDenialTurn;
1835
+ private describeCommand;
1836
+ /**
1837
+ * Creates a new version of an existing turn with updated content.
1838
+ * @param workspace Current workspace state.
1839
+ * @param turnId ID of the turn to edit.
1840
+ * @param newBlocks New content blocks for the turn.
1841
+ * @param roleSnapshot Optional role name to record with this version.
1842
+ * @returns A patch to merge into the workspace state.
1504
1843
  */
1505
1844
  editTurn(workspace: Workspace, turnId: UUID, newBlocks: ContentBlock[], roleSnapshot?: string): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1845
+ /**
1846
+ * Creates a new branch from a specific turn (the parent must be set on the turn).
1847
+ * @param workspace Current workspace state.
1848
+ * @param turn The new turn that continues from an existing parent.
1849
+ * @returns A patch to merge into the workspace state.
1850
+ */
1506
1851
  branch(workspace: Workspace, turn: Turn): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1852
+ /**
1853
+ * Deletes a specific version of a turn and all its descendants.
1854
+ * @param workspace Current workspace state.
1855
+ * @param turnId ID of the turn to delete.
1856
+ * @param version Version number of the turn to delete.
1857
+ * @param newHead Optional new head pointer after deletion.
1858
+ * @returns A patch to merge into the workspace state.
1859
+ */
1507
1860
  deleteTurn(workspace: Workspace, turnId: UUID, version: number, newHead: TurnRef | null): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1861
+ /**
1862
+ * Switch to the previous version of a turn (if available).
1863
+ * This changes the active chain head but does not create new data.
1864
+ * @param workspace Current workspace state.
1865
+ * @param turnId ID of the turn whose version to switch.
1866
+ * @returns A patch to merge into the workspace state.
1867
+ */
1508
1868
  switchVersionLeft(workspace: Workspace, turnId: UUID): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1869
+ /**
1870
+ * Switch to the next version of a turn (if available).
1871
+ * This changes the active chain head but does not create new data.
1872
+ * @param workspace Current workspace state.
1873
+ * @param turnId ID of the turn whose version to switch.
1874
+ * @returns A patch to merge into the workspace state.
1875
+ */
1509
1876
  switchVersionRight(workspace: Workspace, turnId: UUID): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1510
1877
  private switchVersion;
1878
+ addPreference(workspace: Workspace, content: string, topics: string[]): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1879
+ listPreferences(workspace: Workspace): Promise<PreferenceSummary[]>;
1880
+ addContext(workspace: Workspace, key: string, content: ContextContent, topics: string[], metadata?: Record<string, any>): Promise<Result<DeepPartial<Workspace>, WorkspaceError>>;
1881
+ listContextSummaries(workspace: Workspace): Promise<ContextSummary[]>;
1882
+ /**
1883
+ * Registers a new blob in the workspace and returns its SHA256 and BlobRef.
1884
+ * This dispatches a blob:register command and extracts the resulting SHA256
1885
+ * from the returned workspace patch.
1886
+ */
1887
+ registerBlob(workspace: Workspace, data: Uint8Array, mediaType: BlobMediaType, filename?: string): Promise<Result<{
1888
+ sha256: SHA256;
1889
+ ref: BlobRef;
1890
+ }, WorkspaceError>>;
1891
+ /**
1892
+ * Resolves the session into an EffectiveSession object, which bundles the
1893
+ * session metadata, role, preferences, context, transcript, and linked task.
1894
+ * @param workspace Current workspace state.
1895
+ * @returns The resolved effective session or an error.
1896
+ */
1511
1897
  resolve(workspace: Workspace): Promise<Result<EffectiveSession, WorkspaceError>>;
1898
+ private findSubtreeTip;
1512
1899
  }
1513
1900
 
1514
1901
  interface SessionManagerConfig {
1515
- flush?: Partial<FlushConfig>;
1516
1902
  }
1517
1903
  interface OpenResult {
1518
1904
  session: Session;
@@ -1522,6 +1908,26 @@ declare class SessionManager {
1522
1908
  private readonly workspaceManager;
1523
1909
  private readonly contentStore;
1524
1910
  constructor(workspaceManager: WorkspaceManager, contentStore: ContentStore);
1911
+ /**
1912
+ * Returns an array of all session metadata entries in the workspace.
1913
+ */
1914
+ list(workspace: Workspace): SessionMeta[];
1915
+ /**
1916
+ * Retrieves the metadata for a specific session without hydrating a Session object.
1917
+ */
1918
+ meta(workspace: Workspace, sessionId: UUID): SessionMeta | undefined;
1919
+ /**
1920
+ * Creates a new session and returns a hydrated Session instance.
1921
+ * This method dispatches a 'session:create' command which is validated by the
1922
+ * reducer (checking for unique IDs and valid roles) and persisted
1923
+ * to the content store.
1924
+ */
1925
+ create(workspace: Workspace, params: {
1926
+ label: string;
1927
+ role?: string;
1928
+ topics?: string[];
1929
+ preferences?: UUID[];
1930
+ }): Promise<Result<OpenResult, WorkspaceError>>;
1525
1931
  open(workspace: Workspace, sessionId: UUID): Promise<Result<OpenResult, WorkspaceError>>;
1526
1932
  get workspace(): WorkspaceManager;
1527
1933
  close(_: Session): Promise<void>;
@@ -1594,4 +2000,37 @@ declare class IndexedDBBlobStorage implements BlobStorage {
1594
2000
  registerBlob(record: BlobRecord, data: Uint8Array): Promise<void>;
1595
2001
  }
1596
2002
 
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 };
2003
+ declare class GoogleGenAIAdapter implements LLMAdapter<{
2004
+ model: string;
2005
+ }, GenerateContentParameters, GenerateContentResponse> {
2006
+ private _;
2007
+ constructor(_: GoogleGenAI);
2008
+ /**
2009
+ * Converts a Prompt into a GenerateContentRequest for @google/genai.
2010
+ */
2011
+ prepare({ prompt, model }: {
2012
+ prompt: Prompt;
2013
+ model: string;
2014
+ }): Promise<{
2015
+ request: {
2016
+ model: string;
2017
+ contents: _google_genai.Content[];
2018
+ config: {
2019
+ systemInstruction: _google_genai.Content;
2020
+ thinkingConfig: {
2021
+ includeThoughts: boolean;
2022
+ };
2023
+ responseMimeType: string;
2024
+ responseSchema: _google_genai.Schema;
2025
+ };
2026
+ };
2027
+ }>;
2028
+ /**
2029
+ * Parses the GenerateContentResponse into a Turn (assistant turn).
2030
+ */
2031
+ parse({ response }: {
2032
+ response: GenerateContentResponse;
2033
+ }): Turn;
2034
+ }
2035
+
2036
+ 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 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, err, extractBlobRecord, extractBlobRef, merge, ok, omitNullUndefined };