@sorbetai/runtime 0.0.0-stage → 0.1.0-alpha.16

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.
@@ -0,0 +1,4230 @@
1
+ import { $ as UnitReader, $t as JsonValueSchema, A as ToolExecutionObservation, At as JournalWrite, B as openUnitStorage, Bt as SessionForkedPayload, C as RunAdmittedObservation, Ct as JournalPage, D as RunSettledObservation, Dt as JournalStoreFaultError, E as RunResourceWaitObservation, Et as JournalStore, F as WaitIdentityObservation, Ft as RunFailureCodeSchema, G as UnitFact, Gt as SubmissionControlInputSchema, H as UnitCommitOutcome, Ht as SessionInputSourceSchema, I as WaitSettledObservation, It as RunJournalFact, J as UnitHistoryErrorCode, Jt as ToolOutputArchiveRecord, K as UnitFactSchema, Kt as SubmissionInputSchema, L as WaitStartedObservation, Lt as RunJournalFactKind, M as ToolOutputMeasurement, Mt as ModelRequestContextSnapshot, N as ToolOutputObservation, Nt as NewJournalFact, O as RuntimeObservationPort, Ot as JournalSubscription, P as ToolPermissionObservation, Pt as RunFailureCode, Q as UnitReadOptions, Qt as JsonValue, R as UnitStorage, Rt as SendSessionInputSchema, S as ObservationTraceContext, St as JournalFactSchema, T as RunExecutionObservation, Tt as JournalReadOptions, U as UnitEntry, Ut as SessionJournalFact, V as OpenedUnitStore, Vt as SessionInputSource, W as UnitEpoch, Wt as SessionJournalFactKind, X as UnitOpenOptions, Xt as ToolResultMessageCommittedPayload, Y as UnitInspectionPage, Yt as ToolOutputArchiveRecordSchema, Z as UnitPage, Zt as UserPromptSchema, _ as ModelDispatchObservation, _t as JournalCursor, a as CompactionSourceFallbackObservation, at as JournalRecoveryFact, b as ModelRetryWaitObservation, bt as JournalFact, c as ContextCapacityObservation, ct as JournalReaderResetRequiredError, d as EffectObservation, dt as CompletedToolResultSchema, et as UnitRecord, f as JournalBatchObservation, ft as ContextForkSeedSchema, g as ModelAttemptObservation, gt as JournalConflictError, h as JournalReopenObservation, ht as JournalAppendOptions, i as CompactionProviderObservation, it as UnitWrite, j as ToolExecutionStartedObservation, jt as ModelRequestBaseCommittedPayload, k as SessionRecoveryObservation, kt as JournalSubscriptionOptions, l as ContextPreparationObservation, lt as JournalWriterBusyError, m as JournalQueueObservation, mt as JOURNAL_FACT_SCHEMA_VERSION, n as CompactionModelObservation, nt as UnitStoreError, o as ContextAttributionObservation, ot as JournalCorruptionError, p as JournalProjectionObservation, pt as EffectUnknownPayload, q as UnitHistoryError, qt as ToolHookEvidenceSchema, r as CompactionObservation, rt as UnitSubscription, s as ContextAttributionSection, st as JournalReaderCapacityError, t as ApprovalReviewObservation, tt as UnitStore, u as ContextSectionEstimate, ut as CompleteModelInputSchema, v as ModelProviderObservation, vt as JournalCursorGapError, w as RunDrainObservation, wt as JournalPayloadMap, x as ModelUnknownObservation, xt as JournalFactKind, y as ModelRetryObservation, yt as JournalCursorSchema, z as UnitStorageWrite, zt as SendSessionInputVariants } from "./contracts-CFmBr0LI.js";
2
+ import * as s from "@earendil-works/pi-schema";
3
+ import * as _sorbetai_schema30 from "@sorbetai/schema";
4
+ import * as _sorbetai_context56 from "@sorbetai/context";
5
+ import { AssistantMessage, ContextHistorySnapshot, ContextManager, ContextModelView, ContextProvenance, ContextSnapshot, ContextSource, ContextTransitionFrame, ImageContent, JsonValue as JsonValue$1, Message, ModelContext, NamedStateOwner, PrefixContextContributor, PrefixContextSource, ReadonlyJsonValue, RequestContextSource, TextContent, ToolCall, ToolDeclaration, ToolResultMessage, TurnContextSource, Usage, UserMessage } from "@sorbetai/context";
6
+ import { ModelToolLease, ModelToolSource, ModelView, ObjectCapabilityOptions, PluginToolResultSnapshot, SessionBehaviorCommand, SessionBehaviorView, UsageTotals } from "@sorbetai/plugins/model";
7
+ import { ArtifactRef, ArtifactStore } from "@sorbetai/artifacts";
8
+ import * as Context from "effect/Context";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Layer from "effect/Layer";
11
+ import * as Scope from "effect/Scope";
12
+
13
+ //#region src/approvals/contracts.d.ts
14
+ declare const ApprovalModeSchema: s.Schema<"human" | "auto">;
15
+ type ApprovalMode = s.Static<typeof ApprovalModeSchema>;
16
+ declare const ApprovalReviewDecisionSchema: s.Schema<{
17
+ outcome: "allowed-once";
18
+ remember?: "session" | "session-full-access" | undefined;
19
+ } | {
20
+ outcome: "rejected";
21
+ reason: string;
22
+ }>;
23
+ declare const ApprovalRequestRecordSchema: s.Schema<{
24
+ approvalRequestId: string;
25
+ toolCallId: string;
26
+ toolName: string;
27
+ reason: string;
28
+ parameters: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
29
+ taskId?: string | undefined;
30
+ parentToolCallId?: string | undefined;
31
+ }>;
32
+ type ApprovalReviewDecision = Readonly<s.Static<typeof ApprovalReviewDecisionSchema>>;
33
+ type ApprovalReviewRequest = Readonly<s.Static<typeof ApprovalRequestRecordSchema>>;
34
+ type ApprovalResolver = (request: ApprovalReviewRequest, signal?: AbortSignal) => Promise<ApprovalReviewDecision>;
35
+ interface ApprovalComposition {
36
+ readonly resolve: ApprovalResolver;
37
+ }
38
+ //#endregion
39
+ //#region src/approvals/reviewer.d.ts
40
+ declare const ApprovalReviewerDecisionSchema: s.Schema<{
41
+ outcome: "allow" | "ask";
42
+ reason: string;
43
+ }>;
44
+ type ApprovalReviewerDecision = Readonly<s.Static<typeof ApprovalReviewerDecisionSchema>>;
45
+ /**
46
+ * Supplies one model completion with no Tools or retries. Runtime snapshots the
47
+ * returned configuration for one Review and owns validation, timeout, durable
48
+ * settlement, cancellation, and Host fallback.
49
+ */
50
+ interface ApprovalReviewer {
51
+ readonly model: {
52
+ readonly provider: string;
53
+ readonly id: string;
54
+ readonly contextWindow: number;
55
+ };
56
+ readonly maxOutputTokens?: number;
57
+ /**
58
+ * Host policy for how long one Review may run. Absent means no deadline: the
59
+ * review waits for the completion or for the request to abort.
60
+ */
61
+ readonly timeoutMs?: number;
62
+ /** Conservatively bounds retained UTF-8 bytes and the request input allocation; oversized actions fall back to human approval. */
63
+ readonly maxContextTokens?: number;
64
+ /** Host-owned execution facts, never credentials or model-authored assertions. */
65
+ readonly environment?: JsonValue;
66
+ /** Host safety gate. A false result falls back to Host approval without calling the model. */
67
+ readonly canReview?: (request: {
68
+ readonly toolName: string;
69
+ }) => boolean;
70
+ readonly complete: (request: {
71
+ readonly context: ModelContext;
72
+ readonly signal: AbortSignal;
73
+ readonly maxTokens: number;
74
+ readonly sessionId: string;
75
+ }) => Promise<AssistantMessage>;
76
+ }
77
+ //#endregion
78
+ //#region src/elicitations/contracts.d.ts
79
+ declare const ElicitationPropertySchema: s.Schema<{
80
+ type: "string";
81
+ minLength?: number | undefined;
82
+ maxLength?: number | undefined;
83
+ format?: "email" | "uri" | "date" | "date-time" | undefined;
84
+ pattern?: string | undefined;
85
+ default?: string | undefined;
86
+ enum?: string[] | undefined;
87
+ oneOf?: {
88
+ const: string;
89
+ title: string;
90
+ description?: string | undefined;
91
+ }[] | undefined;
92
+ title?: string | undefined;
93
+ description?: string | undefined;
94
+ _meta?: Record<string, unknown> | undefined;
95
+ } | {
96
+ type: "number";
97
+ minimum?: number | undefined;
98
+ maximum?: number | undefined;
99
+ default?: number | undefined;
100
+ title?: string | undefined;
101
+ description?: string | undefined;
102
+ _meta?: Record<string, unknown> | undefined;
103
+ } | {
104
+ type: "integer";
105
+ minimum?: number | undefined;
106
+ maximum?: number | undefined;
107
+ default?: number | undefined;
108
+ title?: string | undefined;
109
+ description?: string | undefined;
110
+ _meta?: Record<string, unknown> | undefined;
111
+ } | {
112
+ type: "boolean";
113
+ default?: boolean | undefined;
114
+ title?: string | undefined;
115
+ description?: string | undefined;
116
+ _meta?: Record<string, unknown> | undefined;
117
+ } | {
118
+ items: {
119
+ type: "string";
120
+ enum: string[];
121
+ } | {
122
+ anyOf: {
123
+ const: string;
124
+ title: string;
125
+ description?: string | undefined;
126
+ }[];
127
+ };
128
+ type: "array";
129
+ minItems?: number | undefined;
130
+ maxItems?: number | undefined;
131
+ default?: string[] | undefined;
132
+ title?: string | undefined;
133
+ description?: string | undefined;
134
+ _meta?: Record<string, unknown> | undefined;
135
+ }>;
136
+ declare const ElicitationFormSchema: s.Schema<{
137
+ properties: Record<string, {
138
+ type: "string";
139
+ minLength?: number | undefined;
140
+ maxLength?: number | undefined;
141
+ format?: "email" | "uri" | "date" | "date-time" | undefined;
142
+ pattern?: string | undefined;
143
+ default?: string | undefined;
144
+ enum?: string[] | undefined;
145
+ oneOf?: {
146
+ const: string;
147
+ title: string;
148
+ description?: string | undefined;
149
+ }[] | undefined;
150
+ title?: string | undefined;
151
+ description?: string | undefined;
152
+ _meta?: Record<string, unknown> | undefined;
153
+ } | {
154
+ type: "number";
155
+ minimum?: number | undefined;
156
+ maximum?: number | undefined;
157
+ default?: number | undefined;
158
+ title?: string | undefined;
159
+ description?: string | undefined;
160
+ _meta?: Record<string, unknown> | undefined;
161
+ } | {
162
+ type: "integer";
163
+ minimum?: number | undefined;
164
+ maximum?: number | undefined;
165
+ default?: number | undefined;
166
+ title?: string | undefined;
167
+ description?: string | undefined;
168
+ _meta?: Record<string, unknown> | undefined;
169
+ } | {
170
+ type: "boolean";
171
+ default?: boolean | undefined;
172
+ title?: string | undefined;
173
+ description?: string | undefined;
174
+ _meta?: Record<string, unknown> | undefined;
175
+ } | {
176
+ items: {
177
+ type: "string";
178
+ enum: string[];
179
+ } | {
180
+ anyOf: {
181
+ const: string;
182
+ title: string;
183
+ description?: string | undefined;
184
+ }[];
185
+ };
186
+ type: "array";
187
+ minItems?: number | undefined;
188
+ maxItems?: number | undefined;
189
+ default?: string[] | undefined;
190
+ title?: string | undefined;
191
+ description?: string | undefined;
192
+ _meta?: Record<string, unknown> | undefined;
193
+ }>;
194
+ type?: "object" | undefined;
195
+ title?: string | undefined;
196
+ description?: string | undefined;
197
+ required?: string[] | undefined;
198
+ }>;
199
+ declare const ElicitationRequestSchema: s.Schema<{
200
+ mode: "form";
201
+ message: string;
202
+ requestedSchema: {
203
+ properties: Record<string, {
204
+ type: "string";
205
+ minLength?: number | undefined;
206
+ maxLength?: number | undefined;
207
+ format?: "email" | "uri" | "date" | "date-time" | undefined;
208
+ pattern?: string | undefined;
209
+ default?: string | undefined;
210
+ enum?: string[] | undefined;
211
+ oneOf?: {
212
+ const: string;
213
+ title: string;
214
+ description?: string | undefined;
215
+ }[] | undefined;
216
+ title?: string | undefined;
217
+ description?: string | undefined;
218
+ _meta?: Record<string, unknown> | undefined;
219
+ } | {
220
+ type: "number";
221
+ minimum?: number | undefined;
222
+ maximum?: number | undefined;
223
+ default?: number | undefined;
224
+ title?: string | undefined;
225
+ description?: string | undefined;
226
+ _meta?: Record<string, unknown> | undefined;
227
+ } | {
228
+ type: "integer";
229
+ minimum?: number | undefined;
230
+ maximum?: number | undefined;
231
+ default?: number | undefined;
232
+ title?: string | undefined;
233
+ description?: string | undefined;
234
+ _meta?: Record<string, unknown> | undefined;
235
+ } | {
236
+ type: "boolean";
237
+ default?: boolean | undefined;
238
+ title?: string | undefined;
239
+ description?: string | undefined;
240
+ _meta?: Record<string, unknown> | undefined;
241
+ } | {
242
+ items: {
243
+ type: "string";
244
+ enum: string[];
245
+ } | {
246
+ anyOf: {
247
+ const: string;
248
+ title: string;
249
+ description?: string | undefined;
250
+ }[];
251
+ };
252
+ type: "array";
253
+ minItems?: number | undefined;
254
+ maxItems?: number | undefined;
255
+ default?: string[] | undefined;
256
+ title?: string | undefined;
257
+ description?: string | undefined;
258
+ _meta?: Record<string, unknown> | undefined;
259
+ }>;
260
+ type?: "object" | undefined;
261
+ title?: string | undefined;
262
+ description?: string | undefined;
263
+ required?: string[] | undefined;
264
+ };
265
+ } | {
266
+ mode: "url";
267
+ elicitationId: string;
268
+ url: string;
269
+ message: string;
270
+ }>;
271
+ declare const ElicitationContentValueSchema: s.Schema<string | number | boolean | string[]>;
272
+ declare const ElicitationResponseSchema: s.Schema<{
273
+ action: "accept";
274
+ content?: Record<string, string | number | boolean | string[]> | undefined;
275
+ } | {
276
+ action: "decline";
277
+ } | {
278
+ action: "cancel";
279
+ }>;
280
+ declare const ElicitationCapabilitiesSchema: s.Schema<{
281
+ form: boolean;
282
+ url: boolean;
283
+ }>;
284
+ type ElicitationProperty = Readonly<s.Static<typeof ElicitationPropertySchema>>;
285
+ type ElicitationForm = Readonly<s.Static<typeof ElicitationFormSchema>>;
286
+ type ElicitationRequest = Readonly<s.Static<typeof ElicitationRequestSchema>>;
287
+ type ElicitationContentValue = s.Static<typeof ElicitationContentValueSchema>;
288
+ type ElicitationResponse = Readonly<s.Static<typeof ElicitationResponseSchema>>;
289
+ type ElicitationCapabilities = Readonly<s.Static<typeof ElicitationCapabilitiesSchema>>;
290
+ interface ElicitationInvocationContext {
291
+ readonly toolCallId?: string;
292
+ }
293
+ interface ElicitationComposition {
294
+ readonly capabilities: ElicitationCapabilities;
295
+ create(request: ElicitationRequest, context?: ElicitationInvocationContext, signal?: AbortSignal): Promise<ElicitationResponse>;
296
+ complete(elicitationId: string): Promise<void>;
297
+ }
298
+ declare class ElicitationUnavailableError extends Error {
299
+ readonly mode: ElicitationRequest['mode'];
300
+ constructor(mode: ElicitationRequest['mode']);
301
+ }
302
+ //#endregion
303
+ //#region src/elicitations/resolution.d.ts
304
+ declare function requestElicitation(request: ElicitationRequest, boundary: ElicitationComposition, context?: ElicitationInvocationContext, signal?: AbortSignal): Promise<ElicitationResponse>;
305
+ //#endregion
306
+ //#region src/journal/model-request-evidence.d.ts
307
+ type ModelRequestBaseFact = Extract<JournalFact, {
308
+ kind: 'model.request.base.committed';
309
+ }>;
310
+ /** Projects the bindings owner’s Prefix declarations into Runtime-attributed Context sources. */
311
+ declare function pluginPrefixSources(bindings: ModelView | null): PrefixContextSource[];
312
+ declare function prepareModelRequestBase(requestBaseId: string, snapshot: ContextSnapshot, tools: readonly ToolDeclaration[], toolBindings?: Readonly<ModelRequestBaseCommittedPayload['toolBindings']>, pluginBindings?: ModelView | null): ModelRequestBaseCommittedPayload;
313
+ /** The earlier request a snapshot may reference for states it did not repeat. */
314
+ interface NamedStateReuseSource {
315
+ readonly modelRequestId: string;
316
+ readonly namedStates: ModelRequestContextSnapshot['namedStates'];
317
+ }
318
+ /**
319
+ * Records only the states whose committed entry changed. A later request repeating a state
320
+ * byte for byte would otherwise re-serialize the whole state set on every model call, which is
321
+ * the one part of request evidence that grows with conversation length.
322
+ */
323
+ declare function compactModelRequestContextSnapshot(snapshot: ContextSnapshot, previous?: NamedStateReuseSource): ModelRequestContextSnapshot;
324
+ /**
325
+ * Restores the states a request reused. Frames are keyed by identity, so a snapshot that omits
326
+ * unchanged states yields the same transitions as the full one; this expansion exists for read
327
+ * models that present the request as it was dispatched.
328
+ */
329
+ declare function expandModelRequestContextSnapshot(snapshot: ModelRequestContextSnapshot, lookup: (modelRequestId: string) => ModelRequestContextSnapshot | undefined): ModelRequestContextSnapshot;
330
+ declare function materializeModelRequestContextSnapshot(base: ModelRequestBaseFact, snapshot: ModelRequestContextSnapshot, _logicalModelCallId?: string): ContextSnapshot;
331
+ //#endregion
332
+ //#region src/journal/tool-result-evidence.d.ts
333
+ type EffectTerminalFact = Extract<JournalFact, {
334
+ kind: 'effect.succeeded' | 'effect.failed' | 'effect.unknown';
335
+ }>;
336
+ declare function projectToolResultObservations(facts: readonly JournalFact[], sessionId: string): PluginToolResultSnapshot;
337
+ /** Diagnostic feedback is derived from uncertainty, never interpreted as a completed effect. */
338
+ declare function projectUnknownEffectResult(effectAttemptId: string, reason: string, recovery?: 'unsafe' | 'safe'): NonNullable<EffectUnknownPayload['feedback']> & {
339
+ details: {
340
+ effectOutcome: 'unknown';
341
+ effectAttemptId: string;
342
+ reason: string;
343
+ recovery: 'unsafe' | 'safe';
344
+ };
345
+ isError: true;
346
+ };
347
+ //#endregion
348
+ //#region src/journal/plugin-record.d.ts
349
+ declare const PluginRecordOwnerSchema: s.Schema<{
350
+ entryId: string;
351
+ activationId?: string | undefined;
352
+ }>;
353
+ declare const AppendPluginRecordSchema: s.Schema<{
354
+ recordType: string;
355
+ recordVersion: number;
356
+ data: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
357
+ expectedRevision: number;
358
+ sourceSequence: number;
359
+ idempotencyKey?: string | undefined;
360
+ }>;
361
+ declare const PluginRecordPayloadSchema: s.Schema<{
362
+ owner: {
363
+ entryId: string;
364
+ activationId?: string | undefined;
365
+ };
366
+ revision: number;
367
+ data: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
368
+ sourceSequence: number;
369
+ recordType: string;
370
+ recordVersion: number;
371
+ idempotencyKey?: string | undefined;
372
+ }>;
373
+ type PluginRecordOwner = s.Static<typeof PluginRecordOwnerSchema>;
374
+ type AppendPluginRecord = s.Static<typeof AppendPluginRecordSchema>;
375
+ type PluginRecordPayload = s.Static<typeof PluginRecordPayloadSchema>;
376
+ declare class PluginRecordConflictError extends Error {
377
+ readonly expectedRevision: number;
378
+ readonly actualRevision: number;
379
+ readonly code = "plugin_record_conflict";
380
+ constructor(expectedRevision: number, actualRevision: number);
381
+ }
382
+ //#endregion
383
+ //#region src/journal/tool-operations.d.ts
384
+ type ExternalToolFact = Extract<SessionJournalFact, {
385
+ kind: `tool.operation.${string}`;
386
+ }>;
387
+ type Accepted$1 = Extract<ExternalToolFact, {
388
+ kind: 'tool.operation.accepted';
389
+ }>;
390
+ /** Recovery view of one external Tool operation; the Journal stays the record. */
391
+ interface ExternalToolOperation {
392
+ readonly accepted: Accepted$1;
393
+ permission?: 'allowed' | 'denied';
394
+ permissionFailed?: boolean;
395
+ approvalId?: string;
396
+ approvalSettled?: boolean;
397
+ effect?: string;
398
+ effectSettled: boolean;
399
+ terminal: boolean;
400
+ }
401
+ //#endregion
402
+ //#region src/journal/commit-line.d.ts
403
+ interface CommitParticipant {
404
+ /** Reconstruct speculative state from its durable projection. */
405
+ reset(): void;
406
+ reserve(entry: UnitEntry): void;
407
+ apply(entry: UnitEntry): void;
408
+ publish?(entry: UnitEntry): void;
409
+ queued?(bytes: number): void;
410
+ settled?(bytes: number): void;
411
+ }
412
+ interface PreparedCommit {
413
+ readonly entry: UnitEntry;
414
+ readonly json: string;
415
+ readonly byteLength: number;
416
+ readonly participant: CommitParticipant;
417
+ }
418
+ /**
419
+ * The group was valid on its own, but an earlier queued group it was built on was
420
+ * definitively rejected. Nothing was written; rebuilding it on the current state is safe.
421
+ */
422
+ declare class JournalGroupDependencyError extends Error {
423
+ constructor(cause: Error);
424
+ }
425
+ /** Atomic groups share FIFO batching; all durable projections advance before publication. */
426
+ declare class JournalCommitLine {
427
+ #private;
428
+ readonly writeBatch: (writes: readonly PreparedCommit[]) => Promise<void>;
429
+ readonly groupFactLimit: number;
430
+ /** Ownership must be reopened after an uncertain write or failed committed projection. */
431
+ readonly onFailure?: ((error: Error) => void) | undefined;
432
+ constructor(writeBatch: (writes: readonly PreparedCommit[]) => Promise<void>, groupFactLimit?: number, /** Ownership must be reopened after an uncertain write or failed committed projection. */
433
+ onFailure?: ((error: Error) => void) | undefined);
434
+ /** Register before accepting writes. A family validates and projects every entry in each group. */
435
+ addFamily(participant: CommitParticipant): void;
436
+ group<T>(build: () => T): Promise<T>;
437
+ /**
438
+ * A group whose build only stages facts from current state, without other side
439
+ * effects, is rebuilt when an earlier group's rejection takes it down with it.
440
+ */
441
+ rebuild<T>(build: () => T): Promise<T>;
442
+ /** A participant prepares only after joining the rollback set, even if validation throws. */
443
+ stage(participant: CommitParticipant, prepare: () => Omit<PreparedCommit, 'participant'>): UnitEntry;
444
+ idle(): Promise<void>;
445
+ close(): Promise<void>;
446
+ }
447
+ //#endregion
448
+ //#region src/journal/unit/conformance.d.ts
449
+ interface UnitStoreConformanceHarness {
450
+ suite(name: string, body: () => void): void;
451
+ test(name: string, body: () => Promise<void>): void;
452
+ }
453
+ interface UnitStoreConformanceFixture {
454
+ readonly store: UnitStore;
455
+ /** Release opened handles and temporary resources, including after a failed assertion. */
456
+ dispose(): Promise<void>;
457
+ }
458
+ /** Register against the consumer's test framework; no runtime dependency on Vitest. */
459
+ declare function registerUnitStoreConformance(harness: UnitStoreConformanceHarness, factory: (unitId: string) => Promise<UnitStoreConformanceFixture>): void;
460
+ //#endregion
461
+ //#region src/journal/unit/memory.d.ts
462
+ /** Reopening preserves facts within this factory; it has no process-loss durability. */
463
+ declare class MemoryUnitStore implements UnitStore {
464
+ #private;
465
+ readonly unitId: string;
466
+ constructor(unitId: string);
467
+ open(options?: UnitOpenOptions): Promise<OpenedUnitStore>;
468
+ }
469
+ //#endregion
470
+ //#region src/journal/unit/sqlite.d.ts
471
+ /** Column values that Durable Object storage and node:sqlite return. */
472
+ type SqliteValue = string | number | bigint | ArrayBuffer | Uint8Array | null;
473
+ /**
474
+ * The synchronous SQL surface the store uses; a Durable Object passes `ctx.storage`.
475
+ * `exec` runs its statement before returning and may yield rows lazily. `transactionSync`
476
+ * commits when its callback returns and rolls back when it throws.
477
+ */
478
+ interface SqliteUnitDatabase {
479
+ readonly sql: {
480
+ exec(query: string, ...bindings: (string | number)[]): Iterable<Record<string, SqliteValue>>;
481
+ };
482
+ transactionSync<T>(callback: () => T): T;
483
+ }
484
+ interface SqliteUnitStoreOptions {
485
+ readonly unitId: string;
486
+ readonly database: SqliteUnitDatabase;
487
+ /** Payload strings longer than `inlineStringBytes` are stored as Artifacts, as in JsonlUnitStore. */
488
+ readonly artifactStore?: ArtifactStore;
489
+ readonly inlineStringBytes?: number;
490
+ /** Durable Object SQLite rejects a string or row above 2 MB; local workerd does not enforce it. */
491
+ readonly maxRowBytes?: number;
492
+ }
493
+ /**
494
+ * One row per record in a Durable Object (or any synchronous SQLite) database. A commit is
495
+ * one transaction, so a batch is wholly present or absent after process loss. Exclusive
496
+ * ownership is per factory: a Durable Object is the single writer for its storage.
497
+ */
498
+ declare class SqliteUnitStore implements UnitStore {
499
+ #private;
500
+ constructor(options: SqliteUnitStoreOptions);
501
+ get unitId(): string;
502
+ open(options?: UnitOpenOptions): Promise<OpenedUnitStore>;
503
+ }
504
+ //#endregion
505
+ //#region src/journal/task-facts.d.ts
506
+ declare const TaskOwnerSchema: s.Schema<{
507
+ session: string;
508
+ } | {
509
+ task: string;
510
+ }>;
511
+ declare const TaskCheckpointSchema: s.Schema<Record<string, JsonValue> & {
512
+ phase: string;
513
+ }>;
514
+ declare const TaskWaitMemberSchema: s.Schema<{
515
+ task: string;
516
+ } | {
517
+ signal: string;
518
+ } | {
519
+ run: string;
520
+ } | {
521
+ submission: string;
522
+ }>;
523
+ declare const TaskJoinPolicySchema: s.Schema<"allSettled" | "firstSettled">;
524
+ declare const TaskOutcomeSchema: s.Schema<{
525
+ status: "completed";
526
+ result: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
527
+ } | {
528
+ status: "failed";
529
+ error: {
530
+ code: string;
531
+ message: string;
532
+ };
533
+ } | {
534
+ status: "aborted";
535
+ reason: string;
536
+ } | {
537
+ status: "orphaned";
538
+ reason: string;
539
+ } | {
540
+ status: "faulted";
541
+ error: {
542
+ code: string;
543
+ message: string;
544
+ };
545
+ }>;
546
+ /** Unit-scoped facts: taskId names the Task, or the waiter that owns a Signal. */
547
+ declare const TaskFactSchema: s.Schema<{
548
+ id: string;
549
+ recordedAt: string;
550
+ schemaVersion: 1;
551
+ taskId: string;
552
+ kind: "task.created";
553
+ payload: {
554
+ kind: string;
555
+ version: number;
556
+ owner: {
557
+ session: string;
558
+ } | {
559
+ task: string;
560
+ };
561
+ background: boolean;
562
+ creationKey: string;
563
+ input: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
564
+ checkpoint: Record<string, JsonValue> & {
565
+ phase: string;
566
+ };
567
+ };
568
+ } | {
569
+ id: string;
570
+ recordedAt: string;
571
+ schemaVersion: 1;
572
+ taskId: string;
573
+ kind: "task.imported";
574
+ payload: {
575
+ owner: {
576
+ session: string;
577
+ };
578
+ result: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
579
+ kind: string;
580
+ version: number;
581
+ background: boolean;
582
+ creationKey: string;
583
+ input: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
584
+ checkpoint: Record<string, JsonValue> & {
585
+ phase: string;
586
+ };
587
+ };
588
+ } | {
589
+ id: string;
590
+ recordedAt: string;
591
+ schemaVersion: 1;
592
+ taskId: string;
593
+ kind: "task.reserved";
594
+ payload: {
595
+ epochId: string;
596
+ phase: string;
597
+ invocationId: string;
598
+ mode: "phase" | "abort";
599
+ definitionSource?: {
600
+ package: string;
601
+ version: string;
602
+ } | undefined;
603
+ };
604
+ } | {
605
+ id: string;
606
+ recordedAt: string;
607
+ schemaVersion: 1;
608
+ taskId: string;
609
+ kind: "task.transitioned";
610
+ payload: {
611
+ status: "pending";
612
+ checkpoint: Record<string, JsonValue> & {
613
+ phase: string;
614
+ };
615
+ fromPhase: string;
616
+ invocationId?: string | undefined;
617
+ } | {
618
+ status: "waiting";
619
+ on: ({
620
+ task: string;
621
+ } | {
622
+ signal: string;
623
+ } | {
624
+ run: string;
625
+ } | {
626
+ submission: string;
627
+ })[];
628
+ policy: "allSettled" | "firstSettled";
629
+ checkpoint: Record<string, JsonValue> & {
630
+ phase: string;
631
+ };
632
+ fromPhase: string;
633
+ invocationId?: string | undefined;
634
+ } | {
635
+ status: "sleeping";
636
+ until: number;
637
+ checkpoint: Record<string, JsonValue> & {
638
+ phase: string;
639
+ };
640
+ fromPhase: string;
641
+ invocationId?: string | undefined;
642
+ };
643
+ } | {
644
+ id: string;
645
+ recordedAt: string;
646
+ schemaVersion: 1;
647
+ taskId: string;
648
+ kind: "task.recovered";
649
+ payload: {
650
+ epochId: string;
651
+ priorState: "pending" | "running";
652
+ restarts: number;
653
+ };
654
+ } | {
655
+ id: string;
656
+ recordedAt: string;
657
+ schemaVersion: 1;
658
+ taskId: string;
659
+ kind: "task.suspended";
660
+ payload: {
661
+ invocationId: string;
662
+ };
663
+ } | {
664
+ id: string;
665
+ recordedAt: string;
666
+ schemaVersion: 1;
667
+ taskId: string;
668
+ kind: "task.parked";
669
+ payload: {
670
+ restarts: number;
671
+ reason: "restart_limit";
672
+ };
673
+ } | {
674
+ id: string;
675
+ recordedAt: string;
676
+ schemaVersion: 1;
677
+ taskId: string;
678
+ kind: "task.retried";
679
+ payload: {
680
+ commandId: string;
681
+ };
682
+ } | {
683
+ id: string;
684
+ recordedAt: string;
685
+ schemaVersion: 1;
686
+ taskId: string;
687
+ kind: "task.abort.requested";
688
+ payload: {
689
+ reason: string;
690
+ requester: string;
691
+ };
692
+ } | {
693
+ id: string;
694
+ recordedAt: string;
695
+ schemaVersion: 1;
696
+ taskId: string;
697
+ kind: "task.completing";
698
+ payload: {
699
+ invocationId: string;
700
+ outcome: {
701
+ status: "completed";
702
+ result: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
703
+ } | {
704
+ status: "failed";
705
+ error: {
706
+ code: string;
707
+ message: string;
708
+ };
709
+ } | {
710
+ status: "aborted";
711
+ reason: string;
712
+ } | {
713
+ status: "orphaned";
714
+ reason: string;
715
+ } | {
716
+ status: "faulted";
717
+ error: {
718
+ code: string;
719
+ message: string;
720
+ };
721
+ };
722
+ };
723
+ } | {
724
+ id: string;
725
+ recordedAt: string;
726
+ schemaVersion: 1;
727
+ taskId: string;
728
+ kind: "task.settled";
729
+ payload: {
730
+ outcome: {
731
+ status: "completed";
732
+ result: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
733
+ } | {
734
+ status: "failed";
735
+ error: {
736
+ code: string;
737
+ message: string;
738
+ };
739
+ } | {
740
+ status: "aborted";
741
+ reason: string;
742
+ } | {
743
+ status: "orphaned";
744
+ reason: string;
745
+ } | {
746
+ status: "faulted";
747
+ error: {
748
+ code: string;
749
+ message: string;
750
+ };
751
+ };
752
+ invocationId?: string | undefined;
753
+ };
754
+ } | {
755
+ id: string;
756
+ recordedAt: string;
757
+ schemaVersion: 1;
758
+ taskId: string;
759
+ kind: "signal.created";
760
+ payload: {
761
+ signalId: string;
762
+ creationKey: string;
763
+ type: "host-command" | "elicitation" | "message-reply";
764
+ payload: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
765
+ invocationId: string;
766
+ };
767
+ } | {
768
+ id: string;
769
+ recordedAt: string;
770
+ schemaVersion: 1;
771
+ taskId: string;
772
+ kind: "signal.resolved";
773
+ payload: {
774
+ signalId: string;
775
+ result: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
776
+ commandId: string;
777
+ };
778
+ } | {
779
+ id: string;
780
+ recordedAt: string;
781
+ schemaVersion: 1;
782
+ taskId: string;
783
+ kind: "signal.cancelled";
784
+ payload: {
785
+ signalId: string;
786
+ reason: string;
787
+ };
788
+ }>;
789
+ type TaskFact = s.Static<typeof TaskFactSchema>;
790
+ type TaskOwner = s.Static<typeof TaskOwnerSchema>;
791
+ type TaskCheckpoint = s.Static<typeof TaskCheckpointSchema>;
792
+ type TaskOutcome$1 = s.Static<typeof TaskOutcomeSchema>;
793
+ type TaskWaitMember = s.Static<typeof TaskWaitMemberSchema>;
794
+ type TaskJoinPolicy = s.Static<typeof TaskJoinPolicySchema>;
795
+ //#endregion
796
+ //#region src/journal/message-facts.d.ts
797
+ declare const UnitMessageSchema: s.Schema<{
798
+ input: {
799
+ kind: "user-message";
800
+ deliveryId: string;
801
+ prompt: string | ({
802
+ type: "text";
803
+ text: string;
804
+ textSignature?: string | undefined;
805
+ } | {
806
+ type: "image";
807
+ data: string;
808
+ mimeType: string;
809
+ })[];
810
+ source: {
811
+ kind: string;
812
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
813
+ };
814
+ } | {
815
+ kind: "context-event";
816
+ deliveryId: string;
817
+ contextSources: ({
818
+ lifecycle: "turn";
819
+ kind: "instructions";
820
+ channel: "developer" | "agents";
821
+ content: string;
822
+ sourceId: string;
823
+ provenance: {
824
+ origin: "file" | "runtime" | "host" | "journal";
825
+ label: string;
826
+ location?: string | undefined;
827
+ };
828
+ } | {
829
+ lifecycle: "turn";
830
+ kind: "extension";
831
+ extensionKind: "extension" | "skill" | "plugin" | "app" | "memory";
832
+ name: string;
833
+ content: string;
834
+ sourceId: string;
835
+ provenance: {
836
+ origin: "file" | "runtime" | "host" | "journal";
837
+ label: string;
838
+ location?: string | undefined;
839
+ };
840
+ } | {
841
+ lifecycle: "turn";
842
+ kind: "document";
843
+ name: string;
844
+ mediaType: string;
845
+ content: string;
846
+ sourceId: string;
847
+ provenance: {
848
+ origin: "file" | "runtime" | "host" | "journal";
849
+ label: string;
850
+ location?: string | undefined;
851
+ };
852
+ } | {
853
+ lifecycle: "turn";
854
+ kind: "event";
855
+ event: {
856
+ kind: "text";
857
+ name: string;
858
+ attributes?: Record<string, string | number>;
859
+ text: string;
860
+ } | {
861
+ kind: "container";
862
+ name: string;
863
+ attributes?: Record<string, string | number>;
864
+ children: _sorbetai_context56.ContextXmlElement[];
865
+ };
866
+ sourceId: string;
867
+ provenance: {
868
+ origin: "file" | "runtime" | "host" | "journal";
869
+ label: string;
870
+ location?: string | undefined;
871
+ };
872
+ metadata?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
873
+ })[];
874
+ source: {
875
+ kind: string;
876
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
877
+ };
878
+ };
879
+ whenBusy: "followUp" | "steer";
880
+ messageId: string;
881
+ sourceUnitId: string;
882
+ targetUnitId: string;
883
+ targetSessionId: string;
884
+ replyTo?: {
885
+ unitId: string;
886
+ sessionId: string;
887
+ } | undefined;
888
+ inReplyTo?: string | undefined;
889
+ }>;
890
+ type UnitMessage = s.Static<typeof UnitMessageSchema>;
891
+ type Input = UnitMessage['input'];
892
+ interface MessageDraft {
893
+ readonly targetUnitId: string;
894
+ readonly targetSessionId: string;
895
+ readonly input: { [K in Input['kind']]: Omit<Extract<Input, {
896
+ kind: K;
897
+ }>, 'deliveryId'> }[Input['kind']];
898
+ readonly whenBusy: UnitMessage['whenBusy'];
899
+ readonly inReplyTo?: string;
900
+ }
901
+ interface SendMessageOptions {
902
+ readonly key: string;
903
+ /** Creates a Task-owned local Signal; reply.key shares the Task's entity creation namespace. */
904
+ readonly reply?: {
905
+ readonly sessionId: string;
906
+ readonly key: string;
907
+ };
908
+ }
909
+ interface SentMessage {
910
+ readonly messageId: string;
911
+ readonly replySignalId?: string;
912
+ }
913
+ declare const MessageFactSchema: s.Schema<{
914
+ id: string;
915
+ recordedAt: string;
916
+ schemaVersion: 1;
917
+ messageId: string;
918
+ kind: "message.outbox.enqueued";
919
+ payload: {
920
+ owner: {
921
+ session: string;
922
+ } | {
923
+ task: string;
924
+ };
925
+ creationKey: string;
926
+ message: {
927
+ input: {
928
+ kind: "user-message";
929
+ deliveryId: string;
930
+ prompt: string | ({
931
+ type: "text";
932
+ text: string;
933
+ textSignature?: string | undefined;
934
+ } | {
935
+ type: "image";
936
+ data: string;
937
+ mimeType: string;
938
+ })[];
939
+ source: {
940
+ kind: string;
941
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
942
+ };
943
+ } | {
944
+ kind: "context-event";
945
+ deliveryId: string;
946
+ contextSources: ({
947
+ lifecycle: "turn";
948
+ kind: "instructions";
949
+ channel: "developer" | "agents";
950
+ content: string;
951
+ sourceId: string;
952
+ provenance: {
953
+ origin: "file" | "runtime" | "host" | "journal";
954
+ label: string;
955
+ location?: string | undefined;
956
+ };
957
+ } | {
958
+ lifecycle: "turn";
959
+ kind: "extension";
960
+ extensionKind: "extension" | "skill" | "plugin" | "app" | "memory";
961
+ name: string;
962
+ content: string;
963
+ sourceId: string;
964
+ provenance: {
965
+ origin: "file" | "runtime" | "host" | "journal";
966
+ label: string;
967
+ location?: string | undefined;
968
+ };
969
+ } | {
970
+ lifecycle: "turn";
971
+ kind: "document";
972
+ name: string;
973
+ mediaType: string;
974
+ content: string;
975
+ sourceId: string;
976
+ provenance: {
977
+ origin: "file" | "runtime" | "host" | "journal";
978
+ label: string;
979
+ location?: string | undefined;
980
+ };
981
+ } | {
982
+ lifecycle: "turn";
983
+ kind: "event";
984
+ event: {
985
+ kind: "text";
986
+ name: string;
987
+ attributes?: Record<string, string | number>;
988
+ text: string;
989
+ } | {
990
+ kind: "container";
991
+ name: string;
992
+ attributes?: Record<string, string | number>;
993
+ children: _sorbetai_context56.ContextXmlElement[];
994
+ };
995
+ sourceId: string;
996
+ provenance: {
997
+ origin: "file" | "runtime" | "host" | "journal";
998
+ label: string;
999
+ location?: string | undefined;
1000
+ };
1001
+ metadata?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
1002
+ })[];
1003
+ source: {
1004
+ kind: string;
1005
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
1006
+ };
1007
+ };
1008
+ whenBusy: "followUp" | "steer";
1009
+ messageId: string;
1010
+ sourceUnitId: string;
1011
+ targetUnitId: string;
1012
+ targetSessionId: string;
1013
+ replyTo?: {
1014
+ unitId: string;
1015
+ sessionId: string;
1016
+ } | undefined;
1017
+ inReplyTo?: string | undefined;
1018
+ };
1019
+ replySignalId?: string | undefined;
1020
+ };
1021
+ } | {
1022
+ id: string;
1023
+ recordedAt: string;
1024
+ schemaVersion: 1;
1025
+ messageId: string;
1026
+ kind: "message.outbox.deferred";
1027
+ payload: {
1028
+ retryAt: number;
1029
+ code: string;
1030
+ };
1031
+ } | {
1032
+ id: string;
1033
+ recordedAt: string;
1034
+ schemaVersion: 1;
1035
+ messageId: string;
1036
+ kind: "message.outbox.acknowledged";
1037
+ payload: {
1038
+ status: "accepted";
1039
+ acceptanceId: string;
1040
+ targetUnitId: string;
1041
+ targetSessionId: string;
1042
+ messageId: string;
1043
+ sourceUnitId: string;
1044
+ };
1045
+ } | {
1046
+ id: string;
1047
+ recordedAt: string;
1048
+ schemaVersion: 1;
1049
+ messageId: string;
1050
+ kind: "message.outbox.rejected";
1051
+ payload: {
1052
+ status: "rejected";
1053
+ code: string;
1054
+ message: string;
1055
+ targetUnitId: string;
1056
+ targetSessionId: string;
1057
+ messageId: string;
1058
+ sourceUnitId: string;
1059
+ };
1060
+ }>;
1061
+ type MessageFact = s.Static<typeof MessageFactSchema>;
1062
+ type MessageIntent = Extract<MessageFact, {
1063
+ kind: 'message.outbox.enqueued';
1064
+ }>['payload'];
1065
+ //#endregion
1066
+ //#region src/journal/message-routing.d.ts
1067
+ declare const MessageReceiptSchema: s.Schema<{
1068
+ status: "accepted";
1069
+ acceptanceId: string;
1070
+ targetUnitId: string;
1071
+ targetSessionId: string;
1072
+ messageId: string;
1073
+ sourceUnitId: string;
1074
+ }>;
1075
+ declare const MessageRejectionSchema: s.Schema<{
1076
+ status: "rejected";
1077
+ code: string;
1078
+ message: string;
1079
+ targetUnitId: string;
1080
+ targetSessionId: string;
1081
+ messageId: string;
1082
+ sourceUnitId: string;
1083
+ }>;
1084
+ declare const MessageDeliveryResultSchema: s.Schema<{
1085
+ status: "accepted";
1086
+ acceptanceId: string;
1087
+ targetUnitId: string;
1088
+ targetSessionId: string;
1089
+ messageId: string;
1090
+ sourceUnitId: string;
1091
+ } | {
1092
+ status: "rejected";
1093
+ code: string;
1094
+ message: string;
1095
+ targetUnitId: string;
1096
+ targetSessionId: string;
1097
+ messageId: string;
1098
+ sourceUnitId: string;
1099
+ } | {
1100
+ status: "unavailable";
1101
+ code: string;
1102
+ }>;
1103
+ type MessageReceipt = s.Static<typeof MessageReceiptSchema>;
1104
+ type MessageRejection = s.Static<typeof MessageRejectionSchema>;
1105
+ type MessageDeliveryResult = s.Static<typeof MessageDeliveryResultSchema>;
1106
+ //#endregion
1107
+ //#region src/journal/pre-b3.d.ts
1108
+ /** Run facts that carried input evidence inline before Submissions owned admission. */
1109
+ declare const PRE_B3_INPUT_FACT_KINDS: readonly ["run.accepted", "run.input.accepted"];
1110
+ type PreB3InputFact = Extract<JournalFact, {
1111
+ kind: (typeof PRE_B3_INPUT_FACT_KINDS)[number];
1112
+ }>;
1113
+ //#endregion
1114
+ //#region src/journal/input.d.ts
1115
+ type Placement = Extract<JournalFact, {
1116
+ kind: 'submission.placed';
1117
+ }>;
1118
+ /** A read model: identity and cursor belong to the placement, content to its acceptance. */
1119
+ type PlacedRunInput = Omit<Placement, 'payload' | 'runId'> & {
1120
+ readonly runId: string;
1121
+ readonly payload: Extract<JournalFact, {
1122
+ kind: 'run.input.accepted';
1123
+ }>['payload'];
1124
+ };
1125
+ type RunInput = PreB3InputFact | PlacedRunInput;
1126
+ /** Joins input evidence once, retaining only acceptances awaiting placement.
1127
+ * Pre-B3 Journals wrote input evidence inline as well; those placements must not
1128
+ * duplicate messages, so `pre-b3.ts` tracks which deliveries were already recorded.
1129
+ */
1130
+ declare class RunInputProjection {
1131
+ #private;
1132
+ apply(fact: JournalFact): RunInput | undefined;
1133
+ reset(): void;
1134
+ }
1135
+ //#endregion
1136
+ //#region src/tools/contracts.d.ts
1137
+ /** Host details are validated as JSON when the result crosses the Journal boundary. */
1138
+ interface ToolResult<Details = unknown> {
1139
+ content: (TextContent | ImageContent)[];
1140
+ details: Details;
1141
+ structuredContent?: ReadonlyJsonValue;
1142
+ usage?: Usage;
1143
+ isError?: boolean;
1144
+ /** Ends the turn only when every call in the completed batch requests it. */
1145
+ terminate?: boolean;
1146
+ }
1147
+ type ToolUpdateCallback<Details = unknown> = (result: ToolResult<Details>) => void;
1148
+ interface ToolDefinition<Parameters$1 extends object = object, Details = unknown> extends Omit<ToolDeclaration, 'parameters'> {
1149
+ label: string;
1150
+ parameters: Parameters$1;
1151
+ outputSchema?: object;
1152
+ /** Raw host arguments; the owning Tool validates them against its parameters. */
1153
+ prepareArguments?: (input: unknown) => s.Static<Parameters$1>;
1154
+ executionMode?: 'parallel' | 'sequential';
1155
+ execute(toolCallId: string, parameters: s.Static<Parameters$1>, signal?: AbortSignal, onUpdate?: ToolUpdateCallback<Details>): Promise<ToolResult<Details>>;
1156
+ }
1157
+ //#endregion
1158
+ //#region src/observation/invoke.d.ts
1159
+ /** Isolates host callbacks, including async functions accidentally assigned to a void callback. */
1160
+ declare function observeRuntime(report: () => void): void;
1161
+ /** Tracing is not authority; adapter failures must not affect dispatch. */
1162
+ declare function readObservationTraceContext(port: RuntimeObservationPort | undefined, identity: Parameters<NonNullable<RuntimeObservationPort['traceContext']>>[0]): ObservationTraceContext | undefined;
1163
+ //#endregion
1164
+ //#region src/tools/discovery/contracts.d.ts
1165
+ declare const ToolSourcesSchema: s.Schema<{
1166
+ namespace: string;
1167
+ description: string;
1168
+ tools?: {
1169
+ name: string;
1170
+ description: string;
1171
+ }[] | undefined;
1172
+ }[]>;
1173
+ type ToolSource = s.Static<typeof ToolSourcesSchema>[number];
1174
+ type ToolExposure = 'direct' | 'deferred' | 'hidden';
1175
+ interface ToolDiscoveryMetadata {
1176
+ /** Hidden Host Tools are omitted from model declarations and search, but can be called by nested Tools. */
1177
+ readonly exposure?: ToolExposure;
1178
+ readonly namespace?: {
1179
+ readonly name: string;
1180
+ readonly description?: string;
1181
+ };
1182
+ }
1183
+ type DiscoverableTool = ToolDefinition | (ToolDefinition & {
1184
+ readonly discovery?: ToolDiscoveryMetadata;
1185
+ readonly recovery?: 'unsafe' | 'safe';
1186
+ });
1187
+ interface ToolSearchOptions {
1188
+ readonly defaultExposure?: ToolExposure;
1189
+ /** Per-name metadata overrides the metadata supplied by each Tool. */
1190
+ readonly tools?: Readonly<Record<string, ToolDiscoveryMetadata>>;
1191
+ /** Default result count (1–20); an individual search can override it with limit. */
1192
+ readonly maxResults?: number;
1193
+ }
1194
+ //#endregion
1195
+ //#region src/tools/execution/context.d.ts
1196
+ interface ContextForkSeed {
1197
+ readonly schemaVersion: 2;
1198
+ readonly source: {
1199
+ readonly sessionId: string;
1200
+ readonly runId: string;
1201
+ readonly modelRequestId: string;
1202
+ readonly responseMessageId: string;
1203
+ readonly toolCallId: string;
1204
+ };
1205
+ readonly sessionSources: PrefixContextSource[];
1206
+ readonly messages: Message[];
1207
+ readonly messageOrigins: ContextForkMessageOrigin[];
1208
+ }
1209
+ type ContextForkMessageOrigin = {
1210
+ readonly kind: 'fork-seed';
1211
+ } | {
1212
+ readonly kind: 'context-frame';
1213
+ } | {
1214
+ readonly kind: 'compaction-summary';
1215
+ } | {
1216
+ readonly kind: 'conversation';
1217
+ readonly sourceKind?: string;
1218
+ };
1219
+ interface ToolInvocationContext {
1220
+ readonly approval: 'approved' | 'not-required';
1221
+ /** W3C tracing metadata only; never permission or durable identity. */
1222
+ readonly traceContext?: ObservationTraceContext;
1223
+ readonly sessionId: string;
1224
+ readonly runId: string;
1225
+ readonly toolCallId: string;
1226
+ readonly effectAttemptId: string;
1227
+ readonly signal?: AbortSignal;
1228
+ /** Aborted for queued user input or steering context; observing it does not consume input. */
1229
+ readonly steeringSignal?: AbortSignal;
1230
+ /** Reconstructs the committed model context on demand. Unavailable for nested calls. */
1231
+ readonly forkSeed?: () => Promise<ContextForkSeed>;
1232
+ readonly elicitation?: ElicitationComposition;
1233
+ /**
1234
+ * Runs another Tool registered to this Run as a nested Effect. Hidden Host
1235
+ * Tools are available only through this callback, never as model declarations
1236
+ * or search results. Sorbet applies the Tool's Hooks and result processing,
1237
+ * while the Host's Permission policy, grants, and approval resolver determine
1238
+ * whether the call is authorized. The Tool cannot override that Host decision.
1239
+ * Sorbet records the nested Journal facts and links the result to this
1240
+ * invocation. The callback is absent when the Host does not support nested
1241
+ * execution. Nested calls cannot fork Context or stage Unit Effects, and a
1242
+ * parent declared `safe` cannot start one. A pending nested approval is
1243
+ * process-local; recovery settles it as unavailable and never replays the
1244
+ * parent Effect.
1245
+ */
1246
+ readonly executeTool?: (name: string, input: JsonValue, options?: {
1247
+ readonly signal?: AbortSignal;
1248
+ }) => Promise<ToolResult>;
1249
+ }
1250
+ interface ContextualTool<TParameters extends object = object, TDetails = unknown> extends Omit<ToolDefinition<TParameters, TDetails>, 'execute'> {
1251
+ /** Interrupted attempts remain unknown; safe permits model-directed repetition. */
1252
+ readonly recovery?: 'unsafe' | 'safe';
1253
+ readonly discovery?: ToolDiscoveryMetadata;
1254
+ /**
1255
+ * Rejects the invocation unless it is the only Tool call in its assistant
1256
+ * message. Use this for commit-like receipts whose claims must follow every
1257
+ * other action in the turn. Rejection occurs before Permission and Effect
1258
+ * admission and returns ordinary Tool feedback so the model can retry.
1259
+ */
1260
+ readonly requiresExclusiveBatch?: boolean;
1261
+ execute(parameters: s.Static<TParameters>, context: ToolInvocationContext, onUpdate?: ToolUpdateCallback<TDetails>): Promise<ToolResult<TDetails>>;
1262
+ }
1263
+ //#endregion
1264
+ //#region src/tools/artifacts/tool.d.ts
1265
+ declare const ArtifactToolInputSchema: s.Schema<{
1266
+ action: "inspect";
1267
+ artifactId: string;
1268
+ } | {
1269
+ action: "read";
1270
+ artifactId: string;
1271
+ offset?: number | undefined;
1272
+ maxBytes?: number | undefined;
1273
+ } | {
1274
+ action: "query";
1275
+ artifactId: string;
1276
+ query: string;
1277
+ offset?: number | undefined;
1278
+ maxScanBytes?: number | undefined;
1279
+ maxMatches?: number | undefined;
1280
+ }>;
1281
+ interface ArtifactOrigin {
1282
+ readonly runId: string;
1283
+ readonly effectAttemptId: string;
1284
+ readonly toolCallId?: string;
1285
+ readonly toolName?: string;
1286
+ }
1287
+ interface SessionArtifact {
1288
+ readonly archive: ToolOutputArchiveRecord;
1289
+ readonly origins: readonly ArtifactOrigin[];
1290
+ }
1291
+ type SessionArtifactResolver = (artifactId: string) => Promise<SessionArtifact | undefined>;
1292
+ interface CreateArtifactToolOptions {
1293
+ readonly store: ArtifactStore;
1294
+ readonly resolve: SessionArtifactResolver;
1295
+ }
1296
+ declare function createArtifactTool(options: CreateArtifactToolOptions): ContextualTool<typeof ArtifactToolInputSchema, object>;
1297
+ declare class SessionArtifactIndex {
1298
+ #private;
1299
+ apply(fact: JournalFact): void;
1300
+ get(artifactId: string): SessionArtifact | undefined;
1301
+ reset(): void;
1302
+ }
1303
+ //#endregion
1304
+ //#region src/tools/discovery/catalog.d.ts
1305
+ declare const SearchInput: s.Schema<{
1306
+ query: string;
1307
+ namespace?: string | undefined;
1308
+ limit?: number | undefined;
1309
+ offset?: number | undefined;
1310
+ }>;
1311
+ declare const SearchResultSchema: s.Schema<{
1312
+ page: {
1313
+ offset: number;
1314
+ total: number;
1315
+ nextOffset?: number | undefined;
1316
+ };
1317
+ selected: {
1318
+ name: string;
1319
+ bindingId: string;
1320
+ }[];
1321
+ }>;
1322
+ type CompletedResult = Pick<ToolResultMessage, 'toolName' | 'isError' | 'details'>;
1323
+ type SearchableTool = Pick<DiscoverableTool, 'name' | 'description' | 'parameters'> & {
1324
+ readonly discovery?: ToolDiscoveryMetadata;
1325
+ };
1326
+ /** Holds visibility separately from the Session's complete bound execution surface. */
1327
+ declare class SessionToolDiscovery<Tool extends SearchableTool = DiscoverableTool> {
1328
+ #private;
1329
+ constructor(options?: ToolSearchOptions);
1330
+ setTools(tools: readonly Tool[], identity?: (tool: Tool) => string): void;
1331
+ sources(): readonly ToolSource[];
1332
+ visibleTools(): Tool[];
1333
+ createTool(): ToolDefinition<typeof SearchInput, s.Static<typeof SearchResultSchema>> & {
1334
+ readonly discovery: ToolDiscoveryMetadata;
1335
+ };
1336
+ acceptResults(results: readonly CompletedResult[]): void;
1337
+ /** Journal selections stay dormant until the exact binding appears in the current catalog. */
1338
+ restore(results: readonly CompletedResult[]): void;
1339
+ }
1340
+ //#endregion
1341
+ //#region src/tools/output/limit.d.ts
1342
+ declare const DEFAULT_MAX_TOOL_OUTPUT_TOKENS = 10000;
1343
+ interface ToolOutputLimitOptions {
1344
+ readonly notice?: string;
1345
+ readonly originalStatistics?: ToolOutputTextStatistics;
1346
+ readonly onStatistics?: (statistics: ToolOutputStatistics) => void;
1347
+ }
1348
+ interface ToolOutputTextStatistics {
1349
+ readonly characters: number;
1350
+ readonly bytes: number;
1351
+ readonly imageCount: number;
1352
+ }
1353
+ interface ToolOutputStatistics {
1354
+ readonly before: ToolOutputTextStatistics;
1355
+ readonly after: ToolOutputTextStatistics;
1356
+ readonly beforeEstimatedTokens: number;
1357
+ readonly afterEstimatedTokens: number;
1358
+ }
1359
+ declare function limitToolOutput<TDetails>(result: ToolResult<TDetails>, maxOutputTokens: number, options?: ToolOutputLimitOptions): ToolResult<TDetails>;
1360
+ //#endregion
1361
+ //#region src/tools/output/archive.d.ts
1362
+ interface StoredToolOutputFile {
1363
+ readonly ref: ArtifactRef;
1364
+ readonly path: string;
1365
+ }
1366
+ interface ToolOutputFileStore extends ArtifactStore {
1367
+ write(bytes: Uint8Array): Promise<StoredToolOutputFile>;
1368
+ /** Writes the exact concatenated UTF-8 text without requiring one complete byte array. */
1369
+ writeText?(chunks: Iterable<string>): Promise<StoredToolOutputFile>;
1370
+ }
1371
+ interface PreparedToolOutput<TDetails> {
1372
+ readonly result: ToolResult<TDetails>;
1373
+ readonly archive?: ToolOutputArchiveRecord;
1374
+ }
1375
+ declare class ToolOutputArchiver {
1376
+ #private;
1377
+ constructor(store: ToolOutputFileStore);
1378
+ prepare<TDetails>(result: ToolResult<TDetails>, maxOutputTokens: number, capture?: (statistics: ToolOutputStatistics) => void): Promise<PreparedToolOutput<TDetails>>;
1379
+ }
1380
+ //#endregion
1381
+ //#region src/tools/execution/parameters.d.ts
1382
+ /** Validates model-supplied arguments and reports bounded, readable schema errors to the model. */
1383
+ declare function parseToolParameters<T extends s.JsonSchema>(toolName: string, schema: T, value: unknown): s.Static<T>;
1384
+ //#endregion
1385
+ //#region src/permissions/contracts.d.ts
1386
+ /** A user's explicit Session grant, projected from the original approval facts. */
1387
+ declare const PermissionGrantSchema: s.Schema<{
1388
+ grantId: string;
1389
+ toolName: string;
1390
+ parameters: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
1391
+ sourceToolCallId: string;
1392
+ grantedAt: string;
1393
+ sourceRunId?: string | undefined;
1394
+ sourceOperationId?: string | undefined;
1395
+ }>;
1396
+ type PermissionGrant = Readonly<s.Static<typeof PermissionGrantSchema>>;
1397
+ /**
1398
+ * A Session-wide grant: the user turned the whole Session into full access from this decision
1399
+ * onward. It authorizes every Tool call without approval until it is revoked, not one action.
1400
+ */
1401
+ declare const SessionPermissionGrantSchema: s.Schema<{
1402
+ grantId: string;
1403
+ sourceToolCallId: string;
1404
+ grantedAt: string;
1405
+ sourceRunId?: string | undefined;
1406
+ sourceOperationId?: string | undefined;
1407
+ }>;
1408
+ type SessionPermissionGrant = Readonly<s.Static<typeof SessionPermissionGrantSchema>>;
1409
+ /** The access decision that a Permission policy can make before execution. */
1410
+ declare const ToolPermissionAccessSchema: s.Schema<"allow" | "deny">;
1411
+ /** Whether an otherwise allowed Tool call needs a Host Approval. */
1412
+ declare const ToolApprovalRequirementSchema: s.Schema<"required" | "not-required">;
1413
+ /** The non-terminal admission instruction produced by a Permission evaluator. */
1414
+ declare const ToolPermissionDirectiveSchema: s.Schema<{
1415
+ access: "deny";
1416
+ reason: string;
1417
+ } | {
1418
+ access: "allow";
1419
+ approval: "not-required";
1420
+ } | {
1421
+ access: "allow";
1422
+ approval: "required";
1423
+ reason: string;
1424
+ }>;
1425
+ declare const PermissionScalarSchema: s.Schema<string | number | boolean | null>;
1426
+ declare const ToolPermissionPolicyEntrySchema: s.Schema<{
1427
+ access: "deny";
1428
+ } | {
1429
+ access: "allow";
1430
+ approval: "not-required";
1431
+ } | {
1432
+ access: "allow";
1433
+ approval: "required";
1434
+ }>;
1435
+ declare const ToolPermissionRuleSchema: s.Schema<{
1436
+ entry: {
1437
+ access: "deny";
1438
+ } | {
1439
+ access: "allow";
1440
+ approval: "not-required";
1441
+ } | {
1442
+ access: "allow";
1443
+ approval: "required";
1444
+ };
1445
+ toolName: string;
1446
+ parameter?: {
1447
+ name: string;
1448
+ value: string | number | boolean | null;
1449
+ } | undefined;
1450
+ }>;
1451
+ declare const ToolPermissionPolicySchema: s.Schema<{
1452
+ fallback: {
1453
+ access: "deny";
1454
+ } | {
1455
+ access: "allow";
1456
+ approval: "not-required";
1457
+ } | {
1458
+ access: "allow";
1459
+ approval: "required";
1460
+ };
1461
+ tools: Record<string, {
1462
+ access: "deny";
1463
+ } | {
1464
+ access: "allow";
1465
+ approval: "not-required";
1466
+ } | {
1467
+ access: "allow";
1468
+ approval: "required";
1469
+ }>;
1470
+ rules: {
1471
+ entry: {
1472
+ access: "deny";
1473
+ } | {
1474
+ access: "allow";
1475
+ approval: "not-required";
1476
+ } | {
1477
+ access: "allow";
1478
+ approval: "required";
1479
+ };
1480
+ toolName: string;
1481
+ parameter?: {
1482
+ name: string;
1483
+ value: string | number | boolean | null;
1484
+ } | undefined;
1485
+ }[];
1486
+ }>;
1487
+ type ToolPermissionAccess = s.Static<typeof ToolPermissionAccessSchema>;
1488
+ type ToolApprovalRequirement = s.Static<typeof ToolApprovalRequirementSchema>;
1489
+ type ToolPermissionDirective = Readonly<s.Static<typeof ToolPermissionDirectiveSchema>>;
1490
+ type PermissionScalar = s.Static<typeof PermissionScalarSchema>;
1491
+ type ToolPermissionPolicyEntry = Readonly<s.Static<typeof ToolPermissionPolicyEntrySchema>>;
1492
+ type ToolPermissionRule = Readonly<s.Static<typeof ToolPermissionRuleSchema>>;
1493
+ type ToolPermissionPolicy = Readonly<s.Static<typeof ToolPermissionPolicySchema>>;
1494
+ interface ToolPermissionRequest<TParameters extends object = object> {
1495
+ readonly toolCallId: string;
1496
+ /** Direct parent when another Tool issued this call from inside its own Effect. */
1497
+ readonly parentToolCallId?: string;
1498
+ readonly toolName: string;
1499
+ readonly description?: string;
1500
+ readonly parameterSchema?: object;
1501
+ /** The validated execution input. Evaluators may inspect it but must not retain or mutate it. */
1502
+ readonly parameters: s.Static<TParameters>;
1503
+ readonly signal?: AbortSignal;
1504
+ }
1505
+ type ToolPermissionEvaluator = (request: ToolPermissionRequest) => Promise<ToolPermissionDirective>;
1506
+ /** Session-owned admission boundary for every registered Tool. */
1507
+ interface PermissionComposition {
1508
+ readonly evaluate: ToolPermissionEvaluator;
1509
+ }
1510
+ //#endregion
1511
+ //#region src/permissions/policy.d.ts
1512
+ /** Evaluates ordered literal rules, then the Tool default and fallback. */
1513
+ declare function evaluateToolPermissionPolicy(policy: ToolPermissionPolicy, request: ToolPermissionRequest): ToolPermissionDirective;
1514
+ //#endregion
1515
+ //#region src/permissions/errors.d.ts
1516
+ declare class PermissionGrantNotFoundError extends Error {
1517
+ readonly grantId: string;
1518
+ readonly code = "permission_grant_not_found";
1519
+ constructor(grantId: string);
1520
+ }
1521
+ //#endregion
1522
+ //#region src/elicitations/tool.d.ts
1523
+ declare const RequestUserInputSchema: s.Schema<{
1524
+ questions: {
1525
+ id: string;
1526
+ question: string;
1527
+ options: {
1528
+ value: string;
1529
+ label: string;
1530
+ description?: string | undefined;
1531
+ }[];
1532
+ }[];
1533
+ }>;
1534
+ interface RequestUserInputDetails {
1535
+ readonly action: 'accept' | 'decline' | 'cancel';
1536
+ readonly answers?: Readonly<Record<string, string | number | boolean | string[]>>;
1537
+ }
1538
+ declare function createRequestUserInputTool(): ContextualTool<typeof RequestUserInputSchema, RequestUserInputDetails>;
1539
+ //#endregion
1540
+ //#region src/events/contracts.d.ts
1541
+ type ToolEventResult = Partial<Pick<ToolResultMessage, 'content' | 'usage' | 'isError'>> & {
1542
+ details?: unknown;
1543
+ structuredContent?: ReadonlyJsonValue;
1544
+ terminate?: boolean;
1545
+ };
1546
+ type AssistantStreamEvent = {
1547
+ type: 'start';
1548
+ partial: AssistantMessage;
1549
+ } | {
1550
+ type: 'text_start';
1551
+ contentIndex: number;
1552
+ partial: AssistantMessage;
1553
+ } | {
1554
+ type: 'thinking_start';
1555
+ contentIndex: number;
1556
+ partial: AssistantMessage;
1557
+ } | {
1558
+ type: 'toolcall_start';
1559
+ contentIndex: number;
1560
+ partial: AssistantMessage;
1561
+ } | {
1562
+ type: 'text_delta';
1563
+ contentIndex: number;
1564
+ delta: string;
1565
+ partial: AssistantMessage;
1566
+ } | {
1567
+ type: 'thinking_delta';
1568
+ contentIndex: number;
1569
+ delta: string;
1570
+ partial: AssistantMessage;
1571
+ } | {
1572
+ type: 'toolcall_delta';
1573
+ contentIndex: number;
1574
+ delta: string;
1575
+ partial: AssistantMessage;
1576
+ } | {
1577
+ type: 'text_end';
1578
+ contentIndex: number;
1579
+ content: string;
1580
+ partial: AssistantMessage;
1581
+ } | {
1582
+ type: 'thinking_end';
1583
+ contentIndex: number;
1584
+ content: string;
1585
+ partial: AssistantMessage;
1586
+ } | {
1587
+ type: 'toolcall_end';
1588
+ contentIndex: number;
1589
+ toolCall: ToolCall;
1590
+ partial: AssistantMessage;
1591
+ } | {
1592
+ type: 'done';
1593
+ reason: 'stop' | 'length' | 'toolUse' | 'deferred';
1594
+ message: AssistantMessage;
1595
+ } | {
1596
+ type: 'error';
1597
+ reason: 'error' | 'aborted';
1598
+ error: AssistantMessage;
1599
+ };
1600
+ type ExecutionEvent = {
1601
+ type: 'agent_start';
1602
+ } | {
1603
+ type: 'turn_start';
1604
+ } | {
1605
+ type: 'agent_end';
1606
+ messages: Message[];
1607
+ } | {
1608
+ type: 'turn_end';
1609
+ message: Message;
1610
+ toolResults: ToolResultMessage[];
1611
+ } | {
1612
+ type: 'message_start';
1613
+ message: Message;
1614
+ } | {
1615
+ type: 'message_end';
1616
+ message: Message;
1617
+ } | {
1618
+ type: 'message_update';
1619
+ message: Message;
1620
+ assistantMessageEvent: AssistantStreamEvent;
1621
+ } | {
1622
+ type: 'tool_execution_start';
1623
+ toolCallId: string;
1624
+ toolName: string;
1625
+ args: JsonValue$1;
1626
+ } | {
1627
+ type: 'tool_execution_update';
1628
+ toolCallId: string;
1629
+ toolName: string;
1630
+ args: JsonValue$1;
1631
+ partialResult: ToolEventResult;
1632
+ } | {
1633
+ type: 'tool_execution_end';
1634
+ toolCallId: string;
1635
+ toolName: string;
1636
+ result: ToolEventResult;
1637
+ isError: boolean;
1638
+ durationMs?: number;
1639
+ };
1640
+ interface ModelRetryStartEvent {
1641
+ readonly type: 'auto_retry_start';
1642
+ readonly attempt: number;
1643
+ /** Absent when the host set no retry ceiling; retrying continues with capped backoff. */
1644
+ readonly maxAttempts?: number;
1645
+ readonly delayMs: number;
1646
+ readonly errorMessage: string;
1647
+ readonly failedModelRequestId: string;
1648
+ readonly logicalModelCallId: string;
1649
+ }
1650
+ interface ModelRetryEndEvent {
1651
+ readonly type: 'auto_retry_end';
1652
+ readonly success: boolean;
1653
+ readonly attempt: number;
1654
+ readonly logicalModelCallId: string;
1655
+ readonly modelRequestId?: string;
1656
+ readonly finalError?: string;
1657
+ }
1658
+ interface ModelContextEstimateEvent {
1659
+ readonly type: 'model.context.estimated';
1660
+ readonly contextTokens: number;
1661
+ readonly contextWindow: number;
1662
+ }
1663
+ interface ModelUsageEvent {
1664
+ readonly type: 'model.usage';
1665
+ /** Latest valid context measurement; absent for failed, aborted, or unmetered responses. */
1666
+ readonly contextTokens?: number;
1667
+ readonly contextWindow: number;
1668
+ readonly usage: Usage;
1669
+ }
1670
+ type RunLiveEvent = ExecutionEvent | ModelRetryStartEvent | ModelRetryEndEvent | ModelContextEstimateEvent | ModelUsageEvent | {
1671
+ readonly type: 'session.behavior.changed';
1672
+ readonly name: string;
1673
+ readonly view: SessionBehaviorView;
1674
+ };
1675
+ /**
1676
+ * A process-local stream with no replay position or durability guarantee.
1677
+ * Slow or absent consumers receive an error when the bounded buffer overflows.
1678
+ */
1679
+ interface RunLiveEventSubscription extends AsyncIterable<RunLiveEvent> {
1680
+ close(): void;
1681
+ }
1682
+ //#endregion
1683
+ //#region src/events/hub.d.ts
1684
+ /** Publishes non-durable SDK events without putting consumer callbacks on Pi's critical path. */
1685
+ declare class RunLiveEventHub {
1686
+ #private;
1687
+ beginRun(runId: string): RunLiveEventSubscription;
1688
+ /** Buffers a private copy, so the producer may keep mutating the objects it published. */
1689
+ publish(runId: string, event: RunLiveEvent): void;
1690
+ /**
1691
+ * Buffers the event as-is. The producer must never mutate it or anything it references after
1692
+ * publishing; consumers read it without copying. Streaming deltas use this so each buffered
1693
+ * event costs its own bytes rather than a copy of everything streamed so far.
1694
+ */
1695
+ publishShared(runId: string, event: RunLiveEvent): void;
1696
+ endRun(runId: string): void;
1697
+ close(): void;
1698
+ }
1699
+ //#endregion
1700
+ //#region src/run/contracts.d.ts
1701
+ type UserPrompt = s.Static<typeof UserPromptSchema> & (string | readonly (TextContent | ImageContent)[]);
1702
+ /** The caller reused one admission identity for different command content. */
1703
+ declare class RunAdmissionConflictError extends Error {
1704
+ readonly idempotencyKey: string;
1705
+ constructor(idempotencyKey: string);
1706
+ }
1707
+ /** The caller reused one Session delivery identity for different content. */
1708
+ declare class SessionInputConflictError extends Error {
1709
+ readonly deliveryId: string;
1710
+ constructor(deliveryId: string);
1711
+ }
1712
+ type RunStatus = 'parked' | 'accepted' | 'executing' | 'waiting_model' | 'waiting_approval' | 'waiting_effect' | 'cancelling' | 'completed' | 'failed' | 'cancelled';
1713
+ /** Metadata identifies the terminal Journal append, not a transient Pi event. */
1714
+ interface DurableRunOutcome {
1715
+ readonly cursor: JournalCursor;
1716
+ readonly recordedAt: string;
1717
+ readonly sequence: number;
1718
+ }
1719
+ /** The single durable settlement promised for an accepted Run. */
1720
+ type RunTerminalOutcome = (DurableRunOutcome & {
1721
+ readonly kind: 'completed';
1722
+ readonly responseMessageId: string;
1723
+ }) | (DurableRunOutcome & {
1724
+ readonly kind: 'failed';
1725
+ readonly error: {
1726
+ readonly code: RunFailureCode;
1727
+ readonly message: string;
1728
+ };
1729
+ }) | (DurableRunOutcome & {
1730
+ readonly kind: 'cancelled';
1731
+ readonly reason: string;
1732
+ });
1733
+ /** Latest lifecycle state derived only from successfully appended Run facts. */
1734
+ interface RunView {
1735
+ readonly sessionId: string;
1736
+ readonly runId: string;
1737
+ readonly status: RunStatus;
1738
+ readonly lastSequence: number;
1739
+ /** Resume position in the Session facts. Task-owned parking is derived from the Unit Task graph. */
1740
+ readonly cursor: JournalCursor;
1741
+ /** Present only after one terminal fact has been durably appended. */
1742
+ readonly outcome?: RunTerminalOutcome;
1743
+ }
1744
+ //#endregion
1745
+ //#region src/run/history/contracts.d.ts
1746
+ type RunFact<Kind$1 extends RunJournalFactKind> = Extract<JournalFact, {
1747
+ kind: Kind$1;
1748
+ }>;
1749
+ type RunFactCandidate = { readonly [Kind in RunJournalFactKind]: {
1750
+ readonly runId: string;
1751
+ readonly kind: Kind;
1752
+ readonly payload: JournalPayloadMap[Kind];
1753
+ } }[RunJournalFactKind];
1754
+ type RunTerminalFact = RunFact<'run.completed' | 'run.failed' | 'run.cancelled'>;
1755
+ interface RequestedModelRequestInspection {
1756
+ readonly modelRequestId: string;
1757
+ readonly status: 'requested';
1758
+ readonly modelRequested: RunFact<'model.requested'>;
1759
+ }
1760
+ interface SettledModelRequestInspection {
1761
+ readonly modelRequestId: string;
1762
+ readonly status: 'completed' | 'failed' | 'aborted';
1763
+ readonly modelRequested: RunFact<'model.requested'>;
1764
+ readonly response: RunFact<'model.response.committed'>;
1765
+ }
1766
+ interface UnknownModelRequestInspection {
1767
+ readonly modelRequestId: string;
1768
+ readonly status: 'unknown';
1769
+ readonly modelRequested: RunFact<'model.requested'>;
1770
+ readonly unknown: RunFact<'model.request.unknown'>;
1771
+ }
1772
+ type ModelRequestInspection = RequestedModelRequestInspection | SettledModelRequestInspection | UnknownModelRequestInspection;
1773
+ interface ToolEffectInspection {
1774
+ readonly requested: RunFact<'effect.requested'>;
1775
+ readonly terminal?: RunFact<'effect.succeeded' | 'effect.failed' | 'effect.unknown'>;
1776
+ }
1777
+ interface ToolApprovalInspection {
1778
+ readonly requested: RunFact<'approval.requested'>;
1779
+ readonly resolved?: RunFact<'approval.resolved'>;
1780
+ }
1781
+ interface ToolCallInspection {
1782
+ readonly modelRequestId: string;
1783
+ readonly responseMessageId: string;
1784
+ readonly toolCall: ToolCall;
1785
+ readonly permission?: RunFact<'tool.permission.decided' | 'tool.permission.failed'>;
1786
+ readonly approval?: ToolApprovalInspection;
1787
+ readonly effect?: ToolEffectInspection;
1788
+ readonly result?: RunFact<'tool.result.message.committed'>;
1789
+ readonly resultMessage?: ToolResultMessage;
1790
+ }
1791
+ /** A Tool invocation started by another Tool rather than by a model Tool call. */
1792
+ interface NestedToolInvocationInspection {
1793
+ readonly toolCallId: string;
1794
+ readonly parentToolCallId: string;
1795
+ readonly toolName?: string;
1796
+ readonly bindingId?: string;
1797
+ readonly permission?: RunFact<'tool.permission.decided' | 'tool.permission.failed'>;
1798
+ readonly effect?: ToolEffectInspection;
1799
+ }
1800
+ interface InterruptedRunState {
1801
+ readonly cancellationReason: string | undefined;
1802
+ readonly unresolvedModelRequests: readonly RunFact<'model.requested'>[];
1803
+ readonly unsettledApprovals: readonly ToolApprovalInspection[];
1804
+ readonly unresolvedEffects: readonly RunFact<'effect.requested'>[];
1805
+ }
1806
+ interface RunInspection {
1807
+ readonly lifecycle: RunView;
1808
+ readonly accepted: RunFact<'run.accepted'>;
1809
+ readonly started?: RunFact<'run.started'>;
1810
+ readonly yields: readonly RunFact<'run.yield.decided'>[];
1811
+ readonly acceptedInputs: readonly (RunFact<'run.input.accepted'> | PlacedRunInput)[];
1812
+ readonly cancellation?: RunFact<'run.cancel.requested'>;
1813
+ readonly terminal?: RunTerminalFact;
1814
+ readonly modelRequests: readonly ModelRequestInspection[];
1815
+ readonly toolCalls: readonly ToolCallInspection[];
1816
+ readonly nestedInvocations: readonly NestedToolInvocationInspection[];
1817
+ }
1818
+ //#endregion
1819
+ //#region src/run/history/submissions.d.ts
1820
+ type Accepted = Extract<JournalFact, {
1821
+ kind: 'submission.accepted';
1822
+ }>;
1823
+ type Placed = RunInput;
1824
+ type Terminal = Extract<JournalFact, {
1825
+ kind: 'submission.withdrawn' | 'submission.applied';
1826
+ }> | RunTerminalFact;
1827
+ interface SubmissionRecord {
1828
+ readonly accepted: Accepted;
1829
+ readonly placed?: Placed;
1830
+ /** Task executor placement boundary; older Pi admissions only have `placed`. */
1831
+ readonly placement?: Extract<JournalFact, {
1832
+ kind: 'submission.placed';
1833
+ }>;
1834
+ /** Control application, withdrawal, or the placed Run's terminal joined when status is read. */
1835
+ readonly terminal?: Terminal;
1836
+ }
1837
+ //#endregion
1838
+ //#region src/run/committer.d.ts
1839
+ type SessionFactCandidate = { readonly [Kind in SessionJournalFactKind]: {
1840
+ readonly operationId: string;
1841
+ readonly kind: Kind;
1842
+ readonly payload: JournalPayloadMap[Kind];
1843
+ } }[SessionJournalFactKind];
1844
+ interface RunFactCommitterOptions {
1845
+ readonly initialize?: (participant: RunFactCommitter) => void;
1846
+ readonly commitLine?: JournalCommitLine;
1847
+ readonly observation?: RuntimeObservationPort;
1848
+ readonly createId?: () => string;
1849
+ readonly now?: () => Date;
1850
+ readonly applyDurableFact?: (fact: JournalFact) => void;
1851
+ }
1852
+ /** The sole boundary that can turn a candidate Run fact into durable history. */
1853
+ declare class RunFactCommitter {
1854
+ #private;
1855
+ private constructor();
1856
+ static open(sessionId: string, store: JournalStore, options?: RunFactCommitterOptions): Promise<RunFactCommitter>;
1857
+ /** Unit creation only: the caller must prove this Session has no committed history. */
1858
+ static create(sessionId: string, store: JournalStore, options: RunFactCommitterOptions & {
1859
+ readonly commitLine: JournalCommitLine;
1860
+ }): RunFactCommitter;
1861
+ /** Attach a Session facade without creating a second writer or missing concurrent commits. */
1862
+ attachProjection(apply: (fact: JournalFact) => void, publish?: (fact: JournalFact) => void): Promise<() => void>;
1863
+ commit<const Input$1 extends RunFactCandidate>(input: Input$1): Promise<RunFact<Input$1['kind']>>;
1864
+ /** Yield decisions and their continuation input or terminal share one crash boundary. */
1865
+ commitYield(decision: Extract<RunFactCandidate, {
1866
+ kind: 'run.yield.decided';
1867
+ }>, next: Extract<RunFactCandidate, {
1868
+ kind: 'run.completed';
1869
+ }> | Extract<SessionFactCandidate, {
1870
+ kind: 'submission.placed';
1871
+ }>): Promise<void>;
1872
+ /** Joins a Task transition to the same validated yield/input or yield/terminal group. */
1873
+ stageYield(decision: Extract<RunFactCandidate, {
1874
+ kind: 'run.yield.decided';
1875
+ }>, next: Extract<RunFactCandidate, {
1876
+ kind: 'run.completed';
1877
+ }> | Extract<SessionFactCandidate, {
1878
+ kind: 'submission.placed';
1879
+ }>): void;
1880
+ /** Used by the unit transaction after all participating Sessions have been loaded. */
1881
+ stageRun(input: RunFactCandidate): JournalFact;
1882
+ acceptSubmission(payload: Extract<JournalFact, {
1883
+ kind: 'submission.accepted';
1884
+ }>['payload'], beforeAccept?: () => void): Promise<void>;
1885
+ /** Stage durable acceptance inside the caller's Unit group, without routing Pi work. */
1886
+ stageSubmission(payload: Extract<JournalFact, {
1887
+ kind: 'submission.accepted';
1888
+ }>['payload'], beforeAccept?: () => void): void;
1889
+ /** False means placement won: cancel the selected Run instead of withdrawing its input. */
1890
+ withdrawSubmission(id: string, reason: string, commandId: string): Promise<boolean>;
1891
+ /** Shares the caller's group with consumption Signals; placement wins on this same line. */
1892
+ stageSubmissionWithdrawal(id: string, reason: string, commandId: string): boolean;
1893
+ submission(id: string): Promise<SubmissionRecord | undefined>;
1894
+ pendingSubmissions(): Promise<readonly SubmissionRecord[]>;
1895
+ commitSession<const Input$1 extends SessionFactCandidate>(input: Input$1, options?: {
1896
+ readonly expectedSequence?: number;
1897
+ }): Promise<Extract<SessionJournalFact, {
1898
+ kind: Input$1['kind'];
1899
+ }>>;
1900
+ stageSession(input: SessionFactCandidate, options?: {
1901
+ readonly expectedSequence?: number;
1902
+ }): JournalFact;
1903
+ view(runId: string): Promise<RunView>;
1904
+ listPermissionGrants(): Promise<readonly PermissionGrant[]>;
1905
+ matchPermissionGrant(toolName: string, parameters: ToolPermissionRequest['parameters']): Promise<PermissionGrant | undefined>;
1906
+ /** The Session-wide full-access authorization, when the user turned it on for this Session. */
1907
+ sessionFullAccessGrant(): Promise<SessionPermissionGrant | undefined>;
1908
+ revokePermissionGrant(grantId: string, operationId: string): Promise<void>;
1909
+ outcome(runId: string): Promise<RunTerminalOutcome>;
1910
+ unfinishedRun(): Promise<RunView | undefined>;
1911
+ admission(idempotencyKey: string): Promise<RunFact<'run.accepted'> | undefined>;
1912
+ hasRuns(): Promise<boolean>;
1913
+ effectTerminalForToolCall(runId: string, toolCallId: string): Promise<EffectTerminalFact | undefined>;
1914
+ /**
1915
+ * Returns the durable Session history after all commits issued through this owner settle:
1916
+ * from genesis, or only the facts after `after`.
1917
+ */
1918
+ journalSnapshot(after?: JournalCursor): Promise<readonly JournalFact[]>;
1919
+ unresolvedModelInvocations(): Promise<readonly Extract<JournalFact, {
1920
+ kind: 'model.invocation.requested';
1921
+ }>[]>;
1922
+ /** Unfinished external Tool operations, from the projection the open pass already folded. */
1923
+ unfinishedExternalToolOperations(): Promise<readonly ExternalToolOperation[]>;
1924
+ interruptedState(runId: string): Promise<InterruptedRunState>;
1925
+ inspect(runId: string): Promise<RunInspection>;
1926
+ /** Returns {@link RunRecord.resumeAttempt} after pending commits settle; does not reserve an attempt. */
1927
+ resumeAttempt(runId: string): Promise<number>;
1928
+ /**
1929
+ * Closes interrupted model requests, Effects and approvals, and fills in missing Tool
1930
+ * feedback without executing a Tool. The caller must exclude concurrent Run execution.
1931
+ * Each append is independent: after a crash, a later call skips already-settled items.
1932
+ *
1933
+ * `resumeId` marks recovery-created Effect unknowns and Tool results so they cannot count
1934
+ * as execution progress. Those facts remain valid even if a crash prevents the matching
1935
+ * `run.resumed` from being written. The returned identities describe only this call's
1936
+ * settlement work; later recovery reads the individual facts, not this summary.
1937
+ * This method neither commits `run.resumed` nor increments the resume counter.
1938
+ */
1939
+ settleForResume(runId: string, options: {
1940
+ readonly resumeId: string;
1941
+ readonly recovery: ReadonlyMap<string, 'unsafe' | 'safe'>;
1942
+ }): Promise<JournalPayloadMap['run.resumed']['settled']>;
1943
+ /** Settles every unresolved durable boundary without inferring an external outcome. */
1944
+ settleInterrupted(runId: string, reason: string): Promise<InterruptedRunState>;
1945
+ /**
1946
+ * Terminalizes interrupted history without acquiring a model or execution facade.
1947
+ * Requires a nonterminal Run and no concurrent execution. Retrying after partial
1948
+ * cleanup settles remaining boundaries as unknown; it never dispatches an attempt.
1949
+ */
1950
+ abandonInterruptedRun(runId: string, reason: string): Promise<RunTerminalOutcome>;
1951
+ /** Apply Journal facts appended by another writer without rebuilding existing Run state. */
1952
+ refresh(): Promise<void>;
1953
+ }
1954
+ //#endregion
1955
+ //#region src/run/terminal.d.ts
1956
+ declare function isRunTerminalFactKind(kind: JournalFactKind): boolean;
1957
+ //#endregion
1958
+ //#region src/run/history/inspect.d.ts
1959
+ declare function inspectRunHistory(facts: readonly JournalFact[]): readonly RunInspection[];
1960
+ //#endregion
1961
+ //#region src/run/history/permission-grants.d.ts
1962
+ /** Projects active grants from an ordered Session prefix without admitting a command. */
1963
+ declare function projectPermissionGrants(facts: readonly JournalFact[]): readonly PermissionGrant[];
1964
+ //#endregion
1965
+ //#region src/run/submission-handle.d.ts
1966
+ interface DurableSubmission {
1967
+ readonly submissionId: string;
1968
+ /** Includes the original acceptance, placement evidence and terminal, if present. */
1969
+ status(): Promise<SubmissionRecord>;
1970
+ /** Returns the target Run. Rejects for withdrawn inputs and applied write/reset controls, which have no Run. Aborting this wait does not withdraw the input. */
1971
+ placed(signal?: AbortSignal): Promise<string>;
1972
+ /**
1973
+ * Returns the placed Run's committed terminal, a withdrawal, or submission.applied
1974
+ * for a write/reset control. Controls finish without starting a Run. Run completion
1975
+ * means answered; failure and cancellation mean unanswered. No separate
1976
+ * settlement fact is written. Aborting this wait does not cancel the input.
1977
+ */
1978
+ settled(signal?: AbortSignal): Promise<NonNullable<SubmissionRecord['terminal']>>;
1979
+ /** Returns false when placement or control application already won. Does not cancel the Run in that case. */
1980
+ withdraw(command: {
1981
+ readonly commandId: string;
1982
+ readonly reason: string;
1983
+ }): Promise<boolean>;
1984
+ }
1985
+ //#endregion
1986
+ //#region src/session/compaction/contracts.d.ts
1987
+ /** Planning needs model capacity and cache pricing, never a Provider implementation. */
1988
+ interface CompactionModel {
1989
+ readonly provider: string;
1990
+ readonly id: string;
1991
+ readonly api: string;
1992
+ readonly contextWindow: number;
1993
+ readonly maxTokens: number;
1994
+ readonly cost: {
1995
+ readonly input: number;
1996
+ readonly cacheRead: number;
1997
+ readonly tiers?: readonly {
1998
+ readonly inputTokensAbove: number;
1999
+ readonly input: number;
2000
+ readonly cacheRead: number;
2001
+ }[];
2002
+ };
2003
+ }
2004
+ interface CompactionSettings {
2005
+ readonly enabled: boolean;
2006
+ readonly reserveTokens: number;
2007
+ readonly keepRecentTokens: number;
2008
+ /** Defaults to 20% of the summary model window, bounded by its output capacity. */
2009
+ readonly summaryMaxOutputTokens?: number;
2010
+ readonly instructions?: string;
2011
+ }
2012
+ interface CompactSessionOptions {
2013
+ readonly signal?: AbortSignal;
2014
+ }
2015
+ type CompactionResult = {
2016
+ readonly kind: 'not-needed';
2017
+ readonly reason: 'below-threshold' | 'no-compactable-history';
2018
+ readonly tokensBefore: number;
2019
+ } | {
2020
+ readonly kind: 'compacted';
2021
+ readonly compactionId: string;
2022
+ readonly tokensBefore: number;
2023
+ readonly tokensAfter: number;
2024
+ readonly contextTokensBefore: number;
2025
+ readonly projectedContextTokensAfter: number;
2026
+ readonly summarizedMessages: number;
2027
+ readonly retainedMessages: number;
2028
+ readonly attempts: readonly CompactionAttemptUsage[];
2029
+ };
2030
+ interface CompactionAttemptUsage {
2031
+ readonly attemptId: string;
2032
+ readonly usage: Usage;
2033
+ }
2034
+ type CompactionFailureCode = 'aborted' | 'summarization_failed' | 'journal_conflict' | 'invalid_history' | 'interrupted' | 'ineffective' | 'budget_exhausted' | 'chunk_overflow' | 'invalid_summary' | 'model_call_error';
2035
+ declare class SessionCompactionBusyError extends Error {
2036
+ constructor(message?: string);
2037
+ }
2038
+ declare class SessionContextCapacityError extends Error {
2039
+ constructor(message?: string);
2040
+ }
2041
+ declare function validateCompactionSettings(settings: Partial<CompactionSettings> | undefined, model: Pick<CompactionModel, 'contextWindow' | 'maxTokens'>): CompactionSettings;
2042
+ //#endregion
2043
+ //#region src/session/run-handle/contracts.d.ts
2044
+ type RunAcceptedReceipt = Extract<JournalFact, {
2045
+ kind: 'run.accepted';
2046
+ }>;
2047
+ type RunCancellationReceipt = Extract<JournalFact, {
2048
+ kind: 'run.cancel.requested';
2049
+ }>;
2050
+ type RunInputAcceptedReceipt = Extract<JournalFact, {
2051
+ kind: 'run.input.accepted';
2052
+ }> | PlacedRunInput;
2053
+ /** A Task executor may place late input in a successor Run at the final boundary. */
2054
+ type RunInputPlacementReceipt = RunAcceptedReceipt | RunInputAcceptedReceipt;
2055
+ interface SorbetRun {
2056
+ readonly receipt: RunAcceptedReceipt;
2057
+ /** Returns the Journal-derived Run view and the cursor for continuing with `facts()`. */
2058
+ snapshot(): Promise<RunView>;
2059
+ /** Replays durable Run facts after an optional cursor, then continues from the same stream. */
2060
+ facts(options?: {
2061
+ readonly after?: JournalCursor;
2062
+ }): JournalSubscription;
2063
+ /**
2064
+ * Claims the Run's process-local event stream. The stream is bound before execution,
2065
+ * buffers events until claimed, and can be claimed only once.
2066
+ */
2067
+ liveEvents(): RunLiveEventSubscription;
2068
+ abort(reason?: string): Promise<RunCancellationReceipt>;
2069
+ steer(prompt: UserPrompt, source?: SessionInputSource): Promise<RunInputPlacementReceipt>;
2070
+ followUp(prompt: UserPrompt, source?: SessionInputSource): Promise<RunInputPlacementReceipt>;
2071
+ /** Resolves after Sorbet has durably appended the run's sole terminal fact. */
2072
+ result(): Promise<RunTerminalOutcome>;
2073
+ /** Waits for local execution and resource release; rejects on cleanup failure. Historical handles have no local resources. */
2074
+ drained(): Promise<void>;
2075
+ }
2076
+ //#endregion
2077
+ //#region src/session/delivery/contracts.d.ts
2078
+ type UserSessionInput = Omit<Readonly<Extract<s.Static<typeof SendSessionInputSchema>, {
2079
+ kind: 'user-message';
2080
+ }>>, 'prompt'> & {
2081
+ readonly prompt: UserPrompt;
2082
+ };
2083
+ type ContextEventSessionInput = Omit<Readonly<Extract<s.Static<typeof SendSessionInputSchema>, {
2084
+ kind: 'context-event';
2085
+ }>>, 'contextSources'> & {
2086
+ readonly contextSources: readonly TurnContextSource[];
2087
+ };
2088
+ type SendSessionInput = UserSessionInput | ContextEventSessionInput;
2089
+ /**
2090
+ * Durable acceptance with a process-local Run handle. Replayed facts keep their
2091
+ * identity; historical handles have no live stream. Local callers share the Run's
2092
+ * single-claim live stream.
2093
+ */
2094
+ type SessionInputAcceptedReceipt = {
2095
+ readonly mode: 'newRun';
2096
+ readonly fact: Extract<JournalFact, {
2097
+ kind: 'run.accepted';
2098
+ }>;
2099
+ readonly run: SorbetRun;
2100
+ } | {
2101
+ readonly mode: 'followUp';
2102
+ readonly fact: RunInputAcceptedReceipt;
2103
+ readonly run: SorbetRun;
2104
+ };
2105
+ /**
2106
+ * Process-local ownership of one identified input. `accepted()` waits for Pi
2107
+ * placement, even when Unit acceptance has already committed. Equivalent pending
2108
+ * submissions share ownership.
2109
+ *
2110
+ * In Unit mode, `cancel()` durably withdraws an unplaced input without cancelling
2111
+ * other work. Once placed, cancellation targets its Run, including other queued
2112
+ * inputs. Standalone mode stops routing or cancels the selected Run without a
2113
+ * durable withdrawal. Cancellation never targets a later unrelated Run.
2114
+ */
2115
+ interface SessionInputSubmission {
2116
+ readonly deliveryId: string;
2117
+ /** Present in Unit mode once submission.accepted has committed. */
2118
+ readonly durable?: DurableSubmission;
2119
+ accepted(): Promise<SessionInputAcceptedReceipt>;
2120
+ cancel(reason?: string): Promise<void>;
2121
+ }
2122
+ //#endregion
2123
+ //#region src/session/conversation/contracts.d.ts
2124
+ interface ConversationEntryIdentity {
2125
+ readonly runId: string;
2126
+ readonly messageId: string;
2127
+ readonly sourceFactId: string;
2128
+ }
2129
+ /** Every durable user message retains the boundary and actor metadata that admitted it. */
2130
+ type ConversationEntry = (ConversationEntryIdentity & {
2131
+ readonly message: Extract<Message, {
2132
+ readonly role: 'user';
2133
+ }>;
2134
+ readonly source: SessionInputSource;
2135
+ }) | (ConversationEntryIdentity & {
2136
+ readonly message: Exclude<Message, {
2137
+ readonly role: 'user' | 'system';
2138
+ }>;
2139
+ readonly source?: never;
2140
+ });
2141
+ //#endregion
2142
+ //#region src/session/conversation/projection.d.ts
2143
+ interface ConversationProjectionOptions {
2144
+ /**
2145
+ * Emits entries admitted after this Journal sequence. The complete fact list is
2146
+ * still replayed: an input accepted before the boundary can be placed after it,
2147
+ * so its acceptance must stay visible for the placement to resolve.
2148
+ */
2149
+ readonly sinceSequence?: number;
2150
+ }
2151
+ /**
2152
+ * Rebuilds a Provider-valid Pi transcript without changing Journal history.
2153
+ * Incomplete Tool turns remain hidden until transcript or terminal evidence
2154
+ * can supply one result for every Tool call. A failed or interrupted assistant
2155
+ * turn is presented as a factual note instead of its raw partial content, so the
2156
+ * Agent can see that its own request failed without re-reading a broken message.
2157
+ */
2158
+ declare function conversationEntries(facts: readonly JournalFact[], options?: ConversationProjectionOptions): readonly ConversationEntry[];
2159
+ //#endregion
2160
+ //#region src/session/conversation/committed.d.ts
2161
+ interface CommittedConversationMessage {
2162
+ readonly sequence: number;
2163
+ readonly cursor: string;
2164
+ readonly recordedAt: string;
2165
+ readonly runId: string;
2166
+ readonly messageId: string;
2167
+ readonly message: Message;
2168
+ }
2169
+ declare function committedConversationMessages(facts: readonly JournalFact[]): readonly CommittedConversationMessage[];
2170
+ //#endregion
2171
+ //#region src/session/conversation/references.d.ts
2172
+ interface ConversationEntryReference {
2173
+ readonly runId: string;
2174
+ readonly messageId: string;
2175
+ readonly sourceFactId: string;
2176
+ }
2177
+ //#endregion
2178
+ //#region src/session/conversation/fork.d.ts
2179
+ type ContextForkSeedContent = ContextForkSeed;
2180
+ declare function createContextForkSeed(input: ContextForkSeedContent): ContextForkSeed;
2181
+ //#endregion
2182
+ //#region src/session/conversation/session-fork.d.ts
2183
+ declare const SessionForkSeedSchema: s.Schema<{
2184
+ schemaVersion: 1;
2185
+ source: {
2186
+ sessionId: string;
2187
+ journalSequence: number;
2188
+ journalCursor?: string | undefined;
2189
+ };
2190
+ conversation: ({
2191
+ runId: string;
2192
+ messageId: string;
2193
+ sourceFactId: string;
2194
+ message: {
2195
+ role: "user";
2196
+ content: string | ({
2197
+ type: "text";
2198
+ text: string;
2199
+ textSignature?: string | undefined;
2200
+ } | {
2201
+ type: "image";
2202
+ data: string;
2203
+ mimeType: string;
2204
+ })[];
2205
+ timestamp: number;
2206
+ };
2207
+ source: {
2208
+ kind: string;
2209
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
2210
+ };
2211
+ } | {
2212
+ runId: string;
2213
+ messageId: string;
2214
+ sourceFactId: string;
2215
+ message: {
2216
+ role: "assistant";
2217
+ content: ({
2218
+ type: "text";
2219
+ text: string;
2220
+ textSignature?: string | undefined;
2221
+ } | {
2222
+ type: "thinking";
2223
+ thinking: string;
2224
+ thinkingSignature?: string | undefined;
2225
+ redacted?: boolean | undefined;
2226
+ } | {
2227
+ type: "toolCall";
2228
+ id: string;
2229
+ name: string;
2230
+ arguments: Record<string, _sorbetai_schema30.JsonValue>;
2231
+ thoughtSignature?: string | undefined;
2232
+ argumentsError?: string | undefined;
2233
+ })[];
2234
+ api: string;
2235
+ provider: string;
2236
+ model: string;
2237
+ usage: {
2238
+ input: number;
2239
+ output: number;
2240
+ cacheRead: number;
2241
+ cacheWrite: number;
2242
+ totalTokens: number;
2243
+ cost: {
2244
+ input: number;
2245
+ output: number;
2246
+ cacheRead: number;
2247
+ cacheWrite: number;
2248
+ total: number;
2249
+ totalFromProvider?: boolean | undefined;
2250
+ };
2251
+ cacheWrite1h?: number | undefined;
2252
+ reasoning?: number | undefined;
2253
+ };
2254
+ stopReason: "error" | "pending" | "stop" | "length" | "toolUse" | "aborted" | "deferred";
2255
+ timestamp: number;
2256
+ responseModel?: string | undefined;
2257
+ responseId?: string | undefined;
2258
+ diagnostics?: {
2259
+ type: string;
2260
+ timestamp: number;
2261
+ error?: {
2262
+ message: string;
2263
+ name?: string | undefined;
2264
+ stack?: string | undefined;
2265
+ code?: string | number | undefined;
2266
+ } | undefined;
2267
+ details?: Record<string, _sorbetai_schema30.JsonValue> | undefined;
2268
+ }[] | undefined;
2269
+ deferred?: {
2270
+ provider: string;
2271
+ modelId: string;
2272
+ api: string;
2273
+ id: string;
2274
+ expiresAt?: number | undefined;
2275
+ pollAfterMs?: number | undefined;
2276
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
2277
+ } | undefined;
2278
+ errorMessage?: string | undefined;
2279
+ rawStopReason?: string | undefined;
2280
+ thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | undefined;
2281
+ providerThinkingLevel?: string | undefined;
2282
+ endTurn?: boolean | undefined;
2283
+ durationMs?: number | undefined;
2284
+ } | {
2285
+ role: "toolResult";
2286
+ toolCallId: string;
2287
+ toolName: string;
2288
+ content: ({
2289
+ type: "text";
2290
+ text: string;
2291
+ textSignature?: string | undefined;
2292
+ } | {
2293
+ type: "image";
2294
+ data: string;
2295
+ mimeType: string;
2296
+ })[];
2297
+ isError: boolean;
2298
+ timestamp: number;
2299
+ details?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
2300
+ usage?: {
2301
+ input: number;
2302
+ output: number;
2303
+ cacheRead: number;
2304
+ cacheWrite: number;
2305
+ totalTokens: number;
2306
+ cost: {
2307
+ input: number;
2308
+ output: number;
2309
+ cacheRead: number;
2310
+ cacheWrite: number;
2311
+ total: number;
2312
+ totalFromProvider?: boolean | undefined;
2313
+ };
2314
+ cacheWrite1h?: number | undefined;
2315
+ reasoning?: number | undefined;
2316
+ } | undefined;
2317
+ durationMs?: number | undefined;
2318
+ };
2319
+ })[];
2320
+ behaviorConstraints?: {
2321
+ name: string;
2322
+ title: string;
2323
+ constraints: {
2324
+ toolNames: string[];
2325
+ workspace?: "read-only" | undefined;
2326
+ };
2327
+ }[] | undefined;
2328
+ }>;
2329
+ type SessionForkSeed = Readonly<Omit<SessionForkedPayload, 'conversation'>> & {
2330
+ readonly conversation: readonly ConversationEntry[];
2331
+ };
2332
+ //#endregion
2333
+ //#region src/session/history/effective-conversation.d.ts
2334
+ /**
2335
+ * Complete model-eligible exchanges at a committed Journal prefix, including
2336
+ * compaction summaries. Unlike committedConversationMessages, this respects
2337
+ * input transformations and compaction. Request-specific selection and Context
2338
+ * material are not applied. Context-fork material is owned by its separate seed.
2339
+ */
2340
+ declare function effectiveConversationEntries(facts: readonly JournalFact[]): readonly ConversationEntry[];
2341
+ /**
2342
+ * What facts read after the latest compaction's source boundary cannot carry: that
2343
+ * compaction's resolved retained tail and earlier request evidence. With it, compaction and
2344
+ * request reconstruction read one epoch instead of the whole Journal. A result that still
2345
+ * needs an earlier fact throws rather than differing, so the caller can repeat it in full.
2346
+ */
2347
+ interface HistoryScope {
2348
+ readonly compactionId: string;
2349
+ readonly retainedTail: readonly ConversationEntry[];
2350
+ readonly requestBase: (requestBaseId: string) => ModelRequestBaseFact | undefined;
2351
+ /** Complete named states of an applied request, as its reuse chain expands to. */
2352
+ readonly namedStates: (modelRequestId: string) => ContextSnapshot['namedStates'] | undefined;
2353
+ }
2354
+ //#endregion
2355
+ //#region src/session/compaction/blocks.d.ts
2356
+ interface SkeletonBlock {
2357
+ readonly index: number;
2358
+ readonly message: UserMessage;
2359
+ readonly tokens: number;
2360
+ }
2361
+ interface CompactionChunk {
2362
+ readonly index: number;
2363
+ readonly blocks: readonly SkeletonBlock[];
2364
+ readonly messages: readonly UserMessage[];
2365
+ readonly tokens: number;
2366
+ }
2367
+ //#endregion
2368
+ //#region src/session/compaction/projection.d.ts
2369
+ interface CompactionSource {
2370
+ readonly sourceSequence: number;
2371
+ readonly sourceReferences: readonly ConversationEntryReference[];
2372
+ readonly entries: readonly ConversationEntry[];
2373
+ readonly effectiveEntries: readonly ConversationEntry[];
2374
+ readonly inheritedMessages: number;
2375
+ readonly previousSummary?: string;
2376
+ }
2377
+ /**
2378
+ * An immutable partition of one Journal snapshot.
2379
+ *
2380
+ * `messagesToSummarize` and `retainedTail` partition the uncompacted source at
2381
+ * a user or Assistant message boundary, matching Pi's cut-point semantics: a
2382
+ * Tool result is never a valid cut start, so a Tool call is never separated
2383
+ * from its result. When the cut lands on an Assistant message inside a turn,
2384
+ * `isSplitTurn` is set and `turnPrefixMessages` holds the summarized prefix of
2385
+ * that turn (empty otherwise). `checkpointPrefix` additionally includes the
2386
+ * previous synthetic summary when one exists. Planning may narrow this
2387
+ * candidate by moving the cut forward before any Provider request is
2388
+ * assembled.
2389
+ */
2390
+ interface SessionCompactionCoverage extends CompactionSource {
2391
+ readonly tokensBefore: number;
2392
+ readonly messagesToSummarize: readonly ConversationEntry[];
2393
+ readonly turnPrefixMessages: readonly ConversationEntry[];
2394
+ readonly isSplitTurn: boolean;
2395
+ readonly checkpointPrefix: readonly ConversationEntry[];
2396
+ readonly retainedTail: readonly ConversationEntry[];
2397
+ readonly coverage: readonly ConversationEntryReference[];
2398
+ }
2399
+ /** Prefix coverage proposed from retention policy, before request-budget planning. */
2400
+ interface SessionCompactionCandidate extends SessionCompactionCoverage {
2401
+ readonly stage: 'candidate';
2402
+ }
2403
+ /** Final prefix coverage that may be persisted and assembled into a Provider request. */
2404
+ interface PreparedSessionCompaction extends SessionCompactionCoverage {
2405
+ readonly stage: 'planned';
2406
+ }
2407
+ /**
2408
+ * Selects a prefix checkpoint candidate without dispatching a model request or
2409
+ * mutating Journal state. The returned `sourceSequence` is the compare-and-append
2410
+ * boundary that must still hold when `compaction.requested` is persisted.
2411
+ */
2412
+ declare function prepareSessionCompaction(facts: readonly JournalFact[], settings: CompactionSettings, force: boolean, estimateMessageTokens: (message: Message) => number, estimateMessagesTokens: (messages: readonly Message[]) => number, requiredReductionTokens: number, excludedMessageId?: string, protectedMessageId?: string, scope?: HistoryScope): SessionCompactionCandidate | undefined;
2413
+ declare function projectedMessagesAfterCompaction(summary: string, retainedTail: readonly ConversationEntry[], timestamp: number): ({
2414
+ role: "user";
2415
+ content: string | ({
2416
+ type: "text";
2417
+ text: string;
2418
+ textSignature?: string | undefined;
2419
+ } | {
2420
+ type: "image";
2421
+ data: string;
2422
+ mimeType: string;
2423
+ })[];
2424
+ timestamp: number;
2425
+ } | {
2426
+ role: "assistant";
2427
+ content: ({
2428
+ type: "text";
2429
+ text: string;
2430
+ textSignature?: string | undefined;
2431
+ } | {
2432
+ type: "thinking";
2433
+ thinking: string;
2434
+ thinkingSignature?: string | undefined;
2435
+ redacted?: boolean | undefined;
2436
+ } | {
2437
+ type: "toolCall";
2438
+ id: string;
2439
+ name: string;
2440
+ arguments: Record<string, _sorbetai_schema30.JsonValue>;
2441
+ thoughtSignature?: string | undefined;
2442
+ argumentsError?: string | undefined;
2443
+ })[];
2444
+ api: string;
2445
+ provider: string;
2446
+ model: string;
2447
+ usage: {
2448
+ input: number;
2449
+ output: number;
2450
+ cacheRead: number;
2451
+ cacheWrite: number;
2452
+ totalTokens: number;
2453
+ cost: {
2454
+ input: number;
2455
+ output: number;
2456
+ cacheRead: number;
2457
+ cacheWrite: number;
2458
+ total: number;
2459
+ totalFromProvider?: boolean | undefined;
2460
+ };
2461
+ cacheWrite1h?: number | undefined;
2462
+ reasoning?: number | undefined;
2463
+ };
2464
+ stopReason: "error" | "pending" | "stop" | "length" | "toolUse" | "aborted" | "deferred";
2465
+ timestamp: number;
2466
+ responseModel?: string | undefined;
2467
+ responseId?: string | undefined;
2468
+ diagnostics?: {
2469
+ type: string;
2470
+ timestamp: number;
2471
+ error?: {
2472
+ message: string;
2473
+ name?: string | undefined;
2474
+ stack?: string | undefined;
2475
+ code?: string | number | undefined;
2476
+ } | undefined;
2477
+ details?: Record<string, _sorbetai_schema30.JsonValue> | undefined;
2478
+ }[] | undefined;
2479
+ deferred?: {
2480
+ provider: string;
2481
+ modelId: string;
2482
+ api: string;
2483
+ id: string;
2484
+ expiresAt?: number | undefined;
2485
+ pollAfterMs?: number | undefined;
2486
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
2487
+ } | undefined;
2488
+ errorMessage?: string | undefined;
2489
+ rawStopReason?: string | undefined;
2490
+ thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | undefined;
2491
+ providerThinkingLevel?: string | undefined;
2492
+ endTurn?: boolean | undefined;
2493
+ durationMs?: number | undefined;
2494
+ } | {
2495
+ role: "toolResult";
2496
+ toolCallId: string;
2497
+ toolName: string;
2498
+ content: ({
2499
+ type: "text";
2500
+ text: string;
2501
+ textSignature?: string | undefined;
2502
+ } | {
2503
+ type: "image";
2504
+ data: string;
2505
+ mimeType: string;
2506
+ })[];
2507
+ isError: boolean;
2508
+ timestamp: number;
2509
+ details?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
2510
+ usage?: {
2511
+ input: number;
2512
+ output: number;
2513
+ cacheRead: number;
2514
+ cacheWrite: number;
2515
+ totalTokens: number;
2516
+ cost: {
2517
+ input: number;
2518
+ output: number;
2519
+ cacheRead: number;
2520
+ cacheWrite: number;
2521
+ total: number;
2522
+ totalFromProvider?: boolean | undefined;
2523
+ };
2524
+ cacheWrite1h?: number | undefined;
2525
+ reasoning?: number | undefined;
2526
+ } | undefined;
2527
+ durationMs?: number | undefined;
2528
+ })[];
2529
+ //#endregion
2530
+ //#region src/session/compaction/fork.d.ts
2531
+ interface CompactionForkEvidence {
2532
+ readonly sourceModelRequestId: string;
2533
+ readonly sharedConversationMessages: number;
2534
+ readonly cacheCompatible: boolean;
2535
+ }
2536
+ /**
2537
+ * Provider-ready input derived from one immutable compaction plan. Building a
2538
+ * fork never changes the plan's source coverage.
2539
+ */
2540
+ interface PreparedCompactionFork {
2541
+ readonly context: ModelContext;
2542
+ readonly evidence: CompactionForkEvidence;
2543
+ }
2544
+ //#endregion
2545
+ //#region src/session/compaction/planning.d.ts
2546
+ interface PlanSessionCompactionOptions {
2547
+ readonly facts: readonly JournalFact[];
2548
+ readonly candidate: SessionCompactionCandidate;
2549
+ readonly model: CompactionModel;
2550
+ readonly timestamp: number;
2551
+ readonly instructions?: string;
2552
+ readonly summaryMaxOutputTokens?: number;
2553
+ /** Set when `facts` start at the latest compaction boundary instead of genesis. */
2554
+ readonly scope?: HistoryScope;
2555
+ }
2556
+ interface CompactionInputBudget {
2557
+ readonly contextLimitTokens: number;
2558
+ readonly fixedInputTokens: number;
2559
+ readonly outputLimitTokens: number;
2560
+ readonly safetyMarginTokens: number;
2561
+ readonly historyLimitTokens: number;
2562
+ readonly chunkTargetTokens: number;
2563
+ }
2564
+ interface CompactionRouteDecision {
2565
+ readonly route: 'direct' | 'skeleton';
2566
+ readonly pendingTokens: number;
2567
+ readonly skeletonTokens: number;
2568
+ readonly cacheReadRate?: number;
2569
+ readonly cacheReadPriceRatio?: number;
2570
+ readonly breakEvenTokens?: number;
2571
+ readonly savingsMargin: number;
2572
+ readonly reason: 'cache-economics' | 'cache-unknown' | 'cache-miss' | 'model-mismatch' | 'pricing-unavailable' | 'direct-overflow' | 'split-turn';
2573
+ }
2574
+ /** One summarizable segment of a compaction: the history prefix or a split-turn prefix. */
2575
+ interface PlannedSummaryUnit {
2576
+ readonly kind: 'history' | 'turn-prefix';
2577
+ readonly command: UserMessage;
2578
+ readonly route: 'direct' | 'skeleton';
2579
+ readonly budget: CompactionInputBudget;
2580
+ readonly decision: CompactionRouteDecision;
2581
+ readonly directFork?: PreparedCompactionFork;
2582
+ readonly chunks: readonly CompactionChunk[];
2583
+ readonly sourceEntries: readonly ConversationEntry[];
2584
+ }
2585
+ /**
2586
+ * Final immutable coverage and Provider-ready inputs for one summary workflow.
2587
+ *
2588
+ * A split turn produces two units: `history` summarizes everything before the
2589
+ * current turn, and `turnPrefix` summarizes the detached prefix of the current
2590
+ * turn with its own prompt, matching Pi's split-turn compaction. Either unit
2591
+ * is absent when it has nothing to summarize.
2592
+ */
2593
+ interface PlannedSessionCompaction {
2594
+ readonly preparation: PreparedSessionCompaction;
2595
+ readonly history?: PlannedSummaryUnit;
2596
+ readonly turnPrefix?: PlannedSummaryUnit;
2597
+ }
2598
+ declare function planSessionCompaction(options: PlanSessionCompactionOptions): PlannedSessionCompaction;
2599
+ //#endregion
2600
+ //#region src/session/compaction/tokens.d.ts
2601
+ interface ContextTokenEstimate {
2602
+ readonly tokens: number;
2603
+ readonly usageTokens: number;
2604
+ readonly trailingTokens: number;
2605
+ readonly lastUsageIndex: number | null;
2606
+ }
2607
+ interface ModelRequestScalarCapture {
2608
+ readonly onMessage: (index: number, contentTokens: number, toolsTokens: number, imageCount: number) => void;
2609
+ readonly onTotals: (systemTokens: number, toolsTokens: number, protocolTokens: number, tokens: number) => void;
2610
+ }
2611
+ /**
2612
+ * Uses the latest completed Provider measurement as an anchor, then estimates
2613
+ * only messages appended after it. This keeps Sorbet's threshold policy local
2614
+ * without discarding better evidence already returned by the Provider.
2615
+ */
2616
+ declare function estimateContextTokens(messages: readonly Message[]): ContextTokenEstimate;
2617
+ declare function shouldCompact(contextTokensBefore: number, contextWindow: number, settings: CompactionSettings): boolean;
2618
+ declare function estimateMessagesTokens(messages: readonly Message[], capture?: ModelRequestScalarCapture['onMessage']): number;
2619
+ declare function estimateMessageTokens(message: Message, capture?: (contentTokens: number, toolsTokens: number, imageCount: number) => void): number;
2620
+ //#endregion
2621
+ //#region src/session/compaction/workflow.d.ts
2622
+ interface CompactionDispatchRequest {
2623
+ readonly phase: 'direct' | 'chunk' | 'merge' | 'final' | 'empty-retry' | 'provider-reduction';
2624
+ readonly unit: 'history' | 'turn-prefix';
2625
+ readonly route: 'direct' | 'skeleton';
2626
+ readonly depth: number;
2627
+ readonly partIndex: number;
2628
+ readonly partCount: number;
2629
+ readonly context: ModelContext;
2630
+ readonly estimatedInputTokens: number;
2631
+ readonly maxOutputTokens: number;
2632
+ }
2633
+ type CompactionDispatchResult = {
2634
+ readonly kind: 'response';
2635
+ readonly attemptId: string;
2636
+ readonly response: AssistantMessage;
2637
+ readonly contextOverflow: boolean;
2638
+ } | {
2639
+ readonly kind: 'failed';
2640
+ readonly attemptId: string;
2641
+ readonly error: Error;
2642
+ };
2643
+ interface CompactionWorkflowOptions {
2644
+ readonly unit: PlannedSummaryUnit;
2645
+ readonly previousSummary?: string;
2646
+ readonly timestamp: number;
2647
+ readonly dispatch: (request: CompactionDispatchRequest) => Promise<CompactionDispatchResult>;
2648
+ }
2649
+ interface CompactionWorkflowResult {
2650
+ readonly summary: string;
2651
+ readonly finalAttemptId: string;
2652
+ readonly attemptIds: readonly string[];
2653
+ readonly attempts: readonly CompactionAttemptUsage[];
2654
+ }
2655
+ declare class CompactionWorkflowError extends Error {
2656
+ readonly code: CompactionFailureCode;
2657
+ constructor(code: CompactionFailureCode, message: string);
2658
+ }
2659
+ declare function executeCompactionWorkflow(options: CompactionWorkflowOptions): Promise<CompactionWorkflowResult>;
2660
+ //#endregion
2661
+ //#region src/session/continuation/contracts.d.ts
2662
+ declare const ContinuationReplayPlanSchema: s.Schema<{
2663
+ schemaVersion: 1;
2664
+ sessionId: string;
2665
+ sourceRunId: string;
2666
+ sourceOutcome: "completed" | "failed" | "cancelled";
2667
+ anchor: {
2668
+ sequence: number;
2669
+ cursor: string;
2670
+ };
2671
+ uncertainties: {
2672
+ modelRequestIds: string[];
2673
+ effectAttemptIds: string[];
2674
+ };
2675
+ }>;
2676
+ type ContinuationReplayPlan = Readonly<s.Static<typeof ContinuationReplayPlanSchema>>;
2677
+ //#endregion
2678
+ //#region src/session/continuation/plan.d.ts
2679
+ declare function buildContinuationReplayPlan(facts: readonly JournalFact[], sourceRunId: string): ContinuationReplayPlan;
2680
+ //#endregion
2681
+ //#region src/tasks/contracts.d.ts
2682
+ type WaitMember = TaskWaitMember;
2683
+ type JoinPolicy = TaskJoinPolicy;
2684
+ type TaskOutcome<R = JsonValue> = {
2685
+ readonly status: 'completed';
2686
+ readonly result: R;
2687
+ } | Exclude<TaskOutcome$1, {
2688
+ status: 'completed';
2689
+ }>;
2690
+ type TaskReservation = Extract<TaskFact, {
2691
+ kind: 'task.reserved';
2692
+ }>['payload'];
2693
+ type TaskState<R = JsonValue> = {
2694
+ readonly status: 'pending' | 'running';
2695
+ } | {
2696
+ readonly status: 'waiting';
2697
+ readonly on: readonly WaitMember[];
2698
+ readonly policy: JoinPolicy;
2699
+ } | {
2700
+ readonly status: 'sleeping';
2701
+ readonly until: number;
2702
+ } | {
2703
+ readonly status: 'completing' | 'terminal';
2704
+ readonly outcome: TaskOutcome<R>;
2705
+ };
2706
+ interface TaskRecord<I = JsonValue, S extends {
2707
+ phase: string;
2708
+ } = TaskCheckpoint, R = JsonValue> {
2709
+ readonly taskId: string;
2710
+ readonly kind: string;
2711
+ readonly version: number;
2712
+ readonly owner: TaskOwner;
2713
+ readonly creationKey: string;
2714
+ readonly background: boolean;
2715
+ readonly input: I;
2716
+ readonly checkpoint: S;
2717
+ readonly state: TaskState<R>;
2718
+ readonly restarts: number;
2719
+ readonly parked: boolean;
2720
+ /** Last durable reservation; only the kernel's live invocation may still use it. */
2721
+ readonly reservation?: TaskReservation;
2722
+ readonly invocationClosed: boolean;
2723
+ readonly abortRequested?: {
2724
+ readonly reason: string;
2725
+ readonly requester: string;
2726
+ };
2727
+ }
2728
+ interface SignalRecord {
2729
+ readonly signalId: string;
2730
+ readonly taskId: string;
2731
+ readonly type: 'host-command' | 'elicitation' | 'message-reply';
2732
+ readonly payload: JsonValue;
2733
+ readonly state: {
2734
+ readonly status: 'open';
2735
+ } | {
2736
+ readonly status: 'resolved';
2737
+ readonly result: JsonValue;
2738
+ } | {
2739
+ readonly status: 'cancelled';
2740
+ readonly reason: string;
2741
+ };
2742
+ }
2743
+ interface RunningTask<I, S> {
2744
+ readonly taskId: string;
2745
+ readonly input: I;
2746
+ readonly checkpoint: S;
2747
+ readonly abortRequested?: TaskRecord['abortRequested'];
2748
+ }
2749
+ type NextState<S, R> = {
2750
+ readonly status: 'pending';
2751
+ readonly checkpoint: S;
2752
+ } | {
2753
+ readonly status: 'waiting';
2754
+ readonly checkpoint: S;
2755
+ readonly on: readonly WaitMember[];
2756
+ readonly policy: JoinPolicy;
2757
+ } | {
2758
+ readonly status: 'sleeping';
2759
+ readonly checkpoint: S;
2760
+ readonly until: number;
2761
+ } | {
2762
+ readonly status: 'completed';
2763
+ readonly result: R;
2764
+ } | {
2765
+ readonly status: 'failed';
2766
+ readonly error: {
2767
+ readonly code: string;
2768
+ readonly message: string;
2769
+ };
2770
+ } | {
2771
+ readonly status: 'aborted';
2772
+ readonly reason: string;
2773
+ };
2774
+ /** Additional write targets prepared before the synchronous group; not an authority grant. */
2775
+ interface SessionParticipants {
2776
+ readonly sessions?: readonly string[];
2777
+ readonly submissions?: readonly string[];
2778
+ }
2779
+ interface CreateTaskOptions<S extends {
2780
+ phase: string;
2781
+ } = TaskCheckpoint, R = JsonValue> {
2782
+ readonly key: string;
2783
+ /** Preserve an existing domain identity when adopting work into a Task. Unique within the Unit. */
2784
+ readonly taskId?: string;
2785
+ /** Defaults to the current Task in a phase, the invoking Session in a staged Tool, or the root for startTask. */
2786
+ readonly owner?: TaskOwner;
2787
+ readonly background?: boolean;
2788
+ /** Cross-Session targets used by top-level initialization; nested creation uses the outer commit. */
2789
+ readonly participants?: SessionParticipants;
2790
+ /**
2791
+ * Optional synchronous initialization in the creation group. The transaction owns
2792
+ * the new Task, so Signals and its initial wait can become durable together.
2793
+ * Return a checkpoint change, wait, sleep or outcome; schemas still apply.
2794
+ * Runs only for a new creation key, never for an idempotent repeat. A throw rejects
2795
+ * the entire group. No external I/O; neither this callback nor its tx may escape.
2796
+ */
2797
+ readonly initialize?: (tx: UnitTx) => NextState<S, R>;
2798
+ }
2799
+ type TaskSubmission = Extract<JournalFact, {
2800
+ kind: 'submission.accepted';
2801
+ }>['payload'];
2802
+ interface TaskSubmitOptions {
2803
+ readonly whenBusy: TaskSubmission['whenBusy'];
2804
+ /** Preserve the input's domain source; Task phases otherwise retain their task:<id> provenance. */
2805
+ readonly preserveSource?: boolean;
2806
+ readonly runConfiguration?: Pick<TaskSubmission, 'toolPermissionPolicy' | 'approvalMode'>;
2807
+ readonly forkSeed?: TaskSubmission['forkSeed'];
2808
+ }
2809
+ interface UnitTx {
2810
+ /**
2811
+ * Create a child and permit its first Submission in this group, without acquiring
2812
+ * execution resources. Caller-supplied identity and metadata must match on a
2813
+ * repeated parent/key. The parent must be open and belong to this Unit.
2814
+ */
2815
+ createSession(input: {
2816
+ readonly sessionId: string;
2817
+ readonly parentSessionId: string;
2818
+ readonly key: string;
2819
+ readonly metadata: JsonValue;
2820
+ }): string;
2821
+ /** Fence new input/admission before Host cleanup. Shares a group with its close Signal. */
2822
+ beginSessionClose(sessionId: string): void;
2823
+ /** Permanent child close after the Host has released its execution facade and resources. */
2824
+ closeSession(sessionId: string): void;
2825
+ /** Enqueue with this group. Reply Signals require a Task phase and share its commit. */
2826
+ sendMessage(message: MessageDraft, options: SendMessageOptions): SentMessage;
2827
+ /** Acceptance shares the Task checkpoint or Tool Effect commit. Routing happens after durability. */
2828
+ submit(sessionId: string, input: TaskSubmission['input'], options: TaskSubmitOptions): string;
2829
+ /**
2830
+ * Withdraw unplaced input in this group. Missing or already placed input returns
2831
+ * false; repeating a withdrawal returns true. Never cancels the selected Run.
2832
+ */
2833
+ withdrawSubmission(submissionId: string, reason: string, commandId: string): boolean;
2834
+ run(runId: string): {
2835
+ readonly ended: boolean;
2836
+ } | undefined;
2837
+ submission(submissionId: string): {
2838
+ readonly sessionId: string;
2839
+ readonly ended: boolean;
2840
+ readonly runId?: string;
2841
+ } | undefined;
2842
+ createTask<I, S extends {
2843
+ phase: string;
2844
+ }, R>(definition: TaskDefinition<I, S, R>, input: I, options: CreateTaskOptions<NoInfer<S>, NoInfer<R>>): string;
2845
+ createSignal(input: {
2846
+ readonly key: string;
2847
+ readonly type: SignalRecord['type'];
2848
+ readonly payload: JsonValue;
2849
+ }): string;
2850
+ resolveSignal(signalId: string, result: JsonValue, commandId: string): void;
2851
+ abortTask(taskId: string, reason: string, requester: string): void;
2852
+ getTask(taskId: string): TaskRecord | undefined;
2853
+ signal(signalId: string): SignalRecord | undefined;
2854
+ }
2855
+ interface TaskRuntime<I, S, R> {
2856
+ readonly taskId: string;
2857
+ readonly epochId: string;
2858
+ readonly signal: AbortSignal;
2859
+ /**
2860
+ * Build one atomic group synchronously. Pending saves retain this invocation;
2861
+ * waiting, sleeping and outcomes close its writes, even if a wait is already satisfied.
2862
+ * The current checkpoint includes this invocation's earlier saves. No next invocation
2863
+ * starts until the handler returns. Returning void writes facts without recording progress.
2864
+ * A callback exception rolls back its group. Caught schema/key violations still fault
2865
+ * the Task before handoff; errors after handoff are reported without changing that decision.
2866
+ */
2867
+ commit(change: (tx: UnitTx, current: RunningTask<I, S>) => NextState<S, R> | void, participants?: SessionParticipants): Promise<void>;
2868
+ /**
2869
+ * Read a Task in this Unit; decode checkpoint and result with its definition's schemas.
2870
+ * An ended Task owned by an ended Task has left memory and reads as undefined.
2871
+ */
2872
+ getTask(id: string): Promise<TaskRecord | undefined>;
2873
+ /** Outcomes of ended Tasks among `ids`; rejects for a Task whose record has left memory. */
2874
+ outcomes(ids: readonly string[]): Promise<readonly TaskOutcome[]>;
2875
+ /** Direct child Tasks of this Task, in creation order. */
2876
+ ownedTasks(): Promise<readonly TaskRecord[]>;
2877
+ abortOwned(id: string, reason: string): Promise<void>;
2878
+ now(): number;
2879
+ /** Accepts caught host exceptions; the kernel normalizes them to Error before observation. */
2880
+ report(error: unknown): void;
2881
+ }
2882
+ interface TaskDefinition<I, S extends {
2883
+ phase: string;
2884
+ }, R> {
2885
+ readonly name: string;
2886
+ readonly version: number;
2887
+ readonly inputSchema: s.Schema<I>;
2888
+ readonly checkpointSchema: s.Schema<S>;
2889
+ readonly resultSchema: s.Schema<R>;
2890
+ initial(input: I): S;
2891
+ readonly phases: { readonly [P in S['phase']]: (task: RunningTask<I, Extract<S, {
2892
+ phase: P;
2893
+ }>>, runtime: TaskRuntime<I, S, R>) => Promise<void> };
2894
+ abort(task: RunningTask<I, S>, runtime: TaskRuntime<I, S, R>): Promise<void>;
2895
+ }
2896
+ interface TaskHandle<I = JsonValue, S extends {
2897
+ phase: string;
2898
+ } = TaskCheckpoint, R = JsonValue> {
2899
+ readonly taskId: string;
2900
+ /** Throws once an ended Task owned by an ended Task has left memory. */
2901
+ record(): TaskRecord<I, S, R>;
2902
+ /**
2903
+ * Rejects on caller cancellation or Unit close; neither operation changes the Task.
2904
+ * A wait that started before settlement resolves even if the record then leaves memory.
2905
+ */
2906
+ settled(signal?: AbortSignal): Promise<TaskOutcome<R>>;
2907
+ }
2908
+ declare class TaskContractError extends Error {
2909
+ readonly code: 'invalid_state' | 'invalid_schema' | 'creation_key_conflict' | 'no_progress';
2910
+ constructor(code: 'invalid_state' | 'invalid_schema' | 'creation_key_conflict' | 'no_progress', message: string, options?: ErrorOptions);
2911
+ }
2912
+ //#endregion
2913
+ //#region src/tasks/definition.d.ts
2914
+ /** Schemas determine handler types and are checked again at every durable boundary. */
2915
+ declare function defineTask<I, S extends {
2916
+ phase: string;
2917
+ }, R>(definition: TaskDefinition<I, S, R>): typeof definition;
2918
+ //#endregion
2919
+ //#region src/tasks/schedule.d.ts
2920
+ declare const ScheduleInputSchema: s.Schema<{
2921
+ sessionId: string;
2922
+ timing: {
2923
+ kind: "at";
2924
+ at: number;
2925
+ } | {
2926
+ kind: "every";
2927
+ startAt: number;
2928
+ intervalMs: number;
2929
+ missed: "skip" | "once" | "all";
2930
+ };
2931
+ target: {
2932
+ kind: "submission";
2933
+ input: {
2934
+ kind: "user-message";
2935
+ prompt: string | ({
2936
+ type: "text";
2937
+ text: string;
2938
+ textSignature?: string | undefined;
2939
+ } | {
2940
+ type: "image";
2941
+ data: string;
2942
+ mimeType: string;
2943
+ })[];
2944
+ source: {
2945
+ kind: string;
2946
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
2947
+ };
2948
+ } | {
2949
+ kind: "context-event";
2950
+ source: {
2951
+ kind: string;
2952
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
2953
+ };
2954
+ contextSources: ({
2955
+ lifecycle: "turn";
2956
+ kind: "instructions";
2957
+ channel: "developer" | "agents";
2958
+ content: string;
2959
+ sourceId: string;
2960
+ provenance: {
2961
+ origin: "file" | "runtime" | "host" | "journal";
2962
+ label: string;
2963
+ location?: string | undefined;
2964
+ };
2965
+ } | {
2966
+ lifecycle: "turn";
2967
+ kind: "extension";
2968
+ extensionKind: "extension" | "skill" | "plugin" | "app" | "memory";
2969
+ name: string;
2970
+ content: string;
2971
+ sourceId: string;
2972
+ provenance: {
2973
+ origin: "file" | "runtime" | "host" | "journal";
2974
+ label: string;
2975
+ location?: string | undefined;
2976
+ };
2977
+ } | {
2978
+ lifecycle: "turn";
2979
+ kind: "document";
2980
+ name: string;
2981
+ mediaType: string;
2982
+ content: string;
2983
+ sourceId: string;
2984
+ provenance: {
2985
+ origin: "file" | "runtime" | "host" | "journal";
2986
+ label: string;
2987
+ location?: string | undefined;
2988
+ };
2989
+ } | {
2990
+ lifecycle: "turn";
2991
+ kind: "event";
2992
+ event: {
2993
+ kind: "text";
2994
+ name: string;
2995
+ attributes?: Record<string, string | number>;
2996
+ text: string;
2997
+ } | {
2998
+ kind: "container";
2999
+ name: string;
3000
+ attributes?: Record<string, string | number>;
3001
+ children: _sorbetai_context56.ContextXmlElement[];
3002
+ };
3003
+ sourceId: string;
3004
+ provenance: {
3005
+ origin: "file" | "runtime" | "host" | "journal";
3006
+ label: string;
3007
+ location?: string | undefined;
3008
+ };
3009
+ metadata?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
3010
+ })[];
3011
+ };
3012
+ whenBusy: "followUp" | "steer";
3013
+ } | {
3014
+ kind: "message";
3015
+ targetUnitId: string;
3016
+ targetSessionId: string;
3017
+ input: {
3018
+ kind: "user-message";
3019
+ prompt: string | ({
3020
+ type: "text";
3021
+ text: string;
3022
+ textSignature?: string | undefined;
3023
+ } | {
3024
+ type: "image";
3025
+ data: string;
3026
+ mimeType: string;
3027
+ })[];
3028
+ source: {
3029
+ kind: string;
3030
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
3031
+ };
3032
+ } | {
3033
+ kind: "context-event";
3034
+ source: {
3035
+ kind: string;
3036
+ data?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
3037
+ };
3038
+ contextSources: ({
3039
+ lifecycle: "turn";
3040
+ kind: "instructions";
3041
+ channel: "developer" | "agents";
3042
+ content: string;
3043
+ sourceId: string;
3044
+ provenance: {
3045
+ origin: "file" | "runtime" | "host" | "journal";
3046
+ label: string;
3047
+ location?: string | undefined;
3048
+ };
3049
+ } | {
3050
+ lifecycle: "turn";
3051
+ kind: "extension";
3052
+ extensionKind: "extension" | "skill" | "plugin" | "app" | "memory";
3053
+ name: string;
3054
+ content: string;
3055
+ sourceId: string;
3056
+ provenance: {
3057
+ origin: "file" | "runtime" | "host" | "journal";
3058
+ label: string;
3059
+ location?: string | undefined;
3060
+ };
3061
+ } | {
3062
+ lifecycle: "turn";
3063
+ kind: "document";
3064
+ name: string;
3065
+ mediaType: string;
3066
+ content: string;
3067
+ sourceId: string;
3068
+ provenance: {
3069
+ origin: "file" | "runtime" | "host" | "journal";
3070
+ label: string;
3071
+ location?: string | undefined;
3072
+ };
3073
+ } | {
3074
+ lifecycle: "turn";
3075
+ kind: "event";
3076
+ event: {
3077
+ kind: "text";
3078
+ name: string;
3079
+ attributes?: Record<string, string | number>;
3080
+ text: string;
3081
+ } | {
3082
+ kind: "container";
3083
+ name: string;
3084
+ attributes?: Record<string, string | number>;
3085
+ children: _sorbetai_context56.ContextXmlElement[];
3086
+ };
3087
+ sourceId: string;
3088
+ provenance: {
3089
+ origin: "file" | "runtime" | "host" | "journal";
3090
+ label: string;
3091
+ location?: string | undefined;
3092
+ };
3093
+ metadata?: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null | undefined;
3094
+ })[];
3095
+ };
3096
+ whenBusy: "followUp" | "steer";
3097
+ } | {
3098
+ kind: "task";
3099
+ input: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
3100
+ taskKind: string;
3101
+ version: number;
3102
+ };
3103
+ }>;
3104
+ /**
3105
+ * The Session owns this background schedule and local firings. Times are Unix
3106
+ * milliseconds; every uses startAt + n * intervalMs without drifting on delivery.
3107
+ * When a later grid point is already due, skip drops the entire backlog, once
3108
+ * fires the latest due point, and all commits each due point separately. Ordinary
3109
+ * timer lateness within one interval still fires the pending point.
3110
+ * Task targets must be registered at creation; their validated initial checkpoint
3111
+ * is captured so firing survives restart even before their handler is registered.
3112
+ */
3113
+ type ScheduleInput = s.Static<typeof ScheduleInputSchema>;
3114
+ //#endregion
3115
+ //#region src/tasks/kernel.d.ts
3116
+ interface TaskKernelOptions {
3117
+ /** Definitions produced by defineTask; registration is process-local and repeated on reopen. */
3118
+ readonly definitions?: readonly object[];
3119
+ readonly onError?: (error: Error) => void;
3120
+ /**
3121
+ * Consecutive unclean recoveries without progress before the Task is parked.
3122
+ * Defaults to Infinity: a repeatedly interrupted Task is recovered again unless
3123
+ * the Host opts into a finite limit.
3124
+ */
3125
+ readonly restartLimit?: number;
3126
+ /** Defaults to unlimited. Slots remain held until handlers return, including after handoff. */
3127
+ readonly concurrency?: {
3128
+ readonly unit?: number;
3129
+ readonly byKind?: Readonly<Record<string, number>>;
3130
+ };
3131
+ }
3132
+ //#endregion
3133
+ //#region src/session/contracts.d.ts
3134
+ interface ModelRetryPolicy {
3135
+ readonly enabled: boolean;
3136
+ /** Maximum retries after the initial physical request. */
3137
+ readonly maxRetries: number;
3138
+ /** Base delay in milliseconds; each subsequent retry doubles it. */
3139
+ readonly baseDelayMs: number;
3140
+ }
3141
+ interface StartRunInput {
3142
+ readonly prompt: UserPrompt;
3143
+ /** Durable provenance for this user message. Defaults to the direct Sorbet SDK boundary. */
3144
+ readonly source?: SessionInputSource;
3145
+ /** Binds this prompt to one admission; a retry observes that Run instead of executing again. */
3146
+ readonly idempotencyKey?: string;
3147
+ /** Immutable, turn-scoped Context admitted with this Run. */
3148
+ readonly contextSources?: readonly ContextSource[];
3149
+ /** Supplies current fixed definitions before each logical model call. */
3150
+ readonly prefixContributors?: readonly PrefixContextContributor[];
3151
+ readonly stateOwners?: readonly NamedStateOwner[];
3152
+ /** Immutable Tool policy for this Run. The Session policy is used when omitted. */
3153
+ readonly toolPermissionPolicy?: ToolPermissionPolicy;
3154
+ /** Approval strategy captured for this Run; defaults to human review. */
3155
+ readonly approvalMode?: ApprovalMode;
3156
+ /** Immutable Provider-neutral prefix captured at an authoritative Tool boundary. */
3157
+ readonly forkSeed?: ContextForkSeed;
3158
+ }
3159
+ type StartContinuationInput = Omit<StartRunInput, 'forkSeed'>;
3160
+ /**
3161
+ * A trusted Unit owner can stage durable changes alongside a successful model response.
3162
+ * Request sources are captured before dispatch; the receipt receives a copy of that
3163
+ * committed snapshot and model-visible Tool results after the last assistant message.
3164
+ */
3165
+ interface UnitModelContext {
3166
+ /** Supplies material for one logical request. Physical retries reuse captured sources. */
3167
+ read?(signal: AbortSignal): Promise<readonly RequestContextSource[]>;
3168
+ /** Runs synchronously in the response's atomic group; it must not perform external I/O. */
3169
+ stage(tx: UnitTx, snapshot: ContextSnapshot, modelRequestId: string, toolResults: readonly {
3170
+ readonly toolName: string;
3171
+ readonly isError: boolean;
3172
+ readonly text: readonly string[];
3173
+ }[]): void;
3174
+ }
3175
+ /**
3176
+ * A host resource owned exclusively by one admitted Run. Runtime invokes
3177
+ * `release` once after durable settlement; a failure faults the Session but
3178
+ * cannot replace the Run's terminal outcome.
3179
+ */
3180
+ interface RunExecutionResource {
3181
+ /** Host guarantee for the acquired execution environment, checked before restricted work. */
3182
+ readonly workspaceAccess?: 'read-only' | 'read-write';
3183
+ release(): void | Promise<void>;
3184
+ }
3185
+ /**
3186
+ * Acquires host resources before a new Run starts and again before a resumed Run executes. Acquisition failure durably fails that Run. The
3187
+ * provider must stop promptly when `signal` is aborted; a resource that resolves
3188
+ * after cancellation is released without starting the Run.
3189
+ */
3190
+ interface RunExecutionResourceProvider {
3191
+ acquire(runId: string, signal: AbortSignal, /** Admission requirements apply to every Run source, including resumed Runs. */
3192
+ requirements?: {
3193
+ readonly workspaceAccess: 'read-only';
3194
+ }): RunExecutionResource | Promise<RunExecutionResource>;
3195
+ }
3196
+ interface ResumeInterruptedRunOptions {
3197
+ readonly resourceProvider?: RunExecutionResourceProvider;
3198
+ readonly signal?: AbortSignal;
3199
+ /**
3200
+ * Required to resume a parked Run. Records attempt 1 on the next `run.resumed`,
3201
+ * without deleting earlier attempts or replaying their Effects or approvals.
3202
+ * The reset takes effect only when that fact commits.
3203
+ */
3204
+ readonly resetAttempts?: boolean;
3205
+ }
3206
+ interface StartRunOptions {
3207
+ readonly resourceProvider?: RunExecutionResourceProvider;
3208
+ }
3209
+ interface SendSessionInputOptions {
3210
+ /** Reject without durable acceptance when busy; otherwise placement waits for the Run boundary. */
3211
+ readonly whenBusy?: 'followUp' | 'steer' | 'reject';
3212
+ readonly forkSeed?: ContextForkSeed;
3213
+ /** Context events default to follow-up; steer presents them after the current Tool batch. */
3214
+ readonly contextEventMode?: 'steer' | 'followUp';
3215
+ /** Immutable Run admission policy; execution environment comes from the host Session. */
3216
+ readonly runConfiguration?: Pick<StartRunInput, 'toolPermissionPolicy' | 'approvalMode'>;
3217
+ readonly signal?: AbortSignal;
3218
+ }
3219
+ declare class SessionForkBusyError extends Error {
3220
+ constructor(message?: string);
3221
+ }
3222
+ /** Strict start() cannot replace a different admitted Run. Use submit() to route input. */
3223
+ declare class SessionRunActiveError extends Error {
3224
+ readonly code = "session_run_active";
3225
+ constructor();
3226
+ }
3227
+ declare class SessionBusyError extends Error {
3228
+ readonly code = "session_busy";
3229
+ constructor(message: string);
3230
+ }
3231
+ //#endregion
3232
+ //#region src/session/external-tools.d.ts
3233
+ interface InvokeToolInput {
3234
+ readonly name: string;
3235
+ readonly arguments: unknown;
3236
+ /** Reject unless the captured Plugin Tool has this exact binding. */
3237
+ readonly expectedBindingId?: string;
3238
+ readonly source?: SessionInputSource;
3239
+ }
3240
+ interface InvokeToolOptions {
3241
+ readonly signal?: AbortSignal;
3242
+ readonly onUpdate?: ToolUpdateCallback<unknown>;
3243
+ readonly toolPermissionPolicy?: ToolPermissionPolicy;
3244
+ /** Acquired after durable admission and released after Tool and Plugin borrowers drain. */
3245
+ readonly resourceProvider?: {
3246
+ acquire(operationId: string, signal: AbortSignal, requirements?: {
3247
+ readonly workspaceAccess: 'read-only';
3248
+ }): RunExecutionResource | Promise<RunExecutionResource>;
3249
+ };
3250
+ }
3251
+ interface ToolOperationReceipt {
3252
+ readonly operationId: string;
3253
+ readonly toolCallId: string;
3254
+ readonly result: s.Static<typeof CompletedToolResultSchema>;
3255
+ }
3256
+ declare class ToolOperationError extends Error {
3257
+ readonly operationId: string;
3258
+ /** `unknown`: the Tool may have produced its Effect; a Host must not blindly retry it. */
3259
+ readonly status: 'failed' | 'denied' | 'cancelled' | 'unknown';
3260
+ constructor(operationId: string, /** `unknown`: the Tool may have produced its Effect; a Host must not blindly retry it. */
3261
+ status: 'failed' | 'denied' | 'cancelled' | 'unknown', message: string);
3262
+ }
3263
+ interface ExternalToolsOptions {
3264
+ readonly sessionId: string;
3265
+ readonly tools: readonly DiscoverableTool[];
3266
+ readonly modelTools?: ModelToolSource;
3267
+ readonly toolNames?: readonly string[];
3268
+ readonly toolOverrides?: readonly string[];
3269
+ readonly permissions?: PermissionComposition;
3270
+ readonly approvals?: ApprovalComposition;
3271
+ readonly createId: () => string;
3272
+ readonly now: () => Date;
3273
+ readonly permitsTool: (name: string) => boolean;
3274
+ readonly requiresReadOnly: () => Promise<boolean>;
3275
+ readonly fault: (error: Error) => void;
3276
+ }
3277
+ /** Executes admitted Host actions through the same policy and Plugin borrow boundaries as model Tools. */
3278
+ declare class SessionExternalTools {
3279
+ #private;
3280
+ constructor(options: ExternalToolsOptions);
3281
+ recover(facts: RunFactCommitter): Promise<void>;
3282
+ invoke(rawInput: InvokeToolInput, options: InvokeToolOptions, ownerSignal: AbortSignal, facts: RunFactCommitter): Promise<ToolOperationReceipt>;
3283
+ }
3284
+ //#endregion
3285
+ //#region src/session/fork-snapshot.d.ts
3286
+ interface ProjectSessionForkSeedOptions {
3287
+ readonly sourceRunId?: string;
3288
+ }
3289
+ /**
3290
+ * Projects a self-contained seed. The caller supplies an ordered, durable,
3291
+ * durable Journal prefix; projection does not establish storage durability.
3292
+ */
3293
+ declare function projectSessionForkSeed(sessionId: string, facts: readonly JournalFact[], options?: ProjectSessionForkSeedOptions): SessionForkSeed;
3294
+ //#endregion
3295
+ //#region src/session/history/conversation.d.ts
3296
+ interface ConversationDelta {
3297
+ readonly placedInput?: RunInput;
3298
+ readonly toolResult?: ToolResultMessage;
3299
+ /** On a Run terminal: every entry of that Run, before released history is dropped. */
3300
+ readonly runEntries?: readonly ConversationEntry[];
3301
+ }
3302
+ //#endregion
3303
+ //#region src/session/history/projection.d.ts
3304
+ type CommittedCompaction = Extract<JournalFact, {
3305
+ kind: 'compaction.committed';
3306
+ }>;
3307
+ /** Incremental, reconstructible Session projections fed only by durable facts. */
3308
+ declare class SessionHistoryProjection {
3309
+ #private;
3310
+ readonly context: ContextManager;
3311
+ constructor(context?: ContextManager);
3312
+ /** Returns a detached committed Tool result immediately; conversation entries wait for the complete Tool batch. */
3313
+ apply(fact: JournalFact, prepared?: ContextSnapshot): ConversationDelta;
3314
+ reset(): void;
3315
+ /**
3316
+ * Facts after `after` together with `scope` stand in for the whole Journal when preparing a
3317
+ * compaction or reconstructing a request of the current epoch. Undefined before the first
3318
+ * compaction, after a reset, or when the boundary fact's cursor is unknown.
3319
+ */
3320
+ historyScope(): {
3321
+ readonly after: JournalCursor;
3322
+ readonly scope: HistoryScope;
3323
+ } | undefined;
3324
+ contextSnapshot(fact: Extract<JournalFact, {
3325
+ kind: 'model.requested';
3326
+ }>): ContextSnapshot;
3327
+ resolveConversationReference(reference: ConversationEntryReference): ConversationEntry;
3328
+ estimateRequestContextTokens(fact: Extract<JournalFact, {
3329
+ kind: 'model.requested';
3330
+ }>): number;
3331
+ requestContextEstimate(fact: Extract<JournalFact, {
3332
+ kind: 'model.requested';
3333
+ }>): () => number;
3334
+ get sequence(): number;
3335
+ get cursor(): JournalCursor | undefined;
3336
+ get contextEpoch(): number;
3337
+ get forkSeed(): ContextForkSeed | undefined;
3338
+ get inheritedConversationEntries(): readonly ConversationEntry[];
3339
+ get hasCompaction(): boolean;
3340
+ get latestCompaction(): CommittedCompaction | undefined;
3341
+ get latestCompactionRetainedTail(): readonly ConversationEntry[];
3342
+ /** Local entries after a fact boundary, excluding reset and compaction-reclaimed history. */
3343
+ conversationEntriesAfter(sequence: number): readonly ConversationEntry[];
3344
+ effectiveConversationEntries(): readonly ConversationEntry[];
3345
+ estimateContextTokens(excludedMessageId?: string): number;
3346
+ }
3347
+ //#endregion
3348
+ //#region src/session/history/context-selection.d.ts
3349
+ interface ContextHistoryProjectionSnapshot {
3350
+ readonly sequence: number;
3351
+ readonly entries: readonly ConversationEntry[];
3352
+ }
3353
+ /** Builds selectable complete units from one already-committed effective projection. */
3354
+ declare function contextHistorySnapshot(projection: ContextHistoryProjectionSnapshot, currentRunId: string): ContextHistorySnapshot;
3355
+ //#endregion
3356
+ //#region src/session/history/model-view.d.ts
3357
+ /** Shared by live adoption, request estimates and durable reconstruction. */
3358
+ declare function projectModelView(entries: readonly ConversationEntry[], frames: readonly ContextTransitionFrame[], view: ContextModelView | undefined, runId: string, replacementLength?: number): {
3359
+ entries: readonly ConversationEntry[];
3360
+ frames: readonly ContextTransitionFrame[];
3361
+ };
3362
+ //#endregion
3363
+ //#region src/session/history/context-transitions.d.ts
3364
+ interface ModelRequestDispatchPart {
3365
+ readonly section: ContextAttributionSection;
3366
+ readonly frameId?: string;
3367
+ readonly stateName?: string;
3368
+ readonly revision?: number;
3369
+ }
3370
+ interface ModelRequestDispatchOptions {
3371
+ readonly sanitizeImages?: boolean;
3372
+ readonly capturePart?: (part: ModelRequestDispatchPart) => void;
3373
+ readonly inheritedSections?: readonly ContextAttributionSection[];
3374
+ }
3375
+ /** Builds the Pi input from Sorbet's retained declarations, independently of Agent system messages. */
3376
+ declare function projectModelRequestDispatch(systemPrompt: string, conversation: readonly Message[], frames: readonly ContextTransitionFrame[], inherited?: readonly Message[], fallbackTools?: readonly ToolDeclaration[], options?: ModelRequestDispatchOptions): ModelContext;
3377
+ //#endregion
3378
+ //#region src/session/history/model-requests.d.ts
3379
+ type ModelRequestedFact = Extract<JournalFact, {
3380
+ kind: 'model.requested';
3381
+ }>;
3382
+ type ModelRequestMessageOrigin = {
3383
+ readonly kind: 'fork-seed';
3384
+ readonly sessionId: string;
3385
+ readonly runId: string;
3386
+ readonly modelRequestId: string;
3387
+ } | {
3388
+ readonly kind: 'context-frame';
3389
+ readonly frameId: string;
3390
+ readonly frameKind: ContextTransitionFrame['kind'];
3391
+ readonly stateName?: string;
3392
+ readonly sourceId?: string;
3393
+ readonly provenance?: ContextProvenance;
3394
+ } | {
3395
+ readonly kind: 'compaction-summary';
3396
+ readonly operationId: string;
3397
+ } | {
3398
+ readonly kind: 'conversation';
3399
+ readonly runId: string;
3400
+ readonly messageId: string;
3401
+ readonly inputMode?: 'steer' | 'followUp';
3402
+ readonly sourceKind?: string;
3403
+ readonly synthetic: boolean;
3404
+ readonly compacted: boolean;
3405
+ readonly syntheticCause?: 'permission-denied' | 'permission-failed' | 'effect-succeeded' | 'effect-failed' | 'effect-unknown' | 'run-terminal';
3406
+ readonly outputArchive?: ToolOutputArchiveRecord;
3407
+ };
3408
+ interface ReconstructedModelRequest {
3409
+ readonly dispatchOrigins: readonly ModelRequestDispatchPart[];
3410
+ readonly fact: ModelRequestedFact;
3411
+ readonly contextSnapshot: ContextSnapshot;
3412
+ readonly context: ModelContext;
3413
+ /** Exact Sorbet-owned declaration timeline passed to Pi, before Provider lowering. */
3414
+ readonly dispatchContext: ModelContext;
3415
+ readonly conversationEntries: readonly ConversationEntry[];
3416
+ readonly contextFrames: readonly ContextTransitionFrame[];
3417
+ readonly messageOrigins: readonly ModelRequestMessageOrigin[];
3418
+ }
3419
+ declare function reconstructModelRequest(facts: readonly JournalFact[], requested: string | ModelRequestedFact, options?: {
3420
+ readonly scope?: HistoryScope;
3421
+ }): ReconstructedModelRequest;
3422
+ //#endregion
3423
+ //#region src/session/history/request-context.d.ts
3424
+ /**
3425
+ * Provider-ready input for a request the Session has not made yet: the exact Pi
3426
+ * input of the latest settled request plus every message committed after it.
3427
+ *
3428
+ * A fork also uses the source model and dispatch settings. The context is a
3429
+ * reconstruction at the Pi boundary. The Provider owns wire encoding and reuse.
3430
+ */
3431
+ interface ProjectedRequestContext {
3432
+ readonly context: ModelContext;
3433
+ readonly sourceModelRequestId: string;
3434
+ readonly model: ModelRequestedFact['payload']['model'];
3435
+ readonly settings?: ModelRequestedFact['payload']['settings'];
3436
+ }
3437
+ interface ProjectRequestContextOptions {
3438
+ readonly scope?: HistoryScope;
3439
+ /** Fork only if this answer still belongs to the latest dispatched request. */
3440
+ readonly responseMessageId?: string;
3441
+ }
3442
+ /**
3443
+ * Reconstructs the latest settled request and extends it with later messages.
3444
+ * Returns `undefined` when no such prefix exists: the Session has not made a
3445
+ * request, that request has no committed response yet, or a compaction, reset or
3446
+ * input rewrite has since invalidated the prefix it described.
3447
+ */
3448
+ declare function projectRequestContext(facts: readonly JournalFact[], options?: ProjectRequestContextOptions): ProjectedRequestContext | undefined;
3449
+ //#endregion
3450
+ //#region src/session/history/input-inclusion.d.ts
3451
+ interface SessionInputInclusion {
3452
+ readonly deliveryId: string;
3453
+ readonly runId: string;
3454
+ readonly modelRequestId: string;
3455
+ readonly factId: string;
3456
+ readonly cursor: string;
3457
+ readonly sequence: number;
3458
+ readonly recordedAt: string;
3459
+ }
3460
+ /** First inclusion uses newly committed input evidence, including compressed conversation prefixes. */
3461
+ declare class SessionInputInclusionProjection {
3462
+ #private;
3463
+ readonly deliveryId?: string | undefined;
3464
+ constructor(deliveryId?: string | undefined);
3465
+ apply(fact: JournalFact): void;
3466
+ inspect(deliveryId: string, runId?: string): SessionInputInclusion | undefined;
3467
+ has(deliveryId: string): boolean;
3468
+ reset(): void;
3469
+ }
3470
+ //#endregion
3471
+ //#region src/session/history/recovery.d.ts
3472
+ /** Tracks outstanding durable identities without retaining terminal payloads. */
3473
+ declare class SessionRecoveryProjection {
3474
+ #private;
3475
+ apply(fact: JournalRecoveryFact): boolean;
3476
+ snapshot(sessionId: string): SessionRecoveryObservation;
3477
+ reset(): void;
3478
+ }
3479
+ /** Projects durable uncertainty without opening a Session, acquiring ownership or performing recovery. */
3480
+ declare function projectSessionRecovery(sessionId: string, facts: readonly JournalRecoveryFact[]): SessionRecoveryObservation;
3481
+ //#endregion
3482
+ //#region src/session/inspection/context-attribution.d.ts
3483
+ interface ModelRequestContextSourceEstimate extends ModelRequestDispatchPart {
3484
+ readonly characterCount?: number;
3485
+ readonly inherited?: boolean;
3486
+ readonly kind?: string;
3487
+ readonly sourceId?: string;
3488
+ readonly provenance?: ContextProvenance;
3489
+ readonly messageIndex: number;
3490
+ readonly estimatedTokens: number;
3491
+ }
3492
+ interface ModelRequestContextAttribution {
3493
+ readonly tokenizer: 'sorbet-character-estimate-v1';
3494
+ readonly measurement: 'estimated';
3495
+ readonly evidenceOrigin: 'compiled_request' | 'journal_derived';
3496
+ readonly estimatedTotalTokens: number;
3497
+ readonly sections: readonly ContextSectionEstimate[];
3498
+ readonly sources: readonly ModelRequestContextSourceEstimate[];
3499
+ readonly multimodal: boolean;
3500
+ readonly providerUsage?: {
3501
+ readonly input: number;
3502
+ readonly output: number;
3503
+ readonly cacheRead: number;
3504
+ readonly cacheWrite: number;
3505
+ readonly reasoning?: number;
3506
+ readonly totalTokens: number;
3507
+ };
3508
+ readonly prefixSourceQuality?: 'measured' | 'unavailable';
3509
+ readonly delta?: {
3510
+ readonly previousModelRequestId: string;
3511
+ readonly comparable: boolean;
3512
+ readonly reason?: 'model_changed' | 'multimodal' | 'context_epoch_changed';
3513
+ readonly sections?: readonly ContextSectionEstimate[];
3514
+ };
3515
+ }
3516
+ //#endregion
3517
+ //#region src/session/inspection/usage.d.ts
3518
+ interface SessionProviderUsageEntry {
3519
+ readonly sequence: number;
3520
+ readonly recordedAt: string;
3521
+ readonly kind: 'run' | 'model-invocation' | 'compaction' | 'approval';
3522
+ /** Invocation source when the entry came from a host initiated model completion. */
3523
+ readonly sourceKind?: string;
3524
+ readonly provider: string;
3525
+ readonly model: string;
3526
+ readonly usage: Usage;
3527
+ }
3528
+ /** Projects timestamped Provider usage without exposing request content or model prompts. */
3529
+ declare function projectSessionProviderUsage(facts: readonly JournalFact[]): readonly SessionProviderUsageEntry[];
3530
+ //#endregion
3531
+ //#region src/session/inspection/model-requests.d.ts
3532
+ interface ModelRequestContentOrigin {
3533
+ readonly requestId: string;
3534
+ readonly subject: 'system-prompt' | 'message';
3535
+ readonly messageIndex?: number;
3536
+ readonly messageOrigin?: ModelRequestMessageOrigin;
3537
+ }
3538
+ type SessionInspectionContentPolicy = {
3539
+ readonly mode?: 'metadata';
3540
+ } | {
3541
+ readonly mode: 'visible';
3542
+ readonly redact: (content: string, origin: ModelRequestContentOrigin) => string;
3543
+ };
3544
+ interface SessionInspectionOptions {
3545
+ readonly content?: SessionInspectionContentPolicy;
3546
+ /** Omit request reconstruction when only lifecycle and conversation evidence is needed. */
3547
+ readonly modelRequests?: 'include' | 'omit';
3548
+ }
3549
+ type InspectedContent = {
3550
+ readonly mode: 'omitted';
3551
+ } | {
3552
+ readonly mode: 'visible';
3553
+ readonly text: string;
3554
+ };
3555
+ interface ModelRequestMessageInspection {
3556
+ readonly index: number;
3557
+ readonly role: Message['role'];
3558
+ readonly characterCount: number;
3559
+ readonly byteCount: number;
3560
+ readonly origin: ModelRequestMessageOrigin;
3561
+ readonly flags: {
3562
+ readonly contextInjection: boolean;
3563
+ readonly syntheticToolResult: boolean;
3564
+ readonly compaction: boolean;
3565
+ readonly forkSeed: boolean;
3566
+ readonly inputMode?: 'steer' | 'followUp';
3567
+ readonly archiveBackedOutput: boolean;
3568
+ };
3569
+ readonly content: InspectedContent;
3570
+ }
3571
+ interface ModelRequestToolInspection {
3572
+ readonly index: number;
3573
+ readonly name: string;
3574
+ readonly description: string;
3575
+ readonly parameters: ToolDeclaration['parameters'];
3576
+ }
3577
+ interface ModelRequestInspection$1 {
3578
+ readonly contextAttribution: ModelRequestContextAttribution;
3579
+ readonly modelRequestId: string;
3580
+ readonly logicalModelCallId: string;
3581
+ readonly retryOfModelRequestId?: string;
3582
+ readonly runId: string;
3583
+ readonly operationId: string;
3584
+ readonly factId: string;
3585
+ readonly sequence: number;
3586
+ readonly cursor: JournalCursor;
3587
+ readonly recordedAt: string;
3588
+ readonly contextEpoch: number;
3589
+ readonly model: {
3590
+ readonly provider: string;
3591
+ readonly api: string;
3592
+ readonly id: string;
3593
+ };
3594
+ readonly systemPrompt: {
3595
+ readonly characterCount: number;
3596
+ readonly byteCount: number;
3597
+ readonly content: InspectedContent;
3598
+ readonly sources: readonly {
3599
+ readonly sourceId: string;
3600
+ readonly kind: string;
3601
+ readonly lifecycle: 'session';
3602
+ readonly provenance: ContextProvenance;
3603
+ }[];
3604
+ };
3605
+ readonly messages: readonly ModelRequestMessageInspection[];
3606
+ readonly tools: readonly ModelRequestToolInspection[];
3607
+ }
3608
+ //#endregion
3609
+ //#region src/session/inspection/project.d.ts
3610
+ interface SessionPromptCacheTotals {
3611
+ readonly providerPromptTokens: number;
3612
+ readonly uncachedPrefillTokens: number;
3613
+ readonly cacheReadTokens: number;
3614
+ readonly cacheWriteTokens: number;
3615
+ }
3616
+ type SessionPromptCacheInspection = SessionPromptCacheTotals & ({
3617
+ readonly reporting: 'unknown';
3618
+ } | {
3619
+ readonly reporting: 'observed';
3620
+ readonly weightedCacheReadRate: number;
3621
+ });
3622
+ interface SessionInspection {
3623
+ readonly recovery: SessionRecoveryObservation;
3624
+ readonly sessionId: string;
3625
+ readonly cursor?: JournalCursor;
3626
+ readonly runs: readonly RunInspection[];
3627
+ readonly conversation: readonly ConversationEntry[];
3628
+ /** Timestamped Provider totals for settled model calls; request content is omitted. */
3629
+ readonly providerUsage: readonly SessionProviderUsageEntry[];
3630
+ readonly promptCache: SessionPromptCacheInspection;
3631
+ readonly modelRequests: readonly ModelRequestInspection$1[];
3632
+ }
3633
+ /** Projects an ordered Journal prefix without opening a Session or performing recovery. */
3634
+ declare function projectSessionInspection(sessionId: string, page: JournalPage, options?: SessionInspectionOptions, observation?: RuntimeObservationPort): SessionInspection;
3635
+ //#endregion
3636
+ //#region src/session/model-invocations.d.ts
3637
+ type CompleteModelData = s.Static<typeof CompleteModelInputSchema>;
3638
+ /**
3639
+ * One durable Host-initiated Provider call. A supplied Context is dispatched with its
3640
+ * existing Tool declarations, but returned Tool calls are response data and are never run.
3641
+ */
3642
+ type CompleteModelInput = Readonly<Omit<CompleteModelData, 'messages'>> & {
3643
+ readonly messages: readonly Readonly<CompleteModelData['messages'][number]>[];
3644
+ };
3645
+ /** The Provider model a hook is dispatched for; `api` names its wire format. */
3646
+ interface ProviderModelDescriptor {
3647
+ readonly provider: string;
3648
+ readonly api: string;
3649
+ readonly id: string;
3650
+ /** The endpoint this request goes to, after any Host endpoint override. */
3651
+ readonly baseUrl: string;
3652
+ }
3653
+ /**
3654
+ * Trusted in-process hooks on one physical Provider request. They see Provider wire shapes,
3655
+ * which Sorbet does not interpret; the committed request evidence is Sorbet's input, not the
3656
+ * rewritten payload.
3657
+ */
3658
+ interface ProviderRequestHooks {
3659
+ /** Returns a replacement payload, or `undefined` to send it unchanged. */
3660
+ readonly prepare?: (payload: unknown, model: ProviderModelDescriptor) => unknown;
3661
+ /** Reads each raw Provider stream event before normalization; events are read-only. */
3662
+ readonly observe?: (event: unknown, model: ProviderModelDescriptor) => void;
3663
+ }
3664
+ interface CompleteModelOptions {
3665
+ readonly source?: SessionInputSource;
3666
+ readonly signal?: AbortSignal;
3667
+ readonly provider?: ProviderRequestHooks;
3668
+ }
3669
+ interface ModelInvocationReceipt {
3670
+ readonly requestId: string;
3671
+ readonly text: string;
3672
+ /** Full Provider response, including any tool-call blocks. This call never dispatches Tools. */
3673
+ readonly response: AssistantMessage;
3674
+ readonly usage: Usage;
3675
+ readonly stopReason: AssistantMessage['stopReason'];
3676
+ readonly model: {
3677
+ readonly provider: string;
3678
+ readonly id: string;
3679
+ };
3680
+ }
3681
+ declare class ModelInvocationUnknownError extends Error {
3682
+ readonly requestId: string;
3683
+ readonly code = "model_invocation_unknown";
3684
+ constructor(requestId: string);
3685
+ }
3686
+ interface InvocationModel {
3687
+ readonly provider: string;
3688
+ readonly api: string;
3689
+ readonly id: string;
3690
+ }
3691
+ interface ModelInvocationsOptions {
3692
+ readonly sessionId: string;
3693
+ readonly model: InvocationModel;
3694
+ readonly resolveModel: (provider: string, id: string) => InvocationModel | undefined;
3695
+ readonly complete: (model: InvocationModel, context: ModelContext, options: {
3696
+ readonly signal: AbortSignal;
3697
+ readonly sessionId: string;
3698
+ readonly sourceModelRequestId?: string;
3699
+ readonly temperature?: number;
3700
+ readonly maxTokens?: number;
3701
+ readonly thinkingLevel?: CompleteModelInput['thinkingLevel'];
3702
+ readonly provider?: ProviderRequestHooks;
3703
+ }) => Promise<AssistantMessage>;
3704
+ readonly createId: () => string;
3705
+ }
3706
+ /** Owns durable physical completions; Pi retains Provider/authentication and stream mechanics. */
3707
+ declare class SessionModelInvocations {
3708
+ #private;
3709
+ constructor(options: ModelInvocationsOptions);
3710
+ recover(facts: RunFactCommitter): Promise<void>;
3711
+ complete(input: CompleteModelInput, options: CompleteModelOptions, ownerSignal: AbortSignal, facts: RunFactCommitter): Promise<ModelInvocationReceipt>;
3712
+ }
3713
+ //#endregion
3714
+ //#region src/session/object-capabilities.d.ts
3715
+ declare const makeSessionObjectCapabilities: (input: {
3716
+ readonly options: ObjectCapabilityOptions | undefined;
3717
+ }) => Effect.Effect<{
3718
+ enabled: boolean;
3719
+ controls: ContextualTool<object, unknown>[];
3720
+ tools: () => ContextualTool<object, unknown>[];
3721
+ captureRequest: (names: readonly string[]) => Effect.Effect<undefined, Error, never>;
3722
+ releaseRequest: Effect.Effect<void, never, never>;
3723
+ close: Effect.Effect<undefined, never, never>;
3724
+ }, never, Scope.Scope>;
3725
+ declare const SessionObjectCapabilities_base: Context.ServiceClass<SessionObjectCapabilities, "sorbet/runtime/session/ObjectCapabilities", {
3726
+ enabled: boolean;
3727
+ controls: ContextualTool<object, unknown>[];
3728
+ tools: () => ContextualTool<object, unknown>[];
3729
+ captureRequest: (names: readonly string[]) => Effect.Effect<undefined, Error, never>;
3730
+ releaseRequest: Effect.Effect<void, never, never>;
3731
+ close: Effect.Effect<undefined, never, never>;
3732
+ }>;
3733
+ declare class SessionObjectCapabilities extends SessionObjectCapabilities_base {
3734
+ static layer(input: Parameters<typeof makeSessionObjectCapabilities>[0]): Layer.Layer<SessionObjectCapabilities, never, never>;
3735
+ }
3736
+ //#endregion
3737
+ //#region src/session/records.d.ts
3738
+ type PluginRecord = Extract<JournalFact, {
3739
+ kind: 'plugin.record.committed';
3740
+ }>;
3741
+ /** Called inside the Session command lane; attribution is supplied by the Host's binding. */
3742
+ declare function appendPluginRecord(facts: RunFactCommitter, owner: PluginRecordOwner, input: AppendPluginRecord, operationId: string, signal?: AbortSignal): Promise<PluginRecord>;
3743
+ declare function capturePluginRecordInput(owner: PluginRecordOwner, input: AppendPluginRecord): {
3744
+ owner: {
3745
+ entryId: string;
3746
+ activationId?: string | undefined;
3747
+ };
3748
+ input: {
3749
+ recordType: string;
3750
+ recordVersion: number;
3751
+ data: string | number | boolean | _sorbetai_schema30.JsonArray | _sorbetai_schema30.JsonObject | null;
3752
+ expectedRevision: number;
3753
+ sourceSequence: number;
3754
+ idempotencyKey?: string | undefined;
3755
+ };
3756
+ };
3757
+ //#endregion
3758
+ //#region src/session/reviewer/service.d.ts
3759
+ declare class SessionApprovalReviewer {
3760
+ #private;
3761
+ constructor(sessionId: string, options: ApprovalReviewer | (() => ApprovalReviewer), createId: () => string, observation?: RuntimeObservationPort);
3762
+ apply(fact: JournalFact): void;
3763
+ reset(): void;
3764
+ review(request: ToolPermissionRequest, runId: string, runFacts: RunFactCommitter): Promise<ApprovalReviewerDecision>;
3765
+ }
3766
+ //#endregion
3767
+ //#region src/session/run-handle/handle.d.ts
3768
+ interface RunViewReader {
3769
+ snapshot(runId: string): Promise<RunView>;
3770
+ runFacts(runId: string, options?: {
3771
+ readonly after?: JournalCursor;
3772
+ }): JournalSubscription;
3773
+ }
3774
+ interface RunController {
3775
+ abortRun(runId: string, reason?: string): Promise<RunCancellationReceipt>;
3776
+ steerRun(runId: string, prompt: UserPrompt, source?: SessionInputSource): Promise<RunInputPlacementReceipt>;
3777
+ followUpRun(runId: string, prompt: UserPrompt, source?: SessionInputSource): Promise<RunInputPlacementReceipt>;
3778
+ }
3779
+ type RunHandleOwner = RunViewReader & RunController;
3780
+ /** Journal-backed handle for one admitted Run. */
3781
+ declare class DurableRun implements SorbetRun {
3782
+ #private;
3783
+ readonly receipt: RunAcceptedReceipt;
3784
+ constructor(session: RunHandleOwner, receipt: RunAcceptedReceipt, settled: Promise<RunTerminalOutcome> | (() => Promise<RunTerminalOutcome>), liveEvents?: RunLiveEventSubscription, drained?: Promise<void>);
3785
+ snapshot(): Promise<RunView>;
3786
+ facts(options?: {
3787
+ readonly after?: JournalCursor;
3788
+ }): JournalSubscription;
3789
+ liveEvents(): RunLiveEventSubscription;
3790
+ abort(reason?: string): Promise<RunCancellationReceipt>;
3791
+ steer(prompt: UserPrompt, source?: SessionInputSource): Promise<RunInputPlacementReceipt>;
3792
+ followUp(prompt: UserPrompt, source?: SessionInputSource): Promise<RunInputPlacementReceipt>;
3793
+ result(): Promise<RunTerminalOutcome>;
3794
+ drained(): Promise<void>;
3795
+ }
3796
+ //#endregion
3797
+ //#region src/session/run-handle/subscription.d.ts
3798
+ /** Filters a session Journal subscription without changing its cursor semantics. */
3799
+ declare class RunSubscription implements JournalSubscription {
3800
+ #private;
3801
+ constructor(source: JournalSubscription, runId: string);
3802
+ close(): void;
3803
+ [Symbol.asyncIterator](): AsyncIterator<JournalFact>;
3804
+ }
3805
+ //#endregion
3806
+ //#region src/session/history/usage.d.ts
3807
+ interface SessionUsageSnapshot {
3808
+ readonly cursor?: JournalCursor;
3809
+ /** Latest context occupancy, absent until a request or inherited conversation is available. */
3810
+ readonly context?: {
3811
+ readonly tokens: number;
3812
+ readonly window: number;
3813
+ readonly measurement: 'measured' | 'estimated';
3814
+ };
3815
+ /** Provider-reported subtotal in this Journal; unknown and open requests may incur additional usage. */
3816
+ readonly usage: Usage;
3817
+ /** Latest Run subtotal, absent until a Run in this Journal has usage. */
3818
+ readonly lastTurn?: SessionTurnUsage;
3819
+ readonly openModelRequests: number;
3820
+ readonly unknownModelRequests: number;
3821
+ /** Persisted responses with error, abort or deferred execution may contain only partial counters. */
3822
+ readonly incompleteModelUsageRequests: number;
3823
+ /** Inherited conversation usage is excluded: it was billed to the source Session. */
3824
+ readonly models: readonly {
3825
+ readonly provider: string;
3826
+ readonly model: string;
3827
+ readonly usage: Usage;
3828
+ }[];
3829
+ }
3830
+ /** One Run's own spend. Compaction and approval reviews stay attributed to the Run that caused them. */
3831
+ interface SessionTurnUsage {
3832
+ readonly runId: string;
3833
+ readonly usage: Usage;
3834
+ readonly openModelRequests: number;
3835
+ readonly unknownModelRequests: number;
3836
+ readonly incompleteModelUsageRequests: number;
3837
+ }
3838
+ declare class SessionUsageProjection {
3839
+ #private;
3840
+ /** A supplied history is borrowed and must receive each fact before apply() is called. */
3841
+ constructor(history?: SessionHistoryProjection);
3842
+ /** Includes Run responses, approval reviews and in-Run compaction, excluding independent calls.
3843
+ * Replaying the Journal restores the same subtotal; missing responses remain counters, not spend. */
3844
+ runTotals(runId: string): UsageTotals;
3845
+ get cursor(): JournalCursor | undefined;
3846
+ apply(fact: JournalFact): void;
3847
+ snapshot(model?: {
3848
+ readonly provider: string;
3849
+ readonly id: string;
3850
+ readonly contextWindow: number;
3851
+ }): SessionUsageSnapshot;
3852
+ }
3853
+ //#endregion
3854
+ //#region src/session/behaviors/service.d.ts
3855
+ interface SessionBehaviorSnapshot {
3856
+ readonly name: string;
3857
+ readonly title: string;
3858
+ readonly version: number;
3859
+ readonly state?: JsonValue;
3860
+ readonly available: boolean;
3861
+ readonly view: SessionBehaviorView;
3862
+ }
3863
+ declare class SessionBehaviors {
3864
+ #private;
3865
+ readonly sessionId: string;
3866
+ readonly bindings: ModelToolSource | undefined;
3867
+ readonly facts: () => Promise<RunFactCommitter>;
3868
+ readonly createId: () => string;
3869
+ readonly now: () => Date;
3870
+ readonly signal: AbortSignal;
3871
+ constructor(sessionId: string, bindings: ModelToolSource | undefined, facts: () => Promise<RunFactCommitter>, createId: () => string, now: () => Date, signal: AbortSignal);
3872
+ apply(fact: JournalFact): void;
3873
+ contextOwners(): NamedStateOwner[];
3874
+ state(name: string): JsonValue | undefined;
3875
+ reset(): void;
3876
+ list(): Promise<readonly SessionBehaviorSnapshot[]>;
3877
+ at(facts: readonly JournalFact[], sequence: number): Promise<readonly SessionBehaviorSnapshot[]>;
3878
+ acquire(): ModelToolLease | undefined;
3879
+ command(name: string, command: SessionBehaviorCommand, expectedVersion: number | undefined, lease: ModelToolLease | undefined, runId?: string, signal?: AbortSignal, activeRun?: boolean): Promise<SessionBehaviorView>;
3880
+ assertAdmission(entries: readonly SessionBehaviorSnapshot[]): void;
3881
+ assertContinuation(source: SessionInputSource, prompt: UserPrompt, idempotencyKey: string | undefined, entries: readonly SessionBehaviorSnapshot[]): void;
3882
+ permits(toolName: string): boolean;
3883
+ }
3884
+ //#endregion
3885
+ //#region src/units/messages.d.ts
3886
+ interface UnitMessageOptions {
3887
+ readonly onError?: (error: Error) => void;
3888
+ /** Runs outside both commit lines. Authenticate the peer and honor cancellation on Unit close. */
3889
+ readonly deliver?: (message: UnitMessage, signal: AbortSignal) => Promise<MessageDeliveryResult>;
3890
+ /** Durable delay after an unavailable/unknown result; defaults to 1 second. No retry count limit. */
3891
+ readonly retryDelayMs?: number;
3892
+ }
3893
+ interface OutboxRecord extends MessageIntent {
3894
+ readonly state: {
3895
+ readonly status: 'pending';
3896
+ readonly retryAt: number;
3897
+ readonly code?: string;
3898
+ } | MessageReceipt | MessageRejection;
3899
+ }
3900
+ //#endregion
3901
+ //#region src/units/catalog.d.ts
3902
+ type UnitSession = Extract<UnitFact, {
3903
+ kind: 'session.created';
3904
+ }>['payload'] & {
3905
+ readonly closing: boolean;
3906
+ readonly closed: boolean;
3907
+ };
3908
+ //#endregion
3909
+ //#region src/units/recovery.d.ts
3910
+ /**
3911
+ * Acquires the same configured execution facade used for interactive work. The
3912
+ * narrow structural contract accepts SorbetSession or a host facade that injects
3913
+ * its Run resource provider; Unit recovery never constructs execution resources.
3914
+ * Acquisition must honor cancellation and return 'unavailable' instead of a
3915
+ * partially configured facade. Run handles are deliberately opaque to this owner.
3916
+ */
3917
+ interface UnitSessionProvider {
3918
+ /**
3919
+ * Finish a durable child close before any ordinary acquisition/resume. The Host
3920
+ * cancels/abandons Runs, withdraws pending input, drains resources and commits
3921
+ * final closure (or confirms release to its owning Task). No model work starts.
3922
+ */
3923
+ close?(sessionId: string, signal: AbortSignal): Promise<'released' | 'unavailable'>;
3924
+ acquire(sessionId: string, signal: AbortSignal): Promise<'unavailable' | {
3925
+ readonly session: {
3926
+ getActiveRun(): Promise<object | undefined>;
3927
+ resumeInterruptedRun(runId: string): Promise<object>;
3928
+ waitForIdle(options: {
3929
+ readonly signal: AbortSignal;
3930
+ }): Promise<void>;
3931
+ };
3932
+ /** Release this borrow; unload must drain execution before disposing resources. */
3933
+ release(): Promise<void>;
3934
+ }>;
3935
+ }
3936
+ interface UnitRecoveryState {
3937
+ readonly sessionId: string;
3938
+ readonly runId?: string;
3939
+ readonly status: 'resumed' | 'parked' | 'waiting-environment' | 'waiting-capacity' | 'manual' | 'faulted';
3940
+ readonly error?: Error;
3941
+ }
3942
+ interface UnitRecoverySnapshot {
3943
+ /** Latest acquisition/admission decisions in this owner; not current Run outcomes. */
3944
+ readonly decisions: readonly UnitRecoveryState[];
3945
+ /** Durable unknown attempts across the tree, including completed Runs and Tool operations. */
3946
+ readonly unknownEffects: number;
3947
+ }
3948
+ //#endregion
3949
+ //#region src/units/work.d.ts
3950
+ /** Durable work at a complete Unit commit boundary; not a claim that execution is available. */
3951
+ interface UnitWorkSummary {
3952
+ readonly unitId: string;
3953
+ readonly observedUnitSequence: number;
3954
+ /** Includes parked/blocked work and waits without a deadline. */
3955
+ readonly hasPendingWork: boolean;
3956
+ /** Unix milliseconds. An undelivered outbox intent without a retry deadline is due at 0. */
3957
+ readonly nextWakeAt: number | undefined;
3958
+ }
3959
+ /**
3960
+ * Rebuild from the reader's committed prefix without a writer lease, Session facade,
3961
+ * Task definitions or transport. The caller retains ownership of the reader.
3962
+ * Scans history through its tail at entry; concurrent later appends are excluded.
3963
+ */
3964
+ declare function readUnitWorkSummary(reader: UnitReader): Promise<UnitWorkSummary>;
3965
+ //#endregion
3966
+ //#region src/units/runtime.d.ts
3967
+ interface OpenUnitOptions {
3968
+ readonly store: UnitStore;
3969
+ /** Borrowed for Session output as well as Journal offload; its lifetime exceeds this unit's. */
3970
+ readonly artifactStore?: ArtifactStore;
3971
+ readonly rootMetadata?: JsonValue;
3972
+ /** First-creation seed; committed with the root catalog entry, never replayed on reopen. */
3973
+ readonly rootFork?: Extract<SessionFactCandidate, {
3974
+ kind: 'session.forked';
3975
+ }>;
3976
+ readonly observation?: RuntimeObservationPort;
3977
+ readonly createId?: () => string;
3978
+ readonly now?: () => Date;
3979
+ readonly tasks?: TaskKernelOptions;
3980
+ readonly messages?: UnitMessageOptions;
3981
+ readonly sessions?: UnitSessionProvider;
3982
+ readonly policies?: {
3983
+ readonly concurrency?: {
3984
+ /** Positive integer or Infinity (default). Counts child Runs through resource drain. */
3985
+ readonly childRunsPerParent?: number;
3986
+ };
3987
+ };
3988
+ /**
3989
+ * Keep the root Session's facts from the open pass for its first participant load, so
3990
+ * attaching it does not decode the Journal again. Set it when the host attaches the root
3991
+ * right after open; unconsumed facts are held until then.
3992
+ */
3993
+ readonly preloadRoot?: boolean;
3994
+ /** Manual mode leaves interrupted Runs for an explicit Session resume call. */
3995
+ readonly resume?: 'automatic' | 'manual';
3996
+ }
3997
+ interface CreateUnitSession {
3998
+ readonly sessionId: string;
3999
+ readonly parentSessionId: string;
4000
+ readonly creationKey: string;
4001
+ readonly metadata: JsonValue;
4002
+ readonly fork?: Extract<SessionFactCandidate, {
4003
+ kind: 'session.forked';
4004
+ }>;
4005
+ }
4006
+ interface UnitTransaction {
4007
+ /** Synchronous Task/Signal changes in this group; default owner is the root Session. */
4008
+ tasks<T>(build: (tx: UnitTx) => T): T;
4009
+ /** Root-Session-owned outbox intent; atomic with this group. Task replies use UnitTx. */
4010
+ sendMessage(message: MessageDraft, options: {
4011
+ readonly key: string;
4012
+ }): SentMessage;
4013
+ /** Participants must be loaded with prepareSessions() before entering a group. */
4014
+ run(sessionId: string, fact: RunFactCandidate): JournalFact;
4015
+ session(sessionId: string, fact: SessionFactCandidate): JournalFact;
4016
+ metadata(sessionId: string, metadata: JsonValue): void;
4017
+ }
4018
+ type UnitCloseResult = {
4019
+ readonly status: 'closed';
4020
+ } | {
4021
+ readonly status: 'failed';
4022
+ readonly error: UnitStoreError;
4023
+ };
4024
+ /** Owns one tree's writer, participants and execution handles. It does not own a host scheduler. */
4025
+ declare class UnitRuntime {
4026
+ #private;
4027
+ /** Resolves after cleanup and lease release are attempted; failure requires a fresh owner. */
4028
+ readonly closed: Promise<UnitCloseResult>;
4029
+ private constructor();
4030
+ static open(options: OpenUnitOptions): Promise<UnitRuntime>;
4031
+ get unitId(): string;
4032
+ /** Current writer lifetime, used by Host-owned processes to detect abandoned work. */
4033
+ get epochId(): string;
4034
+ get artifactStore(): ArtifactStore | undefined;
4035
+ /** Borrowed Session read views; direct appends are rejected. */
4036
+ get journal(): JournalStore;
4037
+ /**
4038
+ * Read committed history through this writer's existing index. Each page selects
4039
+ * its prefix at invocation; later calls may include newer commits. Cursors survive
4040
+ * reopen. The caller owns no resource and cannot append through this view.
4041
+ * Rejects once the Unit store closes or faults, as other store reads do.
4042
+ */
4043
+ readHistory(options?: UnitReadOptions): Promise<UnitPage>;
4044
+ sessions(): readonly UnitSession[];
4045
+ /**
4046
+ * Start automatic work once; repeats share the initial acquisition/admission pass.
4047
+ * Does not wait for Run completion. Acquisition failures are reported by recovery().
4048
+ */
4049
+ resume(): Promise<void>;
4050
+ /** Execution-facade coordination: provider-managed inputs wait for acquisition to finish. */
4051
+ canRecoverInputs(sessionId: string): boolean;
4052
+ /**
4053
+ * Session coordination before new admission or interrupted-Run resume. Root Runs
4054
+ * do not consume child capacity. Release after admission failure or execution
4055
+ * drain; waiting does not place a Submission or acquire Run resources.
4056
+ */
4057
+ acquireRunSlot(sessionId: string, signal: AbortSignal): Promise<() => void>;
4058
+ /**
4059
+ * Retry acquisition after publishing a usable attachment; inert before resume().
4060
+ * Resolves after admission or recording unavailability/failure, not Run completion.
4061
+ */
4062
+ notifyAvailable(sessionId: string): Promise<void>;
4063
+ /** Owner-local recovery decisions alongside committed, tree-wide Effect uncertainty. */
4064
+ recovery(): UnitRecoverySnapshot;
4065
+ /**
4066
+ * Observes completion of each Session acquisition/admission pass, including
4067
+ * unavailable or faulted passes. This is not Run completion. No initial replay;
4068
+ * use recovery() for the current snapshot. Callback exceptions are isolated.
4069
+ */
4070
+ subscribeRecovery(notify: (snapshot: UnitRecoverySnapshot) => void): () => void;
4071
+ startTask<I, S extends {
4072
+ phase: string;
4073
+ }, R>(definition: TaskDefinition<I, S, R>, input: I, options: CreateTaskOptions<NoInfer<S>, NoInfer<R>>): Promise<TaskHandle<I, S, R>>;
4074
+ /**
4075
+ * Import already completed history before resume(). Accepts a known Session owner,
4076
+ * including a permanently closed one, without reopening it or running a Task phase.
4077
+ * The validated input/result and terminal identity share one fact. Repeating a key
4078
+ * requires identical content; ordinary Task creation still requires an open owner.
4079
+ */
4080
+ importCompletedTask<I, S extends {
4081
+ phase: string;
4082
+ }, R>(definition: TaskDefinition<I, S, R>, input: I, result: NoInfer<R>, options: {
4083
+ readonly key: string;
4084
+ readonly sessionId: string;
4085
+ readonly background?: boolean;
4086
+ }): Promise<TaskHandle<I, S, R>>;
4087
+ /** Create a Session-owned background schedule; firings and their next deadline commit atomically. */
4088
+ schedule(input: ScheduleInput, options: {
4089
+ readonly key: string;
4090
+ }): Promise<TaskHandle>;
4091
+ /**
4092
+ * A Session binding overrides the Unit default for Tasks owned by that Session,
4093
+ * including nested Tasks. Bindings are process-local and must be restored on reopen.
4094
+ * An executing phase keeps the definition captured at reservation.
4095
+ */
4096
+ registerTask<I, S extends {
4097
+ phase: string;
4098
+ }, R>(definition: TaskDefinition<I, S, R>, scope?: {
4099
+ readonly sessionId: string;
4100
+ }): void;
4101
+ /**
4102
+ * Abort and drain handlers registered for this Session, preserving their checkpoints,
4103
+ * waits and restart counts. Unit-level definitions (e.g. child Reporters) stay live.
4104
+ * Re-register the Session definitions to resume; release is not a Task cancellation.
4105
+ */
4106
+ releaseTaskBindings(sessionId: string): Promise<void>;
4107
+ task(taskId: string): TaskHandle | undefined;
4108
+ /** A detached copy of the committed Signal state; never exposes queued writes. */
4109
+ signal(signalId: string): SignalRecord | undefined;
4110
+ inspect(): {
4111
+ tasks: {
4112
+ blocked: "definition_missing" | "version_mismatch" | undefined;
4113
+ invoking: boolean;
4114
+ taskId: string;
4115
+ kind: string;
4116
+ version: number;
4117
+ owner: TaskOwner;
4118
+ creationKey: string;
4119
+ background: boolean;
4120
+ input: JsonValue;
4121
+ checkpoint: Record<string, JsonValue> & {
4122
+ phase: string;
4123
+ };
4124
+ state: TaskState<JsonValue>;
4125
+ restarts: number;
4126
+ parked: boolean;
4127
+ reservation?: TaskReservation;
4128
+ invocationClosed: boolean;
4129
+ abortRequested?: {
4130
+ readonly reason: string;
4131
+ readonly requester: string;
4132
+ };
4133
+ }[];
4134
+ messages: {
4135
+ outbox: readonly OutboxRecord[];
4136
+ transportAvailable: boolean;
4137
+ };
4138
+ };
4139
+ /**
4140
+ * Scope includes nested Tasks; a Session scope excludes its child Sessions. `live` lists
4141
+ * unfinished Tasks only. Without it, snapshots also include ended Tasks still held in
4142
+ * memory: those owned by a Session or by an unfinished Task. Other ended Tasks are
4143
+ * history, read from the Journal. `kind` filters before copying.
4144
+ */
4145
+ taskGraph(scope?: {
4146
+ readonly sessionId?: string;
4147
+ readonly taskId?: string;
4148
+ readonly live?: boolean;
4149
+ readonly kind?: string;
4150
+ }): {
4151
+ snapshot: () => {
4152
+ blocked: "definition_missing" | "version_mismatch" | undefined;
4153
+ invoking: boolean;
4154
+ taskId: string;
4155
+ kind: string;
4156
+ version: number;
4157
+ owner: TaskOwner;
4158
+ creationKey: string;
4159
+ background: boolean;
4160
+ input: JsonValue;
4161
+ checkpoint: Record<string, JsonValue> & {
4162
+ phase: string;
4163
+ };
4164
+ state: TaskState<JsonValue>;
4165
+ restarts: number;
4166
+ parked: boolean;
4167
+ reservation?: TaskReservation;
4168
+ invocationClosed: boolean;
4169
+ abortRequested?: {
4170
+ readonly reason: string;
4171
+ readonly requester: string;
4172
+ };
4173
+ }[];
4174
+ subscribe: (notify: () => void) => () => void;
4175
+ };
4176
+ /** Join this Session's currently runnable phases without joining Unit recovery or sibling I/O. */
4177
+ waitForSessionTasks(sessionId: string, signal: AbortSignal): Promise<void>;
4178
+ /** Latest fully applied commit, independent of provider/transport availability or in-flight calls. */
4179
+ workSummary(): UnitWorkSummary;
4180
+ /**
4181
+ * Immediately delivers the current snapshot, then one per committed batch after
4182
+ * all projections apply. Callbacks run synchronously; hosts own asynchronous index
4183
+ * writes and their failures. Subscriber exceptions cannot affect commits. Unsubscribe
4184
+ * when releasing the host index; Unit close clears listeners after its final commit.
4185
+ */
4186
+ subscribeWork(notify: (summary: UnitWorkSummary) => void): () => void;
4187
+ nextWakeAt(): number | undefined;
4188
+ tick(): Promise<void>;
4189
+ hasPendingWork(): boolean;
4190
+ /** The host must verify the peer independently before passing authenticatedSourceUnitId. */
4191
+ receiveMessage(message: UnitMessage, authenticatedSourceUnitId: string): Promise<MessageReceipt | MessageRejection>;
4192
+ abortTask(taskId: string, reason: string, requester: string): Promise<void>;
4193
+ retryTask(taskId: string, commandId: string): Promise<void>;
4194
+ resolveSignal(signalId: string, result: JsonValue, commandId: string): Promise<void>;
4195
+ /** Reacquire input state and waits without opening a Session or dispatching model work. */
4196
+ submission(submissionId: string): Promise<DurableSubmission | undefined>;
4197
+ createSession(input: CreateUnitSession): Promise<void>;
4198
+ /** Loading happens before any reservations; group callbacks perform no asynchronous work. */
4199
+ prepareSessions(sessionIds: readonly string[]): Promise<void>;
4200
+ /**
4201
+ * Build one indivisible group synchronously, after prepareSessions(). Construction
4202
+ * failure discards only this group; write rejection also rejects queued dependants
4203
+ * with JournalGroupDependencyError. Their builds may have side effects, so a
4204
+ * dependant is not rebuilt here; the caller may build it again.
4205
+ * An uncertain write or failed durable projection requires reopening the unit.
4206
+ */
4207
+ group<T>(build: (transaction: UnitTransaction) => T): Promise<T>;
4208
+ /** Join an existing synchronous Task/Unit commit with Session-owned consequences. */
4209
+ stageSessionEffects(sessionId: string, build: (tx: UnitTx) => void): void;
4210
+ /** One lightweight participant per Session, shared with its optional execution facade. */
4211
+ participant(sessionId: string, initialize?: (participant: RunFactCommitter) => void): Promise<RunFactCommitter>;
4212
+ /** Permanently closes a child after its execution facade has stopped; history remains readable. */
4213
+ closeSession(sessionId: string): Promise<void>;
4214
+ /** Claim before asynchronous Session initialization; releasing a facade keeps durable history. */
4215
+ claimExecution(sessionId: string, close: () => Promise<void>, withdraw?: (id: string, reason: string, commandId: string) => Promise<boolean>, inputsCommitted?: () => Promise<void>, waitForIdle?: (signal: AbortSignal) => Promise<void>): (() => void) | undefined;
4216
+ /**
4217
+ * Join current Task phases, delivery, Session acquisition, Runs and resource drain.
4218
+ * Does not start a dormant Unit or wait for future sleeps, replies, parked work
4219
+ * or unavailable environments. Active approval/model/tool calls still hold the
4220
+ * wait. Cancellation stops only this wait, not execution. New external admission
4221
+ * may make the Unit busy again; hosts must serialize idle eviction with admission.
4222
+ */
4223
+ waitForIdle(options?: {
4224
+ readonly signal?: AbortSignal;
4225
+ }): Promise<void>;
4226
+ close(): Promise<void>;
4227
+ }
4228
+ //#endregion
4229
+ export { type AppendPluginRecord, type ApprovalComposition, type ApprovalMode, ApprovalModeSchema, type ApprovalResolver, type ApprovalReviewDecision, ApprovalReviewDecisionSchema, type ApprovalReviewObservation, type ApprovalReviewRequest, type ApprovalReviewer, type ApprovalReviewerDecision, CommittedConversationMessage, CompactSessionOptions, CompactionAttemptUsage, type CompactionDispatchRequest, type CompactionDispatchResult, type CompactionModel, type CompactionModelObservation, type CompactionObservation, type CompactionProviderObservation, CompactionResult, CompactionSettings, type CompactionSourceFallbackObservation, CompactionWorkflowError, CompleteModelInput, CompleteModelOptions, type ContextAttributionObservation, type ContextAttributionSection, type ContextCapacityObservation, ContextEventSessionInput, type ContextForkSeed, ContextForkSeedSchema, type ContextPreparationObservation, type ContextSectionEstimate, type ContextualTool, ContinuationReplayPlan, ContinuationReplayPlanSchema, type ConversationEntry, type CreateTaskOptions, type CreateUnitSession, DEFAULT_MAX_TOOL_OUTPUT_TOKENS, type DiscoverableTool, type DurableSubmission, type EffectObservation, type ElicitationCapabilities, ElicitationCapabilitiesSchema, type ElicitationComposition, type ElicitationContentValue, ElicitationContentValueSchema, type ElicitationForm, ElicitationFormSchema, type ElicitationInvocationContext, type ElicitationProperty, ElicitationPropertySchema, type ElicitationRequest, ElicitationRequestSchema, type ElicitationResponse, ElicitationResponseSchema, ElicitationUnavailableError, type HistoryScope, type InvokeToolInput, type InvokeToolOptions, JOURNAL_FACT_SCHEMA_VERSION, type JoinPolicy, type JournalAppendOptions, type JournalBatchObservation, JournalConflictError, JournalCorruptionError, type JournalCursor, JournalCursorGapError, JournalCursorSchema, type JournalFact, type JournalFactKind, JournalFactSchema, JournalGroupDependencyError, type JournalPage, type JournalProjectionObservation, type JournalQueueObservation, type JournalReadOptions, JournalReaderCapacityError, JournalReaderResetRequiredError, type JournalRecoveryFact, type JournalReopenObservation, DurableRun as JournalRunHandle, type JournalStore, JournalStoreFaultError, type JournalSubscription, type JournalSubscriptionOptions, type JournalWrite, JournalWriterBusyError, type JsonValue, JsonValueSchema, MemoryUnitStore, type MessageDeliveryResult, type MessageDraft, type MessageReceipt, type MessageRejection, type ModelAttemptObservation, type ModelContextEstimateEvent, type ModelDispatchObservation, ModelInvocationReceipt, ModelInvocationUnknownError, type ModelProviderObservation, type ModelRequestContentOrigin, ModelRequestContextAttribution, ModelRequestContextSourceEstimate, type ModelRequestInspection, type ModelRequestMessageInspection, type ModelRequestToolInspection, type ModelRequestedFact, type ModelRetryEndEvent, type ModelRetryObservation, ModelRetryPolicy, type ModelRetryStartEvent, type ModelRetryWaitObservation, type ModelUnknownObservation, type ModelUsageEvent, type NewJournalFact, type NextState, type ObservationTraceContext, type OpenUnitOptions, type OpenedUnitStore, type PermissionComposition, type PermissionGrant, PermissionGrantNotFoundError, PermissionGrantSchema, type PermissionScalar, PermissionScalarSchema, type PlacedRunInput, PluginRecord, PluginRecordConflictError, type PluginRecordOwner, type PluginRecordPayload, type ProjectRequestContextOptions, ProjectSessionForkSeedOptions, type ProjectedRequestContext, type ReconstructedModelRequest, ResumeInterruptedRunOptions, RunAcceptedReceipt, RunAdmissionConflictError, type RunAdmittedObservation, RunCancellationReceipt, type RunDrainObservation, type RunExecutionObservation, RunExecutionResource, RunExecutionResourceProvider, type RunFailureCode, RunFailureCodeSchema, type RunInput, RunInputAcceptedReceipt, RunInputPlacementReceipt, RunInputProjection, type RunInspection, type RunJournalFact, type RunJournalFactKind, type RunLiveEvent, RunLiveEventHub, type RunLiveEventSubscription, type RunResourceWaitObservation, type RunSettledObservation, type RunStatus, RunSubscription, type RunTerminalOutcome, type RunView, type RunningTask, type RuntimeObservationPort, type ScheduleInput, type SendMessageOptions, SendSessionInput, SendSessionInputOptions, SendSessionInputSchema, SendSessionInputVariants, type SentMessage, SessionApprovalReviewer, SessionArtifactIndex, SessionBehaviorSnapshot, SessionBehaviors, SessionBusyError, SessionCompactionBusyError, SessionContextCapacityError, SessionExternalTools, SessionForkBusyError, SessionForkSeed, SessionForkSeedSchema, SessionHistoryProjection, SessionInputAcceptedReceipt, SessionInputConflictError, SessionInputInclusion, SessionInputInclusionProjection, type SessionInputSource, SessionInputSourceSchema, SessionInputSubmission, SessionInspection, type SessionInspectionContentPolicy, type SessionInspectionOptions, type SessionJournalFact, type SessionJournalFactKind, SessionModelInvocations, SessionObjectCapabilities, type SessionParticipants, type SessionPermissionGrant, SessionPermissionGrantSchema, SessionPromptCacheInspection, SessionProviderUsageEntry, type SessionRecoveryObservation, SessionRecoveryProjection, SessionRunActiveError, SessionToolDiscovery, SessionTurnUsage, SessionUsageProjection, SessionUsageSnapshot, type SignalRecord, SorbetRun, type SqliteUnitDatabase, SqliteUnitStore, type SqliteUnitStoreOptions, type SqliteValue, StartContinuationInput, StartRunInput, StartRunOptions, type StoredToolOutputFile, SubmissionControlInputSchema, SubmissionInputSchema, TaskContractError, type TaskDefinition, type TaskHandle, type TaskOutcome, type TaskRecord, type TaskRuntime, type ToolApprovalInspection, type ToolApprovalRequirement, ToolApprovalRequirementSchema, type ToolCallInspection, type ToolDefinition, type ToolDiscoveryMetadata, type ToolEffectInspection, type ToolExecutionObservation, type ToolExecutionStartedObservation, type ToolExposure, ToolHookEvidenceSchema, type ToolInvocationContext, ToolOperationError, type ToolOperationReceipt, type ToolOutputArchiveRecord, ToolOutputArchiveRecordSchema, ToolOutputArchiver, type ToolOutputFileStore, type ToolOutputMeasurement, type ToolOutputObservation, type ToolPermissionAccess, ToolPermissionAccessSchema, type ToolPermissionDirective, ToolPermissionDirectiveSchema, type ToolPermissionEvaluator, type ToolPermissionObservation, type ToolPermissionPolicy, type ToolPermissionPolicyEntry, ToolPermissionPolicyEntrySchema, ToolPermissionPolicySchema, type ToolPermissionRequest, type ToolPermissionRule, ToolPermissionRuleSchema, type ToolResult, type ToolResultMessageCommittedPayload, type ToolSearchOptions, ToolSourcesSchema, type ToolUpdateCallback, type UnitCloseResult, type UnitCommitOutcome, type UnitEntry, type UnitEpoch, type UnitFact, UnitFactSchema, UnitHistoryError, type UnitHistoryErrorCode, type UnitInspectionPage, type UnitMessage, UnitMessageSchema, UnitModelContext, type UnitOpenOptions, type UnitPage, type UnitReadOptions, type UnitReader, type UnitRecord, type UnitRecoverySnapshot, type UnitRecoveryState, UnitRuntime, type UnitSession, type UnitSessionProvider, type UnitStorage, type UnitStorageWrite, type UnitStore, type UnitStoreConformanceFixture, type UnitStoreConformanceHarness, UnitStoreError, type UnitSubscription, type UnitTransaction, type UnitTx, type UnitWorkSummary, type UnitWrite, type UserPrompt, UserPromptSchema, UserSessionInput, type WaitIdentityObservation, type WaitMember, type WaitSettledObservation, type WaitStartedObservation, appendPluginRecord, buildContinuationReplayPlan, capturePluginRecordInput, committedConversationMessages, compactModelRequestContextSnapshot, contextHistorySnapshot, conversationEntries, createArtifactTool, createContextForkSeed, createRequestUserInputTool, defineTask, effectiveConversationEntries, estimateContextTokens, estimateMessageTokens, estimateMessagesTokens, evaluateToolPermissionPolicy, executeCompactionWorkflow, expandModelRequestContextSnapshot, inspectRunHistory, isRunTerminalFactKind, limitToolOutput, materializeModelRequestContextSnapshot, observeRuntime, openUnitStorage, parseToolParameters, planSessionCompaction, pluginPrefixSources, prepareModelRequestBase, prepareSessionCompaction, projectModelRequestDispatch, projectModelView, projectPermissionGrants, projectRequestContext, projectSessionForkSeed, projectSessionInspection, projectSessionProviderUsage, projectSessionRecovery, projectToolResultObservations, projectUnknownEffectResult, projectedMessagesAfterCompaction, readObservationTraceContext, readUnitWorkSummary, reconstructModelRequest, registerUnitStoreConformance, requestElicitation, shouldCompact, validateCompactionSettings };
4230
+ //# sourceMappingURL=index.d.ts.map