@sorbetai/runtime 0.1.0-alpha.16 → 0.1.0-alpha.18

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.
@@ -1,2713 +0,0 @@
1
- import * as s from "@earendil-works/pi-schema";
2
- import { check, compile, decode, objectProperties } from "@sorbetai/schema";
3
- import { AssistantMessageSchema, ContextAssemblyEvidenceSchema, ContextSourcesSchema, ImageContentSchema, JsonValueSchema, MessageSchema, ModelContextMessageSchema, ModelContextSchema, ModelRequestSettingsSchema, NamedStateSnapshotSchema, PrefixContextSourceSchema, PrefixSnapshotSchema, RequestMaterialSnapshotSchema, TextContentSchema, ToolResultMessageSchema, ToolStateSnapshotSchema, TurnContextSourceSchema, TurnMaterialSnapshotSchema, UsageSchema, UserMessageSchema } from "@sorbetai/context";
4
- import { isEqual, isError, isFunction, isNumber, isPlainObject, isPromise, isString, omit, pick } from "es-toolkit";
5
- import { raceSignal } from "race-signal";
6
- import { ModelViewSchema, PluginInputSchema, PreparedToolHooksSchema, SessionBehaviorCommandSchema, SessionBehaviorViewSchema } from "@sorbetai/plugins/model";
7
- import { ArtifactRefSchema } from "@sorbetai/artifacts";
8
- import ensureError from "ensure-error";
9
- import { sortedIndexOf } from "es-toolkit/compat";
10
-
11
- //#region src/serialization.ts
12
- const Utf8Encoder = new TextEncoder();
13
- /**
14
- * The UTF-8 byte size of serialized text.
15
- *
16
- * Journal frames, Artifact thresholds, and inspection budgets are measured in
17
- * bytes, not characters. `Buffer.byteLength` answers that in Node but has no
18
- * browser equivalent, and the Runtime core runs in both, so the measurement
19
- * uses the encoding API both environments share.
20
- */
21
- function utf8ByteLength(text) {
22
- return Utf8Encoder.encode(text).byteLength;
23
- }
24
- /** Captures a JSON representation at the SDK boundary, using JSON.stringify field semantics. */
25
- function captureJsonValue(input) {
26
- const json = JSON.stringify(input);
27
- if (json === void 0) throw new TypeError("Value is not serializable as JSON");
28
- return decode(JsonValueSchema, JSON.parse(json));
29
- }
30
-
31
- //#endregion
32
- //#region src/approvals/contracts.ts
33
- const NonEmptyString$2 = s.str({ minLength: 1 });
34
- const ApprovalModeSchema = s.union([s.lit("human"), s.lit("auto")]);
35
- /**
36
- * `session` remembers the exact prepared action; `session-full-access` turns the whole
37
- * Session into full access: every later call is admitted without approval and without
38
- * the sandbox boundary until the grant is revoked.
39
- */
40
- const ApprovalRememberSchema = s.union([s.lit("session"), s.lit("session-full-access")]);
41
- const ApprovalReviewDecisionSchema = s.union([s.obj({
42
- outcome: s.lit("allowed-once"),
43
- remember: s.opt(ApprovalRememberSchema)
44
- }, { open: false }), s.obj({
45
- outcome: s.lit("rejected"),
46
- reason: NonEmptyString$2
47
- }, { open: false })]);
48
- const ApprovalRequestRecordSchema = s.obj({
49
- approvalRequestId: NonEmptyString$2,
50
- taskId: s.opt(NonEmptyString$2),
51
- toolCallId: NonEmptyString$2,
52
- parentToolCallId: s.opt(NonEmptyString$2),
53
- toolName: NonEmptyString$2,
54
- reason: NonEmptyString$2,
55
- parameters: JsonValueSchema
56
- }, { open: false });
57
- const ApprovalResolutionIdentity = {
58
- approvalRequestId: NonEmptyString$2,
59
- toolCallId: NonEmptyString$2
60
- };
61
- const ApprovalResolvedRecordSchema = s.union([
62
- s.obj({
63
- ...ApprovalResolutionIdentity,
64
- outcome: s.lit("allowed-once"),
65
- remember: s.opt(ApprovalRememberSchema)
66
- }, { open: false }),
67
- s.obj({
68
- ...ApprovalResolutionIdentity,
69
- outcome: s.lit("rejected"),
70
- reason: NonEmptyString$2
71
- }, { open: false }),
72
- s.obj({
73
- ...ApprovalResolutionIdentity,
74
- outcome: s.lit("cancelled"),
75
- reason: NonEmptyString$2
76
- }, { open: false }),
77
- s.obj({
78
- ...ApprovalResolutionIdentity,
79
- outcome: s.lit("unavailable"),
80
- message: NonEmptyString$2
81
- }, { open: false })
82
- ]);
83
-
84
- //#endregion
85
- //#region src/approvals/resolution.ts
86
- async function resolveApproval(request, boundary, signal) {
87
- const common = {
88
- approvalRequestId: request.approvalRequestId,
89
- toolCallId: request.toolCallId
90
- };
91
- if (signal?.aborted) return cancelled(common);
92
- if (boundary.kind === "unavailable") return {
93
- ...common,
94
- outcome: "unavailable",
95
- message: "Session has no Approval resolver"
96
- };
97
- try {
98
- const pending = boundary.resolve(structuredClone(request), signal);
99
- const decision = signal === void 0 ? await pending : await raceSignal(pending, signal);
100
- if (!check(ApprovalReviewDecisionSchema, decision)) throw new TypeError("Approval resolver returned an invalid decision");
101
- return decision.outcome === "allowed-once" ? {
102
- ...common,
103
- outcome: "allowed-once",
104
- remember: decision.remember
105
- } : {
106
- ...common,
107
- outcome: "rejected",
108
- reason: decision.reason
109
- };
110
- } catch (cause) {
111
- if (signal?.aborted) return cancelled(common);
112
- return {
113
- ...common,
114
- outcome: "unavailable",
115
- message: isError(cause) ? cause.message : String(cause)
116
- };
117
- }
118
- }
119
- function cancelled(common) {
120
- return {
121
- ...common,
122
- outcome: "cancelled",
123
- reason: "Approval review was cancelled"
124
- };
125
- }
126
-
127
- //#endregion
128
- //#region src/approvals/reviewer.ts
129
- const ApprovalReviewerDecisionSchema = s.obj({
130
- outcome: s.union([s.lit("allow"), s.lit("ask")]),
131
- reason: s.str({
132
- minLength: 1,
133
- maxLength: 1e3
134
- })
135
- }, { open: false });
136
-
137
- //#endregion
138
- //#region src/journal/message-routing.ts
139
- const Identity$4 = s.str({ minLength: 1 });
140
- const Address = s.obj({
141
- unitId: Identity$4,
142
- sessionId: Identity$4
143
- }, { open: false });
144
- /** Transport authenticates sourceUnitId independently; this envelope is durable routing evidence. */
145
- const MessageRoutingProperties = {
146
- messageId: Identity$4,
147
- sourceUnitId: Identity$4,
148
- targetUnitId: Identity$4,
149
- targetSessionId: Identity$4,
150
- replyTo: s.opt(Address),
151
- inReplyTo: s.opt(Identity$4)
152
- };
153
- const MessageRoutingSchema = s.obj(MessageRoutingProperties, { open: false });
154
- const ReceiptIdentity = s.obj(pick(objectProperties(MessageRoutingSchema), [
155
- "messageId",
156
- "sourceUnitId",
157
- "targetUnitId",
158
- "targetSessionId"
159
- ]), { open: false });
160
- const MessageReceiptSchema = s.obj({
161
- ...objectProperties(ReceiptIdentity),
162
- status: s.lit("accepted"),
163
- acceptanceId: Identity$4
164
- }, { open: false });
165
- const MessageRejectionSchema = s.obj({
166
- ...objectProperties(ReceiptIdentity),
167
- status: s.lit("rejected"),
168
- code: Identity$4,
169
- message: Identity$4
170
- }, { open: false });
171
- const MessageDeliveryResultSchema = s.union([
172
- MessageReceiptSchema,
173
- MessageRejectionSchema,
174
- s.obj({
175
- status: s.lit("unavailable"),
176
- code: Identity$4
177
- }, { open: false })
178
- ]);
179
-
180
- //#endregion
181
- //#region src/permissions/contracts.ts
182
- const NonEmptyString$1 = s.str({ minLength: 1 });
183
- /** A user's explicit Session grant, projected from the original approval facts. */
184
- const PermissionGrantSchema = s.obj({
185
- grantId: NonEmptyString$1,
186
- toolName: NonEmptyString$1,
187
- parameters: JsonValueSchema,
188
- sourceRunId: s.opt(NonEmptyString$1),
189
- sourceOperationId: s.opt(NonEmptyString$1),
190
- sourceToolCallId: NonEmptyString$1,
191
- grantedAt: NonEmptyString$1
192
- }, { open: false });
193
- /**
194
- * A Session-wide grant: the user turned the whole Session into full access from this decision
195
- * onward. It authorizes every Tool call without approval until it is revoked, not one action.
196
- */
197
- const SessionPermissionGrantSchema = s.obj({
198
- grantId: NonEmptyString$1,
199
- sourceRunId: s.opt(NonEmptyString$1),
200
- sourceOperationId: s.opt(NonEmptyString$1),
201
- sourceToolCallId: NonEmptyString$1,
202
- grantedAt: NonEmptyString$1
203
- }, { open: false });
204
- const PermissionGrantReferenceSchema = s.obj({ grantId: NonEmptyString$1 }, { open: false });
205
- /** The access decision that a Permission policy can make before execution. */
206
- const ToolPermissionAccessSchema = s.union([s.lit("allow"), s.lit("deny")]);
207
- /** Whether an otherwise allowed Tool call needs a Host Approval. */
208
- const ToolApprovalRequirementSchema = s.union([s.lit("required"), s.lit("not-required")]);
209
- /** The non-terminal admission instruction produced by a Permission evaluator. */
210
- const ToolPermissionDirectiveSchema = s.union([
211
- s.obj({
212
- access: s.lit("deny"),
213
- reason: NonEmptyString$1
214
- }, { open: false }),
215
- s.obj({
216
- access: s.lit("allow"),
217
- approval: s.lit("not-required")
218
- }, { open: false }),
219
- s.obj({
220
- access: s.lit("allow"),
221
- approval: s.lit("required"),
222
- reason: NonEmptyString$1
223
- }, { open: false })
224
- ]);
225
- const PermissionScalarSchema = s.union([
226
- s.str(),
227
- s.num(),
228
- s.bool(),
229
- s.nul()
230
- ]);
231
- const ToolPermissionPolicyEntrySchema = s.union([
232
- s.obj({ access: s.lit("deny") }, { open: false }),
233
- s.obj({
234
- access: s.lit("allow"),
235
- approval: s.lit("not-required")
236
- }, { open: false }),
237
- s.obj({
238
- access: s.lit("allow"),
239
- approval: s.lit("required")
240
- }, { open: false })
241
- ]);
242
- const ToolPermissionRuleSchema = s.obj({
243
- entry: ToolPermissionPolicyEntrySchema,
244
- toolName: NonEmptyString$1,
245
- parameter: s.opt(s.obj({
246
- name: NonEmptyString$1,
247
- value: PermissionScalarSchema
248
- }, { open: false }))
249
- }, { open: false });
250
- const ToolPermissionPolicySchema = s.obj({
251
- fallback: ToolPermissionPolicyEntrySchema,
252
- tools: s.map(ToolPermissionPolicyEntrySchema),
253
- rules: s.arr(ToolPermissionRuleSchema)
254
- }, { open: false });
255
-
256
- //#endregion
257
- //#region src/permissions/policy.ts
258
- /** Evaluates ordered literal rules, then the Tool default and fallback. */
259
- function evaluateToolPermissionPolicy(policy, request) {
260
- const parsedPolicy = decode(ToolPermissionPolicySchema, policy);
261
- const matchingRule = parsedPolicy.rules.find((rule) => {
262
- if (rule.toolName !== request.toolName) return false;
263
- if (rule.parameter === void 0) return true;
264
- const parameters = request.parameters;
265
- return isPlainObject(parameters) && Object.entries(parameters).some(([name, value]) => name === rule.parameter?.name && value === rule.parameter.value);
266
- });
267
- const toolDefault = parsedPolicy.tools[request.toolName];
268
- let entry = parsedPolicy.fallback;
269
- let source = "fallback";
270
- if (toolDefault !== void 0) {
271
- entry = toolDefault;
272
- source = "Tool default";
273
- }
274
- if (matchingRule !== void 0) {
275
- entry = matchingRule.entry;
276
- source = "rule";
277
- }
278
- if (entry.access === "deny") return {
279
- access: "deny",
280
- reason: `${source} denies ${request.toolName}`
281
- };
282
- if (entry.approval !== "not-required") return {
283
- access: "allow",
284
- approval: entry.approval,
285
- reason: `${source} requires approval for ${request.toolName}`
286
- };
287
- return {
288
- access: "allow",
289
- approval: "not-required"
290
- };
291
- }
292
-
293
- //#endregion
294
- //#region src/permissions/errors.ts
295
- var PermissionGrantNotFoundError = class extends Error {
296
- code = "permission_grant_not_found";
297
- constructor(grantId) {
298
- super(`Permission grant ${grantId} was not found`);
299
- this.grantId = grantId;
300
- this.name = "PermissionGrantNotFoundError";
301
- }
302
- };
303
-
304
- //#endregion
305
- //#region src/journal/plugin-record.ts
306
- const Identity$3 = s.str({ minLength: 1 });
307
- const PluginRecordOwnerSchema = s.obj({
308
- entryId: Identity$3,
309
- activationId: s.opt(Identity$3)
310
- }, { open: false });
311
- const AppendPluginRecordSchema = s.obj({
312
- recordType: Identity$3,
313
- recordVersion: s.int({ minimum: 1 }),
314
- data: JsonValueSchema,
315
- expectedRevision: s.int({ minimum: 0 }),
316
- sourceSequence: s.int({ minimum: 0 }),
317
- idempotencyKey: s.opt(Identity$3)
318
- }, { open: false });
319
- const PluginRecordPayloadSchema = s.obj({
320
- ...omit(objectProperties(AppendPluginRecordSchema), ["expectedRevision"]),
321
- owner: PluginRecordOwnerSchema,
322
- revision: s.int({ minimum: 1 })
323
- }, { open: false });
324
- var PluginRecordConflictError = class extends Error {
325
- code = "plugin_record_conflict";
326
- constructor(expectedRevision, actualRevision) {
327
- super(`Plugin record expected revision ${expectedRevision}, but current revision is ${actualRevision}`);
328
- this.expectedRevision = expectedRevision;
329
- this.actualRevision = actualRevision;
330
- this.name = "PluginRecordConflictError";
331
- }
332
- };
333
- /** Validates the same revision stream during write reservation and durable replay. */
334
- var PluginRecordHistory = class PluginRecordHistory {
335
- #revisions = /* @__PURE__ */ new Map();
336
- #keys = /* @__PURE__ */ new Set();
337
- apply(payload, sequence) {
338
- const stream = JSON.stringify([payload.owner.entryId, payload.recordType]);
339
- const current = this.#revisions.get(stream) ?? 0;
340
- if (payload.revision !== current + 1) throw new PluginRecordConflictError(payload.revision - 1, current);
341
- if (payload.sourceSequence >= sequence) throw new Error("Plugin record source is beyond its committed Journal prefix");
342
- const key$1 = this.#key(payload);
343
- if (key$1 !== void 0 && this.#keys.has(key$1)) throw new Error("Plugin record idempotency key was already committed");
344
- this.#revisions.set(stream, payload.revision);
345
- if (key$1 !== void 0) this.#keys.add(key$1);
346
- }
347
- clone() {
348
- const copy = new PluginRecordHistory();
349
- for (const [key$1, value] of this.#revisions) copy.#revisions.set(key$1, value);
350
- for (const key$1 of this.#keys) copy.#keys.add(key$1);
351
- return copy;
352
- }
353
- #key(payload) {
354
- if (payload.idempotencyKey === void 0) return;
355
- return JSON.stringify([
356
- payload.owner.entryId,
357
- payload.recordType,
358
- payload.idempotencyKey
359
- ]);
360
- }
361
- };
362
- /** Activation identity changes on reload; durable command identity does not. */
363
- function samePluginRecord(payload, input) {
364
- return payload.recordVersion === input.recordVersion && payload.revision === input.expectedRevision + 1 && payload.sourceSequence === input.sourceSequence && isEqual(payload.data, input.data);
365
- }
366
-
367
- //#endregion
368
- //#region src/journal/contracts.ts
369
- const NonEmptyString = s.str({ minLength: 1 });
370
- const CompleteModelInputSchema = s.obj({
371
- purpose: NonEmptyString,
372
- system: s.str(),
373
- messages: s.arr(s.obj({
374
- role: s.union([s.lit("user"), s.lit("assistant")]),
375
- content: s.str()
376
- }, { open: false })),
377
- context: s.opt(ModelContextSchema),
378
- sourceModelRequestId: s.opt(NonEmptyString),
379
- model: s.opt(s.obj({
380
- provider: NonEmptyString,
381
- id: NonEmptyString
382
- }, { open: false })),
383
- temperature: s.opt(s.num()),
384
- maxOutputTokens: s.opt(s.int({ minimum: 1 })),
385
- thinkingLevel: s.opt(s.union([
386
- "off",
387
- "minimal",
388
- "low",
389
- "medium",
390
- "high",
391
- "xhigh",
392
- "max"
393
- ].map((value) => s.lit(value))))
394
- }, { open: false });
395
- const SessionInputSourceSchema = s.obj({
396
- kind: NonEmptyString,
397
- data: s.opt(JsonValueSchema)
398
- }, { open: false });
399
- const JOURNAL_FACT_SCHEMA_VERSION = 3;
400
- const UserMessageSchema$1 = UserMessageSchema;
401
- const AssistantMessageSchema$1 = s.obj({
402
- ...objectProperties(AssistantMessageSchema),
403
- thinkingLevel: s.opt(s.str())
404
- }, { open: false });
405
- const ToolResultMessageSchema$1 = ToolResultMessageSchema;
406
- const ConversationEntrySchema = s.union([s.obj({
407
- runId: NonEmptyString,
408
- messageId: NonEmptyString,
409
- sourceFactId: NonEmptyString,
410
- message: UserMessageSchema$1,
411
- source: SessionInputSourceSchema
412
- }, { open: false }), s.obj({
413
- runId: NonEmptyString,
414
- messageId: NonEmptyString,
415
- sourceFactId: NonEmptyString,
416
- message: s.union([AssistantMessageSchema$1, ToolResultMessageSchema$1])
417
- }, { open: false })]);
418
- const ConversationEntryReferenceSchema = s.obj({
419
- runId: NonEmptyString,
420
- messageId: NonEmptyString,
421
- sourceFactId: NonEmptyString
422
- }, { open: false });
423
- const ToolSchema = s.obj({
424
- name: NonEmptyString,
425
- description: s.str(),
426
- parameters: JsonValueSchema
427
- }, { open: false });
428
- const CompletedToolResultSchema = s.obj({
429
- content: s.arr(s.union([TextContentSchema, ImageContentSchema])),
430
- details: s.opt(JsonValueSchema),
431
- usage: s.opt(UsageSchema),
432
- terminate: s.opt(s.bool()),
433
- isError: s.opt(s.bool()),
434
- structuredContent: s.opt(JsonValueSchema)
435
- }, { open: false });
436
- const ToolOutputArchiveRecordSchema = s.obj({
437
- encoding: s.lit("utf-8"),
438
- ref: ArtifactRefSchema,
439
- estimatedTextTokens: s.int({ minimum: 1 })
440
- }, { open: false });
441
- const SessionForkedPayloadSchema = s.obj({
442
- schemaVersion: s.lit(1),
443
- source: s.obj({
444
- sessionId: NonEmptyString,
445
- journalSequence: s.int({ minimum: 0 }),
446
- journalCursor: s.opt(NonEmptyString)
447
- }, { open: false }),
448
- behaviorConstraints: s.opt(s.arr(s.obj({
449
- name: NonEmptyString,
450
- title: NonEmptyString,
451
- constraints: s.obj({
452
- toolNames: s.arr(NonEmptyString),
453
- workspace: s.opt(s.lit("read-only"))
454
- }, { open: false })
455
- }, { open: false }))),
456
- conversation: s.arr(ConversationEntrySchema)
457
- }, { open: false });
458
- const GoalStatusSchema = s.union([
459
- s.lit("active"),
460
- s.lit("paused"),
461
- s.lit("complete"),
462
- s.lit("blocked")
463
- ]);
464
- const GoalCreatedPayloadSchema = s.obj({
465
- goalId: NonEmptyString,
466
- objective: s.str({ minLength: 1 }),
467
- maxTokenBudget: s.opt(s.int({ minimum: 1 }))
468
- }, { open: false });
469
- const GoalStatusChangedPayloadSchema = s.obj({
470
- goalId: NonEmptyString,
471
- status: GoalStatusSchema
472
- }, { open: false });
473
- const GoalContinuationRequestedPayloadSchema = s.obj({ goalId: NonEmptyString }, { open: false });
474
- const GoalRemovedPayloadSchema = s.obj({ goalId: NonEmptyString }, { open: false });
475
- const SessionBehaviorChangedPayloadSchema = s.obj({
476
- command: SessionBehaviorCommandSchema,
477
- sourceRunId: s.opt(NonEmptyString),
478
- name: NonEmptyString,
479
- title: NonEmptyString,
480
- contributionId: NonEmptyString,
481
- version: s.int({ minimum: 1 }),
482
- state: JsonValueSchema,
483
- view: SessionBehaviorViewSchema,
484
- leaseId: NonEmptyString,
485
- bindings: s.obj(pick(objectProperties(ModelViewSchema), ["schemaVersion", "sessionBehaviors"]), { open: false })
486
- }, { open: false });
487
- const CompactionRequestedPayloadSchema = s.obj({
488
- sourceRunId: s.opt(NonEmptyString),
489
- reason: s.union([
490
- s.lit("manual"),
491
- s.lit("threshold"),
492
- s.lit("overflow")
493
- ]),
494
- sourceSequence: s.int({ minimum: 0 }),
495
- sourceReferences: s.arr(ConversationEntryReferenceSchema),
496
- coverage: s.arr(ConversationEntryReferenceSchema),
497
- strategy: s.union([s.lit("direct"), s.lit("skeleton")]),
498
- model: s.obj({
499
- provider: NonEmptyString,
500
- api: NonEmptyString,
501
- id: NonEmptyString
502
- }, { open: false }),
503
- protocolVersion: s.lit(3),
504
- mode: s.opt(s.union([
505
- s.lit("model"),
506
- s.lit("deterministic"),
507
- s.lit("observer")
508
- ])),
509
- compiler: s.opt(s.obj({
510
- entryId: NonEmptyString,
511
- key: NonEmptyString,
512
- version: s.int({ minimum: 1 })
513
- }, { open: false })),
514
- observer: s.opt(s.obj({
515
- entryId: s.opt(NonEmptyString),
516
- key: NonEmptyString,
517
- version: s.int({ minimum: 1 })
518
- }, { open: false })),
519
- splitTurn: s.opt(s.bool()),
520
- fork: s.opt(s.obj({
521
- sourceModelRequestId: NonEmptyString,
522
- sharedConversationMessages: s.int({ minimum: 0 }),
523
- cacheCompatible: s.bool()
524
- }, { open: false })),
525
- route: s.obj({
526
- pendingTokens: s.int({ minimum: 0 }),
527
- skeletonTokens: s.int({ minimum: 0 }),
528
- cacheReadRate: s.opt(s.num({
529
- minimum: 0,
530
- maximum: 1
531
- })),
532
- cacheReadPriceRatio: s.opt(s.num({ minimum: 0 })),
533
- breakEvenTokens: s.opt(s.num({ minimum: 0 })),
534
- savingsMargin: s.num({
535
- minimum: 0,
536
- maximum: 1
537
- }),
538
- reason: s.union([
539
- s.lit("cache-economics"),
540
- s.lit("cache-unknown"),
541
- s.lit("cache-miss"),
542
- s.lit("model-mismatch"),
543
- s.lit("pricing-unavailable"),
544
- s.lit("direct-overflow"),
545
- s.lit("split-turn")
546
- ])
547
- }, { open: false }),
548
- budget: s.obj({
549
- contextLimitTokens: s.int({ minimum: 1 }),
550
- fixedInputTokens: s.int({ minimum: 0 }),
551
- outputLimitTokens: s.int({ minimum: 1 }),
552
- safetyMarginTokens: s.int({ minimum: 1 }),
553
- historyLimitTokens: s.int({ minimum: 1 }),
554
- chunkTargetTokens: s.int({ minimum: 1 })
555
- }, { open: false }),
556
- overflowTrigger: s.opt(s.obj({
557
- runId: NonEmptyString,
558
- modelRequestId: NonEmptyString,
559
- responseMessageId: NonEmptyString,
560
- classification: s.union([s.lit("context-overflow"), s.lit("recoverable-length")]),
561
- desiredMaxOutputTokens: s.num({ exclusiveMinimum: 0 }),
562
- actualOutputTokens: s.num({ minimum: 0 })
563
- }, { open: false })),
564
- contextTokensBefore: s.int({ minimum: 0 }),
565
- estimatedTokensBefore: s.int({ minimum: 0 }),
566
- summarizedMessages: s.int({ minimum: 1 }),
567
- retainedMessages: s.int({ minimum: 0 }),
568
- settings: s.obj({
569
- reserveTokens: s.int({ minimum: 1 }),
570
- keepRecentTokens: s.int({ minimum: 0 }),
571
- summaryMaxOutputTokens: s.opt(s.int({ minimum: 1 }))
572
- }, { open: false })
573
- }, { open: false });
574
- const CompactionModelRequestedPayloadSchema = s.obj({
575
- attemptId: NonEmptyString,
576
- phase: s.union([
577
- s.lit("direct"),
578
- s.lit("chunk"),
579
- s.lit("merge"),
580
- s.lit("final"),
581
- s.lit("empty-retry"),
582
- s.lit("provider-reduction")
583
- ]),
584
- unit: s.opt(s.union([s.lit("history"), s.lit("turn-prefix")])),
585
- route: s.union([s.lit("direct"), s.lit("skeleton")]),
586
- depth: s.int({ minimum: 0 }),
587
- partIndex: s.int({ minimum: 0 }),
588
- partCount: s.int({ minimum: 1 }),
589
- estimatedInputTokens: s.int({ minimum: 0 }),
590
- maxOutputTokens: s.int({ minimum: 1 }),
591
- model: s.obj({
592
- provider: NonEmptyString,
593
- api: NonEmptyString,
594
- id: NonEmptyString
595
- }, { open: false })
596
- }, { open: false });
597
- const CompactionModelResponseCommittedPayloadSchema = s.obj({
598
- attemptId: NonEmptyString,
599
- response: AssistantMessageSchema$1
600
- }, { open: false });
601
- const CompactionModelFailedPayloadSchema = s.obj({
602
- attemptId: NonEmptyString,
603
- code: s.union([
604
- s.lit("aborted"),
605
- s.lit("interrupted"),
606
- s.lit("model_call_error")
607
- ]),
608
- message: NonEmptyString
609
- }, { open: false });
610
- const CompactionCommittedPayloadSchema = s.obj({
611
- sourceSequence: s.int({ minimum: 0 }),
612
- sourceReferences: s.arr(ConversationEntryReferenceSchema),
613
- coverage: s.arr(ConversationEntryReferenceSchema),
614
- summary: NonEmptyString,
615
- mode: s.opt(s.union([
616
- s.lit("model"),
617
- s.lit("deterministic"),
618
- s.lit("observer")
619
- ])),
620
- finalAttemptId: s.opt(NonEmptyString),
621
- attemptIds: s.opt(s.arr(NonEmptyString)),
622
- contextTokensBefore: s.int({ minimum: 0 }),
623
- estimatedTokensBefore: s.int({ minimum: 0 }),
624
- estimatedTokensAfter: s.int({ minimum: 0 }),
625
- projectedContextTokensAfter: s.int({ minimum: 0 }),
626
- reductionRatio: s.num({
627
- minimum: 0,
628
- maximum: 1
629
- }),
630
- retainedTail: s.arr(ConversationEntryReferenceSchema),
631
- projectionVersion: s.lit(2)
632
- }, { open: false });
633
- const ModelRequestBaseCommittedPayloadSchema = s.obj({
634
- requestBaseId: NonEmptyString,
635
- pluginBindings: s.union([s.nul(), ModelViewSchema]),
636
- prefix: PrefixSnapshotSchema,
637
- tools: s.arr(ToolSchema),
638
- toolBindings: s.arr(s.obj({
639
- toolName: NonEmptyString,
640
- bindingId: NonEmptyString,
641
- origin: s.union([s.lit("host"), s.lit("plugin")])
642
- }, { open: false }))
643
- }, { open: false });
644
- const ModelRequestContextSnapshotSchema = s.obj({
645
- schemaVersion: s.lit(1),
646
- preparedAt: NonEmptyString,
647
- contextEpoch: s.int({ minimum: 0 }),
648
- prefix: s.obj({ revision: s.int({ minimum: 1 }) }, { open: false }),
649
- namedStates: s.arr(NamedStateSnapshotSchema),
650
- namedStateReuse: s.opt(s.obj({
651
- modelRequestId: NonEmptyString,
652
- stateNames: s.arr(NonEmptyString, { minItems: 1 })
653
- }, { open: false })),
654
- tools: s.opt(s.obj(omit(objectProperties(ToolStateSnapshotSchema), ["definitions"]), { open: false })),
655
- turnMaterial: TurnMaterialSnapshotSchema,
656
- requestMaterial: s.opt(RequestMaterialSnapshotSchema),
657
- modelInput: s.obj({
658
- stateMessages: s.arr(ModelContextMessageSchema),
659
- turnMessages: s.arr(ModelContextMessageSchema),
660
- requestMessages: s.opt(s.arr(ModelContextMessageSchema))
661
- }, { open: false }),
662
- evidence: ContextAssemblyEvidenceSchema
663
- }, { open: false });
664
- const CompactionSkippedPayloadSchema = s.obj({
665
- reason: s.lit("insufficient-reduction"),
666
- projectedContextTokensAfter: s.int({ minimum: 0 }),
667
- triggerTokens: s.int({ minimum: 1 }),
668
- reductionRatio: s.num({
669
- minimum: 0,
670
- maximum: 1
671
- })
672
- }, { open: false });
673
- const CompactionFailedPayloadSchema = s.obj({
674
- sourceSequence: s.int({ minimum: 0 }),
675
- code: s.union([
676
- s.lit("aborted"),
677
- s.lit("summarization_failed"),
678
- s.lit("journal_conflict"),
679
- s.lit("invalid_history"),
680
- s.lit("interrupted"),
681
- s.lit("ineffective"),
682
- s.lit("budget_exhausted"),
683
- s.lit("chunk_overflow"),
684
- s.lit("invalid_summary"),
685
- s.lit("model_call_error")
686
- ]),
687
- message: NonEmptyString
688
- }, { open: false });
689
- const RunFailureCodeSchema = s.union([
690
- s.lit("harness_interrupted"),
691
- s.lit("journal_error"),
692
- s.lit("model_aborted"),
693
- s.lit("model_unavailable"),
694
- s.lit("model_error"),
695
- s.lit("model_invalid_response"),
696
- s.lit("runtime_error"),
697
- s.lit("tool_boundary_error")
698
- ]);
699
- const RunContinuationEvidenceSchema = s.obj({
700
- sourceRunId: NonEmptyString,
701
- sourceSequence: s.int({ minimum: 1 }),
702
- sourceCursor: NonEmptyString
703
- }, { open: false });
704
- const ContextForkSeedSchema = s.obj({
705
- schemaVersion: s.lit(2),
706
- source: s.obj({
707
- sessionId: NonEmptyString,
708
- runId: NonEmptyString,
709
- modelRequestId: NonEmptyString,
710
- responseMessageId: NonEmptyString,
711
- toolCallId: NonEmptyString
712
- }, { open: false }),
713
- sessionSources: s.arr(PrefixContextSourceSchema),
714
- messages: s.arr(MessageSchema),
715
- messageOrigins: s.arr(s.union([
716
- s.obj({ kind: s.lit("fork-seed") }, { open: false }),
717
- s.obj({ kind: s.lit("context-frame") }, { open: false }),
718
- s.obj({ kind: s.lit("compaction-summary") }, { open: false }),
719
- s.obj({
720
- kind: s.lit("conversation"),
721
- sourceKind: s.opt(NonEmptyString)
722
- }, { open: false })
723
- ]))
724
- }, { open: false });
725
- /**
726
- * `run.accepted` is Sorbet's admission boundary for one run. It must be the
727
- * first and only admission fact for the run; work may begin after its append
728
- * completes. A user-message cause records the exact Pi message and its durable
729
- * provenance. A context-event cause starts execution without adding a public
730
- * conversation message. Both capture their turn-scoped Context before dispatch.
731
- * `contextSources` preserves caller input for admission identity; optional
732
- * `runtimeContextSources` records injected execution context, such as the current Goal.
733
- */
734
- const RunAcceptedPayloadSchema = s.union([s.obj({
735
- cause: s.lit("user-message"),
736
- messageId: NonEmptyString,
737
- yieldUsageLimit: s.opt(s.int({ minimum: 0 })),
738
- model: s.opt(s.obj({
739
- provider: NonEmptyString,
740
- id: NonEmptyString
741
- }, { open: false })),
742
- idempotencyKey: s.opt(NonEmptyString),
743
- deliveryId: s.opt(NonEmptyString),
744
- source: SessionInputSourceSchema,
745
- forkSeed: s.opt(s.unknown()),
746
- message: UserMessageSchema$1,
747
- contextSources: ContextSourcesSchema,
748
- runtimeContextSources: s.opt(ContextSourcesSchema),
749
- toolPermissionPolicy: s.opt(ToolPermissionPolicySchema),
750
- approvalMode: s.opt(ApprovalModeSchema),
751
- continuation: s.opt(RunContinuationEvidenceSchema)
752
- }, { open: false }), s.obj({
753
- cause: s.lit("context-event"),
754
- messageId: NonEmptyString,
755
- yieldUsageLimit: s.opt(s.int({ minimum: 0 })),
756
- model: s.opt(s.obj({
757
- provider: NonEmptyString,
758
- id: NonEmptyString
759
- }, { open: false })),
760
- deliveryId: NonEmptyString,
761
- source: SessionInputSourceSchema,
762
- contextSources: ContextSourcesSchema,
763
- runtimeContextSources: s.opt(ContextSourcesSchema),
764
- toolPermissionPolicy: s.opt(ToolPermissionPolicySchema),
765
- approvalMode: s.opt(ApprovalModeSchema)
766
- }, { open: false })]);
767
- const RunYieldIdentity = {
768
- yieldId: NonEmptyString,
769
- continuation: s.int({ minimum: 1 }),
770
- responseMessageId: NonEmptyString
771
- };
772
- const RunYieldDecidedPayloadSchema = s.union([
773
- s.obj({
774
- ...RunYieldIdentity,
775
- decision: s.lit("continue"),
776
- decidedBy: NonEmptyString,
777
- message: PluginInputSchema
778
- }, { open: false }),
779
- s.obj({
780
- ...RunYieldIdentity,
781
- decision: s.lit("stop")
782
- }, { open: false }),
783
- s.obj({
784
- ...RunYieldIdentity,
785
- decision: s.lit("limit"),
786
- budget: s.obj({
787
- metric: s.lit("run.totalTokens"),
788
- used: s.int({ minimum: 0 }),
789
- limit: s.int({ minimum: 0 })
790
- }, { open: false })
791
- }, { open: false })
792
- ]);
793
- const RunStartedPayloadSchema = s.obj({}, { open: false });
794
- /**
795
- * Input admitted to a Run. A/B records Pi injection; C records boundary placement,
796
- * including additional inputs in a final batch before the successor Run starts.
797
- * This fact alone does not prove inclusion in a model request.
798
- */
799
- const RunInputAcceptedPayloadSchema = s.union([s.obj({
800
- cause: s.lit("user-message"),
801
- messageId: NonEmptyString,
802
- mode: s.union([s.lit("steer"), s.lit("followUp")]),
803
- message: UserMessageSchema$1,
804
- deliveryId: s.opt(NonEmptyString),
805
- source: SessionInputSourceSchema
806
- }, { open: false }), s.obj({
807
- cause: s.lit("context-event"),
808
- messageId: NonEmptyString,
809
- mode: s.union([s.lit("steer"), s.lit("followUp")]),
810
- contextSources: ContextSourcesSchema,
811
- deliveryId: NonEmptyString,
812
- source: SessionInputSourceSchema
813
- }, { open: false })]);
814
- /** Durable cancellation intent committed before Sorbet calls Pi `Agent.abort()`. */
815
- const RunCancelRequestedPayloadSchema = s.obj({ reason: NonEmptyString }, { open: false });
816
- /**
817
- * `model.requested` is the write-ahead boundary for one physical Provider call.
818
- * A safe retry receives a new request identity, links to the failed request, and
819
- * reuses the logical call's exact immutable input evidence. The append must
820
- * complete before control passes to Pi, but it does not prove that the Provider
821
- * received the request. Evidence excludes credentials, executable Tool
822
- * functions, and Provider-lowered wire data.
823
- */
824
- const ModelRequestedPayloadSchema = s.obj({
825
- contextInputMessageIds: s.opt(s.arr(NonEmptyString)),
826
- settings: s.opt(ModelRequestSettingsSchema),
827
- historyThroughSequence: s.int({ minimum: 0 }),
828
- conversationSourcePrefix: s.opt(s.obj({
829
- modelRequestId: NonEmptyString,
830
- count: s.int({ minimum: 1 })
831
- }, { open: false })),
832
- conversationSources: s.opt(s.arr(s.union([s.obj({
833
- kind: s.lit("conversation"),
834
- reference: ConversationEntryReferenceSchema
835
- }, { open: false }), s.obj({
836
- kind: s.lit("inline"),
837
- message: s.union([
838
- UserMessageSchema$1,
839
- AssistantMessageSchema$1,
840
- ToolResultMessageSchema$1
841
- ])
842
- }, { open: false })]))),
843
- modelRequestId: NonEmptyString,
844
- logicalModelCallId: NonEmptyString,
845
- leaseId: s.opt(NonEmptyString),
846
- retryOfModelRequestId: s.opt(NonEmptyString),
847
- resumeOfModelRequestId: s.opt(NonEmptyString),
848
- requestBaseId: NonEmptyString,
849
- contextSnapshot: ModelRequestContextSnapshotSchema,
850
- model: s.obj({
851
- provider: NonEmptyString,
852
- api: NonEmptyString,
853
- id: NonEmptyString
854
- }, { open: false })
855
- }, { open: false });
856
- /**
857
- * Settles an admitted request when no committed Provider response can be
858
- * recovered. It permits Run recovery but does not prove that the Provider did
859
- * no work and is not authority to retry the request.
860
- */
861
- const ModelRequestUnknownPayloadSchema = s.obj({
862
- modelRequestId: NonEmptyString,
863
- reason: NonEmptyString
864
- }, { open: false });
865
- /**
866
- * `tool.permission.decided` admits or denies one committed Pi Tool call.
867
- * An allowed decision permits dispatch but does not prove that dispatch began;
868
- * only a following `effect.requested` establishes that boundary.
869
- */
870
- const ToolPermissionDecidedPayloadSchema = s.union([s.obj({
871
- toolCallId: NonEmptyString,
872
- parentToolCallId: s.opt(NonEmptyString),
873
- toolName: s.opt(NonEmptyString),
874
- bindingId: s.opt(NonEmptyString),
875
- outcome: s.lit("allowed"),
876
- grant: s.opt(PermissionGrantReferenceSchema)
877
- }, { open: false }), s.obj({
878
- toolCallId: NonEmptyString,
879
- parentToolCallId: s.opt(NonEmptyString),
880
- toolName: s.opt(NonEmptyString),
881
- bindingId: s.opt(NonEmptyString),
882
- outcome: s.lit("denied"),
883
- reason: NonEmptyString
884
- }, { open: false })]);
885
- /** `tool.permission.failed` records that no permission decision was produced. */
886
- const ToolPermissionFailedPayloadSchema = s.obj({
887
- toolCallId: NonEmptyString,
888
- message: NonEmptyString
889
- }, { open: false });
890
- /** Records why one committed Tool action requires Host review. */
891
- const ApprovalRequestedPayloadSchema = ApprovalRequestRecordSchema;
892
- /** Records the sole terminal Host-review outcome for one Approval request. */
893
- const ApprovalResolvedPayloadSchema = ApprovalResolvedRecordSchema;
894
- const ApprovalReviewOutcomeSchema = s.union([s.lit("allow"), s.lit("ask")]);
895
- const ApprovalReviewFailureCodeSchema = s.union([
896
- s.lit("aborted"),
897
- s.lit("timeout"),
898
- s.lit("invalid_response"),
899
- s.lit("model_call_error"),
900
- s.lit("context_capacity"),
901
- s.lit("context_changed"),
902
- s.lit("unavailable")
903
- ]);
904
- const ApprovalReviewedPayloadSchema = s.obj({
905
- reviewId: NonEmptyString,
906
- toolCallId: NonEmptyString,
907
- parentToolCallId: s.opt(NonEmptyString),
908
- toolName: NonEmptyString,
909
- sourceSequence: s.int({ minimum: 1 }),
910
- model: s.obj({
911
- provider: NonEmptyString,
912
- id: NonEmptyString
913
- }, { open: false }),
914
- promptVersion: NonEmptyString,
915
- outcome: ApprovalReviewOutcomeSchema,
916
- reason: NonEmptyString,
917
- failureCode: s.opt(ApprovalReviewFailureCodeSchema),
918
- usage: s.opt(UsageSchema)
919
- }, { open: false });
920
- const ToolHookInputProperties = { leaseId: NonEmptyString };
921
- const ToolHookInputSchema = s.obj(ToolHookInputProperties, { open: false });
922
- /**
923
- * `effect.requested` is the write-ahead boundary for one effect attempt. Its
924
- * append must complete before the executor is invoked. An attempt left without
925
- * a terminal fact may have reached the external world and must not be retried
926
- * automatically without an implemented reconciliation or idempotency policy.
927
- */
928
- const EffectRequestedPayloadSchema = s.obj({
929
- effectAttemptId: NonEmptyString,
930
- retryOf: s.opt(NonEmptyString),
931
- toolCallId: NonEmptyString,
932
- parentToolCallId: s.opt(NonEmptyString),
933
- recovery: s.opt(s.union([s.lit("unsafe"), s.lit("safe")])),
934
- toolName: s.opt(NonEmptyString),
935
- bindingId: s.opt(NonEmptyString),
936
- parameters: s.opt(JsonValueSchema),
937
- hookInput: s.opt(ToolHookInputSchema),
938
- executionBinding: s.opt(s.obj({
939
- leaseId: NonEmptyString,
940
- bindingId: NonEmptyString
941
- }, { open: false }))
942
- }, { open: false });
943
- /**
944
- * `effect.succeeded` records that the executor returned an output for the
945
- * identified attempt. It is terminal for that attempt; no other effect
946
- * terminal may be committed for the same `effectAttemptId`.
947
- */
948
- const EffectSucceededPayloadSchema = s.obj({
949
- effectAttemptId: NonEmptyString,
950
- result: CompletedToolResultSchema,
951
- outputArchive: s.opt(ToolOutputArchiveRecordSchema)
952
- }, { open: false });
953
- /**
954
- * `effect.failed` records that the executor did not return a successful output.
955
- * `cancelled` reports whether cancellation was observed at failure time; it
956
- * does not prove that the external effect did not partially occur. It is
957
- * terminal for the identified attempt.
958
- */
959
- const EffectFailedPayloadSchema = s.obj({
960
- effectAttemptId: NonEmptyString,
961
- result: CompletedToolResultSchema,
962
- outputArchive: s.opt(ToolOutputArchiveRecordSchema),
963
- cancelled: s.bool()
964
- }, { open: false });
965
- /**
966
- * `effect.unknown` closes an abandoned or unacknowledged attempt when Sorbet cannot determine
967
- * whether the external operation occurred. Stage A never automatically re-executes it;
968
- * `safe` recovery changes only the feedback about making a new Tool call.
969
- */
970
- const EffectUnknownPayloadSchema = s.obj({
971
- effectAttemptId: NonEmptyString,
972
- resumeId: s.opt(NonEmptyString),
973
- reason: NonEmptyString,
974
- feedback: s.opt(s.obj({
975
- content: s.arr(TextContentSchema),
976
- details: s.opt(JsonValueSchema)
977
- }, { open: false })),
978
- outputArchive: s.opt(ToolOutputArchiveRecordSchema)
979
- }, { open: false });
980
- /**
981
- * `model.response.committed` persists the complete Pi AssistantMessage for one
982
- * physical request, including failed and aborted responses. Provider usage is
983
- * read from the message itself and is never estimated or copied into a second
984
- * durable field. The fact is not a Run terminal.
985
- */
986
- const ModelResponseCommittedPayloadSchema = s.obj({
987
- modelRequestId: NonEmptyString,
988
- messageId: NonEmptyString,
989
- message: AssistantMessageSchema$1
990
- }, { open: false });
991
- const ToolHookEvidenceSchema = s.obj({
992
- ...ToolHookInputProperties,
993
- disposition: s.union([
994
- s.lit("executed"),
995
- s.lit("blocked"),
996
- s.lit("responded"),
997
- s.lit("failed")
998
- ]),
999
- effectAttemptId: s.opt(NonEmptyString),
1000
- hookId: s.opt(NonEmptyString)
1001
- }, { open: false });
1002
- /**
1003
- * Ordinary executed results reference their Effect terminal. Hook feedback is
1004
- * independently persisted and linked to its bindings and any actual Attempt;
1005
- * synthetic results without Hooks remain inline. None replaces Effect authority.
1006
- *
1007
- * Across all source kinds, `resumeId` has the settlement/progress meaning documented on
1008
- * {@link EffectUnknownPayloadSchema}. Ordinary execution omits it, even in a resumed Run.
1009
- */
1010
- const ToolResultMessageCommittedPayloadSchema = s.union([
1011
- s.obj({
1012
- messageId: NonEmptyString,
1013
- resumeId: s.opt(NonEmptyString),
1014
- source: s.obj({
1015
- kind: s.lit("hook"),
1016
- message: ToolResultMessageSchema$1,
1017
- evidence: ToolHookEvidenceSchema
1018
- }, { open: false })
1019
- }, { open: false }),
1020
- s.obj({
1021
- messageId: NonEmptyString,
1022
- resumeId: s.opt(NonEmptyString),
1023
- source: s.obj({
1024
- kind: s.lit("effect"),
1025
- effectAttemptId: NonEmptyString,
1026
- toolCallId: NonEmptyString,
1027
- toolName: NonEmptyString,
1028
- timestamp: s.num(),
1029
- durationMs: s.opt(s.num({ minimum: 0 }))
1030
- }, { open: false })
1031
- }, { open: false }),
1032
- s.obj({
1033
- messageId: NonEmptyString,
1034
- resumeId: s.opt(NonEmptyString),
1035
- source: s.obj({
1036
- kind: s.lit("inline"),
1037
- message: ToolResultMessageSchema$1
1038
- }, { open: false })
1039
- }, { open: false })
1040
- ]);
1041
- /**
1042
- * `run.completed` is the successful terminal fact. Its response is the public
1043
- * settled message referenced by identity rather than copied into this payload.
1044
- * A run may contain exactly one of `run.completed`, `run.failed`, or
1045
- * `run.cancelled`, after which no new run work may begin.
1046
- */
1047
- const RunCompletedPayloadSchema = s.obj({ responseMessageId: NonEmptyString }, { open: false });
1048
- /**
1049
- * `run.failed` is the non-cancellation terminal fact. The error code is the
1050
- * runtime's stable programmatic classification and the message is its
1051
- * diagnostic. Pi and Provider reason strings belong in diagnostic content,
1052
- * never in the code namespace. Requested effects must be settled first; this
1053
- * fact does not reinterpret their outcomes. Optional modelError captures Pi's
1054
- * Provider retry classification for Goal continuation; it never authorizes an
1055
- * existing Effect attempt to be replayed.
1056
- */
1057
- const RunFailedPayloadSchema = s.obj({
1058
- errorCode: RunFailureCodeSchema,
1059
- message: NonEmptyString,
1060
- modelError: s.opt(s.obj({
1061
- retryable: s.bool(),
1062
- retryExhausted: s.bool()
1063
- }, { open: false }))
1064
- }, { open: false });
1065
- /**
1066
- * `run.cancelled` is the terminal fact written when cancellation wins terminal
1067
- * settlement. Requested effects must be settled first. The reason does not
1068
- * imply that already-dispatched model calls or effects performed no work.
1069
- */
1070
- const RunCancelledPayloadSchema = s.obj({ reason: NonEmptyString }, { open: false });
1071
- function newRunFactSchema(kind, payload) {
1072
- return {
1073
- kind,
1074
- payload,
1075
- schema: s.obj({
1076
- sessionId: NonEmptyString,
1077
- runId: NonEmptyString,
1078
- kind: s.lit(kind),
1079
- payload
1080
- }, { open: false })
1081
- };
1082
- }
1083
- function newSessionFactSchema(kind, payload) {
1084
- return {
1085
- kind,
1086
- payload,
1087
- schema: s.obj({
1088
- sessionId: NonEmptyString,
1089
- operationId: NonEmptyString,
1090
- kind: s.lit(kind),
1091
- payload
1092
- }, { open: false })
1093
- };
1094
- }
1095
- /**
1096
- * Authoritative catalog of executable Journal fact kinds and payload shapes.
1097
- * Append and persisted schemas are both generated from this single catalog.
1098
- */
1099
- const ExternalToolAcceptedPayloadSchema = s.obj({
1100
- toolCallId: NonEmptyString,
1101
- name: NonEmptyString,
1102
- arguments: JsonValueSchema,
1103
- source: SessionInputSourceSchema,
1104
- binding: s.opt(s.obj({
1105
- leaseId: NonEmptyString,
1106
- bindingId: NonEmptyString,
1107
- descriptor: JsonValueSchema
1108
- }, { open: false }))
1109
- }, { open: false });
1110
- const ExternalToolTerminalPayloadSchema = s.obj({
1111
- status: s.union([
1112
- s.lit("succeeded"),
1113
- s.lit("failed"),
1114
- s.lit("denied"),
1115
- s.lit("cancelled"),
1116
- s.lit("unknown")
1117
- ]),
1118
- result: s.opt(CompletedToolResultSchema),
1119
- message: s.opt(NonEmptyString)
1120
- }, { open: false });
1121
- const PromptTextContentSchema = s.obj({
1122
- type: s.lit("text"),
1123
- text: s.str(),
1124
- textSignature: s.opt(s.str())
1125
- }, { open: false });
1126
- const PromptImageContentSchema = s.obj({
1127
- type: s.lit("image"),
1128
- data: s.str({ minLength: 1 }),
1129
- mimeType: s.str({ minLength: 1 })
1130
- }, { open: false });
1131
- /** Provider-ready user content admitted durably by Sorbet. */
1132
- const UserPromptSchema = s.union([s.str({ minLength: 1 }), s.arr(s.union([PromptTextContentSchema, PromptImageContentSchema]), { minItems: 1 })]);
1133
- const SendSessionInputVariants = [s.obj({
1134
- kind: s.lit("user-message"),
1135
- deliveryId: NonEmptyString,
1136
- prompt: UserPromptSchema,
1137
- source: SessionInputSourceSchema
1138
- }, { open: false }), s.obj({
1139
- kind: s.lit("context-event"),
1140
- deliveryId: NonEmptyString,
1141
- contextSources: s.arr(TurnContextSourceSchema),
1142
- source: SessionInputSourceSchema
1143
- }, { open: false })];
1144
- const SendSessionInputSchema = s.union(SendSessionInputVariants);
1145
- const SubmissionControlInputSchema = s.union([s.obj({
1146
- kind: s.lit("write"),
1147
- deliveryId: NonEmptyString,
1148
- text: s.str(),
1149
- source: SessionInputSourceSchema
1150
- }, { open: false }), s.obj({
1151
- kind: s.lit("reset"),
1152
- deliveryId: NonEmptyString,
1153
- source: SessionInputSourceSchema
1154
- }, { open: false })]);
1155
- const SubmissionInputSchema = s.union([SendSessionInputSchema, SubmissionControlInputSchema]);
1156
- const SubmissionAcceptedPayloadSchema = s.obj({
1157
- input: SubmissionInputSchema,
1158
- message: s.opt(MessageRoutingSchema),
1159
- whenBusy: s.union([s.lit("followUp"), s.lit("steer")]),
1160
- toolPermissionPolicy: s.opt(ToolPermissionPolicySchema),
1161
- approvalMode: s.opt(ApprovalModeSchema),
1162
- forkSeed: s.opt(ContextForkSeedSchema)
1163
- }, { open: false });
1164
- const SessionFactDefinitions = [
1165
- newSessionFactSchema("submission.accepted", SubmissionAcceptedPayloadSchema),
1166
- newSessionFactSchema("submission.applied", s.obj({
1167
- kind: s.union([s.lit("write"), s.lit("reset")]),
1168
- boundary: s.union([s.lit("immediate"), s.lit("final")]),
1169
- order: s.int({ minimum: 0 })
1170
- }, { open: false })),
1171
- newSessionFactSchema("submission.placed", s.obj({
1172
- runId: NonEmptyString,
1173
- messageId: NonEmptyString,
1174
- boundary: s.union([
1175
- s.lit("start"),
1176
- s.lit("postTools"),
1177
- s.lit("final")
1178
- ]),
1179
- order: s.int({ minimum: 0 })
1180
- }, { open: false })),
1181
- newSessionFactSchema("submission.withdrawn", s.obj({
1182
- reason: NonEmptyString,
1183
- commandId: NonEmptyString
1184
- }, { open: false })),
1185
- newSessionFactSchema("submission.settled", s.union([s.obj({
1186
- runId: NonEmptyString,
1187
- outcome: s.lit("answered")
1188
- }, { open: false }), s.obj({
1189
- runId: NonEmptyString,
1190
- outcome: s.lit("unanswered"),
1191
- reason: s.union([
1192
- s.lit("model_error"),
1193
- s.lit("cancelled"),
1194
- s.lit("failed"),
1195
- s.lit("interrupted")
1196
- ])
1197
- }, { open: false })])),
1198
- newSessionFactSchema("model.invocation.requested", s.obj({
1199
- ...omit(objectProperties(CompleteModelInputSchema), ["model"]),
1200
- requestId: NonEmptyString,
1201
- source: SessionInputSourceSchema,
1202
- model: s.obj({
1203
- provider: NonEmptyString,
1204
- api: NonEmptyString,
1205
- id: NonEmptyString
1206
- }, { open: false })
1207
- }, { open: false })),
1208
- newSessionFactSchema("model.invocation.response.committed", s.obj({
1209
- requestId: NonEmptyString,
1210
- response: AssistantMessageSchema$1
1211
- }, { open: false })),
1212
- newSessionFactSchema("model.invocation.unknown", s.obj({
1213
- requestId: NonEmptyString,
1214
- reason: NonEmptyString
1215
- }, { open: false })),
1216
- newSessionFactSchema("plugin.record.committed", PluginRecordPayloadSchema),
1217
- newSessionFactSchema("tool.operation.accepted", ExternalToolAcceptedPayloadSchema),
1218
- newSessionFactSchema("tool.operation.approval.requested", ApprovalRequestedPayloadSchema),
1219
- newSessionFactSchema("tool.operation.approval.resolved", ApprovalResolvedPayloadSchema),
1220
- newSessionFactSchema("tool.operation.permission.decided", ToolPermissionDecidedPayloadSchema),
1221
- newSessionFactSchema("tool.operation.permission.failed", ToolPermissionFailedPayloadSchema),
1222
- newSessionFactSchema("tool.operation.effect.requested", EffectRequestedPayloadSchema),
1223
- newSessionFactSchema("tool.operation.effect.succeeded", EffectSucceededPayloadSchema),
1224
- newSessionFactSchema("tool.operation.effect.failed", EffectFailedPayloadSchema),
1225
- newSessionFactSchema("tool.operation.effect.unknown", EffectUnknownPayloadSchema),
1226
- newSessionFactSchema("tool.operation.terminal", ExternalToolTerminalPayloadSchema),
1227
- newSessionFactSchema("permission.grant.revoked", s.obj({ grantId: NonEmptyString }, { open: false })),
1228
- newSessionFactSchema("session.forked", SessionForkedPayloadSchema),
1229
- newSessionFactSchema("model.request.base.committed", ModelRequestBaseCommittedPayloadSchema),
1230
- newSessionFactSchema("goal.created", GoalCreatedPayloadSchema),
1231
- newSessionFactSchema("goal.status.changed", GoalStatusChangedPayloadSchema),
1232
- newSessionFactSchema("goal.continuation.requested", GoalContinuationRequestedPayloadSchema),
1233
- newSessionFactSchema("goal.removed", GoalRemovedPayloadSchema),
1234
- newSessionFactSchema("session.behavior.changed", SessionBehaviorChangedPayloadSchema),
1235
- newSessionFactSchema("compaction.requested", CompactionRequestedPayloadSchema),
1236
- newSessionFactSchema("compaction.model.requested", CompactionModelRequestedPayloadSchema),
1237
- newSessionFactSchema("compaction.model.response.committed", CompactionModelResponseCommittedPayloadSchema),
1238
- newSessionFactSchema("compaction.model.failed", CompactionModelFailedPayloadSchema),
1239
- newSessionFactSchema("compaction.committed", CompactionCommittedPayloadSchema),
1240
- newSessionFactSchema("compaction.failed", CompactionFailedPayloadSchema),
1241
- newSessionFactSchema("compaction.skipped", CompactionSkippedPayloadSchema)
1242
- ];
1243
- const RunFactDefinitions = [
1244
- newRunFactSchema("run.accepted", RunAcceptedPayloadSchema),
1245
- newRunFactSchema("run.started", RunStartedPayloadSchema),
1246
- newRunFactSchema("run.resumed", s.obj({
1247
- resumeId: NonEmptyString,
1248
- attempt: s.int({ minimum: 1 }),
1249
- resetAttempts: s.bool(),
1250
- anchorSequence: s.int({ minimum: 1 }),
1251
- settled: s.obj({
1252
- modelRequestIds: s.arr(NonEmptyString, { uniqueItems: true }),
1253
- effectAttemptIds: s.arr(NonEmptyString, { uniqueItems: true }),
1254
- approvalRequestIds: s.arr(NonEmptyString, { uniqueItems: true }),
1255
- notExecutedToolCallIds: s.arr(NonEmptyString, { uniqueItems: true })
1256
- }, { open: false })
1257
- }, { open: false })),
1258
- newRunFactSchema("run.parked", s.obj({
1259
- attempts: s.int({ minimum: 1 }),
1260
- limit: s.int({ minimum: 1 }),
1261
- reason: s.lit("resume_limit")
1262
- }, { open: false })),
1263
- newRunFactSchema("run.input.accepted", RunInputAcceptedPayloadSchema),
1264
- newRunFactSchema("tool.retry.requested", s.obj({
1265
- toolCallId: NonEmptyString,
1266
- retryOf: NonEmptyString
1267
- }, { open: false })),
1268
- newRunFactSchema("run.input.transformed", s.obj({
1269
- messageId: NonEmptyString,
1270
- leaseId: NonEmptyString,
1271
- bindings: s.obj(pick(objectProperties(ModelViewSchema), ["schemaVersion", "inputTransforms"]), { open: false }),
1272
- content: PluginInputSchema
1273
- }, { open: false })),
1274
- newRunFactSchema("run.cancel.requested", RunCancelRequestedPayloadSchema),
1275
- newRunFactSchema("model.requested", ModelRequestedPayloadSchema),
1276
- newRunFactSchema("model.request.unknown", ModelRequestUnknownPayloadSchema),
1277
- newRunFactSchema("tool.preparation.committed", s.obj({
1278
- toolCallId: NonEmptyString,
1279
- prepared: PreparedToolHooksSchema,
1280
- parentToolCallId: s.opt(NonEmptyString),
1281
- toolName: s.opt(NonEmptyString),
1282
- bindingId: s.opt(NonEmptyString)
1283
- }, { open: false })),
1284
- newRunFactSchema("tool.permission.decided", ToolPermissionDecidedPayloadSchema),
1285
- newRunFactSchema("tool.permission.failed", ToolPermissionFailedPayloadSchema),
1286
- newRunFactSchema("approval.requested", ApprovalRequestedPayloadSchema),
1287
- newRunFactSchema("approval.resolved", ApprovalResolvedPayloadSchema),
1288
- newRunFactSchema("approval.reviewed", ApprovalReviewedPayloadSchema),
1289
- newRunFactSchema("effect.requested", EffectRequestedPayloadSchema),
1290
- newRunFactSchema("effect.succeeded", EffectSucceededPayloadSchema),
1291
- newRunFactSchema("effect.failed", EffectFailedPayloadSchema),
1292
- newRunFactSchema("effect.unknown", EffectUnknownPayloadSchema),
1293
- newRunFactSchema("model.response.committed", ModelResponseCommittedPayloadSchema),
1294
- newRunFactSchema("tool.result.message.committed", ToolResultMessageCommittedPayloadSchema),
1295
- newRunFactSchema("run.yield.decided", RunYieldDecidedPayloadSchema),
1296
- newRunFactSchema("run.completed", RunCompletedPayloadSchema),
1297
- newRunFactSchema("run.failed", RunFailedPayloadSchema),
1298
- newRunFactSchema("run.cancelled", RunCancelledPayloadSchema)
1299
- ];
1300
- const NewJournalFactSchema = s.union([...SessionFactDefinitions.map((definition) => definition.schema), ...RunFactDefinitions.map((definition) => definition.schema)]);
1301
- function storedRunFactSchema(kind, payload) {
1302
- return s.obj({
1303
- id: NonEmptyString,
1304
- sessionId: NonEmptyString,
1305
- runId: NonEmptyString,
1306
- sequence: s.int({ minimum: 1 }),
1307
- cursor: NonEmptyString,
1308
- recordedAt: NonEmptyString,
1309
- kind: s.lit(kind),
1310
- schemaVersion: s.lit(JOURNAL_FACT_SCHEMA_VERSION),
1311
- payload
1312
- }, { open: false });
1313
- }
1314
- function storedSessionFactSchema(kind, payload) {
1315
- return s.obj({
1316
- id: NonEmptyString,
1317
- sessionId: NonEmptyString,
1318
- operationId: NonEmptyString,
1319
- sequence: s.int({ minimum: 1 }),
1320
- cursor: NonEmptyString,
1321
- recordedAt: NonEmptyString,
1322
- kind: s.lit(kind),
1323
- schemaVersion: s.lit(JOURNAL_FACT_SCHEMA_VERSION),
1324
- payload
1325
- }, { open: false });
1326
- }
1327
- const JournalFactDefinitions = [...SessionFactDefinitions.map((definition) => ({
1328
- scope: "session",
1329
- kind: definition.kind,
1330
- schema: storedSessionFactSchema(definition.kind, definition.payload)
1331
- })), ...RunFactDefinitions.map((definition) => ({
1332
- scope: "run",
1333
- kind: definition.kind,
1334
- schema: storedRunFactSchema(definition.kind, definition.payload)
1335
- }))];
1336
- const JournalFactSchema = s.union(JournalFactDefinitions.map((definition) => definition.schema));
1337
- const JournalCursorSchema = NonEmptyString;
1338
- /**
1339
- * True for facts a Session projection owns. Derived from the catalog, so a new
1340
- * Session fact kind is classified without editing a second list. `SessionJournalFact`
1341
- * carries `runId?: never`, which is what lets call sites split the two scopes.
1342
- */
1343
- const SessionFactKindSet = new Set(SessionFactDefinitions.map((definition) => definition.kind));
1344
- /**
1345
- * Submissions are owned by a Unit store, which can settle them across processes. A
1346
- * bare Session Journal must reject them instead of accepting an unsettleable operation.
1347
- */
1348
- const DURABLE_SUBMISSION_FACT_KINDS = [
1349
- "submission.accepted",
1350
- "submission.applied",
1351
- "submission.placed",
1352
- "submission.withdrawn",
1353
- "submission.settled"
1354
- ];
1355
- const DurableSubmissionFactKindSet = new Set(DURABLE_SUBMISSION_FACT_KINDS);
1356
- function isDurableSubmissionFactKind(kind) {
1357
- return DurableSubmissionFactKindSet.has(kind);
1358
- }
1359
- const JOURNAL_APPEND_BATCH_MAX_FACTS = 256;
1360
- const JOURNAL_APPEND_BATCH_MAX_BYTES = 4 * 1024 * 1024;
1361
- const JOURNAL_READ_DEFAULT_LIMIT = 256;
1362
- const JOURNAL_READ_MAX_LIMIT = 1e3;
1363
- var JournalConflictError = class extends Error {
1364
- expectedSequence;
1365
- actualSequence;
1366
- constructor(expectedSequence, actualSequence) {
1367
- super(`Journal append expected sequence ${expectedSequence}, but the durable tail is ${actualSequence}`);
1368
- this.name = "JournalConflictError";
1369
- this.expectedSequence = expectedSequence;
1370
- this.actualSequence = actualSequence;
1371
- }
1372
- };
1373
- var JournalStoreFaultError = class extends Error {
1374
- constructor(message, options) {
1375
- super(message, options);
1376
- this.name = "JournalStoreFaultError";
1377
- }
1378
- };
1379
- /**
1380
- * A resume cursor the store cannot resolve. This is the explicit gap/resync
1381
- * signal required when a consumer's position predates a rewritten or rebuilt
1382
- * history: hosts must restart from an uncursored snapshot+tail read instead of
1383
- * assuming their stream continued seamlessly.
1384
- */
1385
- var JournalCursorGapError = class extends Error {
1386
- cursor;
1387
- constructor(cursor, options) {
1388
- super(cursor === void 0 ? "Journal resume position is not part of this session history" : `Journal cursor does not belong to this session history: ${cursor}`, options);
1389
- this.name = "JournalCursorGapError";
1390
- this.cursor = cursor;
1391
- }
1392
- };
1393
-
1394
- //#endregion
1395
- //#region src/journal/errors.ts
1396
- var JournalCorruptionError = class extends Error {
1397
- constructor(message, options) {
1398
- super(message, options);
1399
- this.name = "JournalCorruptionError";
1400
- }
1401
- };
1402
- var JournalReaderResetRequiredError = class extends Error {
1403
- code = "journal_reader_reset_required";
1404
- constructor() {
1405
- super("The Journal file was replaced or truncated; reopen the read-only reader");
1406
- this.name = "JournalReaderResetRequiredError";
1407
- }
1408
- };
1409
- var JournalReaderCapacityError = class extends Error {
1410
- code = "journal_reader_capacity";
1411
- constructor(maxIndexedFacts, maxIndexedBytes, maxFrameBytes, maxIdentityBytes) {
1412
- super(`Read-only Journal exceeds its ${maxIndexedFacts} fact, ${maxIndexedBytes ?? "unspecified"} charged-index-byte, ${maxFrameBytes ?? "unspecified"} frame-byte, or ${maxIdentityBytes ?? "unspecified"} lifecycle-identity-byte limit`);
1413
- this.maxIndexedFacts = maxIndexedFacts;
1414
- this.maxIndexedBytes = maxIndexedBytes;
1415
- this.maxFrameBytes = maxFrameBytes;
1416
- this.maxIdentityBytes = maxIdentityBytes;
1417
- this.name = "JournalReaderCapacityError";
1418
- }
1419
- };
1420
- var JournalWriterBusyError = class extends Error {
1421
- filePath;
1422
- constructor(filePath, options) {
1423
- super(`Journal already has an active writer: ${filePath}`, options);
1424
- this.name = "JournalWriterBusyError";
1425
- this.filePath = filePath;
1426
- }
1427
- };
1428
-
1429
- //#endregion
1430
- //#region src/identity.ts
1431
- /**
1432
- * Runtime-owned identity creation.
1433
- *
1434
- * Journal facts, Runs, Sessions, Tasks, and commit markers are identified by
1435
- * values that must not collide across processes, browser tabs, or reopen
1436
- * epochs, so they come from the platform CSPRNG rather than a counter.
1437
- *
1438
- * `crypto.randomUUID` is only exposed in a secure context. A browser console
1439
- * served over plain HTTP on a LAN address has no secure context, so the
1440
- * fallback derives the same UUIDv4 shape from `crypto.getRandomValues`, which
1441
- * is available in insecure contexts.
1442
- */
1443
- function createId() {
1444
- const source = globalThis.crypto;
1445
- if (isFunction(source.randomUUID)) return source.randomUUID();
1446
- const bytes = source.getRandomValues(new Uint8Array(16));
1447
- bytes[6] = (bytes[6] ?? 0) & 15 | 64;
1448
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
1449
- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
1450
- return [
1451
- hex.slice(0, 4).join(""),
1452
- hex.slice(4, 6).join(""),
1453
- hex.slice(6, 8).join(""),
1454
- hex.slice(8, 10).join(""),
1455
- hex.slice(10, 16).join("")
1456
- ].join("-");
1457
- }
1458
-
1459
- //#endregion
1460
- //#region src/journal/task-facts.ts
1461
- const Identity$2 = s.str({ minLength: 1 });
1462
- const Restarts = s.int({ minimum: 0 });
1463
- const TaskSessionOwnerSchema = s.obj({ session: Identity$2 }, { open: false });
1464
- const TaskOwnerSchema = s.union([TaskSessionOwnerSchema, s.obj({ task: Identity$2 }, { open: false })]);
1465
- const TaskCheckpointSchema = { allOf: [s.map(JsonValueSchema), s.obj({ phase: Identity$2 }, { open: true })] };
1466
- const TaskWaitMemberVariants = [
1467
- s.obj({ task: Identity$2 }, { open: false }),
1468
- s.obj({ signal: Identity$2 }, { open: false }),
1469
- s.obj({ run: Identity$2 }, { open: false }),
1470
- s.obj({ submission: Identity$2 }, { open: false })
1471
- ];
1472
- const TaskWaitMemberSchema = s.union(TaskWaitMemberVariants);
1473
- const TaskJoinPolicySchema = s.union([s.lit("allSettled"), s.lit("firstSettled")]);
1474
- const TaskErrorSchema = s.obj({
1475
- code: Identity$2,
1476
- message: s.str()
1477
- }, { open: true });
1478
- const TaskOutcomeSchema = s.union([
1479
- s.obj({
1480
- status: s.lit("completed"),
1481
- result: JsonValueSchema
1482
- }, { open: true }),
1483
- s.obj({
1484
- status: s.lit("failed"),
1485
- error: TaskErrorSchema
1486
- }, { open: true }),
1487
- s.obj({
1488
- status: s.lit("aborted"),
1489
- reason: s.str()
1490
- }, { open: true }),
1491
- s.obj({
1492
- status: s.lit("orphaned"),
1493
- reason: s.str()
1494
- }, { open: true }),
1495
- s.obj({
1496
- status: s.lit("faulted"),
1497
- error: TaskErrorSchema
1498
- }, { open: true })
1499
- ]);
1500
- const Transition = {
1501
- checkpoint: TaskCheckpointSchema,
1502
- fromPhase: Identity$2,
1503
- invocationId: s.opt(Identity$2)
1504
- };
1505
- const Creation = {
1506
- kind: Identity$2,
1507
- version: s.int({ minimum: 1 }),
1508
- owner: TaskOwnerSchema,
1509
- background: s.bool(),
1510
- creationKey: Identity$2,
1511
- input: JsonValueSchema,
1512
- checkpoint: TaskCheckpointSchema
1513
- };
1514
- const TaskPayloads = {
1515
- "task.created": s.obj(Creation, { open: true }),
1516
- "task.imported": s.obj({
1517
- ...Creation,
1518
- owner: TaskSessionOwnerSchema,
1519
- result: JsonValueSchema
1520
- }, { open: true }),
1521
- "task.reserved": s.obj({
1522
- epochId: Identity$2,
1523
- phase: Identity$2,
1524
- invocationId: Identity$2,
1525
- mode: s.union([s.lit("phase"), s.lit("abort")]),
1526
- definitionSource: s.opt(s.obj({
1527
- package: Identity$2,
1528
- version: Identity$2
1529
- }, { open: true }))
1530
- }, { open: true }),
1531
- "task.transitioned": s.union([
1532
- s.obj({
1533
- ...Transition,
1534
- status: s.lit("pending")
1535
- }, { open: true }),
1536
- s.obj({
1537
- ...Transition,
1538
- status: s.lit("waiting"),
1539
- on: s.arr(TaskWaitMemberSchema),
1540
- policy: TaskJoinPolicySchema
1541
- }, { open: true }),
1542
- s.obj({
1543
- ...Transition,
1544
- status: s.lit("sleeping"),
1545
- until: s.num()
1546
- }, { open: true })
1547
- ]),
1548
- "task.recovered": s.obj({
1549
- epochId: Identity$2,
1550
- priorState: s.union([s.lit("running"), s.lit("pending")]),
1551
- restarts: Restarts
1552
- }, { open: true }),
1553
- "task.suspended": s.obj({ invocationId: Identity$2 }, { open: true }),
1554
- "task.parked": s.obj({
1555
- restarts: Restarts,
1556
- reason: s.lit("restart_limit")
1557
- }, { open: true }),
1558
- "task.retried": s.obj({ commandId: Identity$2 }, { open: true }),
1559
- "task.abort.requested": s.obj({
1560
- reason: s.str(),
1561
- requester: Identity$2
1562
- }, { open: true }),
1563
- "task.completing": s.obj({
1564
- invocationId: Identity$2,
1565
- outcome: TaskOutcomeSchema
1566
- }, { open: true }),
1567
- "task.settled": s.obj({
1568
- invocationId: s.opt(Identity$2),
1569
- outcome: TaskOutcomeSchema
1570
- }, { open: true }),
1571
- "signal.created": s.obj({
1572
- signalId: Identity$2,
1573
- creationKey: Identity$2,
1574
- type: s.union([
1575
- s.lit("host-command"),
1576
- s.lit("elicitation"),
1577
- s.lit("message-reply")
1578
- ]),
1579
- payload: JsonValueSchema,
1580
- invocationId: Identity$2
1581
- }, { open: true }),
1582
- "signal.resolved": s.obj({
1583
- signalId: Identity$2,
1584
- result: JsonValueSchema,
1585
- commandId: Identity$2
1586
- }, { open: true }),
1587
- "signal.cancelled": s.obj({
1588
- signalId: Identity$2,
1589
- reason: s.str()
1590
- }, { open: true })
1591
- };
1592
- function taskFact(kind) {
1593
- return s.obj({
1594
- id: Identity$2,
1595
- recordedAt: s.str({ minLength: 1 }),
1596
- schemaVersion: s.lit(1),
1597
- taskId: Identity$2,
1598
- kind: s.lit(kind),
1599
- payload: TaskPayloads[kind]
1600
- }, { open: true });
1601
- }
1602
- /** Unit-scoped facts: taskId names the Task, or the waiter that owns a Signal. */
1603
- const TaskFactSchema = s.union([
1604
- taskFact("task.created"),
1605
- taskFact("task.imported"),
1606
- taskFact("task.reserved"),
1607
- taskFact("task.transitioned"),
1608
- taskFact("task.recovered"),
1609
- taskFact("task.suspended"),
1610
- taskFact("task.parked"),
1611
- taskFact("task.retried"),
1612
- taskFact("task.abort.requested"),
1613
- taskFact("task.completing"),
1614
- taskFact("task.settled"),
1615
- taskFact("signal.created"),
1616
- taskFact("signal.resolved"),
1617
- taskFact("signal.cancelled")
1618
- ]);
1619
-
1620
- //#endregion
1621
- //#region src/journal/message-facts.ts
1622
- const Identity$1 = s.str({ minLength: 1 });
1623
- const UnitMessageSchema = s.obj({
1624
- ...MessageRoutingProperties,
1625
- input: SendSessionInputSchema,
1626
- whenBusy: s.union([s.lit("followUp"), s.lit("steer")])
1627
- }, { open: false });
1628
- const Payloads = {
1629
- "message.outbox.enqueued": s.obj({
1630
- owner: TaskOwnerSchema,
1631
- creationKey: Identity$1,
1632
- message: UnitMessageSchema,
1633
- replySignalId: s.opt(Identity$1)
1634
- }, { open: false }),
1635
- "message.outbox.deferred": s.obj({
1636
- retryAt: s.num({ minimum: 0 }),
1637
- code: Identity$1
1638
- }, { open: false }),
1639
- "message.outbox.acknowledged": MessageReceiptSchema,
1640
- "message.outbox.rejected": MessageRejectionSchema
1641
- };
1642
- function fact(kind) {
1643
- return s.obj({
1644
- id: Identity$1,
1645
- recordedAt: Identity$1,
1646
- schemaVersion: s.lit(1),
1647
- messageId: Identity$1,
1648
- kind: s.lit(kind),
1649
- payload: Payloads[kind]
1650
- }, { open: false });
1651
- }
1652
- const MessageFactSchema = s.union([
1653
- fact("message.outbox.enqueued"),
1654
- fact("message.outbox.deferred"),
1655
- fact("message.outbox.acknowledged"),
1656
- fact("message.outbox.rejected")
1657
- ]);
1658
-
1659
- //#endregion
1660
- //#region src/journal/unit/contracts.ts
1661
- const Identity = s.str({ minLength: 1 });
1662
- const UnitPayloads = {
1663
- "unit.created": s.obj({ rootSessionId: Identity }, { open: true }),
1664
- "unit.epoch.started": s.obj({
1665
- epochId: Identity,
1666
- previousEpoch: s.union([s.nul(), s.obj({
1667
- id: Identity,
1668
- closed: s.bool()
1669
- }, { open: true })]),
1670
- durability: s.union([s.lit("sync"), s.lit("memory")])
1671
- }, { open: true }),
1672
- "unit.epoch.closed": s.obj({
1673
- epochId: Identity,
1674
- reason: Identity
1675
- }, { open: true }),
1676
- "session.created": s.obj({
1677
- sessionId: Identity,
1678
- owner: s.union([s.lit("ownerless"), s.obj({ session: Identity }, { open: true })]),
1679
- creationKey: Identity,
1680
- origin: s.union([s.lit("created"), s.lit("migrated")]),
1681
- metadata: JsonValueSchema
1682
- }, { open: true }),
1683
- "session.metadata.changed": s.obj({
1684
- sessionId: Identity,
1685
- metadata: JsonValueSchema
1686
- }, { open: true }),
1687
- "session.closing": s.obj({ sessionId: Identity }, { open: true }),
1688
- "session.closed": s.obj({ sessionId: Identity }, { open: true })
1689
- };
1690
- function unitFact(kind) {
1691
- return s.obj({
1692
- id: Identity,
1693
- recordedAt: s.str({ minLength: 1 }),
1694
- schemaVersion: s.lit(1),
1695
- kind: s.lit(kind),
1696
- payload: UnitPayloads[kind]
1697
- }, { open: true });
1698
- }
1699
- const UnitFactSchema = s.union([
1700
- unitFact("unit.created"),
1701
- unitFact("unit.epoch.started"),
1702
- unitFact("unit.epoch.closed"),
1703
- unitFact("session.created"),
1704
- unitFact("session.metadata.changed"),
1705
- unitFact("session.closing"),
1706
- unitFact("session.closed"),
1707
- TaskFactSchema,
1708
- MessageFactSchema
1709
- ]);
1710
- const UnitEntrySchema = s.union([s.obj({
1711
- scope: s.lit("session"),
1712
- fact: JournalFactSchema
1713
- }, { open: true }), s.obj({
1714
- scope: s.lit("unit"),
1715
- fact: UnitFactSchema
1716
- }, { open: true })]);
1717
- var UnitStoreError = class extends Error {
1718
- constructor(code, message, options) {
1719
- super(message, options);
1720
- this.code = code;
1721
- this.name = "UnitStoreError";
1722
- }
1723
- };
1724
- /** A unit frame that the durable history of its unit rejects. */
1725
- var UnitHistoryError = class extends Error {
1726
- constructor(code, message, options) {
1727
- super(message, options);
1728
- this.code = code;
1729
- this.name = "UnitHistoryError";
1730
- }
1731
- };
1732
-
1733
- //#endregion
1734
- //#region src/journal/unit/identities.ts
1735
- const key = new Uint32Array(4);
1736
- const Dashes = new Set([
1737
- 8,
1738
- 13,
1739
- 18,
1740
- 23
1741
- ]);
1742
- /**
1743
- * Packs a canonical lowercase UUID into `key`. Lowercase only, so distinct strings never
1744
- * pack to the same 128 bits. One pass without regex or slices: opening a Unit packs every
1745
- * fact identity it replays.
1746
- */
1747
- function pack(id) {
1748
- if (id.length !== 36) return false;
1749
- let word = 0;
1750
- let digits = 0;
1751
- for (let index = 0; index < 36; index++) {
1752
- const code = id.charCodeAt(index);
1753
- if (Dashes.has(index)) {
1754
- if (code !== 45) return false;
1755
- continue;
1756
- }
1757
- let nibble;
1758
- if (code >= 48 && code <= 57) nibble = code - 48;
1759
- else if (code >= 97 && code <= 102) nibble = code - 87;
1760
- else return false;
1761
- word = word << 4 | nibble;
1762
- if (++digits % 8 === 0) {
1763
- key[digits / 8 - 1] = word;
1764
- word = 0;
1765
- }
1766
- }
1767
- return true;
1768
- }
1769
- function hash(words, offset) {
1770
- const mixed = Math.imul((words[offset] ?? 0) ^ (words[offset + 1] ?? 0) ^ (words[offset + 2] ?? 0) ^ (words[offset + 3] ?? 0), 2654435761);
1771
- return (mixed ^ mixed >>> 16) >>> 0;
1772
- }
1773
- /**
1774
- * Identity → index for identities kept as long as a Unit's whole history (fact and commit
1775
- * identities). Runtime identities are canonical UUIDs; each packs into 16 bytes stored at
1776
- * its index plus an open-addressing slot, instead of a retained string and a Map entry
1777
- * (about a quarter of the memory). Other identities (injected test ids) use a Map.
1778
- */
1779
- var IdentityIndex = class {
1780
- /** The packed key of index `i` occupies words [4i, 4i + 4). */
1781
- #words = new Uint32Array(256);
1782
- /** Index + 1 per occupied slot; 0 is empty. Kept at most three-quarters full. */
1783
- #slots = new Int32Array(128);
1784
- #count = 0;
1785
- #other = /* @__PURE__ */ new Map();
1786
- get(id) {
1787
- if (!pack(id)) return this.#other.get(id);
1788
- const index = this.#find();
1789
- return index < 0 ? void 0 : index;
1790
- }
1791
- has(id) {
1792
- return this.get(id) !== void 0;
1793
- }
1794
- /**
1795
- * Indexes must be distinct, small and non-negative: the packed key is stored at its index.
1796
- * An identity keeps its first index.
1797
- */
1798
- set(id, index) {
1799
- if (!pack(id)) {
1800
- if (!this.#other.has(id)) this.#other.set(id, index);
1801
- return;
1802
- }
1803
- if (this.#find() >= 0) return;
1804
- if (index * 4 + 4 > this.#words.length) {
1805
- const words = new Uint32Array(Math.max(index * 4 + 4, Math.ceil(this.#words.length * .375) * 4));
1806
- words.set(this.#words);
1807
- this.#words = words;
1808
- }
1809
- if (++this.#count * 4 > this.#slots.length * 3) {
1810
- const previous = this.#slots;
1811
- this.#slots = new Int32Array(previous.length * 2);
1812
- for (const occupant of previous) if (occupant !== 0) this.#place(occupant - 1);
1813
- }
1814
- this.#words.set(key, index * 4);
1815
- this.#place(index);
1816
- }
1817
- /** Index of the packed key, or -1. */
1818
- #find() {
1819
- const mask = this.#slots.length - 1;
1820
- let slot = hash(key, 0) & mask;
1821
- for (let occupant = this.#slots[slot] ?? 0; occupant !== 0; occupant = this.#slots[slot] ?? 0) {
1822
- const offset = (occupant - 1) * 4;
1823
- if (this.#words[offset] === key[0] && this.#words[offset + 1] === key[1] && this.#words[offset + 2] === key[2] && this.#words[offset + 3] === key[3]) return occupant - 1;
1824
- slot = slot + 1 & mask;
1825
- }
1826
- return -1;
1827
- }
1828
- #place(index) {
1829
- const mask = this.#slots.length - 1;
1830
- let slot = hash(this.#words, index * 4) & mask;
1831
- while (this.#slots[slot] !== 0) slot = slot + 1 & mask;
1832
- this.#slots[slot] = index + 1;
1833
- }
1834
- };
1835
-
1836
- //#endregion
1837
- //#region src/journal/unit/history.ts
1838
- const ExecutionAdmissions = new Set([
1839
- "submission.accepted",
1840
- "run.accepted",
1841
- "run.input.accepted",
1842
- "submission.placed",
1843
- "run.resumed"
1844
- ]);
1845
- const TaskSessionOwnerValidator = compile(TaskSessionOwnerSchema);
1846
- const ReadLimitSchema = s.int({
1847
- minimum: 1,
1848
- maximum: JOURNAL_READ_MAX_LIMIT
1849
- });
1850
- /** The owner kind is part of identity: a Task and a Session may have the same textual ID. */
1851
- function creationIdentity(owner, creationKey) {
1852
- return JSON.stringify([owner, creationKey]);
1853
- }
1854
- /**
1855
- * Membership and creation identities of one unit.
1856
- *
1857
- * `durable` holds the records and creation keys the unit has committed;
1858
- * `staged` holds what the batch under validation adds. A lookup prefers the
1859
- * staged record, so one batch observes its own earlier facts, and a rejected
1860
- * batch drops the staged layer without touching the durable one.
1861
- */
1862
- var UnitMembership = class {
1863
- #durable = /* @__PURE__ */ new Map();
1864
- #durableKeys = /* @__PURE__ */ new Set();
1865
- #staged = /* @__PURE__ */ new Map();
1866
- #stagedKeys = /* @__PURE__ */ new Set();
1867
- #tasks = /* @__PURE__ */ new Map();
1868
- #stagedTasks = /* @__PURE__ */ new Map();
1869
- #signals = /* @__PURE__ */ new Map();
1870
- #stagedSignals = /* @__PURE__ */ new Map();
1871
- #messages = /* @__PURE__ */ new Map();
1872
- #stagedMessages = /* @__PURE__ */ new Map();
1873
- #submissions = /* @__PURE__ */ new Set();
1874
- #stagedSubmissions = /* @__PURE__ */ new Set();
1875
- /** Restoring committed history stages straight into the durable layer. */
1876
- #direct = false;
1877
- constructor(unitId) {
1878
- this.unitId = unitId;
1879
- }
1880
- /**
1881
- * Open discards the whole history on any failure, so committed frames need no staging layer
1882
- * to roll back. Promoting and clearing it per frame was most of the restore cost.
1883
- */
1884
- restoring(fold) {
1885
- this.#direct = true;
1886
- try {
1887
- fold();
1888
- } finally {
1889
- this.#direct = false;
1890
- }
1891
- }
1892
- message(id) {
1893
- return this.#stagedMessages.get(id) ?? this.#messages.get(id);
1894
- }
1895
- stageMessage(id, routing, terminal) {
1896
- (this.#direct ? this.#messages : this.#stagedMessages).set(id, {
1897
- routing,
1898
- terminal
1899
- });
1900
- }
1901
- submission(id) {
1902
- if (this.#submissions.has(id) || this.#stagedSubmissions.has(id)) throw new UnitHistoryError("submission_exists", "Submission identity is already accepted in this unit");
1903
- (this.#direct ? this.#submissions : this.#stagedSubmissions).add(id);
1904
- }
1905
- taskTerminal(taskId) {
1906
- return this.#stagedTasks.get(taskId) ?? this.#tasks.get(taskId);
1907
- }
1908
- stageTask(taskId, terminal) {
1909
- (this.#direct ? this.#tasks : this.#stagedTasks).set(taskId, terminal);
1910
- }
1911
- signal(signalId) {
1912
- return this.#stagedSignals.get(signalId) ?? this.#signals.get(signalId);
1913
- }
1914
- stageSignal(signalId, taskId, settled) {
1915
- (this.#direct ? this.#signals : this.#stagedSignals).set(signalId, {
1916
- taskId,
1917
- settled
1918
- });
1919
- }
1920
- reserveKey(owner, creationKey) {
1921
- if (this.keyTaken(owner, creationKey)) throw new UnitHistoryError("creation_key_conflict", "Owner creation key is already used");
1922
- (this.#direct ? this.#durableKeys : this.#stagedKeys).add(creationIdentity(owner, creationKey));
1923
- }
1924
- find(sessionId) {
1925
- return this.#staged.get(sessionId) ?? this.#durable.get(sessionId);
1926
- }
1927
- /** Creation keys share one owner namespace across Sessions, Tasks and Signals. */
1928
- keyTaken(owner, creationKey) {
1929
- const identity = creationIdentity(owner, creationKey);
1930
- return this.#stagedKeys.has(identity) || this.#durableKeys.has(identity);
1931
- }
1932
- /** Stage the record a fact produces and reserve the Session's creation key. */
1933
- stage(record) {
1934
- (this.#direct ? this.#durable : this.#staged).set(record.sessionId, record);
1935
- (this.#direct ? this.#durableKeys : this.#stagedKeys).add(creationIdentity({ session: this.ownerOf(record.owner) }, record.creationKey));
1936
- }
1937
- /** Advance a Session's record; its creation key was reserved when it was created. */
1938
- advance(record) {
1939
- (this.#direct ? this.#durable : this.#staged).set(record.sessionId, record);
1940
- }
1941
- /** Promote the staged records to the durable catalog. */
1942
- accept() {
1943
- for (const [sessionId, record] of this.#staged) this.#durable.set(sessionId, record);
1944
- for (const identity of this.#stagedKeys) this.#durableKeys.add(identity);
1945
- for (const [id, terminal] of this.#stagedTasks) this.#tasks.set(id, terminal);
1946
- for (const [id, signal] of this.#stagedSignals) this.#signals.set(id, signal);
1947
- for (const [id, message] of this.#stagedMessages) this.#messages.set(id, message);
1948
- for (const id of this.#stagedSubmissions) this.#submissions.add(id);
1949
- this.discard();
1950
- }
1951
- /** Drop the staged records; the durable catalog keeps its state. */
1952
- discard() {
1953
- this.#staged.clear();
1954
- this.#stagedKeys.clear();
1955
- this.#stagedTasks.clear();
1956
- this.#stagedSignals.clear();
1957
- this.#stagedMessages.clear();
1958
- this.#stagedSubmissions.clear();
1959
- }
1960
- /** The owner of a Session; the unit root Session owns itself. */
1961
- ownerOf(owner) {
1962
- return owner === "ownerless" ? this.unitId : owner.session;
1963
- }
1964
- };
1965
- /**
1966
- * The unit state one batch is folded into.
1967
- *
1968
- * Validation folds a batch into a projection that stages everything the batch
1969
- * adds and leaves the committed prefix untouched. Application folds the same
1970
- * facts through the same rules, so a proven frame and an applied frame cannot
1971
- * disagree about what a fact means.
1972
- */
1973
- var UnitProjection = class {
1974
- #members;
1975
- #epochs;
1976
- #unitId;
1977
- #created;
1978
- #epoch;
1979
- constructor(options) {
1980
- this.#unitId = options.unitId;
1981
- this.#members = options.members;
1982
- this.#epochs = options.epochs;
1983
- this.#created = options.created;
1984
- this.#epoch = options.epoch;
1985
- }
1986
- get created() {
1987
- return this.#created;
1988
- }
1989
- get epoch() {
1990
- return this.#epoch;
1991
- }
1992
- /** Fold one record into the projection. */
1993
- fold(record) {
1994
- const entry = record.entry;
1995
- if (entry.scope === "session") this.#foldSessionFact(entry.fact);
1996
- else this.#foldUnitFact(record, entry.fact);
1997
- if (!this.#created) throw new UnitHistoryError("creation_missing", "Unit creation must precede all other facts");
1998
- if (entry.scope === "unit" && entry.fact.kind === "unit.created") return;
1999
- const epoch = this.#epoch;
2000
- if (epoch === void 0 || epoch.id !== record.epochId) throw new UnitHistoryError("epoch_missing", "Fact has no matching unit Epoch");
2001
- if (epoch.closed && !(entry.scope === "unit" && entry.fact.kind === "unit.epoch.closed")) throw new UnitHistoryError("epoch_closed", "Cannot append after the unit Epoch closed");
2002
- }
2003
- /** A Session fact advances the Session's own sequence by exactly one. */
2004
- #foldSessionFact(fact$1) {
2005
- const current = this.#requireSession(fact$1.sessionId);
2006
- if ((current.closed || current.closing) && ExecutionAdmissions.has(fact$1.kind)) throw new UnitHistoryError("session_closing", "Session no longer accepts execution or input");
2007
- if (fact$1.cursor !== fact$1.id) throw new UnitHistoryError("session_cursor_invalid", `Session cursor is invalid: ${fact$1.sessionId}`);
2008
- if (fact$1.sequence !== current.sequence + 1) throw new UnitHistoryError("session_sequence_invalid", `Session sequence is invalid: ${fact$1.sessionId}`);
2009
- if (fact$1.kind === "submission.accepted") {
2010
- this.#members.submission(fact$1.operationId);
2011
- const route = fact$1.payload.message;
2012
- if (route !== void 0 && (route.targetUnitId !== this.#unitId || route.targetSessionId !== fact$1.sessionId || route.messageId !== fact$1.operationId || route.messageId !== fact$1.payload.input.deliveryId)) throw new UnitHistoryError("message_invalid", "Inbox routing does not match its Submission");
2013
- }
2014
- this.#members.advance({
2015
- ...current,
2016
- sequence: fact$1.sequence
2017
- });
2018
- }
2019
- #foldUnitFact(record, fact$1) {
2020
- switch (fact$1.kind) {
2021
- case "unit.created":
2022
- if (this.#created || record.unitSequence !== 1 || fact$1.payload.rootSessionId !== this.#unitId) throw new UnitHistoryError("root_identity", "A unit has one immutable root identity");
2023
- this.#created = true;
2024
- return;
2025
- case "unit.epoch.started":
2026
- if (!this.#created || fact$1.payload.epochId !== record.epochId || this.#epochs.has(record.epochId) || this.#epoch?.id === record.epochId) throw new UnitHistoryError("epoch_reused", "Unit Epoch identity was reused or is inconsistent");
2027
- if (!isEqual(fact$1.payload.previousEpoch, this.#epoch ?? null)) throw new UnitHistoryError("epoch_predecessor", "Unit Epoch must describe its actual predecessor");
2028
- this.#epoch = {
2029
- id: record.epochId,
2030
- closed: false
2031
- };
2032
- this.#epochs.add(record.epochId);
2033
- return;
2034
- case "unit.epoch.closed": {
2035
- const epoch = this.#epoch;
2036
- if (epoch === void 0 || epoch.id !== fact$1.payload.epochId || epoch.closed) throw new UnitHistoryError("epoch_inactive", "Cannot close an inactive unit Epoch");
2037
- this.#epoch = {
2038
- id: epoch.id,
2039
- closed: true
2040
- };
2041
- return;
2042
- }
2043
- case "session.created":
2044
- this.#foldSessionCreated(fact$1);
2045
- return;
2046
- case "session.metadata.changed":
2047
- this.#requireSession(fact$1.payload.sessionId);
2048
- return;
2049
- case "session.closing":
2050
- case "session.closed": {
2051
- const current = this.#requireSession(fact$1.payload.sessionId);
2052
- if (fact$1.kind === "session.closing" && (current.closed || current.owner === "ownerless")) throw new UnitHistoryError("session_closing", "Only an open child can begin closing");
2053
- this.#members.stage({
2054
- ...current,
2055
- closing: fact$1.kind === "session.closing",
2056
- closed: current.closed || fact$1.kind === "session.closed"
2057
- });
2058
- return;
2059
- }
2060
- case "message.outbox.enqueued":
2061
- case "message.outbox.deferred":
2062
- case "message.outbox.acknowledged":
2063
- case "message.outbox.rejected":
2064
- this.#foldMessage(fact$1);
2065
- return;
2066
- default: this.#foldTaskFact(fact$1);
2067
- }
2068
- }
2069
- #foldMessage(fact$1) {
2070
- if (fact$1.kind === "message.outbox.enqueued") {
2071
- if (this.#members.message(fact$1.messageId) !== void 0) throw new UnitHistoryError("message_exists", "Outbox identity was reused");
2072
- const { owner, message, creationKey, replySignalId } = fact$1.payload;
2073
- if (TaskSessionOwnerValidator.check(owner)) {
2074
- if (this.#requireSession(owner.session).closed) throw new UnitHistoryError("parent_closed", "Outbox owner Session is closed");
2075
- } else this.#requireTask(owner.task);
2076
- if (message.sourceUnitId !== this.#unitId || message.targetUnitId === this.#unitId || message.messageId !== fact$1.messageId || message.input.deliveryId !== fact$1.messageId) throw new UnitHistoryError("message_invalid", "Outbox routing does not match its source unit");
2077
- if (message.replyTo !== void 0) {
2078
- if (message.replyTo.unitId !== this.#unitId || this.#requireSession(message.replyTo.sessionId).closed) throw new UnitHistoryError("message_invalid", "Reply address must be an open local Session");
2079
- }
2080
- if (replySignalId !== void 0) {
2081
- const signal = this.#members.signal(replySignalId);
2082
- if (TaskSessionOwnerValidator.check(owner) || signal?.taskId !== owner.task || message.replyTo === void 0) throw new UnitHistoryError("message_invalid", "Reply Signal must belong to the sending Task");
2083
- }
2084
- this.#members.reserveKey(owner, creationKey);
2085
- const { input: _input, whenBusy: _whenBusy,...routing } = message;
2086
- this.#members.stageMessage(fact$1.messageId, routing, false);
2087
- return;
2088
- }
2089
- const current = this.#members.message(fact$1.messageId);
2090
- if (current === void 0) throw new UnitHistoryError("message_unknown", "Outbox message does not exist");
2091
- if (current.terminal) throw new UnitHistoryError("message_settled", "Outbox message already ended");
2092
- if (fact$1.kind === "message.outbox.deferred") return;
2093
- const receipt = fact$1.payload;
2094
- const route = current.routing;
2095
- if (receipt.messageId !== fact$1.messageId || receipt.sourceUnitId !== route.sourceUnitId || receipt.targetUnitId !== route.targetUnitId || receipt.targetSessionId !== route.targetSessionId) throw new UnitHistoryError("message_invalid", "Outbox receipt does not match the sent message");
2096
- this.#members.stageMessage(fact$1.messageId, route, true);
2097
- }
2098
- #foldTaskFact(fact$1) {
2099
- switch (fact$1.kind) {
2100
- case "task.created":
2101
- case "task.imported": {
2102
- if (this.#members.taskTerminal(fact$1.taskId) !== void 0) throw new UnitHistoryError("task_exists", `Task already exists: ${fact$1.taskId}`);
2103
- const { owner, creationKey } = fact$1.payload;
2104
- if (TaskSessionOwnerValidator.check(owner)) {
2105
- const session = this.#requireSession(owner.session);
2106
- if ((session.closed || session.closing) && fact$1.kind !== "task.imported") throw new UnitHistoryError("parent_closed", "Task needs an open owner Session");
2107
- } else this.#requireTask(owner.task);
2108
- this.#members.reserveKey(owner, creationKey);
2109
- this.#members.stageTask(fact$1.taskId, fact$1.kind === "task.imported");
2110
- return;
2111
- }
2112
- case "signal.resolved":
2113
- case "signal.cancelled": {
2114
- const signal = this.#members.signal(fact$1.payload.signalId);
2115
- if (signal === void 0 || signal.taskId !== fact$1.taskId) throw new UnitHistoryError("signal_unknown", "Signal does not belong to this Task");
2116
- if (signal.settled) throw new UnitHistoryError("signal_settled", "Signal already has a terminal fact");
2117
- this.#members.stageSignal(fact$1.payload.signalId, fact$1.taskId, true);
2118
- return;
2119
- }
2120
- case "task.settled":
2121
- this.#requireTask(fact$1.taskId);
2122
- this.#members.stageTask(fact$1.taskId, true);
2123
- return;
2124
- case "signal.created": {
2125
- this.#requireTask(fact$1.taskId);
2126
- const { signalId, creationKey } = fact$1.payload;
2127
- if (this.#members.signal(signalId) !== void 0) throw new UnitHistoryError("signal_exists", `Signal already exists: ${signalId}`);
2128
- this.#members.reserveKey({ task: fact$1.taskId }, creationKey);
2129
- this.#members.stageSignal(signalId, fact$1.taskId, false);
2130
- return;
2131
- }
2132
- default: this.#requireTask(fact$1.taskId);
2133
- }
2134
- }
2135
- #requireTask(taskId) {
2136
- const terminal = this.#members.taskTerminal(taskId);
2137
- if (terminal === void 0) throw new UnitHistoryError("task_unknown", `Task is outside this unit: ${taskId}`);
2138
- if (terminal) throw new UnitHistoryError("task_terminal", `Task already ended: ${taskId}`);
2139
- }
2140
- /** A child Session joins an open parent of the same unit under a free creation key. */
2141
- #foldSessionCreated(fact$1) {
2142
- const payload = fact$1.payload;
2143
- if (this.#members.find(payload.sessionId) !== void 0) throw new UnitHistoryError("session_exists", `Session already exists: ${payload.sessionId}`);
2144
- const root = payload.owner === "ownerless";
2145
- if (root !== (payload.sessionId === this.#unitId)) throw new UnitHistoryError("owner_mismatch", "Only the unit root Session can be ownerless");
2146
- const ownerId = this.#members.ownerOf(payload.owner);
2147
- if (!root) {
2148
- const parent = this.#members.find(ownerId);
2149
- if (parent === void 0) throw new UnitHistoryError("parent_missing", "A child Session needs a parent Session in the same unit");
2150
- if (parent.closed || parent.closing) throw new UnitHistoryError("parent_closed", "A child Session needs an open parent in the same unit");
2151
- }
2152
- if (this.#members.keyTaken({ session: ownerId }, payload.creationKey)) throw new UnitHistoryError("creation_key_conflict", "Session creation key conflict");
2153
- this.#members.stage({
2154
- sessionId: payload.sessionId,
2155
- owner: payload.owner,
2156
- creationKey: payload.creationKey,
2157
- sequence: 0,
2158
- closing: false,
2159
- closed: false
2160
- });
2161
- }
2162
- #requireSession(sessionId) {
2163
- const current = this.#members.find(sessionId);
2164
- if (current === void 0) throw new UnitHistoryError("session_unknown", `Session is outside this unit: ${sessionId}`);
2165
- return current;
2166
- }
2167
- };
2168
- /** Retains identities, membership and positions; Session metadata and payloads stay in storage. */
2169
- var UnitHistory = class {
2170
- #members;
2171
- /** Fact identity → position: resolves cursors and rejects duplicate facts. */
2172
- #ids = new IdentityIndex();
2173
- #sessionPositions = /* @__PURE__ */ new Map();
2174
- /** Commit identities, indexed by frame ordinal. */
2175
- #commits = new IdentityIndex();
2176
- #frames = 0;
2177
- #epochs = /* @__PURE__ */ new Set();
2178
- #created = false;
2179
- #epoch;
2180
- #tail = 0;
2181
- constructor(unitId) {
2182
- this.unitId = unitId;
2183
- this.#members = new UnitMembership(unitId);
2184
- }
2185
- get tail() {
2186
- return this.#tail;
2187
- }
2188
- get epoch() {
2189
- return this.#epoch;
2190
- }
2191
- /**
2192
- * Prove a whole batch against the durable prefix without changing it.
2193
- *
2194
- * Order, identity, and scope are checked per record; the projection then
2195
- * applies the unit rules to staged membership and creation identities. A batch
2196
- * that fails leaves no trace of the facts it staged.
2197
- */
2198
- validate(records) {
2199
- const first = records[0];
2200
- if (first === void 0) throw new UnitHistoryError("empty_commit", "A unit commit must contain at least one fact");
2201
- if (this.#commits.has(first.commitId)) throw new UnitHistoryError("commit_reused", "Unit commit identity was reused");
2202
- const projection = this.#projection(new Set(this.#epochs));
2203
- const factIds = /* @__PURE__ */ new Set();
2204
- try {
2205
- for (const [offset, record] of records.entries()) {
2206
- this.#assertFrame(record, offset, first, factIds);
2207
- projection.fold(record);
2208
- }
2209
- } finally {
2210
- this.#members.discard();
2211
- }
2212
- }
2213
- /**
2214
- * Commit a proven batch to the durable prefix.
2215
- *
2216
- * The same projection rules run again over the durable Epoch set, so an
2217
- * applied frame cannot mean anything else than the validated frame did.
2218
- */
2219
- apply(records) {
2220
- const projection = this.#projection(this.#epochs);
2221
- this.#members.discard();
2222
- for (const record of records) {
2223
- projection.fold(record);
2224
- const position = this.#tail++;
2225
- this.#ids.set(record.entry.fact.id, position);
2226
- this.#track(record, position);
2227
- }
2228
- const first = records[0];
2229
- if (first !== void 0) this.#commits.set(first.commitId, this.#frames++);
2230
- this.#created = projection.created;
2231
- this.#epoch = projection.epoch;
2232
- this.#members.accept();
2233
- }
2234
- /** Opening builds an unpublished index; any failure discards the entire owner. */
2235
- restore(records) {
2236
- const first = records[0];
2237
- if (first === void 0) throw new UnitHistoryError("empty_commit", "A unit commit must contain at least one fact");
2238
- if (this.#commits.has(first.commitId)) throw new UnitHistoryError("commit_reused", "Unit commit identity was reused");
2239
- const projection = this.#projection(this.#epochs);
2240
- this.#members.restoring(() => {
2241
- for (const record of records) {
2242
- this.#assertFrame(record, 0, first);
2243
- projection.fold(record);
2244
- const position = this.#tail++;
2245
- this.#ids.set(record.entry.fact.id, position);
2246
- this.#track(record, position);
2247
- }
2248
- });
2249
- this.#commits.set(first.commitId, this.#frames++);
2250
- this.#created = projection.created;
2251
- this.#epoch = projection.epoch;
2252
- }
2253
- positions(options) {
2254
- const limit = decode(ReadLimitSchema, options.limit ?? JOURNAL_READ_DEFAULT_LIMIT);
2255
- let after = -1;
2256
- if (options.after !== void 0) {
2257
- const position = this.#ids.get(options.after);
2258
- if (position === void 0) throw new JournalCursorGapError(options.after);
2259
- after = position;
2260
- }
2261
- if (options.sessionId === void 0) {
2262
- const end = Math.min(this.#tail, after + 1 + limit);
2263
- return {
2264
- positions: Array.from({ length: end - after - 1 }, (_, i) => after + 1 + i),
2265
- hasMore: end < this.#tail
2266
- };
2267
- }
2268
- const positions = this.#sessionPositions.get(options.sessionId) ?? [];
2269
- const index = options.after === void 0 ? -1 : sortedIndexOf(positions, after);
2270
- if (options.after !== void 0 && index === -1) throw new JournalCursorGapError(options.after);
2271
- return {
2272
- positions: positions.slice(index + 1, index + 1 + limit),
2273
- hasMore: index + 1 + limit < positions.length
2274
- };
2275
- }
2276
- #projection(epochs) {
2277
- return new UnitProjection({
2278
- unitId: this.unitId,
2279
- members: this.#members,
2280
- epochs,
2281
- created: this.#created,
2282
- epoch: this.#epoch
2283
- });
2284
- }
2285
- /** Order, identity, and scope checks for one record of an atomic frame. */
2286
- #assertFrame(record, offset, first, factIds) {
2287
- if (record.unitId !== this.unitId) throw new UnitHistoryError("unit_mismatch", "Unit identity does not match its committed prefix");
2288
- if (record.unitSequence !== this.#tail + offset + 1) throw new UnitHistoryError("sequence_mismatch", "Unit sequence does not match its committed prefix");
2289
- if (record.commitId !== first.commitId || record.epochId !== first.epochId) throw new UnitHistoryError("frame_split", "An atomic frame must have one commit identity and Epoch");
2290
- const id = record.entry.fact.id;
2291
- if (this.#ids.has(id) || factIds?.has(id) === true) throw new UnitHistoryError("duplicate_fact", `Duplicate unit fact: ${id}`);
2292
- factIds?.add(id);
2293
- }
2294
- /** Track where a Session's facts live in the unit stream. */
2295
- #track(record, position) {
2296
- const entry = record.entry;
2297
- if (entry.scope === "session") {
2298
- this.#sessionPositions.get(entry.fact.sessionId)?.push(position);
2299
- return;
2300
- }
2301
- if (entry.fact.kind === "session.created") this.#sessionPositions.set(entry.fact.payload.sessionId, []);
2302
- }
2303
- };
2304
- function unitRecordCursor(record) {
2305
- return decode(JournalCursorSchema, record.entry.fact.id);
2306
- }
2307
- function assertUnitHistory(history, records) {
2308
- try {
2309
- history.restore(records);
2310
- } catch (cause) {
2311
- throw new UnitStoreError("unit_corrupt", "Unit frame violates its durable history", { cause });
2312
- }
2313
- }
2314
-
2315
- //#endregion
2316
- //#region src/journal/unit/opened.ts
2317
- var UnitStream = class {
2318
- #cursor;
2319
- #closed = false;
2320
- #failure;
2321
- #wake;
2322
- #nextPending = false;
2323
- #buffer = [];
2324
- constructor(store, options, remove) {
2325
- this.store = store;
2326
- this.options = options;
2327
- this.remove = remove;
2328
- this.#cursor = options.after;
2329
- }
2330
- notify() {
2331
- this.#wake?.();
2332
- this.#wake = void 0;
2333
- }
2334
- fail(error) {
2335
- this.#failure = error;
2336
- this.notify();
2337
- }
2338
- close() {
2339
- this.#closed = true;
2340
- this.remove();
2341
- this.notify();
2342
- }
2343
- [Symbol.asyncIterator]() {
2344
- return {
2345
- next: () => this.#next(),
2346
- return: async () => {
2347
- this.close();
2348
- return {
2349
- done: true,
2350
- value: void 0
2351
- };
2352
- }
2353
- };
2354
- }
2355
- async #next() {
2356
- if (this.#nextPending) throw new Error("Unit subscriptions do not support concurrent next()");
2357
- this.#nextPending = true;
2358
- try {
2359
- while (!this.#closed) {
2360
- if (this.#failure !== void 0) throw this.#failure;
2361
- const ready = this.#buffer.shift();
2362
- if (ready !== void 0) {
2363
- this.#cursor = unitRecordCursor(ready);
2364
- return {
2365
- done: false,
2366
- value: ready
2367
- };
2368
- }
2369
- const changed = new Promise((resolve) => {
2370
- this.#wake = resolve;
2371
- });
2372
- const page = await this.store.read({
2373
- sessionId: this.options.sessionId,
2374
- after: this.#cursor
2375
- });
2376
- this.#buffer.push(...page.records);
2377
- if (this.#buffer.length === 0 && !this.#closed) await changed;
2378
- }
2379
- return {
2380
- done: true,
2381
- value: void 0
2382
- };
2383
- } finally {
2384
- this.#nextPending = false;
2385
- }
2386
- }
2387
- };
2388
- var UnitHandle = class {
2389
- epochId = createId();
2390
- previousEpoch;
2391
- #storage;
2392
- #history;
2393
- #queue = Promise.resolve();
2394
- #closing;
2395
- #failure;
2396
- #subscribers = /* @__PURE__ */ new Set();
2397
- constructor(storage, history) {
2398
- this.#storage = storage;
2399
- this.#history = history;
2400
- this.previousEpoch = history.epoch;
2401
- }
2402
- get unitId() {
2403
- return this.#storage.unitId;
2404
- }
2405
- get durability() {
2406
- return this.#storage.durability;
2407
- }
2408
- get tail() {
2409
- return this.#history.tail;
2410
- }
2411
- commit(writes, options) {
2412
- try {
2413
- this.#assertOpen();
2414
- } catch (cause) {
2415
- return Promise.resolve({
2416
- status: "not-committed",
2417
- error: ensureError(cause)
2418
- });
2419
- }
2420
- const expected = options.expectedSequence;
2421
- return this.#serialize(async () => {
2422
- if (this.#failure !== void 0) return {
2423
- status: "not-committed",
2424
- error: this.#failure
2425
- };
2426
- if (expected !== this.tail) return {
2427
- status: "conflict",
2428
- error: this.#fail("Unit commit expected a different durable tail")
2429
- };
2430
- const commitId = createId();
2431
- const batch = writes.map(({ entry, json }, i) => ({
2432
- record: {
2433
- unitId: this.unitId,
2434
- unitSequence: this.tail + i + 1,
2435
- epochId: this.epochId,
2436
- commitId,
2437
- entry
2438
- },
2439
- json
2440
- }));
2441
- const records = batch.map(({ record }) => record);
2442
- try {
2443
- this.#history.validate(records);
2444
- } catch (cause) {
2445
- return {
2446
- status: "not-committed",
2447
- error: ensureError(cause)
2448
- };
2449
- }
2450
- let result;
2451
- try {
2452
- result = await this.#storage.append(batch);
2453
- } catch (cause) {
2454
- return {
2455
- status: "unknown",
2456
- error: this.#fail("Unit storage failed without a definite outcome", ensureError(cause))
2457
- };
2458
- }
2459
- if (result.status !== "committed") {
2460
- if (result.status !== "not-committed") this.#fail("Unit write outcome requires reopen", result.error);
2461
- return result;
2462
- }
2463
- try {
2464
- this.#history.apply(records);
2465
- } catch (cause) {
2466
- return {
2467
- status: "unknown",
2468
- error: this.#fail("Unit committed but its local index failed", ensureError(cause))
2469
- };
2470
- }
2471
- for (const stream of this.#subscribers) stream.notify();
2472
- return { status: "committed" };
2473
- });
2474
- }
2475
- read(options = {}) {
2476
- this.#assertOpen();
2477
- const { positions, hasMore } = this.#history.positions(options);
2478
- return this.#serialize(async () => {
2479
- const records = await this.#storage.read(positions);
2480
- const last = records.at(-1);
2481
- return {
2482
- records,
2483
- cursor: last === void 0 ? options.after : unitRecordCursor(last),
2484
- hasMore
2485
- };
2486
- });
2487
- }
2488
- subscribe(options = {}) {
2489
- this.#assertOpen();
2490
- this.#history.positions(options);
2491
- const stream = new UnitStream(this, { ...options }, () => this.#subscribers.delete(stream));
2492
- this.#subscribers.add(stream);
2493
- return stream;
2494
- }
2495
- rebuildIndexes() {
2496
- this.#assertOpen();
2497
- return this.#serialize(async () => {
2498
- const history = new UnitHistory(this.unitId);
2499
- await this.#storage.load((records) => assertUnitHistory(history, records));
2500
- this.#history = history;
2501
- });
2502
- }
2503
- close() {
2504
- this.#closing ??= this.#serialize(async () => {
2505
- for (const stream of [...this.#subscribers]) stream.close();
2506
- await this.#storage.close();
2507
- });
2508
- return this.#closing;
2509
- }
2510
- #serialize(action) {
2511
- const work = this.#queue.then(action);
2512
- this.#queue = work.then(() => {}, () => {});
2513
- return work;
2514
- }
2515
- #assertOpen() {
2516
- if (this.#failure !== void 0) throw this.#failure;
2517
- if (this.#closing !== void 0) throw new UnitStoreError("unit_closed", "Unit store is closed");
2518
- }
2519
- #fail(message, cause) {
2520
- this.#failure = new UnitStoreError("unit_failed", message, { cause });
2521
- for (const stream of this.#subscribers) stream.fail(this.#failure);
2522
- return this.#failure;
2523
- }
2524
- };
2525
- /** Opens a backend as a Unit writer. A failed open closes the backend. */
2526
- async function openUnitStorage(storage, options = {}) {
2527
- try {
2528
- const history = new UnitHistory(storage.unitId);
2529
- await storage.load((records) => {
2530
- assertUnitHistory(history, records);
2531
- options.replay?.(records);
2532
- });
2533
- return new UnitHandle(storage, history);
2534
- } catch (cause) {
2535
- await storage.close();
2536
- throw cause;
2537
- }
2538
- }
2539
-
2540
- //#endregion
2541
- //#region src/journal/offloaded-fact.ts
2542
- const PathSegmentSchema = s.union([s.str(), s.int({ minimum: 0 })]);
2543
- const PersistedStringEnvelopeSchema = s.obj({
2544
- storageVersion: s.lit(1),
2545
- fact: JsonValueSchema,
2546
- strings: s.arr(s.obj({
2547
- path: s.arr(PathSegmentSchema),
2548
- ref: ArtifactRefSchema
2549
- }, { open: false }), { minItems: 1 })
2550
- }, { open: false });
2551
- const PersistedPayloadEnvelopeSchema = s.obj({
2552
- storageVersion: s.lit(2),
2553
- fact: s.map(JsonValueSchema),
2554
- payload: ArtifactRefSchema
2555
- }, { open: false });
2556
- const PersistedJournalEnvelopeSchema = s.union([PersistedStringEnvelopeSchema, PersistedPayloadEnvelopeSchema]);
2557
- const PersistedJournalEnvelopeValidator = compile(PersistedJournalEnvelopeSchema);
2558
- const JsonValueValidator = compile(JsonValueSchema);
2559
- /**
2560
- * Bounded least-recently-used memory of published payload strings. One Tool result is
2561
- * recorded as several facts (Effect, Signal, Task settlement), so the same body would
2562
- * otherwise be published as a separate Artifact for every fact that mentions it.
2563
- */
2564
- var ExternalizedStringReuse = class {
2565
- #refs = /* @__PURE__ */ new Map();
2566
- #bytes = 0;
2567
- constructor(maxBytes = 4 * 1024 * 1024) {
2568
- this.maxBytes = maxBytes;
2569
- }
2570
- take(text) {
2571
- const ref = this.#refs.get(text);
2572
- if (ref === void 0) return void 0;
2573
- this.#refs.delete(text);
2574
- this.#refs.set(text, ref);
2575
- return ref;
2576
- }
2577
- remember(text, ref) {
2578
- if (this.#refs.get(text) !== void 0) {
2579
- this.#refs.delete(text);
2580
- this.#bytes -= utf8ByteLength(text);
2581
- }
2582
- this.#refs.set(text, ref);
2583
- this.#bytes += utf8ByteLength(text);
2584
- while (this.#bytes > this.maxBytes) {
2585
- const oldest = this.#refs.keys().next();
2586
- if (oldest.done === true) break;
2587
- this.#refs.delete(oldest.value);
2588
- this.#bytes -= utf8ByteLength(oldest.value);
2589
- }
2590
- }
2591
- };
2592
- function encodeJournalFact(fact$1, store, inlineStringBytes, reuse) {
2593
- const candidates = [];
2594
- const encoded = {
2595
- ...fact$1,
2596
- payload: externalizeStrings(fact$1.payload ?? null, ["payload"], candidates, inlineStringBytes)
2597
- };
2598
- if (candidates.length === 0) return encoded;
2599
- return persistEnvelope(encoded, candidates, store, reuse);
2600
- }
2601
- async function persistEnvelope(fact$1, candidates, store, reuse) {
2602
- const strings = [];
2603
- for (const candidate of candidates) {
2604
- const ref = reuse?.take(candidate.text) ?? (store.putText === void 0 ? await store.put(new TextEncoder().encode(candidate.text)) : await store.putText([candidate.text]));
2605
- reuse?.remember(candidate.text, ref);
2606
- strings.push({
2607
- path: [...candidate.path],
2608
- ref
2609
- });
2610
- }
2611
- return {
2612
- storageVersion: 1,
2613
- fact: fact$1,
2614
- strings
2615
- };
2616
- }
2617
- async function encodeJournalPayload(fact$1, store) {
2618
- const text = JSON.stringify(fact$1.payload ?? null);
2619
- const ref = store.putText === void 0 ? await store.put(new TextEncoder().encode(text)) : await store.putText([text]);
2620
- return {
2621
- storageVersion: 2,
2622
- fact: {
2623
- ...fact$1,
2624
- payload: null
2625
- },
2626
- payload: ref
2627
- };
2628
- }
2629
- function decodeJournalEnvelope(value, store) {
2630
- if (!PersistedJournalEnvelopeValidator.check(value)) return value;
2631
- return decodePersistedEnvelope(value, store);
2632
- }
2633
- async function decodePersistedEnvelope(value, store) {
2634
- if (store === void 0) throw new Error("Journal contains externalized data but no Artifact Store was provided");
2635
- if (value.storageVersion === 2) {
2636
- if (value.fact.payload !== null) throw new Error("Journal payload reference does not point to a placeholder");
2637
- const decoded = JSON.parse(await readString(store, value.payload));
2638
- const payload = JsonValueValidator.check(decoded) ? decoded : decode(JsonValueSchema, decoded);
2639
- return {
2640
- ...value.fact,
2641
- payload
2642
- };
2643
- }
2644
- let fact$1 = value.fact;
2645
- for (const entry of value.strings) {
2646
- const replacement = await readString(store, entry.ref);
2647
- fact$1 = replacePlaceholder(fact$1, entry.path, replacement);
2648
- }
2649
- return fact$1;
2650
- }
2651
- function externalizeStrings(value, path, candidates, inlineStringBytes) {
2652
- if (isString(value)) {
2653
- if (utf8ByteLength(value) < inlineStringBytes) return value;
2654
- candidates.push({
2655
- path: [...path],
2656
- text: value
2657
- });
2658
- return null;
2659
- }
2660
- if (Array.isArray(value)) return value.map((entry, index) => externalizeStrings(entry, [...path, index], candidates, inlineStringBytes));
2661
- if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([key$1, entry]) => [key$1, externalizeStrings(entry, [...path, key$1], candidates, inlineStringBytes)]));
2662
- return value;
2663
- }
2664
- async function readString(store, ref) {
2665
- const bytes = await store.read(ref);
2666
- if (bytes === void 0) throw new Error(`Journal artifact ${ref.id} is missing`);
2667
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2668
- }
2669
- function replacePlaceholder(value, path, replacement) {
2670
- const [segment, ...remaining] = path;
2671
- if (segment === void 0) {
2672
- if (value !== null) throw new Error("Journal string reference does not point to a placeholder");
2673
- return replacement;
2674
- }
2675
- if (isNumber(segment)) {
2676
- if (!Array.isArray(value) || segment >= value.length) throw new Error("Journal string reference has an invalid array path");
2677
- return value.map((entry, index) => index === segment ? replacePlaceholder(entry, remaining, replacement) : entry);
2678
- }
2679
- if (!isPlainObject(value) || !Object.keys(value).includes(segment)) throw new Error("Journal string reference has an invalid object path");
2680
- return Object.fromEntries(Object.entries(value).map(([key$1, entry]) => [key$1, key$1 === segment ? replacePlaceholder(entry, remaining, replacement) : entry]));
2681
- }
2682
-
2683
- //#endregion
2684
- //#region src/observation/invoke.ts
2685
- /** Isolates host callbacks, including async functions accidentally assigned to a void callback. */
2686
- function observeRuntime(report) {
2687
- try {
2688
- const pending = report();
2689
- if (isPromise(pending)) pending.catch(() => {});
2690
- } catch {}
2691
- }
2692
- const TraceContextSchema = s.obj({
2693
- traceparent: s.str({ pattern: "^00-(?!0{32}-)[0-9a-f]{32}-(?!0{16}-)[0-9a-f]{16}-[0-9a-f]{2}$" }),
2694
- tracestate: s.opt(s.str({ maxLength: 512 }))
2695
- }, { open: true });
2696
- /** Tracing is not authority; adapter failures must not affect dispatch. */
2697
- function readObservationTraceContext(port, identity) {
2698
- if (port === void 0) return;
2699
- try {
2700
- const value = port.traceContext?.(identity);
2701
- if (value === void 0 || !check(TraceContextSchema, value)) return;
2702
- return {
2703
- traceparent: value.traceparent,
2704
- tracestate: value.tracestate
2705
- };
2706
- } catch {
2707
- return;
2708
- }
2709
- }
2710
-
2711
- //#endregion
2712
- export { AppendPluginRecordSchema as $, JOURNAL_APPEND_BATCH_MAX_BYTES as A, JournalStoreFaultError as B, JournalCorruptionError as C, CompleteModelInputSchema as D, JournalWriterBusyError as E, JournalConflictError as F, SessionForkedPayloadSchema as G, RunFailureCodeSchema as H, JournalCursorGapError as I, SubmissionInputSchema as J, SessionInputSourceSchema as K, JournalCursorSchema as L, JOURNAL_FACT_SCHEMA_VERSION as M, JOURNAL_READ_DEFAULT_LIMIT as N, CompletedToolResultSchema as O, JOURNAL_READ_MAX_LIMIT as P, isDurableSubmissionFactKind as Q, JournalFactDefinitions as R, createId as S, utf8ByteLength as St, JournalReaderResetRequiredError as T, SendSessionInputSchema as U, NewJournalFactSchema as V, SendSessionInputVariants as W, ToolOutputArchiveRecordSchema as X, ToolHookEvidenceSchema as Y, UserPromptSchema as Z, TaskCheckpointSchema as _, resolveApproval as _t, decodeJournalEnvelope as a, evaluateToolPermissionPolicy as at, TaskSessionOwnerSchema as b, JsonValueSchema as bt, openUnitStorage as c, SessionPermissionGrantSchema as ct, unitRecordCursor as d, ToolPermissionDirectiveSchema as dt, PluginRecordConflictError as et, UnitFactSchema as f, ToolPermissionPolicyEntrySchema as ft, UnitMessageSchema as g, ApprovalReviewerDecisionSchema as gt, MessageFactSchema as h, MessageDeliveryResultSchema as ht, PersistedJournalEnvelopeSchema as i, PermissionGrantNotFoundError as it, JOURNAL_APPEND_BATCH_MAX_FACTS as j, ContextForkSeedSchema as k, UnitHistory as l, ToolApprovalRequirementSchema as lt, UnitStoreError as m, ToolPermissionRuleSchema as mt, readObservationTraceContext as n, PluginRecordOwnerSchema as nt, encodeJournalFact as o, PermissionGrantSchema as ot, UnitHistoryError as p, ToolPermissionPolicySchema as pt, SubmissionControlInputSchema as q, ExternalizedStringReuse as r, samePluginRecord as rt, encodeJournalPayload as s, PermissionScalarSchema as st, observeRuntime as t, PluginRecordHistory as tt, assertUnitHistory as u, ToolPermissionAccessSchema as ut, TaskFactSchema as v, ApprovalModeSchema as vt, JournalReaderCapacityError as w, TaskWaitMemberVariants as x, captureJsonValue as xt, TaskOwnerSchema as y, ApprovalReviewDecisionSchema as yt, JournalFactSchema as z };
2713
- //# sourceMappingURL=observation-DyvvxD35.js.map