@sorbetai/context 0.0.0-stage → 0.1.0-alpha.17

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.
package/dist/index.js ADDED
@@ -0,0 +1,1277 @@
1
+ import * as s from "@earendil-works/pi-schema";
2
+ import { JsonValueSchema, check, decode } from "@sorbetai/schema";
3
+ import { isEqual, partition } from "es-toolkit";
4
+
5
+ //#region src/model-input/xml/serializer.ts
6
+ function escapeText(text) {
7
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
8
+ }
9
+ function openingTag(name, attributes = {}) {
10
+ let tag = `<${name}`;
11
+ for (const [key, value] of Object.entries(attributes)) {
12
+ const escaped = escapeText(String(value)).replace(/"/g, "&quot;").replace(/\t/g, "&#x9;").replace(/\n/g, "&#xA;").replace(/\r/g, "&#xD;");
13
+ tag += ` ${key}="${escaped}"`;
14
+ }
15
+ return tag;
16
+ }
17
+ function serializeXmlElement(name, attributes, text) {
18
+ const tag = openingTag(name, attributes);
19
+ return text === void 0 || text.length === 0 ? `${tag}/>` : `${tag}>${escapeText(text)}</${name}>`;
20
+ }
21
+ /** Element and attribute names come from trusted typed producers, not raw XML input. */
22
+ function serializeContextXmlElement(root, indent = "") {
23
+ if (root.kind === "text") return indent + serializeXmlElement(root.name, root.attributes ?? {}, root.text);
24
+ const tag = indent + openingTag(root.name, root.attributes);
25
+ if (root.children.length === 0) return `${tag}/>`;
26
+ return `${tag}>\n${root.children.map((child) => serializeContextXmlElement(child, `${indent} `)).join("\n")}\n${indent}</${root.name}>`;
27
+ }
28
+
29
+ //#endregion
30
+ //#region src/model-input/renderer.ts
31
+ function renderPrefix(sources, inheritedSources = []) {
32
+ if (inheritedSources.length === 0 && sources.length === 0) return "";
33
+ let xml = "<sorbet-system-context>\n";
34
+ for (const source of inheritedSources) xml += ` ${renderPrefixSource(source)}\n`;
35
+ for (const source of sources) xml += ` ${renderPrefixSource(source)}\n`;
36
+ return `${xml}</sorbet-system-context>`;
37
+ }
38
+ function renderPrefixSource(source) {
39
+ switch (source.kind) {
40
+ case "instructions": return source.channel === "system" ? serializeXmlElement("system-instructions", {}, source.content) : serializeXmlElement("instructions", { channel: source.channel }, source.content);
41
+ case "extension": return serializeXmlElement("extension-section", {
42
+ type: source.extensionKind,
43
+ name: source.name
44
+ }, source.content);
45
+ case "workspace": return serializeXmlElement("workspace", {}, source.root);
46
+ }
47
+ }
48
+ /**
49
+ * One named-state frame carries the state's own element. Later frames with the same name
50
+ * supersede earlier ones, so neither a revision nor a base reference reaches the model.
51
+ */
52
+ function renderNamedState(element) {
53
+ return {
54
+ role: "user",
55
+ content: serializeContextXmlElement(element)
56
+ };
57
+ }
58
+ /** A state that no longer exists is explicit rather than silent. */
59
+ function renderNamedStateRemoval(stateName) {
60
+ return {
61
+ role: "user",
62
+ content: serializeXmlElement(stateName, { removed: "true" })
63
+ };
64
+ }
65
+ function renderTurnMaterial(source) {
66
+ switch (source.kind) {
67
+ case "instructions": return {
68
+ role: "user",
69
+ content: serializeXmlElement("instructions", { channel: source.channel }, source.content)
70
+ };
71
+ case "extension": return {
72
+ role: "user",
73
+ content: serializeXmlElement("extension-section", {
74
+ type: source.extensionKind,
75
+ name: source.name
76
+ }, source.content)
77
+ };
78
+ case "document": return {
79
+ role: "user",
80
+ content: serializeXmlElement("document", {
81
+ name: source.name,
82
+ mediaType: source.mediaType
83
+ }, source.content)
84
+ };
85
+ case "event": return {
86
+ role: "user",
87
+ content: serializeContextXmlElement(source.event)
88
+ };
89
+ }
90
+ }
91
+ /** Request authors contribute user text, never assistant or Tool-result authority. */
92
+ function renderRequestMaterial(source) {
93
+ return {
94
+ role: "user",
95
+ content: source.content
96
+ };
97
+ }
98
+
99
+ //#endregion
100
+ //#region src/model-input/contracts.ts
101
+ const ModelContextMessageSchema = s.obj({
102
+ role: s.lit("user"),
103
+ content: s.str()
104
+ }, { open: false });
105
+ const ModelInputSchema = s.obj({
106
+ systemPrompt: s.str(),
107
+ stateMessages: s.arr(ModelContextMessageSchema),
108
+ turnMessages: s.arr(ModelContextMessageSchema),
109
+ requestMessages: s.opt(s.arr(ModelContextMessageSchema))
110
+ }, { open: false });
111
+ /** Serializable dispatch settings, pinned with a physical request and reused after interruption. */
112
+ const ModelRequestSettingsSchema = s.obj({
113
+ temperature: s.opt(s.num()),
114
+ maxOutputTokens: s.opt(s.int({ minimum: 1 })),
115
+ thinkingLevel: s.opt(s.union([
116
+ s.lit("off"),
117
+ s.lit("minimal"),
118
+ s.lit("low"),
119
+ s.lit("medium"),
120
+ s.lit("high"),
121
+ s.lit("xhigh"),
122
+ s.lit("max")
123
+ ]))
124
+ }, { open: false });
125
+
126
+ //#endregion
127
+ //#region src/history.ts
128
+ const ContextMessageReferenceProperties = {
129
+ runId: s.str({ minLength: 1 }),
130
+ messageId: s.str({ minLength: 1 })
131
+ };
132
+ const ContextMessageReferenceSchema = s.obj(ContextMessageReferenceProperties, { open: false });
133
+
134
+ //#endregion
135
+ //#region src/xml.ts
136
+ /** Valid XML element and attribute name for state, event and extension vocabulary. */
137
+ const NamedStateNameSchema = s.str({
138
+ minLength: 1,
139
+ pattern: "^(?![Xx][Mm][Ll])[A-Za-z_][A-Za-z0-9_.-]*$"
140
+ });
141
+ const ElementReference = { $ref: "urn:sorbet:context-xml-element" };
142
+ const ContextXmlElementSchema = {
143
+ $id: "urn:sorbet:context-xml-element",
144
+ ...s.union([s.obj({
145
+ kind: s.lit("text"),
146
+ name: NamedStateNameSchema,
147
+ attributes: s.opt(s.map(s.union([s.str(), s.num()]))),
148
+ text: s.str()
149
+ }, { open: false }), s.obj({
150
+ kind: s.lit("container"),
151
+ name: NamedStateNameSchema,
152
+ attributes: s.opt(s.map(s.union([s.str(), s.num()]))),
153
+ children: s.arr(ElementReference)
154
+ }, { open: false })])
155
+ };
156
+
157
+ //#endregion
158
+ //#region src/state/contracts.ts
159
+ const NamedStateReadResultSchema = s.union([s.obj({
160
+ present: s.lit(true),
161
+ value: JsonValueSchema,
162
+ element: ContextXmlElementSchema
163
+ }, { open: false }), s.obj({ present: s.lit(false) }, { open: false })]);
164
+ /**
165
+ * Captures an owned JSON representation with `JSON.stringify` field semantics. Owner,
166
+ * Hook and Tool values cross this boundary before schema validation, so callers receive
167
+ * a copy instead of retaining author state.
168
+ */
169
+ function captureJsonValue(input) {
170
+ const encoded = JSON.stringify(input);
171
+ if (encoded === void 0) throw new TypeError("Value is not serializable as JSON");
172
+ return JSON.parse(encoded);
173
+ }
174
+
175
+ //#endregion
176
+ //#region src/model-view.ts
177
+ /** Experimental chronological history selection; the consumer retains the active execution. */
178
+ const ContextModelViewSchema = s.obj({
179
+ throughSequence: s.int({ minimum: 1 }),
180
+ history: s.arr(ContextMessageReferenceSchema, { uniqueItems: true }),
181
+ reclaimBefore: s.opt(ContextMessageReferenceSchema),
182
+ stateOrigins: s.opt(s.arr(s.obj({
183
+ stateName: NamedStateNameSchema,
184
+ revision: s.int({ minimum: 1 })
185
+ }, { open: false }), { uniqueItems: true }))
186
+ }, { open: false });
187
+
188
+ //#endregion
189
+ //#region src/tools/contracts.ts
190
+ const ToolDeclarationSchema = s.obj({
191
+ name: s.str({ minLength: 1 }),
192
+ description: s.str(),
193
+ parameters: s.map(JsonValueSchema)
194
+ }, { open: false });
195
+ const ToolStateSnapshotSchema = s.obj({
196
+ revision: s.int({ minimum: 1 }),
197
+ definitions: s.arr(ToolDeclarationSchema),
198
+ delivery: s.union([
199
+ s.obj({ kind: s.lit("unchanged") }, { open: false }),
200
+ s.obj({
201
+ kind: s.lit("restoration"),
202
+ afterMessageCount: s.lit(0)
203
+ }, { open: false }),
204
+ s.obj({
205
+ kind: s.lit("transition"),
206
+ afterMessageCount: s.int({ minimum: 0 }),
207
+ added: s.arr(s.str({ minLength: 1 }), { uniqueItems: true }),
208
+ removed: s.arr(s.str({ minLength: 1 }), { uniqueItems: true })
209
+ }, { open: false })
210
+ ])
211
+ }, { open: false });
212
+
213
+ //#endregion
214
+ //#region src/messages.ts
215
+ const NonEmptyString$2 = s.str({ minLength: 1 });
216
+ const TextContentSchema = s.obj({
217
+ type: s.lit("text"),
218
+ text: s.str(),
219
+ textSignature: s.opt(s.str())
220
+ }, { open: false });
221
+ const ImageContentSchema = s.obj({
222
+ type: s.lit("image"),
223
+ data: s.str(),
224
+ mimeType: NonEmptyString$2
225
+ }, { open: false });
226
+ const ThinkingContentSchema = s.obj({
227
+ type: s.lit("thinking"),
228
+ thinking: s.str(),
229
+ thinkingSignature: s.opt(s.str()),
230
+ redacted: s.opt(s.bool())
231
+ }, { open: false });
232
+ const ToolCallProperties = {
233
+ type: s.lit("toolCall"),
234
+ id: NonEmptyString$2,
235
+ name: NonEmptyString$2,
236
+ arguments: s.map(JsonValueSchema),
237
+ thoughtSignature: s.opt(s.str()),
238
+ argumentsError: s.opt(s.str())
239
+ };
240
+ const ToolCallSchema = s.obj(ToolCallProperties, { open: false });
241
+ const UsageSchema = s.obj({
242
+ input: s.num({ minimum: 0 }),
243
+ output: s.num({ minimum: 0 }),
244
+ cacheRead: s.num({ minimum: 0 }),
245
+ cacheWrite: s.num({ minimum: 0 }),
246
+ cacheWrite1h: s.opt(s.num({ minimum: 0 })),
247
+ reasoning: s.opt(s.num({ minimum: 0 })),
248
+ totalTokens: s.num({ minimum: 0 }),
249
+ cost: s.obj({
250
+ input: s.num({ minimum: 0 }),
251
+ output: s.num({ minimum: 0 }),
252
+ cacheRead: s.num({ minimum: 0 }),
253
+ cacheWrite: s.num({ minimum: 0 }),
254
+ total: s.num({ minimum: 0 }),
255
+ totalFromProvider: s.opt(s.bool())
256
+ }, { open: false })
257
+ }, { open: false });
258
+ const UserMessageProperties = {
259
+ role: s.lit("user"),
260
+ content: s.union([s.str(), s.arr(s.union([TextContentSchema, ImageContentSchema]))]),
261
+ timestamp: s.num()
262
+ };
263
+ const UserMessageSchema = s.obj(UserMessageProperties, { open: false });
264
+ const AssistantMessageSchema = s.obj({
265
+ role: s.lit("assistant"),
266
+ content: s.arr(s.union([
267
+ TextContentSchema,
268
+ ThinkingContentSchema,
269
+ ToolCallSchema
270
+ ])),
271
+ api: NonEmptyString$2,
272
+ provider: NonEmptyString$2,
273
+ model: NonEmptyString$2,
274
+ responseModel: s.opt(NonEmptyString$2),
275
+ responseId: s.opt(NonEmptyString$2),
276
+ diagnostics: s.opt(s.arr(s.obj({
277
+ type: NonEmptyString$2,
278
+ timestamp: s.num(),
279
+ error: s.opt(s.obj({
280
+ name: s.opt(s.str()),
281
+ message: s.str(),
282
+ stack: s.opt(s.str()),
283
+ code: s.opt(s.union([s.str(), s.num()]))
284
+ }, { open: false })),
285
+ details: s.opt(s.map(JsonValueSchema))
286
+ }, { open: false }))),
287
+ usage: UsageSchema,
288
+ stopReason: s.union([
289
+ s.lit("pending"),
290
+ s.lit("stop"),
291
+ s.lit("length"),
292
+ s.lit("toolUse"),
293
+ s.lit("error"),
294
+ s.lit("aborted"),
295
+ s.lit("deferred")
296
+ ]),
297
+ deferred: s.opt(s.obj({
298
+ provider: NonEmptyString$2,
299
+ modelId: NonEmptyString$2,
300
+ api: NonEmptyString$2,
301
+ id: NonEmptyString$2,
302
+ expiresAt: s.opt(s.num()),
303
+ pollAfterMs: s.opt(s.num()),
304
+ data: s.opt(JsonValueSchema)
305
+ }, { open: false })),
306
+ errorMessage: s.opt(s.str()),
307
+ rawStopReason: s.opt(s.str()),
308
+ thinkingLevel: s.opt(s.union([
309
+ "off",
310
+ "minimal",
311
+ "low",
312
+ "medium",
313
+ "high",
314
+ "xhigh",
315
+ "max"
316
+ ].map((value) => s.lit(value)))),
317
+ providerThinkingLevel: s.opt(s.str()),
318
+ endTurn: s.opt(s.bool()),
319
+ timestamp: s.num(),
320
+ durationMs: s.opt(s.num({ minimum: 0 }))
321
+ }, { open: false });
322
+ const ToolResultMessageSchema = s.obj({
323
+ role: s.lit("toolResult"),
324
+ toolCallId: NonEmptyString$2,
325
+ toolName: NonEmptyString$2,
326
+ content: s.arr(s.union([TextContentSchema, ImageContentSchema])),
327
+ details: s.opt(JsonValueSchema),
328
+ usage: s.opt(UsageSchema),
329
+ isError: s.bool(),
330
+ timestamp: s.num(),
331
+ durationMs: s.opt(s.num({ minimum: 0 }))
332
+ }, { open: false });
333
+ const SystemMessageSchema = s.obj({
334
+ role: s.lit("system"),
335
+ content: s.union([s.str(), s.arr(TextContentSchema)]),
336
+ sections: s.opt(s.map(s.union([s.str(), s.nul()]))),
337
+ toolsAdded: s.opt(s.arr(ToolDeclarationSchema)),
338
+ toolsRemoved: s.opt(s.arr(s.obj({ name: NonEmptyString$2 }, { open: false }))),
339
+ timestamp: s.num()
340
+ }, { open: false });
341
+ const MessageSchema = s.union([
342
+ SystemMessageSchema,
343
+ UserMessageSchema,
344
+ AssistantMessageSchema,
345
+ ToolResultMessageSchema
346
+ ]);
347
+ const ModelContextSchema = s.obj({
348
+ systemPrompt: s.opt(s.str()),
349
+ messages: s.arr(MessageSchema),
350
+ tools: s.opt(s.arr(ToolDeclarationSchema))
351
+ }, { open: true });
352
+
353
+ //#endregion
354
+ //#region src/source/contracts.ts
355
+ const NonEmptyString$1 = s.str({ minLength: 1 });
356
+ const ContextProvenanceSchema = s.obj({
357
+ origin: s.union([
358
+ s.lit("file"),
359
+ s.lit("runtime"),
360
+ s.lit("host"),
361
+ s.lit("journal")
362
+ ]),
363
+ label: NonEmptyString$1,
364
+ location: s.opt(NonEmptyString$1)
365
+ }, { open: false });
366
+ const ContextSourceIdentityProperties = {
367
+ sourceId: NonEmptyString$1,
368
+ provenance: ContextProvenanceSchema
369
+ };
370
+ /** Material proposed for one logical call; retention controls later model visibility, not storage. */
371
+ const RequestContextSourceSchema = s.obj({
372
+ ...ContextSourceIdentityProperties,
373
+ content: s.str(),
374
+ retention: s.union([s.lit("request"), s.lit("epoch")]),
375
+ placement: s.opt(s.lit("before-conversation")),
376
+ metadata: s.opt(JsonValueSchema)
377
+ }, { open: false });
378
+ const NonSystemInstructionChannelSchema = s.union([s.lit("developer"), s.lit("agents")]);
379
+ const SessionInstructionsContextSourceProperties = {
380
+ ...ContextSourceIdentityProperties,
381
+ kind: s.lit("instructions"),
382
+ channel: s.union([
383
+ s.lit("system"),
384
+ s.lit("developer"),
385
+ s.lit("agents")
386
+ ]),
387
+ content: s.str()
388
+ };
389
+ const TurnInstructionsContextSourceProperties = {
390
+ ...ContextSourceIdentityProperties,
391
+ kind: s.lit("instructions"),
392
+ channel: NonSystemInstructionChannelSchema,
393
+ content: s.str()
394
+ };
395
+ const SessionInstructionsContextSourceSchema = s.obj({
396
+ ...SessionInstructionsContextSourceProperties,
397
+ lifecycle: s.lit("session")
398
+ }, { open: false });
399
+ const TurnInstructionsContextSourceSchema = s.obj({
400
+ ...TurnInstructionsContextSourceProperties,
401
+ lifecycle: s.lit("turn")
402
+ }, { open: false });
403
+ const InstructionsContextSourceSchema = s.union([SessionInstructionsContextSourceSchema, TurnInstructionsContextSourceSchema]);
404
+ const ExtensionContextSourceProperties = {
405
+ ...ContextSourceIdentityProperties,
406
+ kind: s.lit("extension"),
407
+ extensionKind: s.union([
408
+ s.lit("skill"),
409
+ s.lit("plugin"),
410
+ s.lit("app"),
411
+ s.lit("extension"),
412
+ s.lit("memory")
413
+ ]),
414
+ name: NonEmptyString$1,
415
+ content: s.str()
416
+ };
417
+ const SessionExtensionContextSourceSchema = s.obj({
418
+ ...ExtensionContextSourceProperties,
419
+ lifecycle: s.lit("session")
420
+ }, { open: false });
421
+ const TurnExtensionContextSourceSchema = s.obj({
422
+ ...ExtensionContextSourceProperties,
423
+ lifecycle: s.lit("turn")
424
+ }, { open: false });
425
+ const ExtensionContextSourceSchema = s.union([SessionExtensionContextSourceSchema, TurnExtensionContextSourceSchema]);
426
+ /** Identifies the fixed root directory for a Session-bound Workspace. */
427
+ const WorkspaceContextSourceSchema = s.obj({
428
+ ...ContextSourceIdentityProperties,
429
+ lifecycle: s.lit("session"),
430
+ kind: s.lit("workspace"),
431
+ root: NonEmptyString$1
432
+ }, { open: false });
433
+ /** Documents are material for one admitted turn, never mutable named state or fixed prefix. */
434
+ const DocumentContextSourceSchema = s.obj({
435
+ ...ContextSourceIdentityProperties,
436
+ lifecycle: s.lit("turn"),
437
+ kind: s.lit("document"),
438
+ name: NonEmptyString$1,
439
+ mediaType: NonEmptyString$1,
440
+ content: s.str()
441
+ }, { open: false });
442
+ /** A one-shot structured event rendered as its exact XML tree for one turn. */
443
+ const EventContextSourceSchema = s.obj({
444
+ ...ContextSourceIdentityProperties,
445
+ lifecycle: s.lit("turn"),
446
+ kind: s.lit("event"),
447
+ event: ContextXmlElementSchema,
448
+ metadata: s.opt(JsonValueSchema)
449
+ }, { open: false });
450
+ const PrefixContextSourceSchema = s.union([
451
+ SessionInstructionsContextSourceSchema,
452
+ SessionExtensionContextSourceSchema,
453
+ WorkspaceContextSourceSchema
454
+ ]);
455
+ const TurnContextSourceSchema = s.union([
456
+ TurnInstructionsContextSourceSchema,
457
+ TurnExtensionContextSourceSchema,
458
+ DocumentContextSourceSchema,
459
+ EventContextSourceSchema
460
+ ]);
461
+ const ContextSourceSchema = s.union([PrefixContextSourceSchema, TurnContextSourceSchema]);
462
+ const ContextSourcesSchema = s.arr(ContextSourceSchema);
463
+
464
+ //#endregion
465
+ //#region src/snapshot/contracts.ts
466
+ const NonEmptyString = s.str({ minLength: 1 });
467
+ const ContextEpoch = s.int({ minimum: 0 });
468
+ const Revision = s.int({ minimum: 1 });
469
+ const ConversationBoundary = s.int({ minimum: 0 });
470
+ const CONTEXT_SNAPSHOT_SCHEMA_VERSION = 1;
471
+ const CONTEXT_ASSEMBLER_VERSION = "sorbet-context-assembler-v1";
472
+ const CONTEXT_RENDERER_VERSION = "sorbet-context-renderer-v4";
473
+ /** Snapshots retain the renderer that produced them; older layouts still reopen. */
474
+ const RENDERER_VERSIONS = [
475
+ "sorbet-context-renderer-v1",
476
+ "sorbet-context-renderer-v2",
477
+ "sorbet-context-renderer-v3",
478
+ CONTEXT_RENDERER_VERSION
479
+ ];
480
+ const ContextAssemblyEvidenceSchema = s.obj({
481
+ assemblerVersion: s.lit(CONTEXT_ASSEMBLER_VERSION),
482
+ rendererVersion: s.union(RENDERER_VERSIONS.map((version) => s.lit(version)))
483
+ }, { open: false });
484
+ const NamedStateDeliverySchema = s.union([
485
+ s.obj({
486
+ kind: s.lit("restoration"),
487
+ afterMessageCount: s.lit(0)
488
+ }, { open: false }),
489
+ s.obj({
490
+ kind: s.lit("transition"),
491
+ previousRevision: s.opt(Revision),
492
+ afterMessageCount: ConversationBoundary
493
+ }, { open: false }),
494
+ s.obj({ kind: s.lit("unchanged") }, { open: false })
495
+ ]);
496
+ const NamedStateIdentityProperties = {
497
+ stateName: NamedStateNameSchema,
498
+ itemKey: s.opt(NonEmptyString),
499
+ revision: Revision,
500
+ delivery: NamedStateDeliverySchema
501
+ };
502
+ const NamedStateSnapshotSchema = s.union([s.obj({
503
+ ...NamedStateIdentityProperties,
504
+ present: s.lit(true),
505
+ value: JsonValueSchema
506
+ }, { open: false }), s.obj({
507
+ ...NamedStateIdentityProperties,
508
+ present: s.lit(false)
509
+ }, { open: false })]);
510
+ const PrefixSnapshotSchema = s.obj({
511
+ revision: Revision,
512
+ inheritedSources: s.arr(PrefixContextSourceSchema),
513
+ sources: s.arr(PrefixContextSourceSchema),
514
+ systemPrompt: s.str()
515
+ }, { open: false });
516
+ const TurnMaterialSnapshotSchema = s.obj({
517
+ scopeId: NonEmptyString,
518
+ sources: s.arr(TurnContextSourceSchema),
519
+ delivery: s.union([s.obj({
520
+ kind: s.lit("append"),
521
+ afterMessageCount: ConversationBoundary
522
+ }, { open: false }), s.obj({ kind: s.lit("unchanged") }, { open: false })])
523
+ }, { open: false });
524
+ const RequestMaterialSnapshotSchema = s.obj({
525
+ modelView: s.opt(ContextModelViewSchema),
526
+ scopeId: NonEmptyString,
527
+ sources: s.arr(RequestContextSourceSchema),
528
+ afterMessageCount: ConversationBoundary,
529
+ replacementConversation: s.opt(s.arr(MessageSchema))
530
+ }, { open: false });
531
+ const CompileContextInputSchema = s.obj({
532
+ contextEpoch: ContextEpoch,
533
+ prefixRevision: Revision,
534
+ inheritedSources: s.arr(PrefixContextSourceSchema),
535
+ prefixSources: s.arr(PrefixContextSourceSchema),
536
+ namedStates: s.arr(NamedStateSnapshotSchema),
537
+ tools: s.opt(ToolStateSnapshotSchema),
538
+ turnMaterial: TurnMaterialSnapshotSchema,
539
+ requestMaterial: s.opt(RequestMaterialSnapshotSchema)
540
+ }, { open: false });
541
+ /** Exact Context-owner evidence captured for one logical model call. */
542
+ const ContextSnapshotSchema = s.obj({
543
+ schemaVersion: s.lit(CONTEXT_SNAPSHOT_SCHEMA_VERSION),
544
+ preparedAt: NonEmptyString,
545
+ contextEpoch: ContextEpoch,
546
+ prefix: PrefixSnapshotSchema,
547
+ namedStates: s.arr(NamedStateSnapshotSchema),
548
+ tools: s.opt(ToolStateSnapshotSchema),
549
+ turnMaterial: TurnMaterialSnapshotSchema,
550
+ requestMaterial: s.opt(RequestMaterialSnapshotSchema),
551
+ modelInput: ModelInputSchema,
552
+ evidence: ContextAssemblyEvidenceSchema
553
+ }, { open: false });
554
+
555
+ //#endregion
556
+ //#region src/compiler.ts
557
+ /** Turns typed owner values into immutable request evidence without assigning revisions. */
558
+ var ContextCompiler = class {
559
+ #now;
560
+ constructor(options = {}) {
561
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
562
+ }
563
+ compile(parsed, options = {}) {
564
+ const systemPrompt = options.previousPrefix?.revision === parsed.prefixRevision ? options.previousPrefix.systemPrompt : renderPrefix(parsed.prefixSources, parsed.inheritedSources);
565
+ const modelInput = {
566
+ systemPrompt,
567
+ stateMessages: parsed.namedStates.flatMap((state) => {
568
+ if (state.delivery.kind === "unchanged") return [];
569
+ if (!state.present) return [renderNamedStateRemoval(state.stateName)];
570
+ const element = options.elements?.get(state.stateName);
571
+ if (element === void 0) throw new TypeError(`State ${state.stateName} was not rendered by its owner`);
572
+ return [renderNamedState(element)];
573
+ }),
574
+ turnMessages: parsed.turnMaterial.delivery.kind === "append" ? parsed.turnMaterial.sources.map(renderTurnMaterial) : []
575
+ };
576
+ if (parsed.requestMaterial !== void 0) modelInput.requestMessages = parsed.requestMaterial.sources.map(renderRequestMaterial);
577
+ const snapshot = {
578
+ schemaVersion: CONTEXT_SNAPSHOT_SCHEMA_VERSION,
579
+ preparedAt: this.#now().toISOString(),
580
+ contextEpoch: parsed.contextEpoch,
581
+ prefix: {
582
+ revision: parsed.prefixRevision,
583
+ inheritedSources: parsed.inheritedSources,
584
+ sources: parsed.prefixSources,
585
+ systemPrompt
586
+ },
587
+ namedStates: parsed.namedStates,
588
+ turnMaterial: parsed.turnMaterial,
589
+ modelInput,
590
+ evidence: {
591
+ assemblerVersion: CONTEXT_ASSEMBLER_VERSION,
592
+ rendererVersion: CONTEXT_RENDERER_VERSION
593
+ }
594
+ };
595
+ if (parsed.requestMaterial !== void 0) snapshot.requestMaterial = parsed.requestMaterial;
596
+ if (parsed.tools !== void 0) snapshot.tools = parsed.tools;
597
+ return snapshot;
598
+ }
599
+ };
600
+
601
+ //#endregion
602
+ //#region src/preparation.ts
603
+ const ToolNamesSchema = s.arr(s.str({ minLength: 1 }), { uniqueItems: true });
604
+ const DraftSchema = s.obj({
605
+ sources: s.arr(ContextSourceSchema),
606
+ requestSources: s.arr(RequestContextSourceSchema),
607
+ modelView: s.opt(ContextModelViewSchema),
608
+ toolNames: s.opt(ToolNamesSchema),
609
+ states: s.arr(s.obj({
610
+ stateName: NamedStateNameSchema,
611
+ state: NamedStateReadResultSchema
612
+ }, { open: false })),
613
+ conversation: s.opt(s.arr(MessageSchema)),
614
+ replacementConversation: s.opt(s.arr(MessageSchema))
615
+ }, { open: false });
616
+ const ContextPreparationResultSchema = s.union([s.obj({
617
+ decision: s.lit("continue"),
618
+ draft: DraftSchema
619
+ }, { open: false }), s.obj({
620
+ decision: s.lit("reject"),
621
+ reason: s.str({ minLength: 1 })
622
+ }, { open: false })]);
623
+ var ContextPreparationRejectedError = class extends Error {
624
+ code = "context_preparation_rejected";
625
+ constructor(reason) {
626
+ super(`Context preparation rejected: ${reason}`);
627
+ this.reason = reason;
628
+ this.name = "ContextPreparationRejectedError";
629
+ }
630
+ };
631
+ /** Runs preparation only; callers retain ownership of owner-schema validation, revision and adoption. */
632
+ async function runContextPreparation(hooks, draft, scope) {
633
+ const capturedHooks = hooks.map((hook) => ({
634
+ hookId: hook.hookId,
635
+ around: hook.around.bind(hook)
636
+ }));
637
+ const ids = capturedHooks.map((hook) => hook.hookId);
638
+ if (ids.some((id) => id.length === 0) || new Set(ids).size !== ids.length) throw new TypeError("Context preparation Hook identities must be non-empty and unique");
639
+ const capturedScope = scope;
640
+ return dispatch(0, draft);
641
+ async function dispatch(index, input) {
642
+ capturedScope.signal?.throwIfAborted();
643
+ const hook = capturedHooks[index];
644
+ if (hook === void 0) return {
645
+ decision: "continue",
646
+ draft: input
647
+ };
648
+ const allowedToolNames = input.toolNames?.slice();
649
+ let open = true;
650
+ let called = false;
651
+ let downstream;
652
+ let downstreamToolNames;
653
+ const next = (nextDraft) => {
654
+ if (!open || called) {
655
+ const violation = /* @__PURE__ */ new Error(`Context Hook ${hook.hookId}: next is closed or already called`);
656
+ const rejected = Promise.reject(violation);
657
+ rejected.catch(() => void 0);
658
+ return rejected;
659
+ }
660
+ called = true;
661
+ downstream = (async () => dispatch(index + 1, narrowTools(nextDraft, allowedToolNames)))().then((result$1) => {
662
+ if (result$1.decision === "continue") downstreamToolNames = result$1.draft.toolNames?.slice();
663
+ return result$1;
664
+ });
665
+ downstream.catch(() => void 0);
666
+ return downstream;
667
+ };
668
+ let result;
669
+ const failures = [];
670
+ try {
671
+ result = await hook.around(input, capturedScope, next);
672
+ } catch (error) {
673
+ failures.push(error);
674
+ } finally {
675
+ open = false;
676
+ }
677
+ let downstreamResult;
678
+ try {
679
+ downstreamResult = await downstream;
680
+ } catch (error) {
681
+ if (!failures.includes(error)) failures.push(error);
682
+ }
683
+ capturedScope.signal?.throwIfAborted();
684
+ if (failures.length === 1) throw failures[0];
685
+ if (failures.length > 1) throw new AggregateError(failures, "Context preparation failed");
686
+ if (result === void 0) throw new Error("Context Hook returned no decision");
687
+ if (downstreamResult?.decision === "reject") return downstreamResult;
688
+ if (result.decision === "continue" && !called) throw new Error(`Context Hook ${hook.hookId}: continue requires next`);
689
+ return result.decision === "reject" ? result : {
690
+ decision: "continue",
691
+ draft: narrowTools(result.draft, downstreamResult?.decision === "continue" ? downstreamToolNames : allowedToolNames)
692
+ };
693
+ }
694
+ }
695
+ function narrowTools(draft, allowed) {
696
+ if (draft.toolNames === void 0) return {
697
+ ...draft,
698
+ toolNames: allowed?.slice()
699
+ };
700
+ const toolNames = decode(ToolNamesSchema, draft.toolNames);
701
+ if (allowed === void 0 || toolNames.some((name) => !allowed.includes(name))) throw new TypeError("Context preparation may only narrow captured Tool names");
702
+ return {
703
+ ...draft,
704
+ toolNames
705
+ };
706
+ }
707
+
708
+ //#endregion
709
+ //#region src/tools/reconciliation.ts
710
+ function captureToolDeclarations(tools) {
711
+ const declarations = decode(s.arr(ToolDeclarationSchema), captureJsonValue(tools.map(({ name, description, parameters }) => ({
712
+ name,
713
+ description,
714
+ parameters
715
+ }))));
716
+ const names = declarations.map((tool) => tool.name);
717
+ if (new Set(names).size !== names.length) throw new TypeError("Duplicate tool declaration name");
718
+ return declarations;
719
+ }
720
+ function reconcileTools(captured, previous, presented, afterMessageCount) {
721
+ const changed = !sameDeclarations(previous?.definitions ?? [], captured);
722
+ const revision = (previous?.revision ?? 0) + (previous === void 0 || changed ? 1 : 0);
723
+ if (!changed && previous !== void 0) return {
724
+ revision,
725
+ definitions: previous.definitions,
726
+ delivery: presented ? { kind: "unchanged" } : {
727
+ kind: "restoration",
728
+ afterMessageCount: 0
729
+ }
730
+ };
731
+ const current = new Map(captured.map((tool) => [tool.name, tool]));
732
+ const removed = [];
733
+ const definitions = [];
734
+ for (const tool of previous?.definitions ?? []) {
735
+ if (!isEqual(tool, current.get(tool.name))) {
736
+ removed.push(tool.name);
737
+ continue;
738
+ }
739
+ definitions.push(tool);
740
+ current.delete(tool.name);
741
+ }
742
+ const added = [...current.keys()];
743
+ definitions.push(...current.values());
744
+ return {
745
+ revision,
746
+ definitions,
747
+ delivery: presented ? {
748
+ kind: "transition",
749
+ afterMessageCount,
750
+ added,
751
+ removed
752
+ } : {
753
+ kind: "restoration",
754
+ afterMessageCount: 0
755
+ }
756
+ };
757
+ }
758
+ function sameDeclarations(previous, current) {
759
+ if (previous.length !== current.length) return false;
760
+ const byName = new Map(previous.map((tool) => [tool.name, tool]));
761
+ return current.every((tool) => isEqual(byName.get(tool.name), tool));
762
+ }
763
+ /** Replay retained evidence on restore, rather than walking history at every request. */
764
+ function toolsArePresented(frames, state) {
765
+ let retained;
766
+ for (const frame of frames) {
767
+ if (frame.kind !== "tools" || frame.tools === void 0) continue;
768
+ if (frame.tools.delivery.kind === "restoration" || retained !== void 0 && frame.tools.revision === retained.revision + 1) retained = frame.tools;
769
+ else retained = void 0;
770
+ }
771
+ return state !== void 0 && retained !== void 0 && retained.revision === state.revision && sameDeclarations(retained.definitions, state.definitions);
772
+ }
773
+
774
+ //#endregion
775
+ //#region src/manager.ts
776
+ /**
777
+ * Owns committed prefix and per-name state revisions. Preparation is pure;
778
+ * Runtime advances this owner only after the matching model.requested is durable.
779
+ */
780
+ var ContextManager = class {
781
+ #compiler;
782
+ #preparationHooks;
783
+ #contextEpoch = 0;
784
+ #prefix;
785
+ #states = /* @__PURE__ */ new Map();
786
+ #tools;
787
+ #toolsPresented = false;
788
+ #turnScopes = /* @__PURE__ */ new Set();
789
+ #requestScopes = /* @__PURE__ */ new Set();
790
+ #frames = /* @__PURE__ */ new Map();
791
+ #frameView;
792
+ #epochHasRequest = false;
793
+ constructor(options = {}) {
794
+ this.#compiler = options.compiler ?? new ContextCompiler();
795
+ this.#preparationHooks = (options.preparationHooks ?? []).map((hook) => ({
796
+ hookId: hook.hookId,
797
+ around: hook.around.bind(hook)
798
+ }));
799
+ const ids = this.#preparationHooks.map((hook) => hook.hookId);
800
+ if (ids.some((id) => id.length === 0) || new Set(ids).size !== ids.length) throw new TypeError("Context preparation Hook identities must be non-empty and unique");
801
+ }
802
+ async prepare(input) {
803
+ const hooks = [...this.#preparationHooks, ...input.preparationHooks ?? []].map((hook) => ({
804
+ hookId: hook.hookId,
805
+ around: hook.around.bind(hook)
806
+ }));
807
+ const ids = hooks.map((hook) => hook.hookId);
808
+ if (ids.some((id) => id.length === 0) || new Set(ids).size !== ids.length) throw new TypeError("Context preparation Hook identities must be non-empty and unique");
809
+ return this.#prepare({
810
+ ...input,
811
+ tools: input.tools === void 0 ? void 0 : captureToolDeclarations(input.tools)
812
+ }, readNamedStates(input.stateOwners, input.signal), input.stateOwners, hooks);
813
+ }
814
+ async #prepare(input, stateReadings, owners, hooks = []) {
815
+ const afterMessageCount = input.afterMessageCount ?? 0;
816
+ if (!Number.isInteger(afterMessageCount) || afterMessageCount < 0) throw new TypeError("Context conversation boundary must be a non-negative integer");
817
+ if (input.turnScopeId.length === 0) throw new TypeError("Context turn scope must not be empty");
818
+ if (input.requestScopeId !== void 0 && (input.requestScopeId.length === 0 || this.#requestScopes.has(input.requestScopeId))) throw new TypeError("Context request scope must be non-empty and not already committed");
819
+ const configuredSources = input.sources ?? [];
820
+ const inheritedSources = [...input.inheritedSources ?? []];
821
+ let requestSources = [...input.requestSources ?? []];
822
+ let modelView = input.modelView;
823
+ let replacementConversation;
824
+ let tools = input.tools;
825
+ const [contributions, initialReadings] = await Promise.all([readPrefixContributions(input.prefixContributors ?? [], input.signal), stateReadings]);
826
+ input.signal?.throwIfAborted();
827
+ if (input.historySelection !== void 0) {
828
+ const selected = await input.historySelection.select(input.historySelection.history, input.signal);
829
+ if (selected !== void 0) modelView = selected;
830
+ input.signal?.throwIfAborted();
831
+ }
832
+ const leadingContributions = contributions.filter((contribution) => contribution.placement === "before-configured-sources");
833
+ const trailingContributions = contributions.filter((contribution) => contribution.placement === void 0);
834
+ const leadingPrefixSources = leadingContributions.flatMap((contribution) => contribution.sources);
835
+ const trailingPrefixSources = trailingContributions.flatMap((contribution) => contribution.sources);
836
+ let resolvedSources = [
837
+ ...leadingPrefixSources,
838
+ ...configuredSources,
839
+ ...trailingPrefixSources
840
+ ];
841
+ let readings = initialReadings;
842
+ if (owners !== void 0 && hooks.length > 0) {
843
+ const result = await runContextPreparation(hooks, {
844
+ sources: resolvedSources,
845
+ states: readings,
846
+ requestSources,
847
+ modelView,
848
+ toolNames: tools?.map((tool) => tool.name),
849
+ ...input.conversation === void 0 ? {} : { conversation: [...input.conversation] }
850
+ }, {
851
+ turnScopeId: input.turnScopeId,
852
+ requestScopeId: input.requestScopeId,
853
+ signal: input.signal
854
+ });
855
+ if (result.decision === "reject") throw new ContextPreparationRejectedError(result.reason);
856
+ const prepared = result.draft;
857
+ resolvedSources = prepared.sources;
858
+ readings = prepared.states;
859
+ requestSources = prepared.requestSources;
860
+ modelView = prepared.modelView;
861
+ replacementConversation = prepared.replacementConversation;
862
+ if (prepared.toolNames !== void 0) tools = tools?.filter((tool) => prepared.toolNames?.includes(tool.name));
863
+ const schemas = new Map(owners.map((owner) => [owner.stateName, owner.schema]));
864
+ const names = /* @__PURE__ */ new Set();
865
+ for (const reading of prepared.states) {
866
+ const schema = schemas.get(reading.stateName);
867
+ if (schema === void 0 || names.has(reading.stateName)) throw new TypeError(`Context preparation returned undeclared or duplicate state ${reading.stateName}`);
868
+ names.add(reading.stateName);
869
+ if (reading.state.present) {
870
+ const value = captureJsonValue(reading.state.value);
871
+ decode(schema, value);
872
+ reading.state.value = value;
873
+ assertElementName(reading.stateName, reading.state.element);
874
+ }
875
+ }
876
+ }
877
+ assertUniqueSourceIds([...inheritedSources, ...resolvedSources]);
878
+ if (new Set(requestSources.map((source) => source.sourceId)).size !== requestSources.length) throw new TypeError("Duplicate request Context source identity");
879
+ if ((requestSources.length > 0 || modelView !== void 0) && input.requestScopeId === void 0) throw new TypeError("Request Context material requires a logical request scope");
880
+ const prefixSources = [];
881
+ const turnSources = [];
882
+ for (const source of resolvedSources) switch (source.lifecycle) {
883
+ case "session":
884
+ prefixSources.push(source);
885
+ break;
886
+ case "turn":
887
+ turnSources.push(source);
888
+ break;
889
+ }
890
+ const prefixChanged = this.#prefix === void 0 || !isEqual(this.#prefix.inheritedSources, inheritedSources) || !isEqual(this.#prefix.sources, prefixSources);
891
+ const prefixRevision = (this.#prefix?.revision ?? 0) + (prefixChanged ? 1 : 0);
892
+ const currentNames = new Set(readings.map((reading) => reading.stateName));
893
+ for (const stateName of this.#states.keys()) if (!currentNames.has(stateName)) readings.push({
894
+ stateName,
895
+ state: { present: false }
896
+ });
897
+ const namedStates = readings.flatMap((reading) => {
898
+ const previous = this.#states.get(reading.stateName);
899
+ if (previous === void 0 && !reading.state.present) return [];
900
+ const changed = previous === void 0 || previous.present !== reading.state.present || previous.present && reading.state.present && !isEqual(previous.value, reading.state.value);
901
+ const revision = previous === void 0 ? 1 : previous.revision + (changed ? 1 : 0);
902
+ const delivery = stateDelivery({
903
+ previous,
904
+ changed,
905
+ present: reading.state.present,
906
+ epochHasRequest: this.#epochHasRequest,
907
+ afterMessageCount
908
+ });
909
+ return [reading.state.present ? {
910
+ stateName: reading.stateName,
911
+ revision,
912
+ delivery,
913
+ present: true,
914
+ value: reading.state.value
915
+ } : {
916
+ stateName: reading.stateName,
917
+ revision,
918
+ delivery,
919
+ present: false
920
+ }];
921
+ });
922
+ const turnMaterial = {
923
+ scopeId: input.turnScopeId,
924
+ sources: turnSources,
925
+ delivery: !this.#turnScopes.has(input.turnScopeId) && turnSources.length > 0 ? {
926
+ kind: "append",
927
+ afterMessageCount
928
+ } : { kind: "unchanged" }
929
+ };
930
+ const compilation = {
931
+ contextEpoch: this.#contextEpoch,
932
+ prefixRevision,
933
+ inheritedSources,
934
+ prefixSources,
935
+ namedStates,
936
+ turnMaterial
937
+ };
938
+ if (tools !== void 0) compilation.tools = reconcileTools([...tools], this.#tools, this.#toolsPresented, afterMessageCount);
939
+ if (input.requestScopeId !== void 0) {
940
+ compilation.requestMaterial = {
941
+ scopeId: input.requestScopeId,
942
+ sources: requestSources,
943
+ afterMessageCount
944
+ };
945
+ if (modelView !== void 0) compilation.requestMaterial.modelView = modelView;
946
+ if (replacementConversation !== void 0) compilation.requestMaterial.replacementConversation = [...replacementConversation];
947
+ }
948
+ return this.#compiler.compile(compilation, {
949
+ previousPrefix: this.#prefix,
950
+ elements: new Map(readings.flatMap((reading) => reading.state.present ? [[reading.stateName, reading.state.element]] : []))
951
+ });
952
+ }
953
+ /** Adopt the prepared value after its request fact is durable. Calls are serialized by the owner. */
954
+ commit(snapshot) {
955
+ this.#prefix = snapshot.prefix;
956
+ this.#states.clear();
957
+ for (const state of snapshot.namedStates) this.#states.set(state.stateName, state);
958
+ if (snapshot.tools !== void 0) {
959
+ this.#tools = snapshot.tools;
960
+ this.#toolsPresented = true;
961
+ }
962
+ this.#turnScopes.add(snapshot.turnMaterial.scopeId);
963
+ if (snapshot.requestMaterial !== void 0) this.#requestScopes.add(snapshot.requestMaterial.scopeId);
964
+ for (const frame of framesFromSnapshot(snapshot)) if (adoptFrame(this.#frames, frame)) this.#frameView = void 0;
965
+ this.#epochHasRequest = true;
966
+ }
967
+ restore(snapshots, contextEpoch) {
968
+ this.#prefix = void 0;
969
+ this.#states.clear();
970
+ this.#tools = void 0;
971
+ this.#toolsPresented = false;
972
+ this.#turnScopes.clear();
973
+ this.#requestScopes.clear();
974
+ this.#frames.clear();
975
+ this.#frameView = void 0;
976
+ this.#epochHasRequest = false;
977
+ const latest = snapshots.at(-1);
978
+ this.#prefix = latest?.prefix;
979
+ for (const state of latest?.namedStates ?? []) this.#states.set(state.stateName, state);
980
+ for (const snapshot of snapshots) {
981
+ if (snapshot.tools !== void 0) this.#tools = snapshot.tools;
982
+ if (snapshot.requestMaterial !== void 0) this.#requestScopes.add(snapshot.requestMaterial.scopeId);
983
+ if (snapshot.contextEpoch === contextEpoch) {
984
+ this.#turnScopes.add(snapshot.turnMaterial.scopeId);
985
+ this.#epochHasRequest = true;
986
+ }
987
+ }
988
+ this.#contextEpoch = contextEpoch;
989
+ const replay = collectContextFrames(snapshots, contextEpoch);
990
+ this.#frames = replay.index;
991
+ this.#frameView = replay.frames;
992
+ this.#toolsPresented = toolsArePresented(replay.frames, this.#tools);
993
+ }
994
+ frames(pending) {
995
+ const additions = pending === void 0 ? [] : framesFromSnapshot(pending, true).filter((frame) => !this.#frames.has(frame.frameId));
996
+ if (additions.length === 0) return this.#frameView ??= [...this.#frames.values()];
997
+ const restoration = additions.find((frame) => frame.kind === "tools" && frame.tools.delivery.kind === "restoration");
998
+ if (restoration === void 0) return [...this.#frames.values(), ...additions];
999
+ return [
1000
+ restoration,
1001
+ ...[...this.#frames.values()].filter((frame) => frame.kind !== "tools"),
1002
+ ...additions.filter((frame) => frame !== restoration)
1003
+ ];
1004
+ }
1005
+ };
1006
+ /** Rebuilds retained frames, plus request-only material when its logical scope is selected. */
1007
+ function contextTransitionFrames(inputs, contextEpoch, requestScopeId) {
1008
+ return collectContextFrames(inputs, contextEpoch, requestScopeId).frames;
1009
+ }
1010
+ function collectContextFrames(inputs, contextEpoch, requestScopeId) {
1011
+ let frames = [];
1012
+ const index = /* @__PURE__ */ new Map();
1013
+ let reordered = false;
1014
+ for (const input of inputs) {
1015
+ const snapshot = input;
1016
+ if (snapshot.contextEpoch !== contextEpoch) continue;
1017
+ for (const frame of framesFromSnapshot(snapshot, requestScopeId !== void 0 && snapshot.requestMaterial?.scopeId === requestScopeId)) {
1018
+ if (index.has(frame.frameId)) continue;
1019
+ index.set(frame.frameId, frame);
1020
+ if (frame.kind === "tools" && frame.tools.delivery.kind === "restoration") {
1021
+ reordered ||= frames.length > 0;
1022
+ frames = [frame, ...frames.filter((retained) => retained.kind !== "tools")];
1023
+ } else frames.push(frame);
1024
+ }
1025
+ }
1026
+ if (reordered) {
1027
+ index.clear();
1028
+ for (const frame of frames) index.set(frame.frameId, frame);
1029
+ }
1030
+ return {
1031
+ frames,
1032
+ index
1033
+ };
1034
+ }
1035
+ function adoptFrame(frames, frame) {
1036
+ if (frames.has(frame.frameId)) return false;
1037
+ if (frame.kind === "tools" && frame.tools.delivery.kind === "restoration") {
1038
+ const retained = [...frames.values()].filter((entry) => entry.kind !== "tools");
1039
+ frames.clear();
1040
+ frames.set(frame.frameId, frame);
1041
+ for (const entry of retained) frames.set(entry.frameId, entry);
1042
+ } else frames.set(frame.frameId, frame);
1043
+ return true;
1044
+ }
1045
+ function stateDelivery(input) {
1046
+ if (!input.epochHasRequest) return input.present ? {
1047
+ kind: "restoration",
1048
+ afterMessageCount: 0
1049
+ } : { kind: "unchanged" };
1050
+ if (!input.changed) return { kind: "unchanged" };
1051
+ return {
1052
+ kind: "transition",
1053
+ ...input.previous === void 0 ? {} : { previousRevision: input.previous.revision },
1054
+ afterMessageCount: input.afterMessageCount
1055
+ };
1056
+ }
1057
+ function framesFromSnapshot(snapshot, includeRequestOnly = false) {
1058
+ const frames = [];
1059
+ if (snapshot.tools !== void 0 && snapshot.tools.delivery.kind !== "unchanged") frames.push({
1060
+ frameId: `tools:${snapshot.contextEpoch}:${snapshot.tools.revision}:${snapshot.tools.delivery.kind}`,
1061
+ kind: "tools",
1062
+ contextEpoch: snapshot.contextEpoch,
1063
+ afterMessageCount: snapshot.tools.delivery.afterMessageCount,
1064
+ preparedAt: snapshot.preparedAt,
1065
+ tools: snapshot.tools
1066
+ });
1067
+ let stateIndex = 0;
1068
+ for (const state of snapshot.namedStates) {
1069
+ if (state.delivery.kind === "unchanged") continue;
1070
+ const message = snapshot.modelInput.stateMessages[stateIndex++];
1071
+ if (message === void 0) throw new Error("Missing prepared state message");
1072
+ frames.push({
1073
+ frameId: `state:${snapshot.contextEpoch}:${state.stateName}:${state.revision}`,
1074
+ kind: "named-state",
1075
+ contextEpoch: snapshot.contextEpoch,
1076
+ afterMessageCount: state.delivery.afterMessageCount,
1077
+ preparedAt: snapshot.preparedAt,
1078
+ stateName: state.stateName,
1079
+ stateRevision: state.revision,
1080
+ message
1081
+ });
1082
+ }
1083
+ if (snapshot.turnMaterial.delivery.kind === "append") {
1084
+ const afterMessageCount = snapshot.turnMaterial.delivery.afterMessageCount;
1085
+ frames.push(...snapshot.modelInput.turnMessages.map((message, index) => ({
1086
+ frameId: `turn:${snapshot.contextEpoch}:${snapshot.turnMaterial.scopeId}:${index}`,
1087
+ kind: "turn-material",
1088
+ contextEpoch: snapshot.contextEpoch,
1089
+ afterMessageCount,
1090
+ preparedAt: snapshot.preparedAt,
1091
+ message
1092
+ })));
1093
+ }
1094
+ if (snapshot.requestMaterial !== void 0) {
1095
+ const material = snapshot.requestMaterial;
1096
+ for (const [index, source] of material.sources.entries()) {
1097
+ if (source.retention === "request" && !includeRequestOnly) continue;
1098
+ const message = snapshot.modelInput.requestMessages?.[index];
1099
+ if (message === void 0) throw new Error("Missing prepared request message");
1100
+ frames.push({
1101
+ frameId: `request:${snapshot.contextEpoch}:${material.scopeId}:${index}`,
1102
+ kind: "request-material",
1103
+ contextEpoch: snapshot.contextEpoch,
1104
+ afterMessageCount: source.placement === "before-conversation" ? 0 : material.afterMessageCount,
1105
+ placement: source.placement,
1106
+ preparedAt: snapshot.preparedAt,
1107
+ message
1108
+ });
1109
+ }
1110
+ }
1111
+ return frames;
1112
+ }
1113
+ function assertElementName(stateName, element) {
1114
+ if (element.name !== stateName) throw new TypeError(`State ${stateName} rendered <${element.name}> instead of its own name`);
1115
+ }
1116
+ async function readNamedStates(owners, signal) {
1117
+ const names = /* @__PURE__ */ new Set();
1118
+ for (const owner of owners) {
1119
+ if (!check(NamedStateNameSchema, owner.stateName)) throw new TypeError(`Invalid XML named state: ${owner.stateName}`);
1120
+ if (names.has(owner.stateName)) throw new TypeError(`Duplicate named state: ${owner.stateName}`);
1121
+ names.add(owner.stateName);
1122
+ }
1123
+ return Promise.all(owners.map(async (owner) => {
1124
+ const result = await stateReadForPreparation(owner, signal);
1125
+ if (!result.present) return {
1126
+ stateName: owner.stateName,
1127
+ state: { present: false }
1128
+ };
1129
+ const value = captureJsonValue(result.value);
1130
+ decode(owner.schema, value);
1131
+ assertElementName(owner.stateName, result.element);
1132
+ return {
1133
+ stateName: owner.stateName,
1134
+ state: {
1135
+ present: true,
1136
+ value,
1137
+ element: result.element
1138
+ }
1139
+ };
1140
+ }));
1141
+ }
1142
+ async function readPrefixContributions(contributors, signal) {
1143
+ const contributorIds = /* @__PURE__ */ new Set();
1144
+ for (const contributor of contributors) {
1145
+ if (contributor.contributorId.length === 0) throw new TypeError("Prefix Context contributorId must not be empty");
1146
+ if (contributorIds.has(contributor.contributorId)) throw new TypeError(`Duplicate Prefix Context contributor: ${contributor.contributorId}`);
1147
+ contributorIds.add(contributor.contributorId);
1148
+ }
1149
+ return await Promise.all(contributors.map(async (contributor) => {
1150
+ const sources = await prefixContributionForPreparation(contributor, signal);
1151
+ return {
1152
+ placement: contributor.placement,
1153
+ sources: structuredClone(sources)
1154
+ };
1155
+ }));
1156
+ }
1157
+ function prefixContributionForPreparation(contributor, signal) {
1158
+ signal?.throwIfAborted();
1159
+ const contribution = contributor.contribute({ signal });
1160
+ if (signal === void 0) return contribution;
1161
+ return new Promise((resolve, reject) => {
1162
+ const abort = () => reject(signal.reason);
1163
+ signal.addEventListener("abort", abort, { once: true });
1164
+ contribution.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
1165
+ });
1166
+ }
1167
+ function stateReadForPreparation(owner, signal) {
1168
+ signal?.throwIfAborted();
1169
+ const reading = owner.read({ signal });
1170
+ if (signal === void 0) return reading;
1171
+ return new Promise((resolve, reject) => {
1172
+ const abort = () => reject(signal.reason);
1173
+ signal.addEventListener("abort", abort, { once: true });
1174
+ reading.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
1175
+ });
1176
+ }
1177
+ function assertUniqueSourceIds(sources) {
1178
+ const sourceIds = /* @__PURE__ */ new Set();
1179
+ for (const source of sources) {
1180
+ if (sourceIds.has(source.sourceId)) throw new TypeError(`Duplicate context sourceId: ${source.sourceId}`);
1181
+ sourceIds.add(source.sourceId);
1182
+ }
1183
+ }
1184
+
1185
+ //#endregion
1186
+ //#region src/prefix-layout.ts
1187
+ /** Inspects v1's rendered prefix without rendering sources or interpreting their text again. */
1188
+ function inspectPrefixSourceLayout(prefix) {
1189
+ const sources = [...prefix.inheritedSources, ...prefix.sources];
1190
+ if (sources.length === 0 && prefix.systemPrompt.length === 0) return {
1191
+ quality: "measured",
1192
+ sources: []
1193
+ };
1194
+ const starts = [...prefix.systemPrompt.matchAll(/^ {2}<(?!\/)[a-z]/gmu)].map((match) => match.index);
1195
+ const rootEnd = prefix.systemPrompt.lastIndexOf("\n</sorbet-system-context>");
1196
+ if (starts.length !== sources.length || rootEnd < 0) return {
1197
+ quality: "unavailable",
1198
+ reason: "renderer_layout_mismatch"
1199
+ };
1200
+ const footprints = [];
1201
+ for (const [index, source] of sources.entries()) {
1202
+ const fromCharacter = starts[index];
1203
+ const throughCharacter = starts[index + 1] ?? rootEnd;
1204
+ if (fromCharacter === void 0 || throughCharacter < fromCharacter) return {
1205
+ quality: "unavailable",
1206
+ reason: "renderer_layout_mismatch"
1207
+ };
1208
+ footprints.push({
1209
+ sourceId: source.sourceId,
1210
+ kind: source.kind,
1211
+ provenance: source.provenance,
1212
+ inherited: index < prefix.inheritedSources.length,
1213
+ fromCharacter,
1214
+ throughCharacter
1215
+ });
1216
+ }
1217
+ return {
1218
+ quality: "measured",
1219
+ sources: footprints
1220
+ };
1221
+ }
1222
+
1223
+ //#endregion
1224
+ //#region src/transitions.ts
1225
+ /** Projects declared request placement and immutable conversation boundaries. */
1226
+ function projectContextTransitions(conversation, frames) {
1227
+ return projectContextTransitionValues(conversation, frames, (message) => structuredClone(message), contextFrameMessage);
1228
+ }
1229
+ function contextFrameMessage(frame) {
1230
+ const timestamp = Date.parse(frame.preparedAt);
1231
+ if (!Number.isFinite(timestamp)) throw new TypeError("Context transition frame has an invalid timestamp");
1232
+ if (frame.kind !== "tools") return {
1233
+ ...frame.message,
1234
+ timestamp
1235
+ };
1236
+ const { definitions, delivery } = frame.tools;
1237
+ const message = {
1238
+ role: "system",
1239
+ content: "",
1240
+ timestamp
1241
+ };
1242
+ if (delivery.kind === "restoration") message.toolsAdded = definitions;
1243
+ if (delivery.kind === "transition") {
1244
+ const added = new Set(delivery.added);
1245
+ if (added.size > 0) message.toolsAdded = definitions.filter((tool) => added.has(tool.name));
1246
+ if (delivery.removed.length > 0) message.toolsRemoved = delivery.removed.map((name) => ({ name }));
1247
+ }
1248
+ return message;
1249
+ }
1250
+ /** Applies Context frame boundaries to any conversation-aligned projection. */
1251
+ function projectContextTransitionValues(conversation, frames, conversationValue, frameValue) {
1252
+ const [leading, timeline] = partition(frames, (frame) => frame.kind === "request-material" && frame.placement === "before-conversation");
1253
+ let previousBoundary = 0;
1254
+ for (const frame of timeline) {
1255
+ if (frame.afterMessageCount < previousBoundary) throw new TypeError("Context transition boundaries must be monotonic");
1256
+ if (frame.afterMessageCount > conversation.length) throw new TypeError("Context transition boundary exceeds the conversation");
1257
+ previousBoundary = frame.afterMessageCount;
1258
+ }
1259
+ const projected = leading.map(frameValue);
1260
+ let boundary = 0;
1261
+ for (const frame of timeline) {
1262
+ while (boundary < frame.afterMessageCount) {
1263
+ const message = conversation[boundary++];
1264
+ if (message !== void 0) projected.push(conversationValue(message));
1265
+ }
1266
+ projected.push(frameValue(frame));
1267
+ }
1268
+ while (boundary < conversation.length) {
1269
+ const message = conversation[boundary++];
1270
+ if (message !== void 0) projected.push(conversationValue(message));
1271
+ }
1272
+ return projected;
1273
+ }
1274
+
1275
+ //#endregion
1276
+ export { AssistantMessageSchema, CONTEXT_ASSEMBLER_VERSION, CONTEXT_RENDERER_VERSION, CONTEXT_SNAPSHOT_SCHEMA_VERSION, CompileContextInputSchema, ContextAssemblyEvidenceSchema, ContextCompiler, ContextManager, ContextMessageReferenceProperties, ContextMessageReferenceSchema, ContextModelViewSchema, ContextPreparationRejectedError, ContextPreparationResultSchema, ContextProvenanceSchema, ContextSnapshotSchema, ContextSourceSchema, ContextSourcesSchema, ContextXmlElementSchema, DocumentContextSourceSchema, EventContextSourceSchema, ExtensionContextSourceSchema, ImageContentSchema, InstructionsContextSourceSchema, JsonValueSchema, MessageSchema, ModelContextMessageSchema, ModelContextSchema, ModelInputSchema, ModelRequestSettingsSchema, NamedStateDeliverySchema, NamedStateNameSchema, NamedStateReadResultSchema, NamedStateSnapshotSchema, PrefixContextSourceSchema, PrefixSnapshotSchema, RequestContextSourceSchema, RequestMaterialSnapshotSchema, SessionExtensionContextSourceSchema, SessionInstructionsContextSourceSchema, SystemMessageSchema, TextContentSchema, ThinkingContentSchema, ToolCallProperties, ToolCallSchema, ToolDeclarationSchema, ToolResultMessageSchema, ToolStateSnapshotSchema, TurnContextSourceSchema, TurnExtensionContextSourceSchema, TurnInstructionsContextSourceSchema, TurnMaterialSnapshotSchema, UsageSchema, UserMessageProperties, UserMessageSchema, WorkspaceContextSourceSchema, captureJsonValue, contextFrameMessage, contextTransitionFrames, inspectPrefixSourceLayout, projectContextTransitionValues, projectContextTransitions, runContextPreparation };
1277
+ //# sourceMappingURL=index.js.map