agent-neckbeard 1.1.28 → 1.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +28 -30
  3. package/dist/archil.d.ts +73 -0
  4. package/dist/archil.js +673 -0
  5. package/dist/build.cjs +129 -5160
  6. package/dist/build.d.cts +9 -5
  7. package/dist/build.d.ts +9 -5
  8. package/dist/build.js +4 -6
  9. package/dist/{chunk-JF5YPOBY.js → chunk-FHNQ5DNA.js} +3235 -511
  10. package/dist/{chunk-M7XNBKG4.js → chunk-I5GIWADK.js} +29 -7
  11. package/dist/chunk-I5NULOJP.js +129 -0
  12. package/dist/chunk-PKUGXECR.js +13 -0
  13. package/dist/chunk-QA4L7ZI2.js +72 -0
  14. package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
  15. package/dist/cli.cjs +124 -5154
  16. package/dist/cli.js +7 -8
  17. package/dist/define-gdmBe9RA.d.ts +227 -0
  18. package/dist/durable.d.ts +53 -0
  19. package/dist/durable.js +92 -0
  20. package/dist/index.cjs +720 -833
  21. package/dist/index.d.cts +139 -78
  22. package/dist/index.d.ts +139 -78
  23. package/dist/index.js +12 -11
  24. package/dist/inside.d.ts +15 -0
  25. package/dist/inside.js +530 -0
  26. package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
  27. package/dist/pi-watch-legacy.d.ts +4503 -0
  28. package/dist/serve.cjs +9 -309
  29. package/dist/serve.d.cts +14 -1
  30. package/dist/serve.d.ts +14 -1
  31. package/dist/serve.js +3 -5
  32. package/docs/AGENT.md +95 -59
  33. package/docs/DAYTONA.md +2 -0
  34. package/docs/DOCKER.md +0 -1
  35. package/docs/E2B.md +1 -1
  36. package/docs/LEGACY.md +1 -8
  37. package/docs/MODAL.md +1 -1
  38. package/package.json +57 -23
  39. package/types/pi-watch.d.cts +68 -0
  40. package/dist/chunk-33IXN6MM.js +0 -21
  41. package/dist/chunk-6P5I7ZCH.js +0 -2552
  42. package/dist/chunk-M3FISP7J.js +0 -377
  43. package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
  44. package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
  45. package/dist/serve-Dan1HQKN.d.cts +0 -89
  46. package/dist/serve-Dan1HQKN.d.ts +0 -89
  47. package/dist/supervisor.cjs +0 -5731
  48. package/dist/supervisor.d.cts +0 -482
  49. package/dist/supervisor.d.ts +0 -482
  50. package/dist/supervisor.js +0 -3187
  51. package/docs/SUPERVISOR.md +0 -258
@@ -0,0 +1,4503 @@
1
+ // @ts-ignore Installed with the optional durable peers.
2
+ import Anthropic from '@anthropic-ai/sdk';
3
+ // @ts-ignore Installed with the optional durable peers.
4
+ import { ResponseCreateParamsStreaming } from 'openai/resources/responses/responses.js';
5
+ // @ts-ignore Installed with the optional durable peers.
6
+ import OpenAI from 'openai';
7
+
8
+ interface InstrumentOptions {
9
+ description?: string;
10
+ unit?: string;
11
+ }
12
+ interface HistogramOptions extends InstrumentOptions {
13
+ /** Bucket hints; callers supply finite, strictly increasing values. */
14
+ boundaries?: readonly number[];
15
+ }
16
+ interface TelemetryCounter {
17
+ add(value: number, attributes?: SpanAttributes): void;
18
+ }
19
+ interface TelemetryUpDownCounter {
20
+ add(value: number, attributes?: SpanAttributes): void;
21
+ }
22
+ interface TelemetryHistogram {
23
+ record(value: number, attributes?: SpanAttributes, context?: TelemetryContext): void;
24
+ }
25
+ /**
26
+ * Optional adapter capability with synchronous factories and recording methods.
27
+ * Typed inputs are trusted; callers supply finite measurements and nonnegative counter increments.
28
+ * Malformed input behavior is unspecified.
29
+ */
30
+ interface TelemetryMetrics {
31
+ counter(name: string, options?: InstrumentOptions): TelemetryCounter;
32
+ upDownCounter(name: string, options?: InstrumentOptions): TelemetryUpDownCounter;
33
+ histogram(name: string, options?: HistogramOptions): TelemetryHistogram;
34
+ }
35
+
36
+ type AttributeValue = string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
37
+ interface SpanAttributes {
38
+ [name: string]: AttributeValue | undefined;
39
+ }
40
+ /** Opaque, JSON-serializable adapter-owned propagation data. */
41
+ type TelemetryCarrier = Record<string, string>;
42
+ /** Optional transport capability implemented by the application's telemetry adapter. */
43
+ interface TelemetryPropagation {
44
+ inject(context: TelemetryContext): TelemetryCarrier | undefined;
45
+ /** Absent or unknown carriers use the root; recognized identifiers are opaque strings. */
46
+ extract(carrier: TelemetryCarrier | undefined): TelemetryContext;
47
+ }
48
+ interface SpanLink {
49
+ context: TelemetryContext;
50
+ attributes?: SpanAttributes;
51
+ }
52
+ interface SpanOptions {
53
+ name: string;
54
+ attributes?: SpanAttributes;
55
+ links?: readonly SpanLink[];
56
+ }
57
+ type SpanStatus = {
58
+ status: "ok";
59
+ } | {
60
+ status: "error";
61
+ error?: {
62
+ name: string;
63
+ message: string;
64
+ };
65
+ };
66
+ /** Adapter contract for trusted typed inputs; malformed input behavior is unspecified. */
67
+ interface TelemetryContext {
68
+ /** Adapter capabilities remain available on child spans and extracted parents. */
69
+ readonly metrics?: TelemetryMetrics;
70
+ readonly propagation?: TelemetryPropagation;
71
+ startSpan<T>(options: SpanOptions, callback: (span: TelemetrySpan) => T | Promise<T>): Promise<T>;
72
+ }
73
+ interface TelemetrySpan extends TelemetryContext {
74
+ addLink(link: SpanLink): void;
75
+ addEvent(name: string, attributes?: SpanAttributes): void;
76
+ setAttributes(attributes: SpanAttributes): void;
77
+ setStatus(status: SpanStatus): void;
78
+ }
79
+
80
+ /** Typed identity for one value carried by a {@link Context}. */
81
+ interface ContextKey<T> {
82
+ readonly token: symbol;
83
+ /** Type-only marker that prevents keys with different value types from being interchangeable. */
84
+ readonly valueType?: (value: T) => T;
85
+ }
86
+ /** Immutable invocation-scoped values passed explicitly through operations. */
87
+ interface Context$1 {
88
+ readonly abortSignal: AbortSignal | undefined;
89
+ readonly telemetry: TelemetrySpan;
90
+ value<T>(key: ContextKey<T>): T | undefined;
91
+ toString(): string;
92
+ }
93
+
94
+ type JsonValue$1 = null | boolean | number | string | JsonValue$1[] | {
95
+ [key: string]: JsonValue$1;
96
+ };
97
+ type IsAny$2<T> = 0 extends 1 & T ? true : false;
98
+ /** Strict-JSON representation of an application data type. Unknown payloads become JsonValue. */
99
+ type JsonRepresentation$1<T> = IsAny$2<T> extends true ? JsonValue$1 : unknown extends T ? JsonValue$1 : T extends null | boolean | number | string ? T : T extends readonly (infer TItem)[] ? JsonRepresentation$1<TItem>[] : T extends object ? {
100
+ [TKey in keyof T]: JsonRepresentation$1<T[TKey]>;
101
+ } : never;
102
+
103
+ /** A mutable transaction-scoped view of a JSON value, preserving tuple positions. */
104
+ type Draft<T, Depth extends readonly unknown[] = []> = Depth["length"] extends 8 ? T : T extends null | boolean | number | string ? T : T extends (...args: never[]) => unknown ? T : T extends object ? {
105
+ -readonly [Key in keyof T]: Draft<T[Key], [...Depth, unknown]>;
106
+ } : T;
107
+
108
+ type Seg = string | number;
109
+ type Path = readonly Seg[];
110
+ type NonEmptyPath = readonly [Seg, ...Seg[]];
111
+ /**
112
+ * Tuples are the form — in memory, on the wire, on disk.
113
+ *
114
+ * `r` is the ONLY op that replaces a whole value. `s`/`d`/`a`/`t` cannot target
115
+ * the root: the type forbids it. `p` and `m` may, because a tracked value can
116
+ * itself be an array. Operation shape is not canonical: an array may be emptied by either
117
+ * a replacement or a root splice.
118
+ *
119
+ * `Op` knows nothing about the path dictionary. Interning, id references and
120
+ * omitted paths live in `WireOp` and exist only between `encode` and `decode`.
121
+ */
122
+ type Op = readonly ["r", JsonValue$1] | readonly ["s", NonEmptyPath, JsonValue$1] | readonly ["d", NonEmptyPath] | readonly ["a", NonEmptyPath, string] | readonly ["t", NonEmptyPath, number] | readonly ["p", Path, number, number, JsonValue$1[]]
123
+ /** Reorder an array in place: `new[i] = old[permutation[i]]`. */
124
+ | readonly ["m", Path, number[]];
125
+
126
+ /**
127
+ * Terminal result of one watch, tagged by `kind`. A watch ends only for good; a failure its source recovers from is a
128
+ * `failed` call (`WatchCall`), and the watch stays open.
129
+ *
130
+ * - `stopped`: `stop()` was called.
131
+ * - `aborted`: the context the watch was acquired with was aborted.
132
+ * - `ended`: the source closed (its owner ended or closed).
133
+ * - `listener_error`: the listener threw or rejected with `error`.
134
+ * - `failed`: the source failed for good with `error`.
135
+ */
136
+ type WatchEnd = {
137
+ readonly kind: "stopped" | "aborted" | "ended";
138
+ } | {
139
+ readonly kind: "listener_error";
140
+ readonly error: Error;
141
+ } | {
142
+ readonly kind: "failed";
143
+ readonly error: unknown;
144
+ };
145
+ /**
146
+ * One call of a JSON watch's listener, and one frame a source hands its watch, tagged by `kind`:
147
+ *
148
+ * - `value`: the newest value, the ops that turn the previous value into it, and whether the document the watch follows
149
+ * was retired since the previous value call. A retirement does not end the watch: `value` is then what the address
150
+ * shows after it (the source decides; a Durable document keeps the last value the watch was given, with no ops), and a
151
+ * document created there later arrives as `[["r", value]]`, possibly in the same call.
152
+ * - `failed`: the source cannot compute its value now, with `error`; the watch stays open, and the next value arrives as
153
+ * `[["r", value]]`. `WatchHandle.value` keeps the last value.
154
+ *
155
+ * Plain data: the frame's context is the listener's second argument, never part of the call.
156
+ */
157
+ type WatchCall<T> = {
158
+ readonly kind: "value";
159
+ readonly value: T;
160
+ readonly ops: readonly Op[];
161
+ readonly retired: boolean;
162
+ } | {
163
+ readonly kind: "failed";
164
+ readonly error: unknown;
165
+ };
166
+ /**
167
+ * Serialized observation of an immutable value: one listener call at a time; changes made meanwhile arrive folded into
168
+ * the next call.
169
+ */
170
+ interface WatchHandle<T> {
171
+ /** Acquisition revision before start; latest delivered immutable revision afterward (a `failed` call keeps it). */
172
+ readonly value: T;
173
+ /** Install the sole asynchronous listener. Never invokes it inline. */
174
+ start(listener: (call: WatchCall<T>, context: Context$1) => Promise<void>): void;
175
+ /** Idempotently stop future callbacks and return this watch's terminal result. */
176
+ stop(): Promise<WatchEnd>;
177
+ /** Settle when the watch terminates; an already-running callback remains caller-owned. */
178
+ readonly closed: Promise<WatchEnd>;
179
+ }
180
+
181
+ /** Azure models ship without a baseUrl: one resource per user, resolved per request. */
182
+ interface AzureEndpointOptions extends StreamOptions {
183
+ azureApiVersion?: string;
184
+ azureResourceName?: string;
185
+ azureBaseUrl?: string;
186
+ azureDeploymentName?: string;
187
+ }
188
+
189
+ interface AzureOpenAIResponsesOptions extends AzureEndpointOptions {
190
+ reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
191
+ toolChoice?: ResponseCreateParamsStreaming["tool_choice"];
192
+ reasoningSummary?: "auto" | "detailed" | "concise" | null;
193
+ }
194
+
195
+ type BedrockThinkingDisplay = "summarized" | "omitted";
196
+ interface BedrockOptions extends StreamOptions {
197
+ region?: string;
198
+ profile?: string;
199
+ toolChoice?: "auto" | "any" | "none" | {
200
+ type: "tool";
201
+ name: string;
202
+ };
203
+ reasoning?: ThinkingLevel;
204
+ thinkingBudgets?: ThinkingBudgets;
205
+ interleavedThinking?: boolean;
206
+ /**
207
+ * Controls how Claude's thinking content is returned in responses.
208
+ * - "summarized": Thinking blocks contain summarized thinking text (default here).
209
+ * - "omitted": Thinking content is redacted but the signature still travels back
210
+ * for multi-turn continuity, reducing time-to-first-text-token.
211
+ *
212
+ * Note: Anthropic's API default for Claude Opus 4.8 and Mythos Preview is
213
+ * "omitted". We default to "summarized" here to keep behavior consistent with
214
+ * older Claude 4 models. Only applies to Claude models on Bedrock.
215
+ */
216
+ thinkingDisplay?: BedrockThinkingDisplay;
217
+ /** Key-value pairs attached to the inference request for cost allocation tagging.
218
+ * Keys: max 64 chars, no `aws:` prefix. Values: max 256 chars. Max 50 pairs.
219
+ * Tags appear in AWS Cost Explorer split cost allocation data.
220
+ * @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html */
221
+ requestMetadata?: Record<string, string>;
222
+ /** Bearer token for Bedrock API key authentication.
223
+ * When set, bypasses SigV4 signing and sends Authorization: Bearer <token> instead.
224
+ * Requires `bedrock:CallWithBearerToken` IAM permission on the token's identity.
225
+ * Set via AWS_BEARER_TOKEN_BEDROCK env var or pass directly.
226
+ * @see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html */
227
+ bearerToken?: string;
228
+ }
229
+
230
+ /**
231
+ * Shared utilities for Google Generative AI and Google Vertex providers.
232
+ */
233
+
234
+ /**
235
+ * Thinking level for Gemini 3 models.
236
+ * Mirrors Google's ThinkingLevel enum values.
237
+ */
238
+ type GoogleApiThinkingLevel = "THINKING_LEVEL_UNSPECIFIED" | "MINIMAL" | "LOW" | "MEDIUM" | "HIGH";
239
+
240
+ interface GoogleOptions extends StreamOptions {
241
+ toolChoice?: "auto" | "none" | "any";
242
+ thinking?: {
243
+ enabled: boolean;
244
+ budgetTokens?: number;
245
+ level?: GoogleApiThinkingLevel;
246
+ };
247
+ }
248
+
249
+ interface GoogleVertexOptions extends StreamOptions {
250
+ toolChoice?: "auto" | "none" | "any";
251
+ thinking?: {
252
+ enabled: boolean;
253
+ budgetTokens?: number;
254
+ level?: GoogleApiThinkingLevel;
255
+ };
256
+ project?: string;
257
+ location?: string;
258
+ }
259
+
260
+ /**
261
+ * Provider-specific options for the Mistral API.
262
+ */
263
+ type MistralReasoningEffort = "none" | "low" | "medium" | "high" | "max";
264
+ interface MistralOptions extends StreamOptions {
265
+ toolChoice?: "auto" | "none" | "any" | "required" | {
266
+ type: "function";
267
+ function: {
268
+ name: string;
269
+ };
270
+ };
271
+ promptMode?: "reasoning";
272
+ reasoningEffort?: MistralReasoningEffort;
273
+ }
274
+
275
+ interface OpenAICodexResponsesOptions extends StreamOptions {
276
+ reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
277
+ reasoningSummary?: "auto" | "concise" | "detailed" | "off" | "on" | null;
278
+ serviceTier?: ResponseCreateParamsStreaming["service_tier"];
279
+ textVerbosity?: "low" | "medium" | "high";
280
+ toolChoice?: "auto" | "none" | "required";
281
+ }
282
+
283
+ interface OpenAICompletionsOptions extends StreamOptions {
284
+ toolChoice?: OpenAI.Chat.Completions.ChatCompletionToolChoiceOption;
285
+ reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
286
+ /** Token budgets per thinking level. Used when `compat.thinkingTokenBudgetField` or `compat.supportsThinkingTokenBudget` is set, or by `{ "$var": "thinking.budget" }`. */
287
+ thinkingBudgets?: ThinkingBudgets;
288
+ }
289
+
290
+ interface OpenAIResponsesOptions extends StreamOptions {
291
+ reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
292
+ reasoningSummary?: "auto" | "detailed" | "concise" | null;
293
+ serviceTier?: ResponseCreateParamsStreaming["service_tier"];
294
+ toolChoice?: ResponseCreateParamsStreaming["tool_choice"];
295
+ }
296
+
297
+ /**
298
+ * pi-messages API implementation.
299
+ *
300
+ * Streams pi's own message protocol directly to a backend: the request is a
301
+ * single POST of `{ model, context, options }` to `<baseUrl>/messages`, the
302
+ * response is an SSE stream of serialized assistant-message events plus a
303
+ * terminal `done`/`error` event. This is the wire protocol spoken by the
304
+ * Radius gateway, but any backend implementing it can be used, e.g. via a
305
+ * models.json custom provider with `"api": "pi-messages"`.
306
+ */
307
+
308
+ interface PiMessagesOptions extends StreamOptions {
309
+ reasoning?: ThinkingLevel;
310
+ toolChoice?: "auto" | "none" | "required" | {
311
+ type: "function";
312
+ function: {
313
+ name: string;
314
+ };
315
+ };
316
+ /** Ask the backend for debug metadata (e.g. routing response headers). */
317
+ debug?: boolean;
318
+ }
319
+
320
+ /** The value type of a TypeBox schema type by its `'~kind'`, or its `Type.Unsafe` type; `unknown` for other kinds. */
321
+ type TypeBoxStatic$1<S> = S extends {
322
+ readonly "~kind": infer K;
323
+ } ? KindStatic$1<S, K> : S extends {
324
+ readonly "~unsafe": infer T;
325
+ } ? T : unknown;
326
+ interface Primitives$1 {
327
+ String: string;
328
+ Number: number;
329
+ Integer: number;
330
+ Boolean: boolean;
331
+ Null: null;
332
+ BigInt: bigint;
333
+ Undefined: undefined;
334
+ Unknown: unknown;
335
+ Any: any;
336
+ }
337
+ type KindStatic$1<S, K> = K extends keyof Primitives$1 ? Primitives$1[K] : K extends "Literal" ? S extends {
338
+ readonly const: infer V;
339
+ } ? V : unknown : K extends "Array" ? S extends {
340
+ readonly items: infer I;
341
+ } ? Static$1<I>[] : unknown : K extends "Object" ? S extends {
342
+ readonly properties: infer P;
343
+ } ? ObjectStatic$1<P> : unknown : K extends "Union" ? S extends {
344
+ readonly anyOf: readonly (infer B)[];
345
+ } ? Static$1<B> : unknown : K extends "Record" ? S extends {
346
+ readonly patternProperties: infer P;
347
+ } ? Record<RecordKey$1<keyof P>, Static$1<P[keyof P]>> : unknown : K extends "Enum" ? S extends {
348
+ readonly enum: readonly (infer V)[];
349
+ } ? V : unknown : K extends "Tuple" ? S extends {
350
+ readonly items: infer I extends readonly unknown[];
351
+ } ? {
352
+ -readonly [N in keyof I]: Static$1<I[N]>;
353
+ } : unknown : unknown;
354
+ type Optional$1 = {
355
+ readonly "~optional": true;
356
+ };
357
+ type Readonly$2 = {
358
+ readonly "~readonly": true;
359
+ };
360
+ type ObjectStatic$1<P> = keyof P extends never ? object : Simplify$1<{
361
+ -readonly [K in keyof P as P[K] extends Optional$1 | Readonly$2 ? never : K]: Static$1<P[K]>;
362
+ } & {
363
+ -readonly [K in keyof P as P[K] extends Optional$1 ? (P[K] extends Readonly$2 ? never : K) : never]?: Static$1<P[K]>;
364
+ } & {
365
+ readonly [K in keyof P as P[K] extends Readonly$2 ? (P[K] extends Optional$1 ? never : K) : never]: Static$1<P[K]>;
366
+ } & {
367
+ readonly [K in keyof P as P[K] extends Optional$1 ? (P[K] extends Readonly$2 ? K : never) : never]?: Static$1<P[K]>;
368
+ }>;
369
+ type Simplify$1<T> = {
370
+ [K in keyof T]: T[K];
371
+ } & {};
372
+ type RecordKey$1<Pattern> = Pattern extends "^-?(?:0|[1-9][0-9]*)$" | "^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" ? number : string;
373
+
374
+ declare const STATIC$1: unique symbol;
375
+ /** A JSON Schema object whose valid values have type `T` (a type-level brand; nothing extra exists at run time). */
376
+ type Schema<T = unknown> = {
377
+ readonly [keyword: string]: unknown;
378
+ } & {
379
+ readonly [STATIC$1]?: T;
380
+ };
381
+ /**
382
+ * The type of the values `S` accepts: the type a builder recorded; for a TypeBox schema (`'~kind'` or `'~unsafe'`),
383
+ * TypeBox's static type for the common kinds (see `TypeBoxStatic`); else `unknown`.
384
+ */
385
+ type Static$1<S> = S extends {
386
+ readonly "~kind": unknown;
387
+ } | {
388
+ readonly "~unsafe": unknown;
389
+ } ? TypeBoxStatic$1<S> : S extends {
390
+ readonly [STATIC$1]?: infer T;
391
+ } ? unknown extends T ? unknown : T : unknown;
392
+
393
+ declare const OpenAICompletionsCompatSchema: Schema<{
394
+ supportsStore?: boolean | undefined;
395
+ supportsDeveloperRole?: boolean | undefined;
396
+ supportsReasoningEffort?: boolean | undefined;
397
+ supportsUsageInStreaming?: boolean | undefined;
398
+ supportsFinishReason?: boolean | undefined;
399
+ maxTokensField?: "max_completion_tokens" | "max_tokens" | undefined;
400
+ requiresToolResultName?: boolean | undefined;
401
+ requiresAssistantAfterToolResult?: boolean | undefined;
402
+ requiresNonNullAssistantContent?: boolean | undefined;
403
+ requiresToolsWithToolHistory?: boolean | undefined;
404
+ requiresThinkingAsText?: boolean | undefined;
405
+ requiresReasoningContentOnAssistantMessages?: boolean | undefined;
406
+ thinkingFormat?: "ant-ling" | "baseten" | "chat-template" | "deepseek" | "openai" | "openrouter" | "qwen" | "qwen-chat-template" | "string-thinking" | "together" | "zai" | undefined;
407
+ chatTemplateKwargs?: Record<string, string | number | boolean | {
408
+ $var: "thinking.budget" | "thinking.effort" | "thinking.enabled";
409
+ omitWhenOff?: boolean | undefined;
410
+ } | null> | undefined;
411
+ chatTemplateArgs?: Record<string, string | number | boolean | {
412
+ $var: "thinking.budget" | "thinking.effort" | "thinking.enabled";
413
+ omitWhenOff?: boolean | undefined;
414
+ } | null> | undefined;
415
+ openRouterRouting?: {
416
+ allow_fallbacks?: boolean | undefined;
417
+ require_parameters?: boolean | undefined;
418
+ data_collection?: "allow" | "deny" | undefined;
419
+ zdr?: boolean | undefined;
420
+ enforce_distillable_text?: boolean | undefined;
421
+ order?: string[] | undefined;
422
+ only?: string[] | undefined;
423
+ ignore?: string[] | undefined;
424
+ quantizations?: string[] | undefined;
425
+ sort?: string | {
426
+ by?: string | undefined;
427
+ partition?: string | null | undefined;
428
+ } | undefined;
429
+ max_price?: {
430
+ prompt?: string | number | undefined;
431
+ completion?: string | number | undefined;
432
+ image?: string | number | undefined;
433
+ audio?: string | number | undefined;
434
+ request?: string | number | undefined;
435
+ } | undefined;
436
+ preferred_min_throughput?: number | {
437
+ p50?: number | undefined;
438
+ p75?: number | undefined;
439
+ p90?: number | undefined;
440
+ p99?: number | undefined;
441
+ } | undefined;
442
+ preferred_max_latency?: number | {
443
+ p50?: number | undefined;
444
+ p75?: number | undefined;
445
+ p90?: number | undefined;
446
+ p99?: number | undefined;
447
+ } | undefined;
448
+ } | undefined;
449
+ vercelGatewayRouting?: {
450
+ only?: string[] | undefined;
451
+ order?: string[] | undefined;
452
+ } | undefined;
453
+ zaiToolStream?: boolean | undefined;
454
+ thinkingTokenBudgetField?: "thinking_budget" | "thinking_budget_tokens" | "thinking_token_budget" | undefined;
455
+ supportsThinkingTokenBudget?: boolean | undefined;
456
+ supportsOpenAIGrammarTools?: boolean | undefined;
457
+ supportsMidConvoSystemMessages?: boolean | undefined;
458
+ supportsMidConvoToolAdditions?: boolean | undefined;
459
+ supportsStrictMode?: boolean | undefined;
460
+ cacheControlFormat?: "anthropic" | undefined;
461
+ sendSessionAffinityHeaders?: boolean | undefined;
462
+ sessionAffinityFormat?: "openai" | "openai-nosession" | "openrouter" | undefined;
463
+ promptCacheKeyMode?: "auto" | "disabled" | "enabled" | undefined;
464
+ supportsLongCacheRetention?: boolean | undefined;
465
+ vllmPriority?: number | undefined;
466
+ }>;
467
+ declare const OpenAIResponsesCompatSchema: Schema<{
468
+ supportsDeveloperRole?: boolean | undefined;
469
+ supportsMidConvoSystemMessages?: boolean | undefined;
470
+ sessionAffinityFormat?: "openai" | "openai-nosession" | "openrouter" | undefined;
471
+ promptCacheKeyMode?: "auto" | "disabled" | "enabled" | undefined;
472
+ supportsLongCacheRetention?: boolean | undefined;
473
+ supportsStrictMode?: boolean | undefined;
474
+ supportsOpenAIGrammarTools?: boolean | undefined;
475
+ supportsAdditionalTools?: boolean | undefined;
476
+ supportsToolSearch?: boolean | undefined;
477
+ supportsExplicitPromptCacheMode?: boolean | undefined;
478
+ supportsMidConvoEffort?: boolean | undefined;
479
+ supportsMaxOutputTokens?: boolean | undefined;
480
+ }>;
481
+ declare const AnthropicMessagesCompatSchema: Schema<{
482
+ supportsEagerToolInputStreaming?: boolean | undefined;
483
+ supportsLongCacheRetention?: boolean | undefined;
484
+ sendSessionAffinityHeaders?: boolean | undefined;
485
+ sessionAffinityFormat?: "openrouter" | undefined;
486
+ supportsCacheControlOnTools?: boolean | undefined;
487
+ supportsTemperature?: boolean | undefined;
488
+ forceAdaptiveThinking?: boolean | undefined;
489
+ allowEmptySignature?: boolean | undefined;
490
+ supportsStrictTools?: boolean | undefined;
491
+ supportsMidConvoEffort?: boolean | undefined;
492
+ supportsMidConvoSystemMessages?: boolean | undefined;
493
+ supportsMidConvoToolChanges?: boolean | undefined;
494
+ supportsMessageThreads?: boolean | undefined;
495
+ allowedFallbackModels?: {
496
+ provider: string;
497
+ model: string;
498
+ cost: {
499
+ input: number;
500
+ output: number;
501
+ cacheRead: number;
502
+ cacheWrite: number;
503
+ tiers?: {
504
+ input: number;
505
+ output: number;
506
+ cacheRead: number;
507
+ cacheWrite: number;
508
+ inputTokensAbove: number;
509
+ }[] | undefined;
510
+ };
511
+ }[] | undefined;
512
+ }>;
513
+ declare const BedrockCompatSchema: Schema<{
514
+ supportsStrictMode?: boolean | undefined;
515
+ }>;
516
+ declare const MistralConversationsCompatSchema: Schema<{
517
+ supportsMidConvoSystemMessages?: boolean | undefined;
518
+ supportsStrictMode?: boolean | undefined;
519
+ }>;
520
+ declare const SystemOneCompatSchema: Schema<{
521
+ imageInput?: "assets" | "images" | "state-image-urls" | undefined;
522
+ sendImageOptInHeader?: boolean | undefined;
523
+ }>;
524
+ /** Compatibility settings for OpenAI-compatible completions APIs. */
525
+ interface OpenAICompletionsCompat extends Static$1<typeof OpenAICompletionsCompatSchema> {
526
+ }
527
+ /** Compatibility settings for OpenAI Responses APIs. */
528
+ interface OpenAIResponsesCompat extends Static$1<typeof OpenAIResponsesCompatSchema> {
529
+ }
530
+ /** Compatibility settings for Anthropic Messages-compatible APIs. */
531
+ interface AnthropicMessagesCompat extends Static$1<typeof AnthropicMessagesCompatSchema> {
532
+ }
533
+ /** Compatibility settings for Amazon Bedrock models. */
534
+ interface BedrockCompat extends Static$1<typeof BedrockCompatSchema> {
535
+ }
536
+ /** Compatibility settings for the Mistral chat API. */
537
+ interface MistralConversationsCompat extends Static$1<typeof MistralConversationsCompatSchema> {
538
+ }
539
+ /** Compatibility settings for System One classifier APIs. */
540
+ interface SystemOneCompat extends Static$1<typeof SystemOneCompatSchema> {
541
+ }
542
+
543
+ declare const ThinkingLevelSchema: Schema<"high" | "low" | "max" | "medium" | "minimal" | "xhigh">;
544
+ declare const ModelThinkingLevelSchema: Schema<"high" | "low" | "max" | "medium" | "minimal" | "off" | "xhigh">;
545
+ declare const ModelInputModalitySchema: Schema<"image" | "text">;
546
+ declare const CacheRetentionSchema: Schema<"long" | "none" | "short">;
547
+ declare const ThinkingLevelMapSchema: Schema<{
548
+ off?: string | null | undefined;
549
+ minimal?: string | null | undefined;
550
+ low?: string | null | undefined;
551
+ medium?: string | null | undefined;
552
+ high?: string | null | undefined;
553
+ xhigh?: string | null | undefined;
554
+ max?: string | null | undefined;
555
+ }>;
556
+ declare const ModelPromptCacheSchema: Schema<{
557
+ short?: number | undefined;
558
+ long?: number | undefined;
559
+ }>;
560
+ declare const ModelCostSchema: Schema<{
561
+ input: number;
562
+ output: number;
563
+ cacheRead: number;
564
+ cacheWrite: number;
565
+ tiers?: {
566
+ input: number;
567
+ output: number;
568
+ cacheRead: number;
569
+ cacheWrite: number;
570
+ inputTokensAbove: number;
571
+ }[] | undefined;
572
+ }>;
573
+ declare const ModelInputLimitsSchema: Schema<{
574
+ maxRequestBytes?: number | undefined;
575
+ images?: {
576
+ resize?: {
577
+ maxWidth?: number | undefined;
578
+ maxHeight?: number | undefined;
579
+ maxBytes?: number | undefined;
580
+ jpegQuality?: number | undefined;
581
+ } | undefined;
582
+ maxPerMessage?: number | undefined;
583
+ maxPerRequest?: number | undefined;
584
+ } | undefined;
585
+ }>;
586
+ type ThinkingLevel = Static$1<typeof ThinkingLevelSchema>;
587
+ type ModelThinkingLevel = Static$1<typeof ModelThinkingLevelSchema>;
588
+ type ThinkingLevelMap = Static$1<typeof ThinkingLevelMapSchema>;
589
+ type ModelInputModality = Static$1<typeof ModelInputModalitySchema>;
590
+ type CacheRetention = Static$1<typeof CacheRetentionSchema>;
591
+ type ModelPromptCache = Static$1<typeof ModelPromptCacheSchema>;
592
+ type ModelCost = Static$1<typeof ModelCostSchema>;
593
+ type ModelInputLimits = Static$1<typeof ModelInputLimitsSchema>;
594
+
595
+ interface DiagnosticErrorInfo {
596
+ name?: string;
597
+ message: string;
598
+ stack?: string;
599
+ code?: string | number;
600
+ }
601
+ interface AssistantMessageDiagnostic {
602
+ type: string;
603
+ timestamp: number;
604
+ error?: DiagnosticErrorInfo;
605
+ details?: JsonObject$1;
606
+ }
607
+
608
+ declare class EventStream<T, R = T> implements AsyncIterable<T> {
609
+ private queue;
610
+ private waiting;
611
+ protected done: boolean;
612
+ private finalResultPromise;
613
+ private resolveFinalResult;
614
+ private isComplete;
615
+ private extractResult;
616
+ constructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R);
617
+ push(event: T): void;
618
+ end(result?: R): void;
619
+ [Symbol.asyncIterator](): AsyncIterator<T>;
620
+ result(): Promise<R>;
621
+ }
622
+ /**
623
+ * Event stream of one assistant response. It also times the response: the final message (`done` or `error` event, or
624
+ * the result passed to `end()`) gets `durationMs`, measured with a monotonic clock from the stream's creation, unless
625
+ * the message already has one or its `timestamp` predates the stream. A stream that forwards a response which started
626
+ * elsewhere, such as a deferred result fetched later, therefore leaves it untimed.
627
+ */
628
+ declare class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
629
+ #private;
630
+ constructor();
631
+ push(event: AssistantMessageEvent): void;
632
+ end(result?: AssistantMessage): void;
633
+ }
634
+
635
+ /**
636
+ * Request auth for a single model request. If a value cannot be expressed as
637
+ * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.
638
+ */
639
+ interface ModelAuth {
640
+ apiKey?: string;
641
+ headers?: ProviderHeaders;
642
+ baseUrl?: string;
643
+ }
644
+ /**
645
+ * Stored api-key credential. `env` holds provider-scoped environment/config
646
+ * values such as Cloudflare account/gateway ids.
647
+ */
648
+ interface ApiKeyCredential {
649
+ type: "api_key";
650
+ key?: string;
651
+ env?: ProviderEnv;
652
+ }
653
+ /** OAuth token data returned by extension compatibility flows. */
654
+ interface OAuthCredentials {
655
+ refresh: string;
656
+ access: string;
657
+ expires: number;
658
+ [key: string]: unknown;
659
+ }
660
+ /** Stored canonical OAuth credential. */
661
+ interface OAuthCredential extends OAuthCredentials {
662
+ type: "oauth";
663
+ }
664
+ /** One type-tagged credential per provider — the shape of today's auth.json. */
665
+ type Credential = ApiKeyCredential | OAuthCredential;
666
+ /** Optional cancellation for public auth and credential operations. */
667
+ interface AuthOperationOptions {
668
+ signal?: AbortSignal;
669
+ }
670
+ /** Environment access for auth resolution. Injectable for tests and browsers. */
671
+ interface AuthContext {
672
+ env(name: string): Promise<string | undefined>;
673
+ /** Check whether a file exists. Supports a leading `~`. Always false in browsers. */
674
+ fileExists(path: string): Promise<boolean>;
675
+ }
676
+ /** Result of resolving auth for a model. */
677
+ interface AuthResult {
678
+ auth: ModelAuth;
679
+ /** Provider-scoped environment/config values resolved from credentials and ambient context. */
680
+ env?: ProviderEnv;
681
+ /** Human-readable label for status UI: "ANTHROPIC_API_KEY", "OAuth", "~/.aws/credentials". */
682
+ source?: string;
683
+ }
684
+ interface AuthCheck {
685
+ source?: string;
686
+ type: "api_key" | "oauth";
687
+ }
688
+ type AuthType = "api_key" | "oauth";
689
+ /**
690
+ * Prompt shown to the user during login. `signal` lets the flow cancel a
691
+ * pending prompt when an out-of-band event resolves the step, e.g. a
692
+ * `manual_code` prompt raced against a callback server, aborted when the
693
+ * callback wins.
694
+ */
695
+ type AuthPrompt = {
696
+ signal?: AbortSignal;
697
+ } & ({
698
+ type: "text";
699
+ message: string;
700
+ placeholder?: string;
701
+ } | {
702
+ type: "secret";
703
+ message: string;
704
+ placeholder?: string;
705
+ } | {
706
+ type: "select";
707
+ message: string;
708
+ options: readonly {
709
+ id: string;
710
+ label: string;
711
+ description?: string;
712
+ }[];
713
+ } | {
714
+ type: "manual_code";
715
+ message: string;
716
+ placeholder?: string;
717
+ });
718
+ interface AuthInfoLink {
719
+ url: string;
720
+ label?: string;
721
+ }
722
+ type AuthEvent = {
723
+ type: "info";
724
+ message: string;
725
+ links?: readonly AuthInfoLink[];
726
+ } | {
727
+ type: "auth_url";
728
+ url: string;
729
+ instructions?: string;
730
+ } | {
731
+ type: "device_code";
732
+ userCode: string;
733
+ verificationUri: string;
734
+ /** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */
735
+ openBrowserOnConfirm?: boolean;
736
+ /** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */
737
+ copyCodeOnConfirm?: boolean;
738
+ intervalSeconds?: number;
739
+ expiresInSeconds?: number;
740
+ } | {
741
+ type: "progress";
742
+ message: string;
743
+ };
744
+ /**
745
+ * Login interaction callbacks serving both api-key and OAuth flows.
746
+ *
747
+ * `prompt()` returns the entered/selected string (`select` returns the option
748
+ * id). Rejects on cancel/abort. `signal` aborts the whole login flow;
749
+ * per-prompt cancellation uses `AuthPrompt.signal`.
750
+ */
751
+ interface AuthInteraction {
752
+ signal?: AbortSignal;
753
+ prompt(prompt: AuthPrompt): Promise<string>;
754
+ notify(event: AuthEvent): void;
755
+ }
756
+ /** Normalized interaction passed to provider login implementations. */
757
+ type ProviderAuthInteraction = AuthInteraction & {
758
+ signal: AbortSignal;
759
+ };
760
+ /**
761
+ * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS
762
+ * profiles, ADC files). Ambient-only providers omit `login`.
763
+ */
764
+ interface ApiKeyAuth {
765
+ /** Display name, e.g. "Anthropic API key". */
766
+ name: string;
767
+ /** Interactive setup (prompt for key/provider env). Absent = ambient-only. */
768
+ login?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;
769
+ /**
770
+ * Optional side-effect-free availability check. Use this when `resolve()` may
771
+ * execute commands or perform other request-time work. Missing means Models
772
+ * checks availability by resolving auth.
773
+ */
774
+ check?(input: {
775
+ ctx: AuthContext;
776
+ credential?: ApiKeyCredential;
777
+ signal: AbortSignal;
778
+ }): Promise<AuthCheck | undefined>;
779
+ /**
780
+ * Resolve auth from the stored credential and/or ambient sources, merging
781
+ * per field (`credential.key ?? env("...")`, `credential.env?.NAME ?? env("...")`).
782
+ * undefined = not configured. Resolution is provider-scoped; model-specific
783
+ * endpoint preparation happens after auth has been resolved.
784
+ */
785
+ resolve(input: {
786
+ ctx: AuthContext;
787
+ credential?: ApiKeyCredential;
788
+ signal: AbortSignal;
789
+ }): Promise<AuthResult | undefined>;
790
+ }
791
+ /** App-supplied context for `Models.login`. */
792
+ interface LoginOptions {
793
+ /**
794
+ * Returns the stable ID of this app installation, e.g. sent to OpenAI as its
795
+ * agent host ID. Called only by login flows that need it, so apps can create
796
+ * the ID on first use and must return the same ID on every later call.
797
+ */
798
+ getDeviceId?: () => string;
799
+ /**
800
+ * Name this app introduces itself with during login, e.g. OpenAI's agent name hint and
801
+ * Codex originator. Defaults to pi's own name.
802
+ */
803
+ agentName?: string;
804
+ }
805
+ /**
806
+ * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked
807
+ * refresh pattern: `refresh` produces a credential, `toAuth` derives request
808
+ * auth from whatever credential ends up stored.
809
+ */
810
+ interface OAuthAuth {
811
+ /** Display name, e.g. "Anthropic (Claude Pro/Max)". */
812
+ name: string;
813
+ /** Whether access through this auth method is backed by a provider subscription. */
814
+ isSubscription?: boolean;
815
+ /** Selector label for the OAuth login option, e.g. "Sign in with SuperGrok or X Premium". */
816
+ loginLabel?: string;
817
+ login(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;
818
+ /**
819
+ * Exchange the refresh token. Network call; throws on failure
820
+ * (invalid_grant etc.). `Models` runs this under the store lock.
821
+ */
822
+ refresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;
823
+ /**
824
+ * Side-effect-free derivation of request auth from a valid credential.
825
+ * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers
826
+ * can load the implementation on first use.
827
+ */
828
+ toAuth(credential: OAuthCredential): Promise<ModelAuth>;
829
+ }
830
+ /**
831
+ * Provider auth. At least one of `apiKey`/`oauth` must be present: even
832
+ * ambient-credential providers and keyless local servers provide `apiKey`
833
+ * auth whose `resolve()` reports whether the provider is configured.
834
+ */
835
+ interface ProviderAuth {
836
+ apiKey?: ApiKeyAuth;
837
+ oauth?: OAuthAuth;
838
+ }
839
+
840
+ interface AuthResolutionOverrides {
841
+ apiKey?: string;
842
+ env?: ProviderEnv;
843
+ /** Require this much remaining OAuth-token validity; defaults to five minutes. */
844
+ minOAuthValidityMs?: number;
845
+ signal?: AbortSignal;
846
+ }
847
+
848
+ interface ModelsStoreEntry {
849
+ /** Persisted models of every type. */
850
+ models: readonly AnyModel[];
851
+ /** Unix timestamp from the remote catalog's Last-Modified header. */
852
+ lastModified?: number;
853
+ /** Unix timestamp of the last completed remote check. */
854
+ checkedAt?: number;
855
+ /**
856
+ * Opaque validator from the remote catalog's ETag header, stored verbatim
857
+ * (quotes included) and echoed back as If-None-Match.
858
+ */
859
+ etag?: string;
860
+ }
861
+
862
+ interface ModelsPublication {
863
+ /** Provider-selected persisted catalog. Omit to leave storage unchanged; null deletes it. */
864
+ persist?: ModelsStoreEntry | null;
865
+ /** Optional synchronous update of provider-private in-memory catalog state. */
866
+ update?: () => void;
867
+ }
868
+ interface RefreshModelsContext {
869
+ /** Effective configured credential. OAuth credentials are refreshed before network access. */
870
+ credential?: Credential;
871
+ /** Immutable provider-scoped catalog snapshot captured before this refresh phase. */
872
+ stored?: Readonly<ModelsStoreEntry>;
873
+ /**
874
+ * Generation-checked publication. Persistence policy remains provider-owned;
875
+ * the update runs synchronously only after the selected persistence mutation.
876
+ */
877
+ publish(publication: ModelsPublication): Promise<boolean>;
878
+ /** False during offline/cache-only initialization. */
879
+ allowNetwork: boolean;
880
+ /** Bypass provider freshness checks and fetch immediately when network access is allowed. */
881
+ force?: boolean;
882
+ /** Always present, including when the public refresh caller omits its optional signal. */
883
+ signal: AbortSignal;
884
+ /**
885
+ * Base URL of the registered provider, including configuration overrides that wrappers apply
886
+ * outside the provider receiving this context.
887
+ */
888
+ baseUrl?: string;
889
+ }
890
+ interface ModelsRefreshOptions {
891
+ allowNetwork?: boolean;
892
+ /** Restrict refresh to these provider IDs. Unknown and static providers are ignored. */
893
+ providers?: readonly string[];
894
+ /** Bypass provider freshness checks and fetch immediately when network access is allowed. */
895
+ force?: boolean;
896
+ signal?: AbortSignal;
897
+ }
898
+ interface ModelsRefreshResult {
899
+ aborted: boolean;
900
+ errors: ReadonlyMap<string, Error>;
901
+ }
902
+ interface ModelsRequestTransforms {
903
+ /** Transform fully assembled model/auth/request headers before provider dispatch. */
904
+ transformHeaders?: (headers: ProviderHeaders) => ProviderHeaders | Promise<ProviderHeaders>;
905
+ }
906
+ type ModelsApiStreamOptions<TApi extends Api> = ApiStreamOptions<TApi> & ModelsRequestTransforms;
907
+ type ModelsSimpleStreamOptions = SimpleStreamOptions & ModelsRequestTransforms;
908
+ type ModelsDeferredFetchOptions = DeferredFetchOptions & ModelsRequestTransforms;
909
+ type ModelsDeferredCancelOptions = DeferredCancelOptions & ModelsRequestTransforms;
910
+ type ModelsImagesOptions = ImagesOptions & ModelsRequestTransforms;
911
+ type ModelsClassifierOptions = ClassifierOptions & ModelsRequestTransforms;
912
+ /** Any model a provider with chat APIs `TApi` can list. */
913
+ type ProviderModel<TApi extends Api> = Model<TApi> | ImageModel<ImageApi> | ClassifierModel<ClassifierApi>;
914
+ /**
915
+ * A provider is the concrete runtime unit. It owns id/name/base metadata,
916
+ * auth methods, model listing, and the operations its models support
917
+ * (streaming, image generation, classification).
918
+ *
919
+ * `TApi` lets concrete provider factories declare which chat APIs their models
920
+ * use (e.g. `openaiProvider(): Provider<"openai-responses" | "openai-completions">`),
921
+ * giving typed chat model lists to direct factory users. Other model types use
922
+ * their operation-specific API unions. Inside a `Models` collection providers
923
+ * are held as `Provider<Api>`.
924
+ */
925
+ interface Provider<TApi extends Api = Api> {
926
+ readonly id: string;
927
+ readonly name: string;
928
+ readonly baseUrl?: string;
929
+ readonly headers?: ProviderHeaders;
930
+ /**
931
+ * Required: at least one of `apiKey`/`oauth`. Every provider has auth
932
+ * semantics — even providers with only ambient credentials (env vars, AWS
933
+ * profiles, ADC files) and keyless local servers provide `apiKey` auth
934
+ * whose `resolve()` reports whether the provider is configured.
935
+ * `Models.getAuth()` returns undefined when the provider is unconfigured.
936
+ */
937
+ readonly auth: ProviderAuth;
938
+ /**
939
+ * Current known chat models, sync. Static providers return their catalog;
940
+ * dynamic providers return the list as of the last `refreshModels()` (empty
941
+ * before the first). Must not throw; `Models` treats a throwing
942
+ * implementation as having no models.
943
+ */
944
+ getModels(): readonly Model<TApi>[];
945
+ /**
946
+ * Current known models of every type, sync, with the same contract as
947
+ * `getModels()`. Providers with only chat models may omit it; `Models` then
948
+ * uses `getModels()`. Model ids are unique within each type; one upstream
949
+ * model may have separate entries for different operations.
950
+ */
951
+ getAllModels?(): readonly ProviderModel<TApi>[];
952
+ /**
953
+ * Dynamic providers only: restore `context.stored` and optionally fetch a newer list using
954
+ * the effective credential. Implementations retain their previous list on failure, publish
955
+ * persistence and synchronous state changes through `context.publish()`, and honor the
956
+ * shared abort signal for blocking work.
957
+ */
958
+ refreshModels?(context: RefreshModelsContext): Promise<void>;
959
+ /**
960
+ * What the network phase of `refreshModels` needs. "credential" (the default) receives the
961
+ * effective credential, so an expired OAuth token is refreshed first. "configured" is for catalogs
962
+ * served by a source other than the provider, such as pi.dev: the phase still runs only when the
963
+ * provider is configured, but OAuth is never refreshed for it and `context.credential` is undefined.
964
+ */
965
+ readonly refreshModelsAuth?: "credential" | "configured";
966
+ /**
967
+ * Optional provider policy for credential-specific model availability.
968
+ * `getModels()` remains the complete synchronous chat catalog; `Models.getAvailable()`
969
+ * applies this filter after confirming that provider auth is configured.
970
+ */
971
+ filterModels?(models: readonly Model<TApi>[], credential: Credential | undefined): readonly Model<TApi>[];
972
+ /**
973
+ * Optional credential-specific availability policy across every model type.
974
+ * Without it, `Models.getAllAvailable()` applies `filterModels` to chat models
975
+ * and keeps every other model.
976
+ */
977
+ filterAllModels?(models: readonly ProviderModel<TApi>[], credential: Credential | undefined): readonly ProviderModel<TApi>[];
978
+ /** Stream a normalized transcript. `Models` normalizes the caller's `Context` before dispatching here. */
979
+ stream<T extends TApi>(model: Model<T>, context: TranscriptContext, options?: ApiStreamOptions<T>): AssistantMessageEventStream;
980
+ streamSimple(model: Model<TApi>, context: TranscriptContext, options?: SimpleStreamOptions): AssistantMessageEventStream;
981
+ fetchDeferred?(model: Model<TApi>, handle: DeferredHandle, options?: DeferredFetchOptions): AssistantMessageEventStream;
982
+ cancelDeferred?(model: Model<TApi>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;
983
+ /** Present when the provider supports dedicated image models. Never rejects. */
984
+ generateImages?(model: ImageModel<ImageApi>, context: ImagesContext, options?: ImagesOptions): Promise<AssistantImages>;
985
+ /** Present when the provider supports structured classifier models. Never rejects. */
986
+ classify?(model: ClassifierModel<ClassifierApi>, context: ClassifierContext, options?: ClassifierOptions): Promise<ClassifierResult>;
987
+ }
988
+ /**
989
+ * Runtime collection of providers plus auth application and request
990
+ * convenience. Providers own request behavior; `Models` resolves auth and
991
+ * delegates each request to the provider that owns the model.
992
+ *
993
+ * Read accessors come in three flavors: the unqualified ones (`getModels`,
994
+ * `getModel`, `getAvailable`) return chat models, the `*OfType` accessors
995
+ * return one model type, and `getAllModels`/`getAllAvailable` return every type.
996
+ */
997
+ interface Models {
998
+ getProviders(): readonly Provider[];
999
+ getProvider(id: string): Provider | undefined;
1000
+ /**
1001
+ * Sync read of last-known chat models from one provider or all providers.
1002
+ * Best-effort: a provider whose `getModels()` throws yields no models.
1003
+ */
1004
+ getModels(provider?: string): readonly Model<Api>[];
1005
+ /**
1006
+ * Sync runtime chat model lookup against last-known lists. Dynamic model lists
1007
+ * are typed as `Model<Api>`; narrow with the `hasApi()` type guard.
1008
+ */
1009
+ getModel(provider: string, id: string): Model<Api> | undefined;
1010
+ /** Sync read of last-known models of one type from one provider or all providers. */
1011
+ getModelsOfType<TType extends ModelType>(type: TType, provider?: string): readonly ModelTypeMap[TType][];
1012
+ /** Sync runtime lookup of a model of one type against last-known lists. */
1013
+ getModelOfType<TType extends ModelType>(type: TType, provider: string, id: string): ModelTypeMap[TType] | undefined;
1014
+ /** Sync read of last-known models of every type from one provider or all providers. */
1015
+ getAllModels(provider?: string): readonly AnyModel[];
1016
+ /**
1017
+ * Refresh selected configured dynamic providers concurrently (all when `providers` is omitted).
1018
+ * Provider errors and cancellation are returned without rejecting; static, unknown, and
1019
+ * unconfigured providers are skipped.
1020
+ */
1021
+ refresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult>;
1022
+ /** Check whether a provider has complete auth configuration without refreshing OAuth. */
1023
+ checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined>;
1024
+ /** Return chat models whose providers have complete auth configuration. */
1025
+ getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]>;
1026
+ /** Return models of one type whose providers have complete auth configuration. */
1027
+ getAvailableOfType<TType extends ModelType>(type: TType, providerId?: string, options?: AuthOperationOptions): Promise<readonly ModelTypeMap[TType][]>;
1028
+ /** Return models of every type whose providers have complete auth configuration. */
1029
+ getAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]>;
1030
+ /**
1031
+ * Resolve provider-scoped auth by provider id, or provider auth plus static
1032
+ * model headers when passed a model. Includes a source label for status UI.
1033
+ * Resolves `undefined` when the provider is unknown or unconfigured.
1034
+ * Rejects with `ModelsError`: code "oauth" when a token refresh fails (the
1035
+ * stored credential is preserved for retry; re-login fixes it), code "auth"
1036
+ * when api-key resolution or the credential store fails. Request paths
1037
+ * surface rejections as stream errors.
1038
+ */
1039
+ getAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;
1040
+ getAuth(model: AnyModel, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;
1041
+ /** Run a provider-owned login flow and persist its returned credential. */
1042
+ login(providerId: string, type: AuthType, interaction: AuthInteraction, options?: LoginOptions): Promise<Credential>;
1043
+ /** Remove the stored credential for a provider. */
1044
+ logout(providerId: string, options?: AuthOperationOptions): Promise<void>;
1045
+ stream<TApi extends Api>(model: Model<TApi>, context: Context, options?: ModelsApiStreamOptions<TApi>): AssistantMessageEventStream;
1046
+ complete<TApi extends Api>(model: Model<TApi>, context: Context, options?: ModelsApiStreamOptions<TApi>): Promise<AssistantMessage>;
1047
+ streamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;
1048
+ completeSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>;
1049
+ streamDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredFetchOptions): AssistantMessageEventStream;
1050
+ fetchDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredFetchOptions): Promise<AssistantMessage>;
1051
+ cancelDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredCancelOptions): Promise<void>;
1052
+ /**
1053
+ * Generate images through the owning provider with auth resolved like
1054
+ * `stream()`. Never rejects: unknown providers, unconfigured auth, and
1055
+ * providers without `generateImages` return an error `AssistantImages`.
1056
+ */
1057
+ generateImages(model: ImageModel<ImageApi>, context: ImagesContext, options?: ModelsImagesOptions): Promise<AssistantImages>;
1058
+ /** Classify structured state through the owning provider. Never rejects. */
1059
+ classify(model: ClassifierModel<ClassifierApi>, context: ClassifierContext, options?: ModelsClassifierOptions): Promise<ClassifierResult>;
1060
+ }
1061
+
1062
+ /**
1063
+ * The `User-Agent` sent to providers:
1064
+ * - `"detailed"`: `pi/<version> (<platform>; <runtime>/<runtime version>; <arch>)`, or `pi/<version> (browser)`
1065
+ * outside Node.js and Bun.
1066
+ * - `"short"`: `pi`.
1067
+ * - `{ custom }`: the given value.
1068
+ */
1069
+ type UserAgentMode = "short" | "detailed" | {
1070
+ custom: string;
1071
+ };
1072
+ /** Who requests are attributed to. `getAttributionHeaders()` maps the fields to each provider's headers. */
1073
+ interface ClientAttribution {
1074
+ /** App name: OpenRouter app title, NVIDIA invoke origin (first letter upper-cased), OpenCode client. */
1075
+ name: string;
1076
+ /** App URL: OpenRouter `HTTP-Referer`, the app's identity in OpenRouter's rankings, grouped by origin. */
1077
+ url: string;
1078
+ /** App categories, e.g. `["cli-agent"]`: OpenRouter `X-OpenRouter-Categories`, comma-separated. */
1079
+ categories?: string[];
1080
+ }
1081
+ /**
1082
+ * How pi-ai identifies the calling app to providers. Every field is optional; absent fields use pi-ai's defaults:
1083
+ * a detailed `User-Agent` with pi-ai's version and no attribution headers. Plain JSON, so it can be persisted.
1084
+ */
1085
+ interface ClientIdentity {
1086
+ /** Default: `"detailed"`. */
1087
+ userAgent?: UserAgentMode;
1088
+ /** Provider attribution headers. Absent or `null`: none; `null` also turns off attribution set by a merged identity. */
1089
+ attribution?: ClientAttribution | null;
1090
+ /** Version in the detailed `User-Agent`. Default: the pi-ai version. */
1091
+ version?: string;
1092
+ }
1093
+
1094
+ type KnownApi = "openai-completions" | "mistral-conversations" | "openai-responses" | "azure-openai-responses" | "openai-codex-responses" | "anthropic-messages" | "bedrock-converse-stream" | "google-generative-ai" | "google-vertex" | "pi-messages";
1095
+ type Api = KnownApi | (string & {});
1096
+ type KnownImageApi = "openrouter-images";
1097
+ type ImageApi = KnownImageApi | (string & {});
1098
+ type KnownClassifierApi = "typesafe-system-one" | "cloudflare-workers-ai-system-one" | "llama-cpp-classify" | "openai-decisions";
1099
+ type ClassifierApi = KnownClassifierApi | (string & {});
1100
+ type KnownProvider = "amazon-bedrock" | "ant-ling" | "anthropic" | "google" | "google-vertex" | "openai" | "azure" | "openai-codex" | "radius" | "typesafe" | "nvidia" | "deepseek" | "github-copilot" | "xai" | "groq" | "cerebras" | "openrouter" | "vercel-ai-gateway" | "zai" | "zai-coding-cn" | "mistral" | "minimax" | "minimax-cn" | "moonshotai" | "moonshotai-cn" | "huggingface" | "fireworks" | "together" | "baseten" | "opencode" | "opencode-go" | "kimi-coding" | "meta" | "cloudflare-workers-ai" | "cloudflare-ai-gateway" | "qwen-token-plan" | "qwen-token-plan-cn" | "qwen-token-plan-individual" | "qwen-token-plan-individual-cn" | "xiaomi" | "xiaomi-token-plan-cn" | "xiaomi-token-plan-ams" | "xiaomi-token-plan-sgp";
1101
+ type ProviderId = KnownProvider | string;
1102
+ type ToolChoice = "auto" | "none";
1103
+ type SamplingParams = Record<string, unknown>;
1104
+ type SamplingParamsByThinkingLevel = Partial<Record<ModelThinkingLevel, SamplingParams>>;
1105
+ /** Token budgets for each thinking level (token-based providers only) */
1106
+ interface ThinkingBudgets {
1107
+ minimal?: number;
1108
+ low?: number;
1109
+ medium?: number;
1110
+ high?: number;
1111
+ }
1112
+ type Transport = "sse" | "websocket" | "websocket-cached" | "auto";
1113
+ /** Provider-scoped environment overrides. Values take precedence over process.env. */
1114
+ type ProviderEnv = Record<string, string>;
1115
+ type ProviderHeaders = Record<string, string | null>;
1116
+ type FetchFunction = typeof globalThis.fetch;
1117
+ interface ProviderResponse {
1118
+ status: number;
1119
+ headers: Record<string, string>;
1120
+ }
1121
+ /** Authentication, HTTP transport, and lifecycle callbacks shared by provider requests. */
1122
+ interface ProviderRequestOptions<TModel = Model<Api>> {
1123
+ signal?: AbortSignal;
1124
+ /** Explicit parent span for telemetry produced by this logical request. */
1125
+ telemetry?: TelemetrySpan;
1126
+ apiKey?: string;
1127
+ /**
1128
+ * Optional fetch implementation for provider HTTP requests.
1129
+ * Defaults to `globalThis.fetch`. Provider adapters that cannot inject a custom implementation may reject it.
1130
+ * This does not affect WebSocket transports.
1131
+ */
1132
+ fetch?: FetchFunction;
1133
+ /**
1134
+ * Provider-scoped environment values. These take precedence over process.env for
1135
+ * provider configuration such as regional settings, endpoint placeholders, and
1136
+ * proxy variables.
1137
+ */
1138
+ env?: ProviderEnv;
1139
+ /**
1140
+ * Optional callback for inspecting or replacing provider payloads before sending.
1141
+ * Return undefined to keep the payload unchanged.
1142
+ */
1143
+ onPayload?: (payload: unknown, model: TModel) => unknown | undefined | Promise<unknown | undefined>;
1144
+ /**
1145
+ * Optional callback invoked after an HTTP response is received.
1146
+ */
1147
+ onResponse?: (response: ProviderResponse, model: TModel) => void | Promise<void>;
1148
+ /**
1149
+ * Optional custom HTTP headers to include in API requests.
1150
+ * Merged with provider defaults; caller values override default headers.
1151
+ * On AWS Bedrock these are injected via a Smithy `build`-step middleware so
1152
+ * they are covered by SigV4 signing; reserved headers (`x-amz-*`,
1153
+ * `authorization`, `host`) are silently ignored to preserve SigV4 / bearer auth.
1154
+ * A null value suppresses a provider/API default header with the same name.
1155
+ */
1156
+ headers?: ProviderHeaders;
1157
+ /**
1158
+ * How the request identifies the calling app: `User-Agent` and provider attribution headers.
1159
+ * Absent fields use pi-ai's defaults: a detailed `User-Agent` and no attribution.
1160
+ */
1161
+ identity?: ClientIdentity;
1162
+ /**
1163
+ * HTTP request timeout in milliseconds for providers/SDKs that support it.
1164
+ * For example, OpenAI and Anthropic SDK clients default to 10 minutes.
1165
+ */
1166
+ timeoutMs?: number;
1167
+ /**
1168
+ * Maximum retry attempts for providers/SDKs that support client-side retries.
1169
+ * For example, OpenAI and Anthropic SDK clients default to 2.
1170
+ */
1171
+ maxRetries?: number;
1172
+ /**
1173
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
1174
+ * If the server's requested delay exceeds this value, the request fails immediately
1175
+ * with an error containing the requested delay, allowing higher-level retry logic
1176
+ * to handle it with user visibility.
1177
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
1178
+ */
1179
+ maxRetryDelayMs?: number;
1180
+ }
1181
+ interface StreamOptions extends ProviderRequestOptions<Model<Api>> {
1182
+ /**
1183
+ * Optional callback invoked after an HTTP response is received and before
1184
+ * its body stream is consumed.
1185
+ */
1186
+ onResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;
1187
+ /**
1188
+ * Optional observer for each parsed provider stream event before Pi normalization.
1189
+ * Event data is adapter-owned and must be treated as read-only.
1190
+ * Adapter support is explicit; unsupported adapters do not invoke it.
1191
+ */
1192
+ onProviderStreamEvent?: (data: unknown, model: Model<Api>) => void | Promise<void>;
1193
+ temperature?: number;
1194
+ /**
1195
+ * Arbitrary sampling parameters merged into the request body as-is, after the named request
1196
+ * fields, so keys here override them. Lets custom OpenAI-compatible servers (llama.cpp, vLLM,
1197
+ * SGLang, ...) receive parameters pi does not model, e.g. `top_p`, `top_k`, `min_p`,
1198
+ * `repetition_penalty`. Merged over `Model.samplingParams` per key. Only applied by
1199
+ * OpenAI-compatible adapters (completions, responses, Azure responses); other APIs ignore it.
1200
+ */
1201
+ samplingParams?: SamplingParams;
1202
+ maxTokens?: number;
1203
+ /**
1204
+ * Preferred transport for providers that support multiple transports.
1205
+ * Providers that do not support this option ignore it.
1206
+ */
1207
+ transport?: Transport;
1208
+ /**
1209
+ * Prompt cache retention preference. Providers map this to their supported values.
1210
+ * Default: "short".
1211
+ */
1212
+ cacheRetention?: CacheRetention;
1213
+ /**
1214
+ * Optional session identifier for providers that support session-based caching.
1215
+ * Providers can use this to enable prompt caching, request routing, or other
1216
+ * session-aware features. Ignored by providers that don't support it.
1217
+ */
1218
+ sessionId?: string;
1219
+ /**
1220
+ * Do not use or record server-side continuation state for this request (for example
1221
+ * Anthropic message threads). Set this for replays such as cache warming, which must not
1222
+ * replace the state of the real conversation. Providers that do not keep continuation
1223
+ * state ignore it.
1224
+ */
1225
+ disableContinuation?: boolean;
1226
+ /**
1227
+ * WebSocket connect timeout in milliseconds for providers that support
1228
+ * WebSocket transports. This covers the connection/open handshake only;
1229
+ * stream idleness after connection uses timeoutMs.
1230
+ */
1231
+ websocketConnectTimeoutMs?: number;
1232
+ /**
1233
+ * Optional metadata to include in API requests.
1234
+ * Providers extract the fields they understand and ignore the rest.
1235
+ * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.
1236
+ */
1237
+ metadata?: Record<string, unknown>;
1238
+ }
1239
+ interface DeferredFetchOptions extends ProviderRequestOptions<Model<Api>> {
1240
+ /**
1241
+ * Maximum provider long-poll duration in milliseconds.
1242
+ * Defaults to 0, which performs one status check.
1243
+ */
1244
+ wait?: number;
1245
+ }
1246
+ /** Request options for best-effort deferred-response cancellation. */
1247
+ type DeferredCancelOptions = ProviderRequestOptions<Model<Api>>;
1248
+ /**
1249
+ * Maps known APIs to their full provider-specific stream option types.
1250
+ * Type-only imports from API implementation modules are erased at emit, so
1251
+ * this is tree-shake safe.
1252
+ */
1253
+ interface ApiOptionsMap {
1254
+ "anthropic-messages": AnthropicOptions;
1255
+ "openai-completions": OpenAICompletionsOptions;
1256
+ "openai-responses": OpenAIResponsesOptions;
1257
+ "openai-codex-responses": OpenAICodexResponsesOptions;
1258
+ "azure-openai-responses": AzureOpenAIResponsesOptions;
1259
+ "google-generative-ai": GoogleOptions;
1260
+ "google-vertex": GoogleVertexOptions;
1261
+ "mistral-conversations": MistralOptions;
1262
+ "bedrock-converse-stream": BedrockOptions;
1263
+ "pi-messages": PiMessagesOptions;
1264
+ }
1265
+ /**
1266
+ * Full stream options for an API. Known APIs resolve to their concrete option
1267
+ * type; custom API strings fall back to the generic shape.
1268
+ */
1269
+ type ApiStreamOptions<TApi extends Api> = TApi extends keyof ApiOptionsMap ? ApiOptionsMap[TApi] : StreamOptions & Record<string, unknown>;
1270
+ interface ClassifierOptions extends ProviderRequestOptions<ClassifierModel<ClassifierApi>> {
1271
+ /**
1272
+ * Divides the answer logits by this value before they are normalized into probabilities.
1273
+ * Values above 1 soften the distribution; values below 1 sharpen it. Must be positive.
1274
+ * APIs that cannot apply it ignore it.
1275
+ */
1276
+ temperature?: number;
1277
+ }
1278
+ interface ImagesOptions extends ProviderRequestOptions<ImageModel<ImageApi>> {
1279
+ /**
1280
+ * Optional metadata to include in API requests.
1281
+ * Providers extract the fields they understand and ignore the rest.
1282
+ */
1283
+ metadata?: Record<string, unknown>;
1284
+ }
1285
+ interface SimpleStreamOptions extends StreamOptions {
1286
+ /** Provider-neutral tool selection for simple requests. When omitted, adapters use provider-specific behavior. */
1287
+ toolChoice?: ToolChoice;
1288
+ reasoning?: ThinkingLevel;
1289
+ /** Ask a capable provider to return a durable handle and continue the request asynchronously. */
1290
+ deferred?: boolean | {
1291
+ window?: "15m" | "1h" | "24h";
1292
+ };
1293
+ /** Custom token budgets for thinking levels (token-based providers only) */
1294
+ thinkingBudgets?: ThinkingBudgets;
1295
+ }
1296
+ interface TextContent {
1297
+ type: "text";
1298
+ text: string;
1299
+ textSignature?: string;
1300
+ }
1301
+ interface ThinkingContent {
1302
+ type: "thinking";
1303
+ thinking: string;
1304
+ thinkingSignature?: string;
1305
+ /** When true, the thinking content was redacted by safety filters. The opaque
1306
+ * encrypted payload is stored in `thinkingSignature` so it can be passed back
1307
+ * to the API for multi-turn continuity. */
1308
+ redacted?: boolean;
1309
+ }
1310
+ interface ImageContent {
1311
+ type: "image";
1312
+ data: string;
1313
+ mimeType: string;
1314
+ }
1315
+ interface ToolCall {
1316
+ type: "toolCall";
1317
+ id: string;
1318
+ name: string;
1319
+ arguments: JsonObject$1;
1320
+ thoughtSignature?: string;
1321
+ /** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */
1322
+ namespace?: string;
1323
+ /**
1324
+ * Set when the model's complete arguments text was not a valid JSON object. `arguments` is then `{}`.
1325
+ * Describes the problem and includes the text the model sent; tool argument validation fails with it.
1326
+ */
1327
+ argumentsError?: string;
1328
+ }
1329
+ interface Usage {
1330
+ input: number;
1331
+ output: number;
1332
+ cacheRead: number;
1333
+ cacheWrite: number;
1334
+ /** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */
1335
+ cacheWrite1h?: number;
1336
+ /**
1337
+ * Reasoning/thinking tokens, when the provider reports them. This is a subset of
1338
+ * `output`: `output` already includes these tokens. Set to a number (possibly 0) by
1339
+ * providers that expose a reasoning breakdown; left undefined by providers that don't.
1340
+ */
1341
+ reasoning?: number;
1342
+ totalTokens: number;
1343
+ cost: {
1344
+ /** Catalog-derived input cost. */
1345
+ input: number;
1346
+ /** Catalog-derived output cost. */
1347
+ output: number;
1348
+ /** Catalog-derived cache-read cost. */
1349
+ cacheRead: number;
1350
+ /** Catalog-derived cache-write cost. */
1351
+ cacheWrite: number;
1352
+ /** Best available total: provider-reported billed cost when supported, otherwise the catalog estimate. */
1353
+ total: number;
1354
+ /** True when `total` is the billed cost reported by the provider. False when it is a catalog estimate; absent also means false. */
1355
+ totalFromProvider?: boolean;
1356
+ };
1357
+ }
1358
+ type StopReason = "pending" | "stop" | "length" | "toolUse" | "error" | "aborted" | "deferred";
1359
+ type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject$1;
1360
+ type JsonObject$1 = {
1361
+ [key: string]: JsonValue;
1362
+ };
1363
+ type IsAny$1<T> = 0 extends 1 & T ? true : false;
1364
+ type IsExactlyJsonValue<T> = [T] extends [JsonValue] ? ([JsonValue] extends [T] ? true : false) : false;
1365
+ type IsJsonProperty<T> = IsAny$1<T> extends true ? false : unknown extends T ? false : [Exclude<T, undefined>] extends [never] ? true : IsJsonCompatible<Exclude<T, undefined>>;
1366
+ type InvalidJsonKeys<T extends object> = {
1367
+ [TKey in keyof T]-?: TKey extends string | number ? (IsJsonProperty<T[TKey]> extends true ? never : TKey) : TKey;
1368
+ }[keyof T];
1369
+ type IsJsonCompatible<T> = IsAny$1<T> extends true ? false : unknown extends T ? false : IsExactlyJsonValue<T> extends true ? true : T extends null | boolean | number | string ? true : T extends undefined ? false : T extends readonly (infer TItem)[] ? IsJsonCompatible<TItem> : T extends (...args: never[]) => unknown ? false : T extends object ? [InvalidJsonKeys<T>] extends [never] ? true : false : false;
1370
+ /** The JSON representation of a typed in-memory value. Optional object properties remain optional. */
1371
+ type JsonRepresentation<T> = IsAny$1<T> extends true ? JsonValue : unknown extends T ? JsonValue : [T] extends [JsonValue] ? T : T extends readonly unknown[] ? {
1372
+ [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>>;
1373
+ } : T extends object ? {
1374
+ [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>>;
1375
+ } : never;
1376
+ interface DeferredHandle {
1377
+ provider: string;
1378
+ modelId: string;
1379
+ api: string;
1380
+ /** Provider token, such as a response id or batch id plus row id. */
1381
+ id: string;
1382
+ expiresAt?: number;
1383
+ pollAfterMs?: number;
1384
+ /** Provider conversion data required to reconstruct the final assistant message. */
1385
+ data?: JsonValue;
1386
+ }
1387
+ /**
1388
+ * System instructions and tool declarations at one point in the transcript.
1389
+ *
1390
+ * The leading system message is the system prompt. Later system messages change it:
1391
+ * `content` adds instructions from that point on, `sections` replace or remove named
1392
+ * prompt sections, and `toolsAdded`/`toolsRemoved` change the tool set. Replaying
1393
+ * every system message in order yields the current prompt and tools. Providers that
1394
+ * accept system messages mid-conversation send each one in place; other providers
1395
+ * rebuild the leading system message from the replayed state.
1396
+ */
1397
+ interface SystemMessage {
1398
+ role: "system";
1399
+ /** Instruction text. On the leading message this is the base prompt; later, additional instructions. */
1400
+ content: string | TextContent[];
1401
+ /**
1402
+ * Named, ordered prompt sections rendered verbatim after `content`. The leading message
1403
+ * declares them; later messages replace sections by name, and `null` removes one. Keep
1404
+ * each section self-delimiting (a tag, a heading) so the model can relate an update to
1405
+ * the original. Avoid integer-like names; JSON objects reorder those.
1406
+ */
1407
+ sections?: Record<string, string | null>;
1408
+ /** Complete definitions of tools that become available at this point. */
1409
+ toolsAdded?: Tool[];
1410
+ /** Tools that stop being available at this point. */
1411
+ toolsRemoved?: ToolReference[];
1412
+ timestamp: number;
1413
+ }
1414
+ interface UserMessage {
1415
+ role: "user";
1416
+ content: string | (TextContent | ImageContent)[];
1417
+ timestamp: number;
1418
+ }
1419
+ interface AssistantMessage {
1420
+ role: "assistant";
1421
+ content: (TextContent | ThinkingContent | ToolCall)[];
1422
+ api: Api;
1423
+ provider: ProviderId;
1424
+ model: string;
1425
+ responseModel?: string;
1426
+ responseId?: string;
1427
+ /** Exact provider-native effort level used for this response. Absent for legacy or unmanaged responses. */
1428
+ providerThinkingLevel?: string;
1429
+ /** Pi thinking level the agent loop requested for this response. Absent outside the agent loop and for legacy responses. */
1430
+ thinkingLevel?: ModelThinkingLevel;
1431
+ diagnostics?: AssistantMessageDiagnostic[];
1432
+ usage: Usage;
1433
+ stopReason: StopReason;
1434
+ deferred?: DeferredHandle;
1435
+ errorMessage?: string;
1436
+ rawStopReason?: string;
1437
+ /**
1438
+ * Provider indication of whether the model explicitly ended its turn.
1439
+ * Preserved for debugging and does not currently affect agent control flow.
1440
+ */
1441
+ endTurn?: boolean;
1442
+ /** Unix timestamp in milliseconds when the request started. */
1443
+ timestamp: number;
1444
+ /**
1445
+ * Milliseconds from `timestamp` until the response ended, measured with a monotonic clock. Set by
1446
+ * `AssistantMessageEventStream` on the final message of a response it saw start; absent for legacy messages and
1447
+ * for deferred results fetched later.
1448
+ */
1449
+ durationMs?: number;
1450
+ }
1451
+ /** A tool call that another tool made while it ran, for example from a codemode script. */
1452
+ interface NestedToolCallRecord {
1453
+ id: string;
1454
+ name: string;
1455
+ /** Omitted when over the size limits; `argumentsBytes` then gives their size. */
1456
+ arguments?: JsonObject$1;
1457
+ /** UTF-8 size of the arguments as JSON, set when `arguments` is omitted. */
1458
+ argumentsBytes?: number;
1459
+ /** `unfinished`: the call was still running when the calling tool finished. */
1460
+ status: "ok" | "error" | "unfinished";
1461
+ durationMs?: number;
1462
+ /** Error text, truncated. */
1463
+ error?: string;
1464
+ }
1465
+ /** Bounded record of the nested calls a tool made. Results are not recorded. */
1466
+ interface NestedToolCalls {
1467
+ calls: NestedToolCallRecord[];
1468
+ /** False when calls were dropped, arguments omitted, or calls had not finished. */
1469
+ complete: boolean;
1470
+ }
1471
+ type ToolResultMessage<TDetails = JsonValue> = IsJsonCompatible<TDetails> extends true ? {
1472
+ role: "toolResult";
1473
+ toolCallId: string;
1474
+ toolName: string;
1475
+ content: (TextContent | ImageContent)[];
1476
+ details?: JsonRepresentation<TDetails>;
1477
+ /** Usage from the tool execution itself, if available. Not part of main LLM context accounting. */
1478
+ usage?: Usage;
1479
+ /** Calls this tool made to other tools. Kept for the session record; not sent to the model. */
1480
+ nestedCalls?: NestedToolCalls;
1481
+ isError: boolean;
1482
+ /** Unix timestamp in milliseconds when the result was created. */
1483
+ timestamp: number;
1484
+ /** Milliseconds the tool's execution took, measured with a monotonic clock. Absent for legacy results. */
1485
+ durationMs?: number;
1486
+ } : never;
1487
+ type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;
1488
+ type ImagesInputContent = TextContent | ImageContent;
1489
+ type ImagesOutputContent = TextContent | ImageContent;
1490
+ interface ImagesContext {
1491
+ input: ImagesInputContent[];
1492
+ }
1493
+ type ImagesStopReason = "stop" | "error" | "aborted";
1494
+ interface AssistantImages {
1495
+ api: ImageApi;
1496
+ provider: ProviderId;
1497
+ model: string;
1498
+ output: ImagesOutputContent[];
1499
+ responseId?: string;
1500
+ usage?: Usage;
1501
+ stopReason: ImagesStopReason;
1502
+ errorMessage?: string;
1503
+ timestamp: number;
1504
+ }
1505
+ interface ClassifierChoiceQuestion {
1506
+ type: "choice";
1507
+ instructions: string;
1508
+ criteria: Record<string, string>;
1509
+ }
1510
+ interface ClassifierScoreQuestion {
1511
+ type: "score";
1512
+ instructions: string;
1513
+ criteria: string[];
1514
+ }
1515
+ interface ClassifierBoolQuestion {
1516
+ type: "bool";
1517
+ instructions: string;
1518
+ criteria: {
1519
+ true: string;
1520
+ false: string;
1521
+ };
1522
+ }
1523
+ type ClassifierQuestion = ClassifierChoiceQuestion | ClassifierScoreQuestion | ClassifierBoolQuestion;
1524
+ interface ClassifierContext {
1525
+ state: JsonObject$1;
1526
+ /**
1527
+ * Images judged together with `state`. Only models whose `input` includes `"image"` accept them;
1528
+ * other models return an error result.
1529
+ */
1530
+ images?: ImageContent[];
1531
+ questions: Record<string, ClassifierQuestion>;
1532
+ }
1533
+ interface ClassifierChoiceAnswer {
1534
+ type: "choice";
1535
+ choice: string;
1536
+ probabilities: Record<string, number>;
1537
+ confidence: number;
1538
+ }
1539
+ interface ClassifierScoreAnswer {
1540
+ type: "score";
1541
+ score: number;
1542
+ confidence: number;
1543
+ }
1544
+ interface ClassifierBoolAnswer {
1545
+ type: "bool";
1546
+ probability: number;
1547
+ }
1548
+ type ClassifierAnswer = ClassifierChoiceAnswer | ClassifierScoreAnswer | ClassifierBoolAnswer;
1549
+ type ClassifierStopReason = "stop" | "error" | "aborted";
1550
+ interface ClassifierResult {
1551
+ api: ClassifierApi;
1552
+ provider: ProviderId;
1553
+ model: string;
1554
+ answers: Record<string, ClassifierAnswer>;
1555
+ /** Token usage and its cost at the model's catalog price, when the service reports token counts. */
1556
+ usage?: Usage;
1557
+ stopReason: ClassifierStopReason;
1558
+ errorMessage?: string;
1559
+ timestamp: number;
1560
+ }
1561
+ /** OpenAI grammar variants for constrained sampling. */
1562
+ type GrammarFormat = "openai_lark" | "openai_regex";
1563
+ type GrammarVariants = Partial<Record<GrammarFormat, string>>;
1564
+ /**
1565
+ * Optional provider-side constrained sampling configs for a tool.
1566
+ *
1567
+ * The `json_schema` value roughly maps to the concept of `strict` in APIs which is
1568
+ * implemented as json-schema constrained sampling by APIs. Grammar variants let
1569
+ * callers provide provider-specific encodings of the same intended language.
1570
+ */
1571
+ type ConstrainedSamplingConfig = {
1572
+ type: "json_schema";
1573
+ strict: "prefer" | "require";
1574
+ } | {
1575
+ type: "grammar";
1576
+ variants: GrammarVariants;
1577
+ };
1578
+ /**
1579
+ * A tool the model may call. `parameters` is the JSON Schema of its arguments: pi-schema's builders (which also type
1580
+ * the arguments, see `Static` in `@earendil-works/pi-schema`), TypeBox schemas, or any JSON Schema object.
1581
+ */
1582
+ interface Tool<TParameters extends object = object> {
1583
+ name: string;
1584
+ description: string;
1585
+ parameters: TParameters;
1586
+ constrainedSampling?: false | ConstrainedSamplingConfig;
1587
+ }
1588
+ interface ToolReference {
1589
+ name: string;
1590
+ }
1591
+ /**
1592
+ * Request input accepted by the public stream entry points (`Models.stream()`,
1593
+ * `streamSimple()`, ...). `systemPrompt` and `tools` are shorthand for a leading
1594
+ * system message; `normalizeContext()` folds them into one before the request
1595
+ * reaches a provider.
1596
+ */
1597
+ interface Context {
1598
+ systemPrompt?: string;
1599
+ messages: Message[];
1600
+ tools?: Tool[];
1601
+ }
1602
+ declare const transcriptContextBrand: unique symbol;
1603
+ /**
1604
+ * Normalized request context passed to providers and API implementations. The
1605
+ * prompt and tool declarations are carried by the transcript's system messages.
1606
+ * Only `normalizeContext()` produces this type, so a raw `Context` cannot reach
1607
+ * provider code by accident.
1608
+ */
1609
+ type TranscriptContext = {
1610
+ messages: Message[];
1611
+ readonly [transcriptContextBrand]: true;
1612
+ };
1613
+ /**
1614
+ * Event protocol for AssistantMessageEventStream.
1615
+ *
1616
+ * Successful streams emit `start` before partial updates and terminate with
1617
+ * `done`. A stream may terminate directly with `error` when request setup fails
1618
+ * before generation starts; after `start`, failures also terminate with `error`.
1619
+ * Direct `streamSimple()` calls throw synchronously when request auth is missing.
1620
+ * Updates and `done` must never appear before `start`.
1621
+ *
1622
+ * `partial` is the shared live response-so-far helper, not an event-time
1623
+ * snapshot. Text and thinking blocks are empty when their `*_start` event is
1624
+ * emitted and grow only through their corresponding `*_delta` events until the
1625
+ * authoritative `*_end`. Redacted thinking may be complete at start and emit no
1626
+ * deltas. Tool-call arguments at `toolcall_start` are provider-specific;
1627
+ * `toolcall_delta` carries subsequent JSON updates.
1628
+ */
1629
+ type AssistantMessageEvent = {
1630
+ type: "start";
1631
+ partial: AssistantMessage;
1632
+ } | {
1633
+ type: "text_start";
1634
+ contentIndex: number;
1635
+ partial: AssistantMessage;
1636
+ } | {
1637
+ type: "text_delta";
1638
+ contentIndex: number;
1639
+ delta: string;
1640
+ partial: AssistantMessage;
1641
+ } | {
1642
+ type: "text_end";
1643
+ contentIndex: number;
1644
+ content: string;
1645
+ partial: AssistantMessage;
1646
+ } | {
1647
+ type: "thinking_start";
1648
+ contentIndex: number;
1649
+ partial: AssistantMessage;
1650
+ } | {
1651
+ type: "thinking_delta";
1652
+ contentIndex: number;
1653
+ delta: string;
1654
+ partial: AssistantMessage;
1655
+ } | {
1656
+ type: "thinking_end";
1657
+ contentIndex: number;
1658
+ content: string;
1659
+ partial: AssistantMessage;
1660
+ } | {
1661
+ type: "toolcall_start";
1662
+ contentIndex: number;
1663
+ partial: AssistantMessage;
1664
+ } | {
1665
+ type: "toolcall_delta";
1666
+ contentIndex: number;
1667
+ delta: string;
1668
+ partial: AssistantMessage;
1669
+ } | {
1670
+ type: "toolcall_end";
1671
+ contentIndex: number;
1672
+ toolCall: ToolCall;
1673
+ partial: AssistantMessage;
1674
+ } | {
1675
+ type: "done";
1676
+ reason: Extract<StopReason, "stop" | "length" | "toolUse" | "deferred">;
1677
+ message: AssistantMessage;
1678
+ } | {
1679
+ type: "error";
1680
+ reason: Extract<StopReason, "aborted" | "error">;
1681
+ error: AssistantMessage;
1682
+ };
1683
+ /** Fields shared by every catalog entry, regardless of what you can do with it. */
1684
+ interface BaseModel<TApi extends string> {
1685
+ id: string;
1686
+ name: string;
1687
+ api: TApi;
1688
+ provider: ProviderId;
1689
+ baseUrl: string;
1690
+ input: ModelInputModality[];
1691
+ /** Provider input limits and cache-safe preprocessing metadata. */
1692
+ inputLimits?: ModelInputLimits;
1693
+ cost: ModelCost;
1694
+ headers?: Record<string, string>;
1695
+ }
1696
+ /** Chat model: usable with `stream()` and friends. */
1697
+ interface Model<TApi extends Api> extends BaseModel<TApi> {
1698
+ /**
1699
+ * Optional: chat is the default model type, so models without `type` are chat
1700
+ * models. Narrow mixed model lists with `isModelType()` instead of comparing
1701
+ * `type` directly.
1702
+ */
1703
+ type?: "chat";
1704
+ reasoning: boolean;
1705
+ /**
1706
+ * Maps pi thinking levels to provider/model-specific values.
1707
+ * Missing keys use provider defaults. null marks a level as unsupported.
1708
+ */
1709
+ thinkingLevelMap?: ThinkingLevelMap;
1710
+ /** Prompt cache lifetimes per retention tier. Unset when the provider's cache behavior is unknown. */
1711
+ promptCache?: ModelPromptCache;
1712
+ contextWindow: number;
1713
+ maxTokens: number;
1714
+ /** Default sampling parameters for this model. See {@link StreamOptions.samplingParams}; per-request keys override these. */
1715
+ samplingParams?: SamplingParams;
1716
+ /** Sampling parameter overrides selected by the effective pi thinking level. */
1717
+ samplingParamsByThinkingLevel?: SamplingParamsByThinkingLevel;
1718
+ /** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */
1719
+ compat?: TApi extends "openai-completions" ? OpenAICompletionsCompat : TApi extends "openai-responses" | "azure-openai-responses" | "openai-codex-responses" ? OpenAIResponsesCompat : TApi extends "anthropic-messages" ? AnthropicMessagesCompat : TApi extends "bedrock-converse-stream" ? BedrockCompat : TApi extends "mistral-conversations" ? MistralConversationsCompat : never;
1720
+ }
1721
+ /** Image-generation model: usable with `generateImages()` only. */
1722
+ interface ImageModel<TApi extends ImageApi> extends BaseModel<TApi> {
1723
+ type: "image";
1724
+ /** Output modalities. Always includes `"image"`; `"text"` means the model can also return text blocks. */
1725
+ output: ("text" | "image")[];
1726
+ }
1727
+ /** Structured classifier model: usable with `classify()` only. */
1728
+ interface ClassifierModel<TApi extends ClassifierApi> extends BaseModel<TApi> {
1729
+ type: "classifier";
1730
+ contextWindow: number;
1731
+ /** Compatibility overrides for System One APIs. If not set, auto-detected from provider, baseUrl, and id. */
1732
+ compat?: TApi extends "typesafe-system-one" | "cloudflare-workers-ai-system-one" ? SystemOneCompat : never;
1733
+ }
1734
+ /** Model shape for each model type. */
1735
+ interface ModelTypeMap {
1736
+ chat: Model<Api>;
1737
+ image: ImageModel<ImageApi>;
1738
+ classifier: ClassifierModel<ClassifierApi>;
1739
+ }
1740
+ /** What a catalog entry is for. Decides which `Models` operation accepts it. */
1741
+ type ModelType = keyof ModelTypeMap;
1742
+ /** Anything a provider can list. Narrow with `isModelType()`. */
1743
+ type AnyModel = ModelTypeMap[ModelType];
1744
+
1745
+ type AnthropicEffort = "low" | "medium" | "high" | "xhigh" | "max";
1746
+ type AnthropicThinkingDisplay = "summarized" | "omitted";
1747
+ interface AnthropicOptions extends StreamOptions {
1748
+ /**
1749
+ * Enable extended thinking.
1750
+ * For adaptive thinking models: the model decides when/how much to think.
1751
+ * For older models: uses budget-based thinking with thinkingBudgetTokens.
1752
+ * Default: undefined (thinking is omitted unless `streamSimple()` maps
1753
+ * a simple reasoning level to this option, or callers set it explicitly).
1754
+ */
1755
+ thinkingEnabled?: boolean;
1756
+ /**
1757
+ * Token budget for extended thinking (older models only).
1758
+ * Ignored for adaptive thinking models.
1759
+ * Default: 1024 when `thinkingEnabled` is true and no budget is provided.
1760
+ */
1761
+ thinkingBudgetTokens?: number;
1762
+ /**
1763
+ * Effort level for adaptive thinking models.
1764
+ * Controls how much thinking Claude allocates:
1765
+ * - "max": Always thinks with no constraints (Opus 4.6 only)
1766
+ * - "xhigh": Highest reasoning level (Opus 4.7+, Fable 5)
1767
+ * - "high": Always thinks, deep reasoning
1768
+ * - "medium": Moderate thinking, may skip for simple queries
1769
+ * - "low": Minimal thinking, skips for simple tasks
1770
+ * Ignored for older models.
1771
+ * Default: omitted unless `streamSimple()` maps a simple reasoning
1772
+ * level to this option.
1773
+ */
1774
+ effort?: AnthropicEffort;
1775
+ /**
1776
+ * Controls how thinking content is returned in API responses.
1777
+ * - "summarized": Thinking blocks contain summarized thinking text.
1778
+ * - "omitted": Thinking blocks return an empty thinking field; the encrypted
1779
+ * signature still travels back for multi-turn continuity. Use for faster
1780
+ * time-to-first-text-token when your UI does not surface thinking.
1781
+ *
1782
+ * Note: Anthropic's API default for Claude Opus 4.7 and Claude Mythos Preview
1783
+ * is "omitted". We default to "summarized" here to keep behavior consistent
1784
+ * with older Claude 4 models. Set this explicitly to "omitted" to opt in.
1785
+ * Default: "summarized" when thinking is enabled.
1786
+ */
1787
+ thinkingDisplay?: AnthropicThinkingDisplay;
1788
+ /**
1789
+ * Whether to request the interleaved thinking beta header for non-adaptive
1790
+ * thinking models. Adaptive thinking models have interleaved thinking built in,
1791
+ * so the header is skipped for them regardless of this setting.
1792
+ * Default: true.
1793
+ */
1794
+ interleavedThinking?: boolean;
1795
+ /**
1796
+ * Anthropic tool choice behavior. String values map to Anthropic's built-in
1797
+ * choices; `{ type: "tool", name }` forces a specific tool.
1798
+ * Default: omitted (Anthropic default behavior, currently equivalent to auto).
1799
+ */
1800
+ toolChoice?: "auto" | "any" | "none" | {
1801
+ type: "tool";
1802
+ name: string;
1803
+ };
1804
+ /**
1805
+ * Pre-built Anthropic client instance. When provided, skips internal client
1806
+ * construction entirely. Use this to inject alternative SDK clients such as
1807
+ * `AnthropicVertex` that shares the same messaging API.
1808
+ */
1809
+ client?: Anthropic;
1810
+ }
1811
+
1812
+ /** Result of a fallible operation. Expected failures are returned instead of thrown. */
1813
+ type Result<TValue, TError> = {
1814
+ ok: true;
1815
+ value: TValue;
1816
+ } | {
1817
+ ok: false;
1818
+ error: TError;
1819
+ };
1820
+ type FileKind = "file" | "directory" | "symlink";
1821
+ type FileErrorCode = "aborted" | "not_found" | "permission_denied" | "not_directory" | "is_directory" | "invalid" | "not_supported" | "unknown";
1822
+ declare class FileError extends Error {
1823
+ code: FileErrorCode;
1824
+ path?: string;
1825
+ constructor(code: FileErrorCode, message: string, path?: string, cause?: Error);
1826
+ }
1827
+ type ExecutionErrorCode = "aborted" | "timeout" | "shell_unavailable" | "spawn_error" | "callback_error" | "unknown";
1828
+ declare class ExecutionError extends Error {
1829
+ code: ExecutionErrorCode;
1830
+ /** Spill file of a command that timed out or was aborted after its output crossed the spill thresholds. */
1831
+ spillPath?: string;
1832
+ constructor(code: ExecutionErrorCode, message: string, cause?: Error);
1833
+ }
1834
+ interface FileInfo {
1835
+ name: string;
1836
+ path: string;
1837
+ kind: FileKind;
1838
+ size: number;
1839
+ mtimeMs: number;
1840
+ }
1841
+ interface TextLine {
1842
+ text: string;
1843
+ terminated: boolean;
1844
+ }
1845
+ interface TextLineReader {
1846
+ readLine(context: Context$1): Promise<Result<TextLine | undefined, FileError>>;
1847
+ close(context: Context$1): Promise<void>;
1848
+ }
1849
+ /** Positional reads from one opened regular file; all calls see the same file even if its path is renamed. */
1850
+ interface BinaryReader {
1851
+ /** Metadata of the opened file, not of whatever its path names now. */
1852
+ info(context: Context$1): Promise<Result<FileInfo, FileError>>;
1853
+ /** Up to `length` bytes at `offset`; fewer only at end of file. */
1854
+ read(offset: number, length: number, context: Context$1): Promise<Result<Uint8Array, FileError>>;
1855
+ /**
1856
+ * One pass over the file that locates lines `[startLine, endLine)` (`endLine` absent: to the end), 0-based, where line
1857
+ * `k` starts after the `k`-th newline byte. Decoded sizes are those of the text `new TextDecoder().decode(file)` would
1858
+ * produce for that range, so a byte-order mark at the start of the file is not counted.
1859
+ */
1860
+ scanLines(options: {
1861
+ startLine: number;
1862
+ endLine?: number;
1863
+ }, context: Context$1): Promise<Result<LineScan, FileError>>;
1864
+ close(context: Context$1): Promise<void>;
1865
+ }
1866
+ /** A file or directory to watch. It may be missing; creating it is a change. */
1867
+ interface WatchTarget {
1868
+ path: string;
1869
+ /** Watch everything below a directory, not only its entries. Symbolic links below it are not followed. */
1870
+ recursive?: boolean;
1871
+ /** Entries below `path` that are neither watched nor reported: names starting with `.`, or these names. */
1872
+ exclude?: {
1873
+ hidden?: boolean;
1874
+ names?: readonly string[];
1875
+ };
1876
+ }
1877
+ /**
1878
+ * What changed, tagged by `kind`:
1879
+ * - `paths`: something at or below each path may have changed (a directory path covers its whole subtree). Calls may be
1880
+ * spurious; a change is never missed while the watcher is healthy.
1881
+ * - `overflow`: coverage was uncertain for a while (lost events, reconnect); rescan everything that is watched.
1882
+ * - `failed`: the watcher stopped with `error`, for example because the watched tree grew past the environment's limit;
1883
+ * no calls follow.
1884
+ */
1885
+ type FileChange = {
1886
+ readonly kind: "paths";
1887
+ readonly paths: string[];
1888
+ } | {
1889
+ readonly kind: "overflow";
1890
+ } | {
1891
+ readonly kind: "failed";
1892
+ readonly error: FileError;
1893
+ };
1894
+ interface FileWatcher {
1895
+ /**
1896
+ * `native`: changes are reported within about two seconds. `polling`: the environment compares snapshots, because
1897
+ * the file system does not report changes reliably (network and FUSE file systems); a change undone between two
1898
+ * snapshots can be missed.
1899
+ */
1900
+ readonly mode: "native" | "polling";
1901
+ /** Stop watching; no `onChange` call starts after this resolves. Idempotent. */
1902
+ stop(context: Context$1): Promise<void>;
1903
+ }
1904
+ /** Where lines of a file are, as `BinaryReader.scanLines` found them. */
1905
+ interface LineScan {
1906
+ /** Newline bytes in the whole file; it has `newlines + 1` lines. */
1907
+ newlines: number;
1908
+ /**
1909
+ * Byte range of the selected lines: from the start of the first to the end of the last, without the newline that
1910
+ * ends it. A selection past the last line is empty at the end of the file.
1911
+ */
1912
+ start: number;
1913
+ end: number;
1914
+ /** Where the first selected line ends: its newline, or the end of the file. */
1915
+ firstLineEnd: number;
1916
+ /** Where the last selected line starts. */
1917
+ lastLineStart: number;
1918
+ /** UTF-8 byte length of the decoded selection and of its first line. */
1919
+ selectedBytes: number;
1920
+ firstLineBytes: number;
1921
+ }
1922
+ /** Pages of one directory's entries. */
1923
+ interface DirReader {
1924
+ /**
1925
+ * Up to `maxEntries` entries in the order the file system returns them, continuing where the previous call stopped.
1926
+ * `done` marks the end; it may come with the last entries or with an empty page. An entry that disappears before its
1927
+ * metadata is read is skipped, as are entries of unsupported kinds. After a failed or aborted call, close the reader.
1928
+ */
1929
+ next(maxEntries: number, context: Context$1): Promise<Result<{
1930
+ entries: FileInfo[];
1931
+ done: boolean;
1932
+ }, FileError>>;
1933
+ close(context: Context$1): Promise<void>;
1934
+ }
1935
+ /** What `FileSystem.listFiles` lists. */
1936
+ interface ListFilesOptions {
1937
+ /**
1938
+ * Include names starting with `.` (on Windows also files with the hidden attribute); default true. Entries named
1939
+ * `.git` are never listed.
1940
+ */
1941
+ hidden?: boolean;
1942
+ /**
1943
+ * Inside a git work tree, skip what git ignores: the `.gitignore` files of the directory, its subdirectories and its
1944
+ * parents, `.git/info/exclude`, and the global excludes file; default true. Unlike `git ls-files`, a tracked file that
1945
+ * matches an ignore rule is skipped too. Outside work trees, `.gitignore` files have no effect.
1946
+ */
1947
+ gitignore?: boolean;
1948
+ /** Names of entries to skip with everything below them, such as `node_modules`. */
1949
+ exclude?: readonly string[];
1950
+ /** Most entries to list; default 50 000. */
1951
+ maxEntries?: number;
1952
+ /** Most bytes of the listing: each entry's UTF-8 path plus two; default 4 MiB, at most 15.9 MiB. */
1953
+ maxBytes?: number;
1954
+ /** Time after which the listing stops; default 10 000 ms. */
1955
+ timeoutMs?: number;
1956
+ }
1957
+ /** One entry of a `FileListing`. */
1958
+ interface FileListEntry {
1959
+ /** Relative to the listed directory, with `/` separators on every system. */
1960
+ path: string;
1961
+ /** A symbolic link is listed as such and not followed. */
1962
+ kind: FileKind;
1963
+ }
1964
+ interface FileListing {
1965
+ /** Depth first, parents before their entries, siblings in byte order of their names. */
1966
+ entries: FileListEntry[];
1967
+ /** A bound in `ListFilesOptions` ended the listing early. */
1968
+ truncated: boolean;
1969
+ }
1970
+ /** Portable filesystem capability. Operations return failures rather than throwing. */
1971
+ interface FileSystem {
1972
+ /**
1973
+ * The file namespace: equal ids see the same files at the same paths, whatever their `cwd`. Every local Node
1974
+ * environment shares one id; each container or remote host has its own.
1975
+ */
1976
+ readonly id: string;
1977
+ cwd: string;
1978
+ absolutePath(path: string, context: Context$1): Promise<Result<string, FileError>>;
1979
+ joinPath(parts: string[], context: Context$1): Promise<Result<string, FileError>>;
1980
+ readTextFile(path: string, context: Context$1): Promise<Result<string, FileError>>;
1981
+ openTextLineReader(path: string, context: Context$1): Promise<Result<TextLineReader, FileError>>;
1982
+ readTextLines(path: string, options: {
1983
+ maxLines?: number;
1984
+ } | undefined, context: Context$1): Promise<Result<string[], FileError>>;
1985
+ readBinaryFile(path: string, context: Context$1): Promise<Result<Uint8Array, FileError>>;
1986
+ /**
1987
+ * Open a regular file for bounded positional reads. A directory fails with `is_directory`, other non-regular files
1988
+ * with `invalid`. With `noFollow`, a symbolic link as the final path component fails with `invalid` instead of being
1989
+ * followed; earlier components are still resolved.
1990
+ */
1991
+ openBinaryReader(path: string, options: {
1992
+ noFollow?: boolean;
1993
+ } | undefined, context: Context$1): Promise<Result<BinaryReader, FileError>>;
1994
+ writeFile(path: string, content: string | Uint8Array, context: Context$1): Promise<Result<void, FileError>>;
1995
+ appendFile(path: string, content: string | Uint8Array, context: Context$1): Promise<Result<void, FileError>>;
1996
+ /** Truncate or extend a file to exactly `size` bytes. */
1997
+ truncateFile(path: string, size: number, context: Context$1): Promise<Result<void, FileError>>;
1998
+ /** Flush file contents and metadata needed to retrieve them from an open file handle. */
1999
+ flushFile(path: string, context: Context$1): Promise<Result<void, FileError>>;
2000
+ renameFile(sourcePath: string, destinationPath: string, context: Context$1): Promise<Result<void, FileError>>;
2001
+ fileInfo(path: string, context: Context$1): Promise<Result<FileInfo, FileError>>;
2002
+ listDir(path: string, context: Context$1): Promise<Result<FileInfo[], FileError>>;
2003
+ /**
2004
+ * Optional: the files, directories and symbolic links below a directory, at any depth, for indexes such as file
2005
+ * completion. Symbolic links are not followed; other kinds of files are not listed; entries that cannot be read are
2006
+ * skipped. See `ListFilesOptions` for hidden and ignored files and for the bounds. Fails with `not_supported` when
2007
+ * the environment cannot list right now (an older remote daemon), so callers fall back to their own walk.
2008
+ */
2009
+ listFiles?(path: string, options: ListFilesOptions | undefined, context: Context$1): Promise<Result<FileListing, FileError>>;
2010
+ openDirReader(path: string, context: Context$1): Promise<Result<DirReader, FileError>>;
2011
+ /**
2012
+ * Report changes to files and directories, for hosts that load resources from the environment. When the returned
2013
+ * watcher exists, coverage is established: a host that watches before it loads cannot miss a change made during the
2014
+ * load. See `FileChange` for what is reported and `FileWatcher.mode` for how reliably.
2015
+ */
2016
+ watch(targets: readonly WatchTarget[], onChange: (change: FileChange) => void, context: Context$1): Promise<Result<FileWatcher, FileError>>;
2017
+ canonicalPath(path: string, context: Context$1): Promise<Result<string, FileError>>;
2018
+ exists(path: string, context: Context$1): Promise<Result<boolean, FileError>>;
2019
+ createDir(path: string, options: {
2020
+ recursive?: boolean;
2021
+ } | undefined, context: Context$1): Promise<Result<void, FileError>>;
2022
+ remove(path: string, options: {
2023
+ recursive?: boolean;
2024
+ force?: boolean;
2025
+ } | undefined, context: Context$1): Promise<Result<void, FileError>>;
2026
+ createTempDir(prefix: string | undefined, context: Context$1): Promise<Result<string, FileError>>;
2027
+ createTempFile(options: {
2028
+ prefix?: string;
2029
+ suffix?: string;
2030
+ } | undefined, context: Context$1): Promise<Result<string, FileError>>;
2031
+ cleanup(context: Context$1): Promise<void>;
2032
+ }
2033
+ /** Spill the complete output to a temporary file once it exceeds either threshold. */
2034
+ interface ShellSpillOptions {
2035
+ afterBytes: number;
2036
+ /** Complete or partial lines. */
2037
+ afterLines: number;
2038
+ }
2039
+ interface ShellExecResult {
2040
+ exitCode: number;
2041
+ /** Temporary file holding the complete raw output, when the spill thresholds were exceeded. */
2042
+ spillPath?: string;
2043
+ }
2044
+ interface ShellExecOptions {
2045
+ cwd?: string;
2046
+ env?: Record<string, string>;
2047
+ inheritEnv?: boolean;
2048
+ timeout?: number;
2049
+ /**
2050
+ * Every decoded chunk of stdout and stderr as it arrives, in arrival order, with the stream it came from: raw,
2051
+ * unbounded, and unthrottled. Each stream is decoded separately, so a character split across chunks survives.
2052
+ */
2053
+ onOutput?: (text: string, context: Context$1, info: ShellOutputInfo) => void;
2054
+ spill?: ShellSpillOptions;
2055
+ /**
2056
+ * The caller keeps only this tail of the output, so the environment may omit output outside it and report the omission
2057
+ * as `info.skipped`. Without it, every chunk is delivered.
2058
+ */
2059
+ window?: ShellOutputWindow;
2060
+ }
2061
+ /**
2062
+ * The tail of the combined output a caller keeps, and how often it samples it. An environment that transfers output
2063
+ * over a slow link uses it to omit what the caller would drop anyway and to send no faster than the caller commits.
2064
+ */
2065
+ interface ShellOutputWindow {
2066
+ /** UTF-8 bytes of decoded text kept at the end of the output. */
2067
+ maxBytes: number;
2068
+ /** Lines kept at the end of the output. */
2069
+ maxLines: number;
2070
+ /** Minimum pause between the caller's samples of the output. */
2071
+ minIntervalMs: number;
2072
+ /** Each sample also pauses the caller in proportion to its size at this rate. */
2073
+ bytesPerSecond: number;
2074
+ }
2075
+ /**
2076
+ * Output an environment omitted, measured on the decoded text `onOutput` would have received: every U+FFFD counts as
2077
+ * three bytes, and no sanitizing is applied.
2078
+ */
2079
+ /** The shape of `OutputSkip` from `@earendil-works/chord/output`, which `OutputBuffer.push()` accepts. */
2080
+ interface ShellOutputSkip {
2081
+ /** UTF-8 byte length of the omitted text. */
2082
+ bytes: number;
2083
+ /** Newlines (U+000A) in the omitted text. */
2084
+ newlines: number;
2085
+ /** Whether the omitted text ends with a newline. */
2086
+ endsWithNewline: boolean;
2087
+ }
2088
+ interface ShellOutputInfo {
2089
+ stream: "stdout" | "stderr";
2090
+ /**
2091
+ * Output omitted immediately before this chunk, only with `window`. The chunk then holds all output after the
2092
+ * omission up to its end, and that is more than the window by at least one byte or one line: more than
2093
+ * `window.maxBytes` bytes or more than `window.maxLines` newlines. So the omitted text can never be in the kept tail.
2094
+ * The omission and such a chunk may span both streams in arrival order; `stream` then names the chunk's last stream.
2095
+ * Callers that need the streams apart do not pass `window`.
2096
+ */
2097
+ skipped?: ShellOutputSkip;
2098
+ }
2099
+ interface Shell {
2100
+ /**
2101
+ * Run a command. A string runs through the environment's shell. An array runs `command[0]` directly with the rest
2102
+ * as its arguments, without a shell, so they reach the program unparsed. Aborting the context or a timeout kills
2103
+ * only this command's processes.
2104
+ */
2105
+ exec(command: string | readonly string[], options: ShellExecOptions | undefined, context: Context$1): Promise<Result<ShellExecResult, ExecutionError>>;
2106
+ /** Kill every command this environment still runs; for its owner's shutdown, never for one request. */
2107
+ cleanup(context: Context$1): Promise<void>;
2108
+ }
2109
+ interface ExecutionEnv extends FileSystem, Shell {
2110
+ }
2111
+
2112
+ /** The value type of a TypeBox schema type by its `'~kind'`, or its `Type.Unsafe` type; `unknown` for other kinds. */
2113
+ type TypeBoxStatic<S> = S extends {
2114
+ readonly "~kind": infer K;
2115
+ } ? KindStatic<S, K> : S extends {
2116
+ readonly "~unsafe": infer T;
2117
+ } ? T : unknown;
2118
+ interface Primitives {
2119
+ String: string;
2120
+ Number: number;
2121
+ Integer: number;
2122
+ Boolean: boolean;
2123
+ Null: null;
2124
+ BigInt: bigint;
2125
+ Undefined: undefined;
2126
+ Unknown: unknown;
2127
+ Any: any;
2128
+ }
2129
+ type KindStatic<S, K> = K extends keyof Primitives ? Primitives[K] : K extends "Literal" ? S extends {
2130
+ readonly const: infer V;
2131
+ } ? V : unknown : K extends "Array" ? S extends {
2132
+ readonly items: infer I;
2133
+ } ? Static<I>[] : unknown : K extends "Object" ? S extends {
2134
+ readonly properties: infer P;
2135
+ } ? ObjectStatic<P> : unknown : K extends "Union" ? S extends {
2136
+ readonly anyOf: readonly (infer B)[];
2137
+ } ? Static<B> : unknown : K extends "Record" ? S extends {
2138
+ readonly patternProperties: infer P;
2139
+ } ? Record<RecordKey<keyof P>, Static<P[keyof P]>> : unknown : K extends "Enum" ? S extends {
2140
+ readonly enum: readonly (infer V)[];
2141
+ } ? V : unknown : K extends "Tuple" ? S extends {
2142
+ readonly items: infer I extends readonly unknown[];
2143
+ } ? {
2144
+ -readonly [N in keyof I]: Static<I[N]>;
2145
+ } : unknown : unknown;
2146
+ type Optional = {
2147
+ readonly "~optional": true;
2148
+ };
2149
+ type Readonly$1 = {
2150
+ readonly "~readonly": true;
2151
+ };
2152
+ type ObjectStatic<P> = keyof P extends never ? object : Simplify<{
2153
+ -readonly [K in keyof P as P[K] extends Optional | Readonly$1 ? never : K]: Static<P[K]>;
2154
+ } & {
2155
+ -readonly [K in keyof P as P[K] extends Optional ? (P[K] extends Readonly$1 ? never : K) : never]?: Static<P[K]>;
2156
+ } & {
2157
+ readonly [K in keyof P as P[K] extends Readonly$1 ? (P[K] extends Optional ? never : K) : never]: Static<P[K]>;
2158
+ } & {
2159
+ readonly [K in keyof P as P[K] extends Optional ? (P[K] extends Readonly$1 ? K : never) : never]?: Static<P[K]>;
2160
+ }>;
2161
+ type Simplify<T> = {
2162
+ [K in keyof T]: T[K];
2163
+ } & {};
2164
+ type RecordKey<Pattern> = Pattern extends "^-?(?:0|[1-9][0-9]*)$" | "^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" ? number : string;
2165
+
2166
+ declare const STATIC: unique symbol;
2167
+ /**
2168
+ * The type of the values `S` accepts: the type a builder recorded; for a TypeBox schema (`'~kind'` or `'~unsafe'`),
2169
+ * TypeBox's static type for the common kinds (see `TypeBoxStatic`); else `unknown`.
2170
+ */
2171
+ type Static<S> = S extends {
2172
+ readonly "~kind": unknown;
2173
+ } | {
2174
+ readonly "~unsafe": unknown;
2175
+ } ? TypeBoxStatic<S> : S extends {
2176
+ readonly [STATIC]?: infer T;
2177
+ } ? unknown extends T ? unknown : T : unknown;
2178
+
2179
+ /** The key of one wait for a signal: JSON, used in sleeps and parks. `T` is a phantom type. */
2180
+ type SignalKey<T> = {
2181
+ readonly signal: string;
2182
+ readonly key: string;
2183
+ readonly "~value"?: T;
2184
+ };
2185
+ /** A signal kind, built by `defineSignal()`: values of type `T` delivered under keys. */
2186
+ interface SignalToken<T> {
2187
+ readonly name: string;
2188
+ readonly version: number;
2189
+ /** The key of one wait; throws for an empty key. */
2190
+ key(key: string): SignalKey<T>;
2191
+ }
2192
+ /** A key's state: the value delivered under it, or expired because its sleep's deadline came first. */
2193
+ type SignalState<T> = {
2194
+ readonly value: T;
2195
+ } | {
2196
+ readonly expired: true;
2197
+ };
2198
+ /**
2199
+ * What a delivery did: `delivered` (durably accepted, not necessarily consumed), `duplicate` (the key holds a value),
2200
+ * `invalid` (not JSON, or not matching the schema), `closed` (the task ended, holds its outcome, is abort-marked, or the
2201
+ * key expired), `not_found` (no such task).
2202
+ */
2203
+ type SignalResult = "delivered" | "duplicate" | "invalid" | "closed" | "not_found";
2204
+
2205
+ /** Why a task cannot be reserved: no registered definition can take it. Derived from the registry. */
2206
+ type BlockedReason = "missing_task" | "task_too_old" | "migration_failed";
2207
+
2208
+ /** A live task's durable status without its checkpoint and outcome payloads (spec §9.4). */
2209
+ type TaskGraphState = {
2210
+ readonly status: "pending" | "running";
2211
+ readonly phase: string;
2212
+ } | {
2213
+ readonly status: "waiting";
2214
+ readonly phase: string;
2215
+ readonly on: readonly TaskId[];
2216
+ readonly policy: JoinPolicy;
2217
+ }
2218
+ /** Asleep until the Harness clock reaches `until`, or one of `signals` holds a value no wake used. */
2219
+ | {
2220
+ readonly status: "sleeping";
2221
+ readonly phase: string;
2222
+ readonly until?: number;
2223
+ readonly signals?: readonly {
2224
+ readonly signal: string;
2225
+ readonly key: string;
2226
+ }[];
2227
+ }
2228
+ /** Outcome held until its ordinary owned work drains. */
2229
+ | {
2230
+ readonly status: "completing";
2231
+ readonly outcome: TaskOutcome<JsonValue$1>["status"];
2232
+ };
2233
+ type TaskGraphNode = {
2234
+ readonly id: TaskId;
2235
+ readonly kind: string;
2236
+ readonly conversationId: ConversationId;
2237
+ /** Owner task; absent for a conversation-owned task. */
2238
+ readonly owner?: TaskId;
2239
+ readonly background: boolean;
2240
+ readonly abortRequested: boolean;
2241
+ readonly state: TaskGraphState;
2242
+ /**
2243
+ * Why it cannot run here, when it cannot: no registered definition takes it (`missing_task`, `task_too_old`,
2244
+ * `migration_failed`). Follows registry changes.
2245
+ */
2246
+ readonly blocked?: BlockedReason;
2247
+ /** Conversations this task owns, in ID order. */
2248
+ readonly conversations: readonly ConversationId[];
2249
+ };
2250
+ /** Every live task of the Session (spec §9.4). */
2251
+ type TaskGraph = {
2252
+ /** Every live task, keyed by its decimal ID. */
2253
+ readonly tasks: Readonly<Record<string, TaskGraphNode>>;
2254
+ };
2255
+ type TaskGraphWatch = WatchHandle<TaskGraph>;
2256
+
2257
+ /** Ledger of one conversation's own spend: its entries, and compaction summarization attempts, which have none. */
2258
+ type UsageState = {
2259
+ /** Assistant entries and summarization attempts, keyed `provider/modelId`. */
2260
+ models: Record<string, JsonRepresentation$1<Usage>>;
2261
+ /** Tool results, keyed by tool name; their usage has no model identity. */
2262
+ tools: Record<string, JsonRepresentation$1<Usage>>;
2263
+ };
2264
+
2265
+ /** Structural view of one conversation: a window over its transcript and its built-in documents (spec §9.3). */
2266
+ type ConversationView = {
2267
+ readonly conversation: ConversationRecord;
2268
+ /**
2269
+ * A window over the transcript, its fork-aware history (`Conversation.entries()`), in entry ID order. Head markers
2270
+ * such as compaction summaries sit where they were written; their `head` tells where the entries they summarize end.
2271
+ */
2272
+ readonly entries: readonly EntryRecord[];
2273
+ /** ID of the entry just before the window; absent when the window starts the transcript. */
2274
+ readonly before?: EntryId;
2275
+ /** Built-in conversation documents keyed by kind; absent documents are absent. */
2276
+ readonly docs: Readonly<Record<string, JsonObject>>;
2277
+ };
2278
+ /**
2279
+ * Which entries a view's window holds (spec §9.3). The window holds between `min` and `max` entries: it starts with
2280
+ * the newest `min` entries, takes appends, and once it would hold more than `max`, drops its oldest in one splice down
2281
+ * to `min`. With `from`, it starts at `from` instead when at most `max` entries are at or after it.
2282
+ */
2283
+ type ConversationWindow = {
2284
+ /**
2285
+ * Where the first value's window starts, inclusive, such as right after the newest entry a client has
2286
+ * (`ConversationTranscript.resume`). It selects only that first value: every entry committed after the attachment is
2287
+ * appended, whatever its ID. A `from` past the newest entry starts the window empty, with `before` the newest entry.
2288
+ */
2289
+ readonly from?: EntryId;
2290
+ /** Default 50; an integer, at least 1. */
2291
+ readonly min?: number;
2292
+ /** Default `2 * min`; an integer, at least `min`. */
2293
+ readonly max?: number;
2294
+ };
2295
+
2296
+ /** Provider and model ID resolved through pi-ai `Models`. */
2297
+ type ModelRef = {
2298
+ readonly provider: string;
2299
+ readonly modelId: string;
2300
+ };
2301
+ type UserInput = UserMessage["content"];
2302
+ /**
2303
+ * The entry an input is placed as, instead of `pi.user`: an application kind, and data the transcript shows, such as its
2304
+ * author. Its model message is still the input's user message.
2305
+ */
2306
+ type InputEntry = {
2307
+ readonly kind: string;
2308
+ readonly data?: JsonValue$1;
2309
+ };
2310
+ /**
2311
+ * Host submission: user input that may start a run, a passive entry write, or a continue: a run without a new user
2312
+ * message, for an idle conversation whose context the model still owes an answer (it ends in a user message or tool
2313
+ * results, for example after a run that ended without an answer).
2314
+ */
2315
+ type SubmissionDraft = {
2316
+ readonly requestId?: string;
2317
+ /**
2318
+ * When the submission settles, deliver `SubmissionSettled` (the settled record) to `notify.taskId` under
2319
+ * `notify.key`, in the settling commit; a delivery the task refuses (`closed`, `not_found`) fails nothing. A
2320
+ * submission that settles before the task sleeps on the key wakes the sleep at once.
2321
+ */
2322
+ readonly notify?: SubmissionNotify;
2323
+ } & ({
2324
+ readonly type: "input";
2325
+ readonly content: UserInput;
2326
+ readonly whenBusy?: "steer" | "followUp" | "reject";
2327
+ /**
2328
+ * `reject`: an idle conversation (no run) rejects the input with `ConversationIdle` and writes nothing, so the input
2329
+ * never starts a run of its own. With `whenBusy: "steer"` it steers the current run or is refused; a run that
2330
+ * answered and waits for its `afterRun` tasks is still busy, and such an input queues and starts the next run.
2331
+ */
2332
+ readonly whenIdle?: "reject";
2333
+ /**
2334
+ * What `Conversation.abort()` and abort cascades do with the input while it is queued: `withdraw` (default)
2335
+ * settles it `unanswered` with reason `aborted`; `keep` leaves it queued, as a failed run leaves its queue under
2336
+ * `afterFailedRun: "keep"`, so the next input places it and that run answers it. For input its sender cannot
2337
+ * take back, such as another agent's message. `Submission.abort()` withdraws it either way.
2338
+ */
2339
+ readonly onAbort?: "withdraw" | "keep";
2340
+ /** Place the input as this entry; default `pi.user` without data. The kind must not start with `pi.`. */
2341
+ readonly entry?: InputEntry;
2342
+ } | {
2343
+ readonly type: "write";
2344
+ readonly entry: EntryDraft;
2345
+ readonly content?: never;
2346
+ readonly whenBusy?: never;
2347
+ readonly whenIdle?: never;
2348
+ } | {
2349
+ /**
2350
+ * Start a run on the context as it is, without a user message. Only when idle: a busy conversation rejects it with
2351
+ * `ConversationBusy`, and it never queues. Items kept in `pi.inbox` are placed first and join the run. A context
2352
+ * with nothing to answer (empty, or ending in an answer, also a text answer cut off at its output limit) ends the
2353
+ * run without a request, `unanswered` with `nothing_to_answer`. A cut-off answer with tool calls is continued:
2354
+ * its calls never ran, and the context ends in their error results (`missing_result`).
2355
+ */
2356
+ readonly type: "continue";
2357
+ readonly content?: never;
2358
+ readonly entry?: never;
2359
+ readonly whenBusy?: never;
2360
+ readonly whenIdle?: never;
2361
+ });
2362
+ type SettledSubmissionRecord = SubmissionRecord & {
2363
+ readonly status: "done" | "unanswered";
2364
+ };
2365
+ /** Awaitable host object for one durably admitted submission. */
2366
+ interface Submission {
2367
+ readonly id: SubmissionId;
2368
+ status(context: Context$1): Promise<SubmissionRecord>;
2369
+ wait(context: Context$1): Promise<SettledSubmissionRecord>;
2370
+ abort(context: Context$1): Promise<"aborted" | "already_placed" | "settled">;
2371
+ }
2372
+ type SettledTask<R> = TaskRecord<JsonValue$1, JsonValue$1, R> & {
2373
+ readonly state: Extract<TaskState<JsonValue$1, R>, {
2374
+ readonly status: "terminal";
2375
+ }>;
2376
+ };
2377
+ /** Erased executable task definition stored in the registry. */
2378
+ type AnyTask = {
2379
+ readonly definition: {
2380
+ readonly name: string;
2381
+ readonly version: number;
2382
+ readonly initial: unknown;
2383
+ readonly phases: Readonly<Record<string, unknown>>;
2384
+ readonly abort: unknown;
2385
+ readonly migrate?: unknown;
2386
+ readonly hooks?: object;
2387
+ };
2388
+ };
2389
+ /** Options of `Conversation.abort()`. */
2390
+ type ConversationAbortOptions = {
2391
+ /**
2392
+ * Cross background boundaries: mark every live task reached ignoring the background flag when the abort is admitted,
2393
+ * withdraw the queued inputs of every conversation reached, and wait until those tasks are terminal and the
2394
+ * conversation is ordinarily idle. Background work created afterwards is neither marked nor awaited.
2395
+ */
2396
+ readonly background?: boolean;
2397
+ };
2398
+ /**
2399
+ * Invocation-bound conversation operations for tasks and tools. Rejects after the invocation ends. `submit` takes any
2400
+ * submission, in both forms of `Conversation.submit()`: a subagent's conversation is an ordinary one, so a tool may also
2401
+ * continue it, and a task may admit a submission in the same commit as its own writes (`runtime.commit()`); entries
2402
+ * the admission appends there carry the task's `byTaskId`. The transaction form also rejects once the invocation is
2403
+ * aborted.
2404
+ */
2405
+ interface ConversationHandle {
2406
+ readonly id: ConversationId;
2407
+ submit(submission: SubmissionDraft, context: Context$1): Promise<Submission>;
2408
+ submit(tx: Tx, submission: SubmissionDraft): Promise<SubmissionId>;
2409
+ /** `Conversation.abort()`: withdraw queued inputs, abort the ordinary ownership scope, and wait until it is idle. */
2410
+ abort(context: Context$1, options?: ConversationAbortOptions): Promise<void>;
2411
+ /** Resolve when the conversation's ordinary ownership scope has no live non-background task. */
2412
+ waitForIdle(context: Context$1): Promise<void>;
2413
+ }
2414
+ /** Post-tools controls requested by a tool result. */
2415
+ type ToolControl = {
2416
+ readonly addTools?: readonly string[];
2417
+ /** End the run without another model request when every result of the round sets it to `true`; `false` is a no-op. */
2418
+ readonly terminate?: boolean;
2419
+ /**
2420
+ * Start a new context with this text as its user message, as `reset(handoff)` writes, and continue the run there.
2421
+ * The last handoff in call order wins.
2422
+ */
2423
+ readonly handoff?: string;
2424
+ };
2425
+ /** Remark about a call for the model and the UI, such as truncation or a spill path; never part of the tool's data. */
2426
+ type ToolDiagnostic = {
2427
+ readonly severity: "info" | "warn" | "error";
2428
+ readonly message: string;
2429
+ readonly code?: string;
2430
+ };
2431
+ /**
2432
+ * What a tool returns, on three channels: `output` for the model, `structuredOutput` for programs that call the tool
2433
+ * (`executeTool()` callers, code mode scripts), and `details` for UIs.
2434
+ */
2435
+ type ToolExecutionResult<TDetails extends JsonValue$1 = JsonValue$1> = {
2436
+ /** For the model. Omitted: the retained `output()` text. */
2437
+ readonly output?: ToolResultMessage["content"];
2438
+ /**
2439
+ * For programs. Required unless `isError` when the tool declares `structuredOutputSchema`, and validated against it;
2440
+ * not allowed without one, where programs get the output itself (`NestedToolExecutionResult.structuredOutput`).
2441
+ */
2442
+ readonly structuredOutput?: JsonValue$1;
2443
+ readonly isError?: boolean;
2444
+ /** Omitted: the last `details()` value becomes the details. */
2445
+ readonly details?: TDetails;
2446
+ /** Added after those recorded through `api.diagnostic()`. */
2447
+ readonly diagnostics?: readonly ToolDiagnostic[];
2448
+ /** Spend of the execution itself, such as a model call; stored on the result and in `pi.usage.tools`. */
2449
+ readonly usage?: Usage;
2450
+ readonly control?: ToolControl;
2451
+ /** A result is no park (`ToolPark`). */
2452
+ readonly sleep?: never;
2453
+ readonly wait?: never;
2454
+ };
2455
+ /**
2456
+ * Result of a nested call, as `executeTool()` returns it. Programs read `structuredOutput`; the output for the model
2457
+ * is not kept, and `control` does not apply.
2458
+ */
2459
+ type NestedToolExecutionResult = {
2460
+ /** The nested call's tool task. */
2461
+ readonly taskId: TaskId;
2462
+ /**
2463
+ * The tool's value for programs. A tool with `structuredOutputSchema`: its validated `structuredOutput`, also on an
2464
+ * error result that has one; absent otherwise, and an error's text is then in an error diagnostic. A tool without:
2465
+ * its bounded output, success or error, as a string for one text item, an `ImageContent` for one image, `""` for
2466
+ * none, and the content list otherwise. Absent on an error result the Harness wrote itself (unavailable, invalid,
2467
+ * blocked, interrupted, aborted); `diagnostics` say what went wrong.
2468
+ */
2469
+ readonly structuredOutput?: JsonValue$1;
2470
+ readonly isError: boolean;
2471
+ readonly details?: JsonValue$1;
2472
+ readonly diagnostics: readonly ToolDiagnostic[];
2473
+ readonly usage?: Usage;
2474
+ /** Execution time of the attempt that produced the result; absent when it never executed. */
2475
+ readonly durationMs?: number;
2476
+ };
2477
+ /**
2478
+ * What `execute()` returns instead of a result to park the call (spec suspendable §4): `sleep` until `until`, for
2479
+ * `signals`, or both; or `wait` for tasks the call's task owns. The call holds no invocation meanwhile, then runs
2480
+ * `execute()` again with the same arguments, `api.wake` saying why, and `api.checkpoint` set to `checkpoint`.
2481
+ */
2482
+ type ToolPark<C extends JsonValue$1 = JsonValue$1> = NoResultFields & ({
2483
+ readonly sleep: {
2484
+ readonly checkpoint?: C;
2485
+ readonly until?: number;
2486
+ readonly signals?: readonly SignalKey<unknown>[];
2487
+ };
2488
+ readonly wait?: never;
2489
+ } | {
2490
+ readonly wait: {
2491
+ readonly checkpoint?: C;
2492
+ readonly on: readonly TaskId[];
2493
+ readonly policy: JoinPolicy;
2494
+ };
2495
+ readonly sleep?: never;
2496
+ });
2497
+ /** A park carries no result field, so code reading a result's fields reads none from a park. */
2498
+ type NoResultFields = {
2499
+ readonly [K in Exclude<keyof ToolExecutionResult, "sleep" | "wait">]?: never;
2500
+ };
2501
+ /** Whether the tools of one round run at once or one after another in call order. */
2502
+ type ToolExecutionMode = "parallel" | "sequential";
2503
+ /** How many queued items of one mode a boundary places: the first, or all of them. */
2504
+ type QueueMode = "all" | "one-at-a-time";
2505
+ /**
2506
+ * Operations available to one tool invocation. A plain object, so a wrapper can spread it. Every operation rejects after
2507
+ * the invocation ends.
2508
+ */
2509
+ interface ToolExecutionApi<TDetails extends JsonValue$1 = JsonValue$1, C extends JsonValue$1 = JsonValue$1> extends DocumentObserver, DocumentReader {
2510
+ readonly taskId: TaskId;
2511
+ readonly conversationId: ConversationId;
2512
+ readonly callId: string;
2513
+ /** Why this run started after a park; undefined on a fresh call, and in `cancel`. */
2514
+ readonly wake: WakeReason | undefined;
2515
+ /** What the call last parked with; undefined on a fresh call or after a park without one. */
2516
+ readonly checkpoint: C | undefined;
2517
+ /** The tool task's phase snapshot. */
2518
+ readonly registry: RegistrySnapshot;
2519
+ /** The calling conversation's agent, as the tool task's phase resolved it. */
2520
+ agent(context: Context$1): Promise<Agent>;
2521
+ /** The current `HarnessOptions.models`, read at each access: the catalog, credentials, and request transforms. */
2522
+ readonly models: Models;
2523
+ /** Built by `HarnessOptions.env` for this call; `undefined` without an environment. */
2524
+ readonly env: ExecutionEnv | undefined;
2525
+ /** The Harness clock (`HarnessOptions.now`), for times a rerun after a restart compares against. */
2526
+ now(): number;
2527
+ /**
2528
+ * Append running output; it becomes the result's `output` when the result omits it. `skipped` counts output
2529
+ * omitted before the chunk, as reported by an environment given `outputWindow` (`ShellOutputInfo.skipped`).
2530
+ */
2531
+ output(chunk: string | Uint8Array, skipped?: ShellOutputSkip): void;
2532
+ /**
2533
+ * The tail this call's output keeps and the pace of its progress commits, for `ShellExecOptions.window`; `undefined`
2534
+ * when the tool keeps the head of its output, which cannot accept skips. A wrapper that replaces `output` and
2535
+ * transforms text must also replace this with `undefined`, so skipped text cannot bypass its transform.
2536
+ */
2537
+ readonly outputWindow: ShellOutputWindow | undefined;
2538
+ /**
2539
+ * The output retained so far, as the model will see it when the result omits `output`, and whether earlier output was
2540
+ * dropped; for a tool that also returns that text in its `structuredOutput`.
2541
+ */
2542
+ retainedOutput(): {
2543
+ readonly text: string;
2544
+ readonly truncated: boolean;
2545
+ };
2546
+ /** Record a model-visible remark about this call. */
2547
+ diagnostic(diagnostic: ToolDiagnostic): void;
2548
+ /** Replace running details; the last value becomes the result details when the result omits `details`. */
2549
+ details(value: TDetails, context: Context$1): Promise<void>;
2550
+ /** A commit of this call's task; `options` may defer storing it (`CommitPersistence`). */
2551
+ commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context$1, options?: CommitOptions): Promise<T>;
2552
+ memo<T extends JsonValue$1>(name: string, context: Context$1): Promise<T | undefined>;
2553
+ memo<T extends JsonValue$1>(name: string, candidate: T, context: Context$1): Promise<T>;
2554
+ /** A signal key's committed state in this call's task, as `TaskRuntime.readSignal()`. */
2555
+ readSignal<T>(token: SignalToken<T>, key: string, context: Context$1): Promise<SignalState<T> | undefined>;
2556
+ /**
2557
+ * Create a task in one commit. A child task of a tool that is not replay-safe defaults to `abandonOnRestart`: the
2558
+ * tool never resumes after a restart, so nothing awaits the child then. With a `key`, validated like a nested call's,
2559
+ * the task is recorded under it in the same commit, and a later call with the key, in this run, a rerun, or a run
2560
+ * after a wake, returns that task; another task kind, other input, or a key a nested call uses throws. After a wake
2561
+ * (`wake` set) a key is required.
2562
+ */
2563
+ createTask<I, S extends {
2564
+ phase: string;
2565
+ }, R, H extends object>(task: Task<I, S, R, H>, input: I, options: Omit<TaskOptions, "conversationId"> & {
2566
+ readonly key?: string;
2567
+ }, context: Context$1): Promise<TaskId<R>>;
2568
+ getTask<R>(id: TaskId<R>, context: Context$1): Promise<TaskRecord<JsonValue$1, JsonValue$1, R> | undefined>;
2569
+ waitForTask<R>(id: TaskId<R>, context: Context$1): Promise<SettledTask<R>>;
2570
+ /** Invocation-bound handle of an existing conversation, such as one this tool created in `commit()`. */
2571
+ conversation(id: ConversationId, context: Context$1): Promise<ConversationHandle | undefined>;
2572
+ /**
2573
+ * Run tool `name` as a nested call of this one and wait for its result. The nested call is its own `pi.tool` task,
2574
+ * owned by this call: it resolves the tool among the conversation's tools, validates, runs the `ToolTask` hooks (which
2575
+ * see `call.parent`), applies output limits and the tool's replay policy, and reports progress in `pi.live.nestedTools`.
2576
+ * Its result returns here instead of entering the transcript. A call that is blocked, invalid, throws, is interrupted,
2577
+ * or is aborted returns an `isError` result.
2578
+ *
2579
+ * The nested call's key names it within this call; its call ID is `<callId>/<key>`. By default the key is the call's
2580
+ * position among this invocation's nested calls, `1`, `2`, ... An explicit `key` must be non-empty, without `/`, not
2581
+ * `__proto__`, and not a positive integer, so it never collides with a default one. After a wake (`wake` set) the
2582
+ * same position may mean another call, so a key is required. A rerun of a replay-safe tool
2583
+ * that makes a call with a used key, by calling in the same order or by passing the same `key`, gets that nested call
2584
+ * back, finished or still running, instead of starting another. A nested call a crash interrupted before its result
2585
+ * committed follows its own replay policy, so this is not exactly-once execution. Reusing a key with another tool or
2586
+ * other arguments throws. A tool that is not replay-safe never reruns: after a restart, its unfinished nested calls
2587
+ * are abandoned (`TaskOptions.abandonOnRestart`) before they run again.
2588
+ *
2589
+ * `progress: false` commits no running output, details, or diagnostics to the nested call's slot, only its status;
2590
+ * the result still carries its details and diagnostics, and a schema-less tool's output as `structuredOutput`. An
2591
+ * interrupted or aborted call's result is built from its slot, so it then has none of them. Either way, programs never
2592
+ * get the partial output of an interrupted or aborted call.
2593
+ *
2594
+ * Nested calls run as soon as they are made, whatever their `executionMode`; the caller decides what runs at once by
2595
+ * what it awaits. Cancelling `context` stops only the wait; the nested call runs on. When this call settles, nested
2596
+ * calls it left running are aborted first. A nested result's `usage` is already counted under its tool; a result
2597
+ * that passes it on counts it again. Rejects, instead of returning a result, once `execute()` has returned, when this
2598
+ * call is aborted, or when the Harness closes.
2599
+ *
2600
+ * Awaiting a nested call holds this call's invocation for as long as it takes, also while it is parked; a tool that
2601
+ * starts calls with `wait: false` and parks on their tasks (`{ wait: { on } }`) lets the Session go idle instead.
2602
+ */
2603
+ executeTool(name: string, args: JsonObject, context: Context$1, options?: {
2604
+ readonly key?: string;
2605
+ readonly progress?: boolean;
2606
+ readonly wait?: true;
2607
+ }): Promise<NestedToolExecutionResult>;
2608
+ /** As above, but returns once the nested call is started or found, with a handle to its result. */
2609
+ executeTool(name: string, args: JsonObject, context: Context$1, options: {
2610
+ readonly key?: string;
2611
+ readonly progress?: boolean;
2612
+ readonly wait: false;
2613
+ }): Promise<NestedToolCall>;
2614
+ }
2615
+ /** A nested call started without waiting for it (`executeTool()` with `wait: false`). */
2616
+ type NestedToolCall = {
2617
+ /** The nested call's tool task, for a park's `wait.on`. */
2618
+ readonly taskId: TaskId;
2619
+ /** The stored result once the nested call is terminal; otherwise waits for it. */
2620
+ result(context: Context$1): Promise<NestedToolExecutionResult>;
2621
+ };
2622
+ /**
2623
+ * The arguments type of a tool with parameter schema `TParameters`: pi-schema's `Static<TParameters>` (the builders'
2624
+ * type, TypeBox's for the common TypeBox kinds, else `unknown`), and `any` for `ToolRegistration<any>`.
2625
+ */
2626
+ type ToolArgs<TParameters> = IsAny<TParameters> extends true ? any : Static<TParameters>;
2627
+ type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false;
2628
+ /**
2629
+ * Executable tool registered in a registry. Only pi-ai `Tool` fields enter the transcript. `args` are typed by
2630
+ * `parameters` (any JSON Schema object; see {@link ToolArgs}), which the Harness validates them against before
2631
+ * `execute()`; `defineTool()` infers both generics.
2632
+ */
2633
+ type ToolRegistration<TParameters extends object = object, TDetails extends JsonValue$1 = JsonValue$1, C extends JsonValue$1 = JsonValue$1> = Tool<TParameters> & {
2634
+ /** Whether an interrupted execution may rerun on recovery. Default `unsafe`. */
2635
+ readonly replay?: "safe" | "unsafe";
2636
+ /** Default: the settings' `toolExecution`. One sequential call makes its whole round sequential. */
2637
+ readonly executionMode?: ToolExecutionMode;
2638
+ /**
2639
+ * Repair arguments models commonly get wrong before validation, such as a JSON string where an array belongs. Must be
2640
+ * pure and must not mutate `args`: it runs again when a call is retried before its intent is recorded. Its result is
2641
+ * still validated against `parameters`.
2642
+ */
2643
+ prepareArguments?(args: unknown): ToolArgs<TParameters>;
2644
+ /**
2645
+ * Schema of `structuredOutput`, which programs that call the tool receive. Omitted: they receive the result's bounded
2646
+ * output, success or error, as `NestedToolExecutionResult.structuredOutput` describes.
2647
+ */
2648
+ readonly structuredOutputSchema?: object;
2649
+ /**
2650
+ * Who may call the tool: the model, other tools through `executeTool()`, or both (default). A code mode tool is
2651
+ * `["model"]`, so scripts cannot start scripts; tools behind code mode, such as MCP tools, can be `["tools"]`, so the
2652
+ * model is never offered them.
2653
+ */
2654
+ readonly callers?: readonly ("model" | "tools")[];
2655
+ /**
2656
+ * Not offered to the model until loaded: the model gets the tool only when `modelTools` names it, in its array or its
2657
+ * `add`, which `control.addTools` (from a tool such as `tool_search`) writes. Other tools can call it any time.
2658
+ */
2659
+ readonly deferred?: true;
2660
+ readonly outputLimits?: {
2661
+ readonly maxBytes?: number;
2662
+ readonly maxLines?: number;
2663
+ readonly retain?: "head" | "tail";
2664
+ };
2665
+ /** A result, or a park (`ToolPark`): the call runs `execute()` again once woken. */
2666
+ execute(args: ToolArgs<TParameters>, api: ToolExecutionApi<TDetails, C>, context: Context$1): Promise<ToolExecutionResult<TDetails> | ToolPark<C>>;
2667
+ /**
2668
+ * Clean up the external work of a call that parked, when it is aborted while no code of the tool runs (spec
2669
+ * suspendable §4.2): `api.checkpoint` is the last park's, `api.wake` undefined, and it starts no nested calls or
2670
+ * tasks. May run more than once, so idempotent. A throw is reported and the call still ends.
2671
+ */
2672
+ cancel?(args: ToolArgs<TParameters>, api: ToolExecutionApi<TDetails, C>, context: Context$1): Promise<void>;
2673
+ };
2674
+ /** Input to system prompt section rendering for one request preparation. */
2675
+ type PromptInput<Tool extends ToolRegistration = ToolRegistration> = {
2676
+ readonly conversationId: ConversationId;
2677
+ /** The request's resolution; `agent.tools` are the tools offered in this request. */
2678
+ readonly agent: Agent<Tool>;
2679
+ /** Built by `HarnessOptions.env` for this preparation; `undefined` without an environment. */
2680
+ readonly env: ExecutionEnv | undefined;
2681
+ /** Sections already in effect after replaying the active transcript. */
2682
+ readonly shown: Readonly<Record<string, string>>;
2683
+ /** Committed document reads. */
2684
+ readonly read: DocumentReader;
2685
+ };
2686
+ /** One system prompt section; the agent's sections render in order before each request. */
2687
+ type PromptSection<Tool extends ToolRegistration = ToolRegistration> = {
2688
+ readonly key: string;
2689
+ render(input: PromptInput<Tool>, context: Context$1): string | undefined | Promise<string | undefined>;
2690
+ /** Default true: wrap the text as `<key>\n...\n</key>`. */
2691
+ readonly tag?: boolean;
2692
+ };
2693
+ /** Built by `hook()`; matches tasks by name. */
2694
+ type HookRegistration = {
2695
+ readonly task: string;
2696
+ readonly handlers: object;
2697
+ };
2698
+ /** Built by `wrapTool()` and `wrapSection()`; targets a tool name or a section key. Wrappers are pure. */
2699
+ type Wrap<Tool extends ToolRegistration = ToolRegistration> = {
2700
+ readonly tool: string;
2701
+ wrap(tool: Tool): Tool;
2702
+ } | {
2703
+ readonly section: string;
2704
+ wrap(section: PromptSection<Tool>): PromptSection<Tool>;
2705
+ };
2706
+ /** Named bundle of code; installed in a registry and selected by conversations by name. */
2707
+ /**
2708
+ * A named group of tools for code mode: the extension that brings the tools declares it. `description` is one line,
2709
+ * shown in the `codemode` prompt section; `instructions` is the longer how-to, returned only by `describeNamespace()`;
2710
+ * `searchTools()` searches both.
2711
+ */
2712
+ type ToolNamespace = {
2713
+ readonly name: string;
2714
+ readonly description: string;
2715
+ readonly instructions?: string;
2716
+ };
2717
+ interface Extension<Tool extends ToolRegistration = ToolRegistration> {
2718
+ readonly name: string;
2719
+ /**
2720
+ * The code-mode namespace of this extension's tools (a tool named by several extensions belongs to the first). The
2721
+ * `codemode` section lists it while the extension is selected, also before it has any tools.
2722
+ */
2723
+ readonly namespace?: ToolNamespace;
2724
+ readonly tools?: readonly Tool[];
2725
+ readonly sections?: readonly PromptSection<Tool>[];
2726
+ readonly hooks?: readonly HookRegistration[];
2727
+ /** Apply where this extension is selected, in order. */
2728
+ readonly wraps?: readonly Wrap<Tool>[];
2729
+ /** Resolved by name for every task, whichever conversations select this extension. */
2730
+ readonly tasks?: readonly AnyTask[];
2731
+ }
2732
+ /** Immutable view of one published registry state. */
2733
+ interface RegistrySnapshot<Tool extends ToolRegistration = ToolRegistration> {
2734
+ installed(): readonly Extension<Tool>[];
2735
+ extension(name: string): Extension<Tool> | undefined;
2736
+ /** Every installed tool with its extension, in install order. Names may repeat across extensions. */
2737
+ tools(): readonly {
2738
+ readonly extension: Extension<Tool>;
2739
+ readonly tool: Tool;
2740
+ }[];
2741
+ sections(): readonly {
2742
+ readonly extension: Extension<Tool>;
2743
+ readonly section: PromptSection<Tool>;
2744
+ }[];
2745
+ /** Built-in and installed task definitions. */
2746
+ tasks(): readonly AnyTask[];
2747
+ task(name: string): AnyTask | undefined;
2748
+ }
2749
+ /** Read side of a registry consumed by a Harness. */
2750
+ interface RegistryReader<Tool extends ToolRegistration = ToolRegistration> {
2751
+ /** Immutable view of the whole current registry. */
2752
+ snapshot(): RegistrySnapshot<Tool>;
2753
+ /** Called synchronously after every publication; wakes the scheduler to reconsider blocked tasks. */
2754
+ subscribe(listener: () => void): () => void;
2755
+ }
2756
+ /** A change to `pi.agent`: a given field replaces the stored one, `null` clears it, `undefined` changes nothing. */
2757
+ type AgentChange = {
2758
+ readonly model?: ModelRef | null;
2759
+ readonly thinkingLevel?: ModelThinkingLevel | null;
2760
+ readonly extensions?: readonly Extension[] | {
2761
+ readonly add?: readonly Extension[];
2762
+ readonly remove?: readonly Extension[];
2763
+ } | null;
2764
+ readonly tools?: readonly ToolRegistration[] | {
2765
+ readonly remove: readonly ToolRegistration[];
2766
+ } | null;
2767
+ /** Replaces the stored filter as a whole; tools loaded with `control.addTools` are in its `add`. */
2768
+ readonly modelTools?: readonly ToolRegistration[] | {
2769
+ readonly remove?: readonly ToolRegistration[];
2770
+ readonly add?: readonly ToolRegistration[];
2771
+ } | null;
2772
+ readonly instructions?: string | null;
2773
+ readonly cwd?: string | null;
2774
+ /** `configure()` throws a `RangeError` unless it is an integer `1` or more (or `null`). */
2775
+ readonly maxTurns?: number | null;
2776
+ /** Replaces the stored settings as a whole; `configure()` throws a `RangeError` unless every token count is an integer `0` or more. */
2777
+ readonly compaction?: CompactionSettings | null;
2778
+ };
2779
+ /** A conversation's agent resolved against a registry snapshot and the settings. */
2780
+ type Agent<Tool extends ToolRegistration = ToolRegistration> = {
2781
+ readonly model?: ModelRef;
2782
+ readonly thinkingLevel: ModelThinkingLevel;
2783
+ readonly extensions: readonly Extension<Tool>[];
2784
+ /** The tools a request offers, in order: enabled, callable by the model, and selected by `modelTools`. */
2785
+ readonly tools: readonly Tool[];
2786
+ /** The tools nested calls (`executeTool()`) resolve among, in order: enabled and callable by tools. */
2787
+ readonly callable: readonly Tool[];
2788
+ /** Enabled deferred tools the model may call and is not offered yet, in registry order: what `tool_search` loads. */
2789
+ readonly deferred: readonly Tool[];
2790
+ /** Extension sections, then `instructions` when set. */
2791
+ readonly sections: readonly PromptSection<Tool>[];
2792
+ readonly instructions?: string;
2793
+ readonly cwd?: string;
2794
+ /**
2795
+ * Tool rounds one run takes at most (`pi.live.run.turns`): the round that reaches it runs its tools, then the run ends
2796
+ * `unanswered` with `turn_limit`. An integer, `1` or more; unset, no limit. Task-owned children and forks inherit it.
2797
+ */
2798
+ readonly maxTurns?: number;
2799
+ /** This conversation's compaction settings over the harness's (`AgentState.compaction`). */
2800
+ readonly compaction?: CompactionSettings;
2801
+ };
2802
+ /**
2803
+ * Runs inside the creating commit, after the creation hook and the `agent` change. The conversation creation is already
2804
+ * a table write, so table reads here throw `ReadAfterWrite`; document access remains available.
2805
+ */
2806
+ type ConversationInit = (tx: Tx, conversationId: ConversationId) => void | Promise<void>;
2807
+ type ConversationCreateOptions = {
2808
+ readonly ownership: ConversationOwnership;
2809
+ /** Applied in the creating commit after the creation hook's copy, before `init`. */
2810
+ readonly agent?: AgentChange;
2811
+ readonly init?: ConversationInit;
2812
+ };
2813
+ /** Curated pi-ai request options; absent fields use pi-ai defaults. */
2814
+ type ConversationStreamOptions = {
2815
+ transport?: Transport;
2816
+ timeoutMs?: number;
2817
+ /** WebSocket connection/open handshake timeout; stream idleness uses `timeoutMs`. */
2818
+ websocketConnectTimeoutMs?: number;
2819
+ /** Custom token budgets for thinking levels on token-based providers. */
2820
+ thinkingBudgets?: ThinkingBudgets;
2821
+ /** Provider/SDK retries inside one request attempt. */
2822
+ maxRetries?: number;
2823
+ maxRetryDelayMs?: number;
2824
+ headers?: Record<string, string>;
2825
+ metadata?: JsonObject;
2826
+ cacheRetention?: CacheRetention;
2827
+ deferred?: boolean | {
2828
+ window?: "15m" | "1h" | "24h";
2829
+ };
2830
+ };
2831
+ /** Durable generation attempt retries; the JSON shape of pi-ai `RetryPolicy`. */
2832
+ type ConversationRetryPolicy = {
2833
+ enabled: boolean;
2834
+ maxRetries: number;
2835
+ baseDelayMs: number;
2836
+ maxAgentDelayMs?: number;
2837
+ };
2838
+ /** Automatic compaction thresholds (spec §8.7); manual compaction ignores `enabled`. */
2839
+ type CompactionPolicy = {
2840
+ /** Threshold and overflow compaction. */
2841
+ enabled: boolean;
2842
+ /** Room kept free for the answer: generation blocks to compact above `contextWindow - reserveTokens`. */
2843
+ reserveTokens: number;
2844
+ /** Approximate size of the recent context a summary keeps verbatim. */
2845
+ keepRecentTokens: number;
2846
+ /** Background compaction starts `backgroundTokens` below the blocking threshold; `0` disables it. */
2847
+ backgroundTokens: number;
2848
+ };
2849
+ /**
2850
+ * Compaction settings of the harness (`HarnessSettings.compaction`) or of one conversation (`AgentState.compaction`).
2851
+ * `modelOverrides` is keyed by exact `"provider/modelId"`; each field it sets replaces the general one for that model,
2852
+ * so small- and large-window models can share a harness.
2853
+ */
2854
+ type CompactionSettings = Partial<CompactionPolicy> & {
2855
+ readonly modelOverrides?: Readonly<Record<string, Partial<CompactionPolicy>>>;
2856
+ };
2857
+ /**
2858
+ * How often running progress is committed, and how long it may wait in memory before it is stored. Progress commits are
2859
+ * deferred (`CommitPersistence`): watches see each at once, and Storage gets them together, at the run's next phase
2860
+ * boundary or after `persistWithinMs`. A host can commit less often, so live answers and tool output appear in larger steps.
2861
+ */
2862
+ type ProgressPolicy = {
2863
+ /** Minimum pause between commits of the answer being generated. */
2864
+ partialIntervalMs: number;
2865
+ /** Minimum pause between commits of running tool output; large commits also pause in proportion to their size. */
2866
+ outputIntervalMs: number;
2867
+ /**
2868
+ * How long these commits, and other deferred commits without their own `withinMs`, may stay in memory before they are
2869
+ * stored (`CommitPersistence`); a crash loses at most about this much of an answer or of tool output. Default 1,000;
2870
+ * `Infinity` stores them only at the next commit that reads or writes their document and at close.
2871
+ */
2872
+ persistWithinMs: number;
2873
+ };
2874
+ /**
2875
+ * `entryId` of a blocking compaction's summary, or the `submissionId` of a conversation-owned compaction's summary
2876
+ * write; both absent when nothing was compacted.
2877
+ */
2878
+ type CompactionResult = {
2879
+ entryId?: EntryId;
2880
+ submissionId?: SubmissionId;
2881
+ };
2882
+ /** Harness-wide run policy. Read at every resolution and never copied; getters are fine. Synchronous: some readers run on the Session line. */
2883
+ type HarnessSettings = {
2884
+ /** Default extension selection; absent: every installed extension, in install order. */
2885
+ readonly extensions?: readonly Extension[];
2886
+ readonly stream?: ConversationStreamOptions;
2887
+ readonly retry?: Partial<ConversationRetryPolicy>;
2888
+ readonly compaction?: CompactionSettings;
2889
+ readonly progress?: Partial<ProgressPolicy>;
2890
+ readonly toolExecution?: ToolExecutionMode;
2891
+ readonly steeringMode?: QueueMode;
2892
+ readonly followUpMode?: QueueMode;
2893
+ /**
2894
+ * How long an inactive conversation keeps its last context read in memory, so its next run reads only newer entries.
2895
+ * Inactive: idle, or with all its live work parked (sleeping, waiting, or holding an outcome). Active conversations
2896
+ * always keep it; `0` drops it once the conversation is inactive.
2897
+ */
2898
+ readonly contextRetentionMs?: number;
2899
+ /**
2900
+ * How long a loaded document that no watch observes stays in memory after its last read or write;
2901
+ * the next access loads it from Storage. Observed documents always stay. Default ten minutes; `0` drops one right
2902
+ * after use; `Infinity` keeps them. Anything else that is not a number of milliseconds means the default.
2903
+ */
2904
+ readonly documentRetentionMs?: number;
2905
+ /**
2906
+ * What a run that fails (`model_error`, `no_model`, `interrupted`, `restart_limit`, `nothing_to_answer`,
2907
+ * `turn_limit`) does with the inputs queued behind it: `keep` leaves them queued until the next input or queued write, `continue` starts the
2908
+ * next run with them, as an answer would, and `withdraw` settles them `unanswered` with reason `run_failed`. Default
2909
+ * `keep`.
2910
+ */
2911
+ readonly afterFailedRun?: AfterFailedRun;
2912
+ /**
2913
+ * How many times in a row a task may be cut off by a crash, eviction, or reset (a close does not count) without
2914
+ * changing its state before it ends instead of running again: a tool call with an error result, a compaction failed
2915
+ * into `pi.live.compactionFailure`, a run with `pi.live.runFailure` reason `restart_limit`, any other task `faulted`
2916
+ * with detail `{ reason: "restart_limit" }`. A generation's request or poll the host died during is a failed attempt
2917
+ * under `retry` first; the limit bounds it only when charging that attempt keeps being cut off. Default 5;
2918
+ * `Infinity` never ends a task for it.
2919
+ */
2920
+ readonly restartLimit?: number;
2921
+ };
2922
+ /**
2923
+ * What a failed run does with the inputs queued behind it (`HarnessSettings.afterFailedRun`): a run that ends with
2924
+ * `model_error`, `no_model`, `interrupted`, `restart_limit`, `nothing_to_answer`, or `turn_limit`.
2925
+ */
2926
+ type AfterFailedRun = "keep" | "continue" | "withdraw";
2927
+ /** Resolved settings: every field over its built-in default, object fields merged. */
2928
+ type Settings = {
2929
+ /** Absent: every installed extension, in install order. */
2930
+ readonly extensions?: readonly Extension[];
2931
+ readonly stream: ConversationStreamOptions;
2932
+ readonly retry: ConversationRetryPolicy;
2933
+ /** Harness-wide policy over the defaults; per-model overrides apply where the model is known. */
2934
+ readonly compaction: CompactionPolicy & Pick<CompactionSettings, "modelOverrides">;
2935
+ readonly progress: ProgressPolicy;
2936
+ readonly toolExecution: ToolExecutionMode;
2937
+ readonly steeringMode: QueueMode;
2938
+ readonly followUpMode: QueueMode;
2939
+ readonly contextRetentionMs: number;
2940
+ readonly documentRetentionMs: number;
2941
+ readonly afterFailedRun: AfterFailedRun;
2942
+ readonly restartLimit: number;
2943
+ };
2944
+ /** What `HarnessOptions.env` builds an environment for. */
2945
+ type EnvTarget = {
2946
+ readonly conversationId: ConversationId;
2947
+ /** The conversation's agent `cwd`. */
2948
+ readonly cwd?: string;
2949
+ readonly read: DocumentReader;
2950
+ };
2951
+ type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {
2952
+ /** Host-owned adapter for content-free admission/phase telemetry; propagation and metrics are optional. */
2953
+ readonly telemetry?: TelemetryContext;
2954
+ /**
2955
+ * pi-ai model access used by generation, compaction, hooks and tools: a `Models`, or a function returning the current
2956
+ * one, called at each use, so a host can replace its model configuration without reopening the Harness.
2957
+ */
2958
+ readonly models: Models | (() => Models);
2959
+ /**
2960
+ * How model requests identify the app to providers, merged field by field over `DEFAULT_HARNESS_IDENTITY`
2961
+ * (`{ attribution: PI_ATTRIBUTION }`, provider attribution to pi). It applies to every request through the Harness's
2962
+ * models, including hooks and tools, and overrides the identity the `Models` was created with; a request's own
2963
+ * `identity` overrides it. Pass `{ attribution: null }` to send no attribution headers.
2964
+ */
2965
+ readonly identity?: ClientIdentity;
2966
+ readonly registry: RegistryReader<Tool>;
2967
+ /** Run settings, or a function returning the current ones; read at each use either way. */
2968
+ readonly settings?: HarnessSettings | (() => HarnessSettings | undefined);
2969
+ /** Builds a conversation's environment at each use. Never called on the Session line; may be async. */
2970
+ readonly env?: (target: EnvTarget, context: Context$1) => ExecutionEnv | undefined | Promise<ExecutionEnv | undefined>;
2971
+ /**
2972
+ * Runs in every commit that creates or forks a conversation, raw `tx.createConversation()` included, after the
2973
+ * built-in `pi.*` documents and before the conveniences apply `agent` and run `init`. A fork already has its copies.
2974
+ * Table reads throw `ReadAfterWrite`, as in `init`; a throw fails the creating commit.
2975
+ */
2976
+ readonly conversationCreated?: (tx: Tx, conversation: ConversationRecord) => void | Promise<void>;
2977
+ /**
2978
+ * The Harness clock, epoch milliseconds; default `Date.now`. Sleeping tasks store deadlines on it, so every process
2979
+ * that opens the same storage must use the same clock.
2980
+ */
2981
+ readonly now?: () => number;
2982
+ /**
2983
+ * Arms the timers of the Session, the scheduler, and its tasks: pacing progress commits, freeing idle memory
2984
+ * (`background`), and, without `onWake`, resuming sleeping tasks; and the timers of `TaskRuntime.setTimer()`. The
2985
+ * Node.js environment, file watcher, and image worker keep their own timers. Default `setTimeout`, with background
2986
+ * timers unreferenced, or declined in Cloudflare Workers and where they cannot be unreferenced. Tests can pass fake
2987
+ * timers; a host can keep timers off a process that should hibernate.
2988
+ */
2989
+ readonly setTimer?: SetTimer;
2990
+ /**
2991
+ * Wakes the process for sleeping tasks instead of a `setTimer` timer. Without it, while scheduling runs, a timer that
2992
+ * keeps the process alive resumes sleeping tasks when they are due. With it, the Harness arms no timer for them: it
2993
+ * calls `onWake` after open and whenever `Harness.wake()` changes, and the host arms its own wakeup, such as a
2994
+ * Durable Object alarm, and calls `resume()` when it fires. Called in a microtask the Session line never waits for,
2995
+ * after the commit that changed the value was adopted, so a host arms a recovery wakeup before calls that can start
2996
+ * work. It may call `wake()` and `resume()`, and must not block. A throw is reported, and the value is offered again
2997
+ * at the next change.
2998
+ */
2999
+ readonly onWake?: (wake: Wake) => void;
3000
+ /**
3001
+ * Receives failures that do not fail the calling operation, such as a throwing hook or listener, a task that faulted,
3002
+ * and the error that fails the Session, once: one `Report`, the `error` and what happened (`kind` and the fields of
3003
+ * its `ReportInfo`). A host can tell a failed Session (`storage_failed`, often a platform reset) from a faulted task
3004
+ * (`task_faulted`). Its own throw or rejection is dropped.
3005
+ */
3006
+ readonly onReport?: (report: Report) => void;
3007
+ /**
3008
+ * Open for reading only, as a viewer of a session that another process drives, for example a synced copy on a device
3009
+ * that only shows it. Open recovers nothing: a `running` task stays as committed. Every commit with writes rejects
3010
+ * with `ReadOnlySession` before it reaches Storage, and so does `resume()` and every call that enables scheduling;
3011
+ * the Harness stays usable for reads and watches. `wake()` is always inactive, and `onWake` is never called. Reopen
3012
+ * without it to write.
3013
+ */
3014
+ readonly readOnly?: boolean;
3015
+ };
3016
+ /**
3017
+ * When a Session next needs a running process (`Harness.wake()`). `active`: some task can run now or is running, or a
3018
+ * reconcile pass such as open's recovery has not landed yet, so a process that dies must be woken again soon, for
3019
+ * example by a recovery alarm. `at`: the earliest sleep not yet due,
3020
+ * when there is one. Neither: nothing needs a process until new work is submitted. Tasks blocked on a missing or
3021
+ * unmigratable definition, `completing` tasks, and waits on live tasks do not count; the work they wait for does.
3022
+ */
3023
+ type Wake = {
3024
+ readonly active: boolean;
3025
+ readonly at?: number;
3026
+ };
3027
+ /** Live task and what the scheduler would do with it under the current registry. */
3028
+ type TaskInspection = {
3029
+ readonly record: TaskRecord<JsonValue$1, JsonValue$1, JsonValue$1>;
3030
+ readonly state: {
3031
+ readonly kind: "running";
3032
+ }
3033
+ /** The next scheduling pass reserves it; `migrates` when its definition is newer and has `migrate`. */
3034
+ | {
3035
+ readonly kind: "pending";
3036
+ readonly migrates: boolean;
3037
+ }
3038
+ /**
3039
+ * Waits for these live tasks: the live part of its `on`, or, when abort-marked, its live ordinary owned work, which
3040
+ * must end before its abort handler starts.
3041
+ */
3042
+ | {
3043
+ readonly kind: "waiting";
3044
+ readonly on: readonly TaskId[];
3045
+ }
3046
+ /** Sleeps until the Harness clock reaches `until`, if set, or a signal it sleeps on arrives. */
3047
+ | {
3048
+ readonly kind: "sleeping";
3049
+ readonly until?: number;
3050
+ }
3051
+ /** Outcome held until its ordinary owned work drains. */
3052
+ | {
3053
+ readonly kind: "completing";
3054
+ }
3055
+ /** Cannot run here: no registered definition can take it (aborting it settles it as `orphaned`). */
3056
+ | {
3057
+ readonly kind: "blocked";
3058
+ readonly reason: "missing_task" | "task_too_old" | "migration_failed";
3059
+ readonly error?: unknown;
3060
+ };
3061
+ };
3062
+ /** Point-in-time view of live work: unfinished tasks and submissions, read on the Session line. */
3063
+ type HarnessInspection = {
3064
+ readonly scheduling: "paused" | "running" | "closing";
3065
+ readonly tasks: readonly TaskInspection[];
3066
+ /** Queued and placed submissions, in ID order. */
3067
+ readonly submissions: readonly SubmissionRecord[];
3068
+ };
3069
+ /** Raw active transcript and derived model context. */
3070
+ type ContextView = {
3071
+ /** Newest applicable head marker, if any. */
3072
+ readonly head: EntryRecord | undefined;
3073
+ /** Raw active entries: the head marker followed by non-head entries from its head through the tail. */
3074
+ readonly entries: readonly EntryRecord[];
3075
+ /** Per entry of `entries`, its model messages after edits and excluded stop reasons, before tool result ordering. */
3076
+ readonly contributions: readonly (readonly Message[])[];
3077
+ /** Model context for the next provider request. */
3078
+ readonly messages: readonly Message[];
3079
+ };
3080
+ /** Stateless handle for one conversation, bound to the Harness that returned it. Compare handles by `id`. */
3081
+ interface Conversation {
3082
+ readonly id: ConversationId;
3083
+ /** Resolved with the current registry snapshot and settings. */
3084
+ agent(context: Context$1): Promise<Agent>;
3085
+ /** `configure()` in its own commit. */
3086
+ configure(change: AgentChange, context: Context$1): Promise<void>;
3087
+ /**
3088
+ * Durably admit user input, a passive entry write, or a continue. A busy conversation, or one with queued items,
3089
+ * queues input and writes that affect model context in `pi.inbox`; `whenBusy: "reject"` rejects input with
3090
+ * `ConversationBusy` instead and writes nothing. An idle conversation rejects `whenIdle: "reject"` input with
3091
+ * `ConversationIdle` and writes nothing. A write of only `kind` and `data` (no `model`, `head`, or `edits`)
3092
+ * is appended at once, even mid-run, as it changes nothing the model sees. A continue starts a run on the context as
3093
+ * it is, after placing queued items; a busy conversation rejects it with `ConversationBusy`, as it never queues.
3094
+ */
3095
+ submit(submission: SubmissionDraft, context: Context$1): Promise<Submission>;
3096
+ /**
3097
+ * Admit a submission inside the caller's commit `tx` (`Harness.commit()`, `Conversation.commit()`, a task's
3098
+ * `runtime.commit()`), with the same rules, and return its ID: the admission is stored with that commit, or not at all
3099
+ * when the callback throws later or the commit fails. Call it before the commit's first table write (`appendEntry()`,
3100
+ * `createTask()`, `createSubmission()`, another admission): otherwise it throws `ReadAfterWrite`, on every path.
3101
+ * Documents may be read and written before and after it. A rejection (`ConversationBusy`, `ConversationIdle`) throws
3102
+ * before any write, so the callback may catch it. Do not call `Submission` or other Harness reads inside the callback:
3103
+ * they wait for the commit holding the line. Its `pi.durable.submit` span covers the admission only, so its `result`
3104
+ * is provisional. Throws for a transaction of another Session.
3105
+ */
3106
+ submit(tx: Tx, submission: SubmissionDraft): Promise<SubmissionId>;
3107
+ /**
3108
+ * Admit a write of a `pi.reset` entry that starts a new context, carrying `handoff` as a user message when given.
3109
+ * Resolves after admission; while busy, it is placed at the next boundary.
3110
+ */
3111
+ reset(handoff: string | undefined, context: Context$1): Promise<void>;
3112
+ /**
3113
+ * Admit a manual compaction task and return its ID. It summarizes while the conversation keeps working and places its
3114
+ * summary through a write submission: at once when idle, otherwise at the next boundary (spec §8.7).
3115
+ */
3116
+ compact(instructions: string | undefined, context: Context$1): Promise<TaskId<CompactionResult>>;
3117
+ /** Session commit whose `tx.createTask()` defaults to this conversation; `options` as for `Session.commit()`. */
3118
+ commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context$1, options?: CommitOptions): Promise<T>;
3119
+ /**
3120
+ * Committed raw active transcript and model context. With `at`, the context as of that visible entry: the same view
3121
+ * `fork(at)` would start with, without creating a conversation.
3122
+ */
3123
+ context(context: Context$1, options?: {
3124
+ readonly at?: EntryId;
3125
+ }): Promise<ContextView>;
3126
+ /** Fork-aware history of this conversation, newest first unless `query.order` is `ascending`. */
3127
+ entries(query: Omit<EntryQuery, "conversationId">, limit: number, cursor: Cursor | undefined, context: Context$1): Promise<Page<EntryRecord, Cursor>>;
3128
+ fork(at: EntryId, options: ConversationCreateOptions, context: Context$1): Promise<Conversation>;
3129
+ /**
3130
+ * Withdraw queued inputs (queued writes stay), mark every live non-background task of the ordinary ownership scope,
3131
+ * signal them, and resolve once the scope is idle. Background subtrees survive unless `background` is set.
3132
+ */
3133
+ abort(context: Context$1, options?: ConversationAbortOptions): Promise<void>;
3134
+ /**
3135
+ * Resolve when the ordinary ownership scope has no live non-background task: this conversation and the conversations
3136
+ * owned, transitively, by its non-background tasks.
3137
+ */
3138
+ waitForIdle(context: Context$1): Promise<void>;
3139
+ /**
3140
+ * The structural view (spec §9.3) as a serialized watch; commits made while its listener runs arrive folded. Its
3141
+ * `entries` are a window over the transcript, as `window` says: the newest 50 by default, then appends, dropping the
3142
+ * oldest past 100. Built on the same mount as `Harness.observeConversation()`.
3143
+ */
3144
+ watch(context: Context$1, window?: ConversationWindow): Promise<ConversationWatch>;
3145
+ }
3146
+ type ConversationWatch = WatchHandle<ConversationView>;
3147
+ /** Durable agent harness over one Session. */
3148
+ interface Harness$1 extends Session {
3149
+ /**
3150
+ * Enable task scheduling. Idempotent; throws after close, and `ReadOnlySession` on a read-only Harness. Calls that
3151
+ * ask for progress enable it too: `Conversation.submit()`, `Conversation.compact()`, `Conversation.abort()`,
3152
+ * `Submission.wait()`, `waitForTask()`, `Harness.waitForIdle()`, and `Conversation.waitForIdle()`. Read-only viewers
3153
+ * never do.
3154
+ */
3155
+ resume(): void;
3156
+ /**
3157
+ * When this Session next needs a running process, from the scheduler's memory: `active` while some task can run now
3158
+ * or is running, `at` for the earliest sleep. Answers also while scheduling is paused. A host that wakes the
3159
+ * process itself, such as a Durable Object alarm, arms from it and calls `resume()` when woken; see
3160
+ * `HarnessOptions.onWake`.
3161
+ */
3162
+ wake(): Wake;
3163
+ /** Return the reserved root conversation, creating it with `agent` and `init` in one commit when absent. */
3164
+ root(context: Context$1, options?: {
3165
+ readonly agent?: AgentChange;
3166
+ readonly init?: ConversationInit;
3167
+ }): Promise<Conversation>;
3168
+ conversation(id: ConversationId, context: Context$1): Promise<Conversation | undefined>;
3169
+ createConversation(options: ConversationCreateOptions, context: Context$1): Promise<Conversation>;
3170
+ getTask<R>(id: TaskId<R>, context: Context$1): Promise<TaskRecord<JsonValue$1, JsonValue$1, R> | undefined>;
3171
+ /** Live tasks and unsettled submissions. Writes nothing and runs no task code. */
3172
+ inspect(context: Context$1): Promise<HarnessInspection>;
3173
+ /** Reacquire a submission, for example after reopen. */
3174
+ submission(id: SubmissionId, context: Context$1): Promise<Submission | undefined>;
3175
+ /** `not_found` for an unknown submission or one of another conversation than `conversationId`. */
3176
+ abortSubmission(id: SubmissionId, context: Context$1, conversationId?: ConversationId): Promise<"aborted" | "already_placed" | "settled" | "not_found">;
3177
+ /**
3178
+ * Commit the abort mark, signal and join an active run invocation, and schedule the abort invocation. A task whose
3179
+ * definition cannot take it settles as `orphaned` instead.
3180
+ */
3181
+ abortTask(id: TaskId, context: Context$1): Promise<"marked" | "terminal">;
3182
+ /**
3183
+ * `tx.signal()` in a commit of its own: deliver `value` to task `taskId` under `key`. Enables scheduling, so a host
3184
+ * arms its recovery wakeup first, as before `submit()`. Checks nothing about the caller.
3185
+ */
3186
+ signal<T>(taskId: TaskId, token: SignalToken<T>, key: string, value: T, context: Context$1): Promise<SignalResult>;
3187
+ /** Resolve with the terminal receipt; cancelling `context` cancels only this wait. */
3188
+ waitForTask<R>(id: TaskId<R>, context: Context$1): Promise<SettledTask<R>>;
3189
+ /** Resolve when the ordinary ownership scope of every ownerless conversation has no live non-background task. */
3190
+ waitForIdle(context: Context$1): Promise<void>;
3191
+ /** Session total: every conversation's `pi.usage` summed. */
3192
+ usage(context: Context$1): Promise<UsageState>;
3193
+ /**
3194
+ * Every live task with its owner edge, status, and owned conversations (spec §9.4), as a serialized watch; commits
3195
+ * made while its listener runs arrive folded.
3196
+ */
3197
+ watchTaskGraph(context: Context$1): Promise<TaskGraphWatch>;
3198
+ /**
3199
+ * Attach a synchronous `Observer` to a conversation's structural view (spec §9.3), atomically on the Session line,
3200
+ * for adapters: `advance` gets each next revision with its operations as memory adopts the commit, inside Storage's
3201
+ * `adopt` for a stored one and before it is stored for a deferred one, so it only records it. `window` as for
3202
+ * `Conversation.watch()`; each observer has its own. `context` governs only the attachment.
3203
+ */
3204
+ observeConversation(id: ConversationId, observer: Observer<ConversationView>, context: Context$1, window?: ConversationWindow): Promise<Observation<ConversationView>>;
3205
+ /**
3206
+ * Attach a synchronous `Observer` to the task graph (spec §9.4), as `observeConversation()` does to a view. A
3207
+ * `blocked` reason that changes without a commit (a registry change, a failed migration) advances it on the Session
3208
+ * line outside any commit and `adopt`, with the background context.
3209
+ */
3210
+ observeTaskGraph(observer: Observer<TaskGraph>, context: Context$1): Promise<Observation<TaskGraph>>;
3211
+ }
3212
+
3213
+ /** JSON object used as the root of every durable document. */
3214
+ type JsonObject = {
3215
+ [key: string]: JsonValue$1;
3216
+ };
3217
+ declare const idBrand: unique symbol;
3218
+ /** Erased nominal number identifying one durable record kind. */
3219
+ type Id<Kind extends string, Type = unknown> = number & {
3220
+ readonly [idBrand]: {
3221
+ readonly kind: Kind;
3222
+ readonly type: Type;
3223
+ };
3224
+ };
3225
+ type ConversationId = Id<"conversation">;
3226
+ type EntryId = Id<"entry">;
3227
+ type TaskId<Result = unknown> = Id<"task", Result>;
3228
+ type SubmissionId = Id<"submission">;
3229
+ type DocumentId = Id<"document">;
3230
+ declare const seqBrand: unique symbol;
3231
+ /** Strictly increasing sequence assigned to one atomic storage commit; gaps are permitted. */
3232
+ type Seq = number & {
3233
+ readonly [seqBrand]: "sequence";
3234
+ };
3235
+ /** Conversation document that retains only its current state. */
3236
+ type LatestConversationSemantics = {
3237
+ readonly scope: "conversation";
3238
+ readonly history: "latest";
3239
+ readonly fork: "current" | "initial";
3240
+ };
3241
+ /** Conversation document whose history remains addressable for as-of reads. */
3242
+ type RewindableConversationSemantics = {
3243
+ readonly scope: "conversation";
3244
+ readonly history: "rewindable";
3245
+ readonly fork: "asOf" | "current" | "initial";
3246
+ };
3247
+ /** Ownership and lifetime of a document; only conversation documents declare history and fork behavior. */
3248
+ type DocumentSemantics = {
3249
+ readonly scope: "session";
3250
+ readonly history?: never;
3251
+ readonly fork?: never;
3252
+ } | LatestConversationSemantics | RewindableConversationSemantics | {
3253
+ readonly scope: "task";
3254
+ readonly history?: never;
3255
+ readonly fork?: never;
3256
+ };
3257
+ /** Stored replay state supplied to a document's checkpoint predicate. */
3258
+ type CheckpointInfo = {
3259
+ /** Deltas already stored after the newest base, excluding the change being evaluated. */
3260
+ readonly deltasSinceBase: number;
3261
+ };
3262
+ /** Definition fields shared by singleton documents and document families. */
3263
+ type CommonDocDefinition<T extends JsonObject> = {
3264
+ /** Stable persisted kind; part of the public protocol. */
3265
+ readonly kind: string;
3266
+ /** Positive integer version of the stored value shape. */
3267
+ readonly version: number;
3268
+ initial(): T;
3269
+ migrate?(value: JsonObject, fromVersion: number): T;
3270
+ /** Required policy: return true to store this ordinary change as a complete base instead of a delta. */
3271
+ checkpointWhen(value: Readonly<T>, ops: readonly Op[], info: CheckpointInfo): boolean;
3272
+ };
3273
+ /** Singleton document definition. */
3274
+ type DocDefinition<T extends JsonObject> = CommonDocDefinition<T> & DocumentSemantics;
3275
+ /** Keyed document family definition; `initial(seed)` runs only when a member is absent. */
3276
+ type DocFamilyDefinition<T extends JsonObject, I extends JsonValue$1> = Omit<CommonDocDefinition<T>, "initial"> & DocumentSemantics & {
3277
+ readonly family: true;
3278
+ initial(seed: I): T;
3279
+ };
3280
+ declare const docType: unique symbol;
3281
+ /** Typed singleton document token passed explicitly to typed access. */
3282
+ interface DocToken<T extends JsonObject, D extends DocDefinition<T>> {
3283
+ readonly definition: D;
3284
+ readonly [docType]?: T;
3285
+ }
3286
+ /** Typed document family token passed explicitly to typed access. */
3287
+ interface DocFamilyToken<T extends JsonObject, I extends JsonValue$1, D extends DocFamilyDefinition<T, I>> {
3288
+ readonly definition: D;
3289
+ readonly [docType]?: T;
3290
+ }
3291
+ type SessionDocToken<T extends JsonObject> = DocToken<T, CommonDocDefinition<T> & {
3292
+ readonly scope: "session";
3293
+ }>;
3294
+ type ConversationDocToken<T extends JsonObject> = DocToken<T, CommonDocDefinition<T> & (LatestConversationSemantics | RewindableConversationSemantics)>;
3295
+ type RewindableConversationDocToken<T extends JsonObject> = DocToken<T, CommonDocDefinition<T> & RewindableConversationSemantics>;
3296
+ type TaskDocToken<T extends JsonObject> = DocToken<T, CommonDocDefinition<T> & {
3297
+ readonly scope: "task";
3298
+ }>;
3299
+ type SessionDocFamilyToken<T extends JsonObject, I extends JsonValue$1> = DocFamilyToken<T, I, DocFamilyDefinition<T, I> & {
3300
+ readonly scope: "session";
3301
+ }>;
3302
+ type ConversationDocFamilyToken<T extends JsonObject, I extends JsonValue$1> = DocFamilyToken<T, I, DocFamilyDefinition<T, I> & (LatestConversationSemantics | RewindableConversationSemantics)>;
3303
+ type RewindableConversationDocFamilyToken<T extends JsonObject, I extends JsonValue$1> = DocFamilyToken<T, I, DocFamilyDefinition<T, I> & RewindableConversationSemantics>;
3304
+ type TaskDocFamilyToken<T extends JsonObject, I extends JsonValue$1> = DocFamilyToken<T, I, DocFamilyDefinition<T, I> & {
3305
+ readonly scope: "task";
3306
+ }>;
3307
+ /** The task a report is about. */
3308
+ type ReportTask = {
3309
+ readonly id: TaskId;
3310
+ /** The task's registered name. */
3311
+ readonly kind: string;
3312
+ readonly conversationId: ConversationId;
3313
+ };
3314
+ /**
3315
+ * A host callback, by its `HarnessOptions` name; `env` is the environment builder, `models` a provider call, and
3316
+ * `telemetry` a telemetry adapter call made while a commit is published, which must not fail it.
3317
+ */
3318
+ type HostCallback = "now" | "settings" | "registry" | "env" | "models" | "setTimer" | "onWake" | "telemetry";
3319
+ /**
3320
+ * What a report to `HarnessOptions.onReport` is about, by `kind` (`Report` adds the error). `extension`, where present,
3321
+ * names the extension whose code failed, when known; for a task's own code, the one that installed the definition the
3322
+ * task ran.
3323
+ * - `storage_failed`: the error failed the Session, which closes: a Storage error, often a platform reset.
3324
+ * - `task_faulted`: the task ended `faulted`: its phase threw (`reason: "threw"`), or its abort handler was cut off
3325
+ * `settings.restartLimit` times (`reason: "restart_limit"`), as was a phase of a task of an extension's kind.
3326
+ * - `task_interrupted`: crashes ended the task: it ended itself after being cut off `settings.restartLimit` times in a
3327
+ * row (`reason: "restart_limit"`; a tool call, a compaction, a generation), or a generation's run ended because the
3328
+ * host kept stopping while the model answered (`reason: "interrupted"`). `restarts` is the task's count when it ended.
3329
+ * - `migration_failed`: the task's stored state could not be migrated; it is blocked until the registry changes.
3330
+ * - `task_outdated`: a running task keeps running under its old definition, which was uninstalled (`missing_task`)
3331
+ * or replaced by one that cannot take over its state: older than the task (`task_too_old`), or newer without a
3332
+ * `migrate` (`migration_failed`).
3333
+ * - `task_error`: the task's own `runtime.report()`, or a failure in running it.
3334
+ * - `extension_error`: a hook, a section, a wrapper, or a tool's invalid structured output; with the task that ran it,
3335
+ * or, outside a task, the conversation whose agent was resolved.
3336
+ * - `host_error`: a host callback threw; with the task that called it, if one did.
3337
+ * - `listener_error`: a commit, close, watch, view, or document listener threw.
3338
+ */
3339
+ type ReportInfo = {
3340
+ readonly kind: "storage_failed";
3341
+ } | {
3342
+ readonly kind: "task_faulted";
3343
+ readonly task: ReportTask;
3344
+ readonly extension?: string;
3345
+ readonly reason: "threw" | "restart_limit";
3346
+ } | {
3347
+ readonly kind: "task_interrupted";
3348
+ readonly task: ReportTask;
3349
+ readonly extension?: string;
3350
+ readonly reason: "restart_limit" | "interrupted";
3351
+ readonly restarts: number;
3352
+ } | {
3353
+ readonly kind: "migration_failed";
3354
+ readonly task: ReportTask;
3355
+ readonly extension?: string;
3356
+ } | {
3357
+ readonly kind: "task_outdated";
3358
+ readonly task: ReportTask;
3359
+ readonly extension?: string;
3360
+ readonly reason: "missing_task" | "task_too_old" | "migration_failed";
3361
+ } | {
3362
+ readonly kind: "task_error";
3363
+ readonly task: ReportTask;
3364
+ readonly extension?: string;
3365
+ } | {
3366
+ readonly kind: "extension_error";
3367
+ readonly extension?: string;
3368
+ readonly task?: ReportTask;
3369
+ readonly conversationId?: ConversationId;
3370
+ } | {
3371
+ readonly kind: "host_error";
3372
+ readonly callback: HostCallback;
3373
+ readonly task?: ReportTask;
3374
+ } | {
3375
+ readonly kind: "listener_error";
3376
+ };
3377
+ /** One report to `HarnessOptions.onReport`: what it is about (`ReportInfo`, by `kind`) and the `error` reported. */
3378
+ type Report = ReportInfo & {
3379
+ readonly error: unknown;
3380
+ };
3381
+ /** Whose code a task's `runtime.report()` is about when not the task's own: an extension's, or a host callback. */
3382
+ type ReportFrom = {
3383
+ readonly kind: "extension";
3384
+ readonly extension?: string;
3385
+ } | {
3386
+ readonly kind: "host";
3387
+ readonly callback: HostCallback;
3388
+ };
3389
+ /**
3390
+ * A host timer, given as `HarnessOptions.setTimer`: call `callback` once, about `delayMs` from now, and return
3391
+ * a function that disarms it. `background` timers only free memory, and a host may decline one by returning
3392
+ * `undefined`, for example where a pending timer keeps the process from hibernating; the Harness then frees that memory
3393
+ * at later commits. Other timers pace or resume work: one the host throws on or declines is armed with `setTimeout`.
3394
+ * A timer should not fire early; callers check their clock again when it fires.
3395
+ */
3396
+ type SetTimer = (callback: () => void, delayMs: number, options: {
3397
+ readonly background: boolean;
3398
+ }) => (() => void) | undefined;
3399
+ /** Live task record reserved by one invocation. */
3400
+ type RunningTask<I, S, R> = TaskRecord<I, S, R> & {
3401
+ readonly state: Extract<TaskState<S, R>, {
3402
+ readonly status: "running";
3403
+ }>;
3404
+ };
3405
+ /**
3406
+ * Next state a task commits for itself: a replacement checkpoint, a wait on tasks, a sleep, or its outcome. A returned `terminal` state is
3407
+ * stored as `completing` while ordinary owned work below the task is live (spec §5.5). A task never writes its own
3408
+ * `wake`: a commit of the same checkpoint keeps it, any other state drops it.
3409
+ */
3410
+ type NextTaskState<S, R> = {
3411
+ readonly status: "running";
3412
+ readonly checkpoint: S;
3413
+ readonly wake?: never;
3414
+ readonly outcome?: never;
3415
+ } | Extract<TaskState<S, R>, {
3416
+ readonly status: "waiting" | "sleeping" | "terminal";
3417
+ }>;
3418
+ /**
3419
+ * Runs one checkpoint phase. It must commit a changed checkpoint or a terminal outcome through `runtime.commit()`;
3420
+ * returning without durable progress faults the task.
3421
+ */
3422
+ type PhaseHandler<I, P, S, R, H extends object> = (task: RunningTask<I, P, R>, runtime: TaskRuntime<I, S, R, H>, context: Context$1) => Promise<void>;
3423
+ /** Dispatches one hook of a task to every matching registered handler, in registry order of the phase snapshot. */
3424
+ interface HookRunner<H extends object> {
3425
+ /**
3426
+ * Call `invoke` with each matching handler named `name`. An ordinary throw from `invoke` is reported and the next
3427
+ * handler runs; once the invocation is signalled, the error propagates. Composition happens inside `invoke`.
3428
+ */
3429
+ each<K extends keyof H>(name: K, invoke: (handler: NonNullable<H[K]>) => void | Promise<void>): Promise<void>;
3430
+ }
3431
+ /**
3432
+ * Operations of one task invocation. Every operation rejects after the invocation ends; watches acquired through it
3433
+ * stop at invocation end.
3434
+ */
3435
+ interface TaskRuntime<I, S, R, H extends object> extends DocumentObserver, DocumentReader {
3436
+ readonly taskId: TaskId<R>;
3437
+ readonly conversationId: ConversationId;
3438
+ /**
3439
+ * Aborted when the run is signalled by `abortTask()`, the Harness closes, or the invocation ends. Work still using it
3440
+ * after the invocation ended, such as a detached wait, is cancelled; it could not write anything anyway.
3441
+ */
3442
+ readonly signal: AbortSignal;
3443
+ /** Registry snapshot of the current phase; refreshed at every phase boundary. */
3444
+ readonly registry: RegistrySnapshot;
3445
+ /** The task's conversation's agent, resolved at most once per phase, at first use, and fixed for the phase. */
3446
+ agent(context: Context$1): Promise<Agent>;
3447
+ /** `HarnessOptions.settings`, resolved at each access. */
3448
+ readonly settings: Settings;
3449
+ /** `HarnessOptions.models`, resolved at each access. */
3450
+ readonly models: Models;
3451
+ /** Calls `HarnessOptions.env` for the task's conversation; rejects with its error. */
3452
+ env(context: Context$1): Promise<ExecutionEnv | undefined>;
3453
+ /** Handlers of this task's name from the extensions its conversation selects, in extension order. */
3454
+ readonly hooks: HookRunner<H>;
3455
+ /**
3456
+ * Commit on the Session line after rereading the task. Rejects when the task is terminal, the invocation ended, the
3457
+ * Harness is closing, or, in a run invocation, the task carries an abort mark. A returned state replaces the task's
3458
+ * state in the same commit; returning nothing leaves it unchanged. `tx.createTask()` defaults to the task's
3459
+ * conversation. Inside the callback read only through `tx`: `snapshot()`, `watchDoc()`, `getTask()`, and the other Session and runtime reads may queue on the line the callback holds, and then never resolve.
3460
+ * `options.persistence` may defer storing a commit that changes only documents (`CommitPersistence`); one that returns
3461
+ * a state is immediate.
3462
+ */
3463
+ commit(change: (tx: Tx, current: RunningTask<I, S, R>) => NextTaskState<S, R> | undefined | Promise<NextTaskState<S, R> | undefined>, context: Context$1, options?: CommitOptions): Promise<void>;
3464
+ /** Read a durable memo of this task. */
3465
+ memo<T extends JsonValue$1>(name: string, context: Context$1): Promise<T | undefined>;
3466
+ /** Store `candidate` unless a memo already exists; return the durable winner. */
3467
+ memo<T extends JsonValue$1>(name: string, candidate: T, context: Context$1): Promise<T>;
3468
+ /**
3469
+ * A signal key's committed state, the value migrated to the token's version; undefined while nothing came. Throws when
3470
+ * the stored value cannot be migrated or the migrated value does not match the schema.
3471
+ */
3472
+ readSignal<T>(token: SignalToken<T>, key: string, context: Context$1): Promise<SignalState<T> | undefined>;
3473
+ /** Committed task record. */
3474
+ getTask<T>(id: TaskId<T>, context: Context$1): Promise<TaskRecord<JsonValue$1, JsonValue$1, T> | undefined>;
3475
+ /** Resolve with the task's terminal receipt; rejects when the invocation ends. */
3476
+ waitForTask<T>(id: TaskId<T>, context: Context$1): Promise<SettledTask<T>>;
3477
+ /**
3478
+ * Abort a task this task owns, as `Harness.abortTask()` does, and resolve once it is terminal. Rejects for a task
3479
+ * another owns; resolves at once for a terminal one.
3480
+ */
3481
+ abortOwned(id: TaskId, context: Context$1): Promise<void>;
3482
+ /**
3483
+ * Live tasks this task owns directly, in ID order: also those an earlier invocation created, before a restart. Tasks
3484
+ * in conversations it owns are not included. Copies of the committed records.
3485
+ */
3486
+ ownedTasks(context: Context$1): Promise<TaskRecord<JsonValue$1, JsonValue$1, JsonValue$1>[]>;
3487
+ /** Outcomes of terminal tasks, in order; rejects when one is missing or not terminal. Used after a wait. */
3488
+ outcomes<T>(ids: readonly TaskId<T>[], context: Context$1): Promise<TaskOutcome<T>[]>;
3489
+ /**
3490
+ * Invocation-bound handle of an existing conversation, for example one this task owns; `undefined` when absent. Its
3491
+ * operations and the submissions it returns reject after the invocation ends; admitted work stays durable.
3492
+ */
3493
+ conversation(id: ConversationId, context: Context$1): Promise<ConversationHandle | undefined>;
3494
+ /** Committed entry visible from the task's conversation. */
3495
+ entry(id: EntryId, context: Context$1): Promise<EntryRecord | undefined>;
3496
+ /** Undefined when the entry is absent, not visible, or has another kind. */
3497
+ entry<D extends JsonValue$1>(token: Entry<D>, id: EntryId, context: Context$1): Promise<TypedEntry<D> | undefined>;
3498
+ /**
3499
+ * Committed raw history of the task's conversation, fork-aware, as `Conversation.entries()`: every entry, also those a
3500
+ * compaction summary or reset left behind. Entries never change, so a range bounded by entry IDs reads the same
3501
+ * before and after a compaction, and in a rerun after a crash.
3502
+ */
3503
+ entries(query: Omit<EntryQuery, "conversationId">, limit: number, cursor: Cursor | undefined, context: Context$1): Promise<Page<EntryRecord, Cursor>>;
3504
+ /** Committed raw active transcript and model context, optionally cut off at the visible entry `at`. */
3505
+ context(conversationId: ConversationId, context: Context$1, options?: {
3506
+ readonly at?: EntryId;
3507
+ }): Promise<ContextView>;
3508
+ /** The Harness clock. */
3509
+ now(): number;
3510
+ /**
3511
+ * Call `callback` once after about `delayMs` on the Harness's timer (`HarnessOptions.setTimer`), for pacing work
3512
+ * inside a phase, such as throttled progress commits. Not durable: the invocation's end disarms it, and after its end
3513
+ * nothing is armed. Returns a function that disarms it. Wait for time between phases with `sleepUntil()`.
3514
+ */
3515
+ setTimer(callback: () => void, delayMs: number): () => void;
3516
+ /**
3517
+ * Forward a non-fatal failure to `HarnessOptions.onReport`, with this task in its info: a `task_error` about the
3518
+ * task's own code, or, with `from`, an `extension_error` about extension code it called, such as a section, or a
3519
+ * `host_error` about a host callback, such as the environment builder.
3520
+ */
3521
+ report(error: unknown, from?: ReportFrom): void;
3522
+ /**
3523
+ * Commit a sleep: the task holds no invocation until the Harness clock reaches `until`, then resumes at `checkpoint`.
3524
+ * Resolves once the sleep is stored, not when the time comes; the phase returns right after. Returning
3525
+ * `{ status: "sleeping", until, checkpoint }` from `commit()` is the same sleep, for one that must commit together
3526
+ * with other writes.
3527
+ */
3528
+ sleepUntil(until: number, checkpoint: S, context: Context$1): Promise<void>;
3529
+ }
3530
+ /** Executable durable state machine definition, registered in the registry by `name`. */
3531
+ type TaskDefinition<I, S extends {
3532
+ phase: string;
3533
+ }, R, H extends object> = {
3534
+ /** Registered task kind persisted in `TaskRecord.kind`. */
3535
+ readonly name: string;
3536
+ /** Definition version persisted with live input and checkpoints. */
3537
+ readonly version: number;
3538
+ /** First durable checkpoint for a newly created task. */
3539
+ initial(input: I): S;
3540
+ /** Exhaustive phase map; each handler receives the task narrowed to its phase. */
3541
+ readonly phases: {
3542
+ readonly [P in S["phase"]]: PhaseHandler<I, Extract<S, {
3543
+ phase: P;
3544
+ }>, S, R, H>;
3545
+ };
3546
+ /** Runs in a fresh invocation after an abort mark and must commit a terminal outcome. */
3547
+ abort(task: RunningTask<I, S, R>, runtime: TaskRuntime<I, S, R, H>, context: Context$1): Promise<void>;
3548
+ /** Convert a record stored by any older supported version; runs at reservation. */
3549
+ migrate?(input: JsonValue$1, checkpoint: JsonValue$1, fromVersion: number): {
3550
+ input: I;
3551
+ checkpoint: S;
3552
+ };
3553
+ readonly hooks?: H;
3554
+ };
3555
+ /** Typed executable task definition. */
3556
+ interface Task<I, S extends {
3557
+ phase: string;
3558
+ }, R, H extends object> {
3559
+ readonly definition: TaskDefinition<I, S, R, H>;
3560
+ }
3561
+ /** Who owns a task: its conversation (a top-level task) or another task of the same conversation (a child task). */
3562
+ type TaskOwnership = {
3563
+ readonly kind: "conversation";
3564
+ } | {
3565
+ readonly kind: "task";
3566
+ readonly taskId: TaskId;
3567
+ };
3568
+ /**
3569
+ * How a waiting task treats the tasks it waits on (spec §5.5): `allSettled` resumes once every task in `on` is terminal,
3570
+ * `failFast` too but aborts the others once one fails, `any` once at least one is terminal.
3571
+ */
3572
+ type JoinPolicy = "failFast" | "allSettled" | "any";
3573
+ /**
3574
+ * Why parked work runs again, as the reservation that woke it recorded: `time` (the sleep's `until`, no signals listed),
3575
+ * `expired` (`until` came before any listed signal), `signal` (the key whose value woke it; read the value with
3576
+ * `readSignal()`), `tasks` (the terminal tasks of the wait's `on` at the reservation). Kept until the task commits another
3577
+ * checkpoint, parks, or ends.
3578
+ */
3579
+ type WakeReason = {
3580
+ readonly reason: "time";
3581
+ } | {
3582
+ readonly reason: "expired";
3583
+ } | {
3584
+ readonly reason: "signal";
3585
+ readonly signal: string;
3586
+ readonly key: string;
3587
+ } | {
3588
+ readonly reason: "tasks";
3589
+ readonly ended: readonly TaskId[];
3590
+ };
3591
+ /** Creation options for a durable task. */
3592
+ type TaskOptions = {
3593
+ /** Omitted: inherit the creator's carrier. "root": start at the adapter root without a stored carrier. */
3594
+ readonly trace?: TelemetryCarrier | "root";
3595
+ /** Immutable creation-time links, attached to the spans of this task's first invocation. */
3596
+ readonly links?: readonly TelemetryCarrier[];
3597
+ /** Required: a task always names its owner (spec §5.5). */
3598
+ readonly ownership: TaskOwnership;
3599
+ /**
3600
+ * Default: the owner task's conversation, or the transaction's bound conversation; required for conversation-owned
3601
+ * tasks created by Session commits that are not bound to a conversation.
3602
+ */
3603
+ readonly conversationId?: ConversationId;
3604
+ /** Conversation-owned tasks only: excluded from ordinary idle waits, conversation aborts, and cascades. */
3605
+ readonly background?: boolean;
3606
+ /**
3607
+ * Its creator awaits it only in memory and does not resume after a restart, so it is pointless once the Harness that
3608
+ * created it is gone. When scheduling starts in a later Harness, the task, if still live, is abort-marked with reason
3609
+ * `restart`, and the mark cascades to its ordinary owned work, before any of it runs again.
3610
+ */
3611
+ readonly abandonOnRestart?: boolean;
3612
+ };
3613
+ /** Ownership selected explicitly whenever a conversation is created. */
3614
+ type ConversationOwnership = {
3615
+ readonly kind: "ownerless";
3616
+ } | {
3617
+ readonly kind: "task";
3618
+ readonly taskId: TaskId;
3619
+ };
3620
+ /** Immutable identity, history ancestry, and task ownership of a transcript scope. */
3621
+ type ConversationRecord = {
3622
+ readonly id: ConversationId;
3623
+ /** Fork source and inclusive parent entry through which history is inherited. */
3624
+ readonly parent?: {
3625
+ readonly conversationId: ConversationId;
3626
+ readonly at: EntryId;
3627
+ };
3628
+ /** Creator edge used for attribution, subtree abort, and subtree idle waits. */
3629
+ readonly owner?: {
3630
+ readonly conversationId: ConversationId;
3631
+ readonly taskId: TaskId;
3632
+ };
3633
+ };
3634
+ /** An immutable override of one visible entry's contribution to model context. */
3635
+ type ContextEdit = {
3636
+ /** Entry whose model messages are omitted or replaced. */
3637
+ readonly target: EntryId;
3638
+ } & ({
3639
+ readonly action: "omit";
3640
+ readonly messages?: never;
3641
+ } | {
3642
+ readonly action: "replace";
3643
+ /** Messages contributed instead of the target entry's model messages. */
3644
+ readonly messages: readonly Message[];
3645
+ });
3646
+ /** Immutable transcript event with separate model-facing and application-facing payloads. */
3647
+ type EntryRecord = {
3648
+ readonly id: EntryId;
3649
+ readonly conversationId: ConversationId;
3650
+ /** Application-defined entry discriminator. */
3651
+ readonly kind: string;
3652
+ /** Messages contributed to model context; absent for display or bookkeeping entries. */
3653
+ readonly model?: readonly Message[];
3654
+ /** JSON payload consumed by views, extensions, or bookkeeping logic. */
3655
+ readonly data?: JsonValue$1;
3656
+ /** First entry in the active context selected by this entry. */
3657
+ readonly head?: EntryId;
3658
+ /** Context-only overrides of earlier visible entries. */
3659
+ readonly edits?: readonly ContextEdit[];
3660
+ /** Task that appended this entry, when it was produced by durable work. */
3661
+ readonly byTaskId?: TaskId;
3662
+ };
3663
+ /** Entry content supplied before the Session assigns identity and task attribution. */
3664
+ type EntryDraft = Omit<EntryRecord, "id" | "conversationId" | "byTaskId" | "head"> & {
3665
+ /** `"self"` starts active context at the newly assigned entry ID. */
3666
+ readonly head?: EntryId | "self";
3667
+ };
3668
+ /** Entry whose `data` has type `D`; `never` means the kind carries no data. */
3669
+ type TypedEntry<D extends JsonValue$1> = Omit<EntryRecord, "data"> & ([D] extends [never] ? {
3670
+ readonly data?: never;
3671
+ } : {
3672
+ readonly data: D;
3673
+ });
3674
+ /** Entry content of a typed kind; the token supplies `kind`. */
3675
+ type TypedEntryDraft<D extends JsonValue$1> = Omit<EntryDraft, "kind" | "data"> & ([D] extends [never] ? {
3676
+ readonly data?: never;
3677
+ } : {
3678
+ readonly data: D;
3679
+ });
3680
+ /** Typed entry kind with a narrowing guard. */
3681
+ interface Entry<D extends JsonValue$1 = never> {
3682
+ readonly kind: string;
3683
+ is(entry: EntryRecord | undefined): entry is TypedEntry<D>;
3684
+ }
3685
+ /** Identity fields shared by every durable submission state. */
3686
+ type SubmissionRecordBase = {
3687
+ /** Adapter-owned context of the admission span; absent without propagation. */
3688
+ readonly trace?: TelemetryCarrier;
3689
+ readonly id: SubmissionId;
3690
+ readonly conversationId: ConversationId;
3691
+ /** Host-provided deduplication key, scoped to the conversation. */
3692
+ readonly requestId?: string;
3693
+ /** The task to deliver `SubmissionSettled` to under `key` when the submission settles. */
3694
+ readonly notify?: SubmissionNotify;
3695
+ };
3696
+ /** Where a settling submission delivers `SubmissionSettled`: a task, and the key it sleeps on. */
3697
+ type SubmissionNotify = {
3698
+ readonly taskId: TaskId;
3699
+ readonly key: string;
3700
+ };
3701
+ /** Durable lifecycle of one admitted user input, passive entry write, or continue. */
3702
+ type SubmissionRecord = (SubmissionRecordBase & {
3703
+ readonly type: "input";
3704
+ } & ({
3705
+ /** Admitted but not yet represented in the transcript. */
3706
+ readonly status: "queued";
3707
+ readonly entry?: never;
3708
+ readonly answer?: never;
3709
+ readonly reason?: never;
3710
+ readonly detail?: never;
3711
+ } | {
3712
+ /** Added to the transcript and owned by an active run. */
3713
+ readonly status: "placed";
3714
+ readonly entry: EntryId;
3715
+ readonly answer?: never;
3716
+ readonly reason?: never;
3717
+ readonly detail?: never;
3718
+ } | {
3719
+ /** Successfully answered user input. */
3720
+ readonly status: "done";
3721
+ readonly entry: EntryId;
3722
+ readonly answer: EntryId;
3723
+ readonly reason?: never;
3724
+ readonly detail?: never;
3725
+ } | {
3726
+ /** Terminal input that can no longer receive an answer. */
3727
+ readonly status: "unanswered";
3728
+ readonly entry?: EntryId;
3729
+ readonly answer?: never;
3730
+ readonly reason: string;
3731
+ readonly detail?: JsonValue$1;
3732
+ })) | (SubmissionRecordBase & {
3733
+ readonly type: "write";
3734
+ } & ({
3735
+ /** Admitted but not yet appended to the transcript. */
3736
+ readonly status: "queued";
3737
+ readonly entry?: never;
3738
+ readonly answer?: never;
3739
+ readonly reason?: never;
3740
+ readonly detail?: never;
3741
+ } | {
3742
+ /** Successfully appended passive entry. */
3743
+ readonly status: "done";
3744
+ readonly entry: EntryId;
3745
+ readonly answer?: never;
3746
+ readonly reason?: never;
3747
+ readonly detail?: never;
3748
+ } | {
3749
+ /** Terminal passive write that could not be placed. */
3750
+ readonly status: "unanswered";
3751
+ readonly entry?: never;
3752
+ readonly answer?: never;
3753
+ readonly reason: string;
3754
+ readonly detail?: JsonValue$1;
3755
+ })) | (SubmissionRecordBase & {
3756
+ /** A run started without a user message; it places no entry and is never queued. */
3757
+ readonly type: "continue";
3758
+ } & ({
3759
+ /** Owned by an active run. */
3760
+ readonly status: "placed";
3761
+ readonly entry?: never;
3762
+ readonly answer?: never;
3763
+ readonly reason?: never;
3764
+ readonly detail?: never;
3765
+ } | {
3766
+ /** The run answered. */
3767
+ readonly status: "done";
3768
+ readonly entry?: never;
3769
+ readonly answer: EntryId;
3770
+ readonly reason?: never;
3771
+ readonly detail?: never;
3772
+ } | {
3773
+ /** The run ended without an answer. */
3774
+ readonly status: "unanswered";
3775
+ readonly entry?: never;
3776
+ readonly answer?: never;
3777
+ readonly reason: string;
3778
+ readonly detail?: JsonValue$1;
3779
+ }));
3780
+ /** Terminal status staged for a submission; identity, type, and entry come from its current record. */
3781
+ type SubmissionSettlement = {
3782
+ readonly status: "done";
3783
+ readonly answer: EntryId;
3784
+ } | {
3785
+ readonly status: "unanswered";
3786
+ readonly reason: string;
3787
+ readonly detail?: JsonValue$1;
3788
+ };
3789
+ /** Submission fields supplied before the Session assigns an ID. */
3790
+ type SubmissionCreate = SubmissionRecord extends infer Record ? Record extends SubmissionRecord ? Omit<Record, "id"> : never : never;
3791
+ /** JSON-safe error snapshot persisted instead of a runtime `Error` object. */
3792
+ type TaskOutcomeError = {
3793
+ readonly message: string;
3794
+ /** Optional structured diagnostic data for inspection or recovery. */
3795
+ readonly detail?: JsonValue$1;
3796
+ };
3797
+ /** Durable reason and optional result recorded when a task becomes terminal. */
3798
+ type TaskOutcome<R> = {
3799
+ readonly status: "completed";
3800
+ readonly result: R;
3801
+ readonly error?: never;
3802
+ readonly reason?: never;
3803
+ }
3804
+ /** Expected task or domain failure explicitly committed by its implementation. */
3805
+ | {
3806
+ readonly status: "failed";
3807
+ readonly error: TaskOutcomeError;
3808
+ readonly result?: R;
3809
+ readonly reason?: never;
3810
+ }
3811
+ /** Explicit cancellation handled by the task's abort protocol. */
3812
+ | {
3813
+ readonly status: "aborted";
3814
+ readonly reason?: string;
3815
+ readonly result?: R;
3816
+ readonly error?: never;
3817
+ }
3818
+ /** Task that cannot resume because its definition or migration is unavailable. */
3819
+ | {
3820
+ readonly status: "orphaned";
3821
+ readonly reason: string;
3822
+ readonly result?: never;
3823
+ readonly error?: never;
3824
+ }
3825
+ /** Runtime-detected contract failure, such as an uncaught throw or no durable progress. */
3826
+ | {
3827
+ readonly status: "faulted";
3828
+ readonly error: TaskOutcomeError;
3829
+ readonly result?: never;
3830
+ readonly reason?: never;
3831
+ };
3832
+ /** Complete durable execution state of a task. */
3833
+ type TaskState<S, R> = {
3834
+ /** Eligible for scheduling. */
3835
+ readonly status: "pending";
3836
+ /** Complete durable state from which execution resumes. */
3837
+ readonly checkpoint: S;
3838
+ /** Why the task woke from its last wait or sleep, kept while it runs at the checkpoint it woke at. */
3839
+ readonly wake?: WakeReason;
3840
+ readonly outcome?: never;
3841
+ } | {
3842
+ /** Reserved by one in-memory task invocation. */
3843
+ readonly status: "running";
3844
+ /** Complete durable state from which execution resumes. */
3845
+ readonly checkpoint: S;
3846
+ /** Why the task woke from its last wait or sleep, kept while it runs at the checkpoint it woke at. */
3847
+ readonly wake?: WakeReason;
3848
+ readonly outcome?: never;
3849
+ } | {
3850
+ /** Parked without an invocation until every task in `on` is terminal; then resumes at `checkpoint`. */
3851
+ readonly status: "waiting";
3852
+ readonly checkpoint: S;
3853
+ readonly on: readonly TaskId[];
3854
+ readonly policy: JoinPolicy;
3855
+ readonly outcome?: never;
3856
+ } | {
3857
+ /**
3858
+ * Parked without an invocation until the Harness clock reaches `until`, in milliseconds on the
3859
+ * `HarnessOptions.now` clock, or one of `signals` holds a value no wake used, whichever comes first; then resumes
3860
+ * at `checkpoint`. Needs `until` or a non-empty `signals`. An abort mark does not wait for it.
3861
+ */
3862
+ readonly status: "sleeping";
3863
+ readonly checkpoint: S;
3864
+ readonly until?: number;
3865
+ readonly signals?: readonly SignalKey<unknown>[];
3866
+ readonly outcome?: never;
3867
+ } | {
3868
+ /** Outcome decided; becomes terminal once no ordinary owned work below is live. Runs no more code. */
3869
+ readonly status: "completing";
3870
+ readonly checkpoint?: never;
3871
+ readonly outcome: TaskOutcome<R>;
3872
+ } | {
3873
+ /** Permanently settled durable result receipt. */
3874
+ readonly status: "terminal";
3875
+ readonly checkpoint?: never;
3876
+ readonly outcome: TaskOutcome<R>;
3877
+ };
3878
+ /** Identity, definition, and scheduling fields shared by every task state. */
3879
+ type TaskRecordBase<I, R> = {
3880
+ /** Adapter-owned context that created this task; phase invocations extract it as their parent. */
3881
+ readonly trace?: TelemetryCarrier;
3882
+ /** Immutable creation-time links for the task's first invocation. */
3883
+ readonly links?: readonly TelemetryCarrier[];
3884
+ readonly id: TaskId<R>;
3885
+ readonly conversationId: ConversationId;
3886
+ /** Registered task definition name. */
3887
+ readonly kind: string;
3888
+ /** Definition version used to migrate live input and checkpoints. */
3889
+ readonly version: number;
3890
+ /** Original task input retained while the task is live or terminal. */
3891
+ readonly input: I;
3892
+ /** Owning task of a child task; absent for a task its conversation owns. Immutable. */
3893
+ readonly owner?: TaskId;
3894
+ /** Whether this conversation-owned task is excluded from ordinary idle waits, conversation aborts, and cascades. */
3895
+ readonly background: boolean;
3896
+ /** Durable abort mark checked before run-mode progress is committed. */
3897
+ readonly abortRequested: boolean;
3898
+ /**
3899
+ * Why the mark was set when not by an abort request: `restart` for a task abandoned after a restart
3900
+ * (`TaskOptions.abandonOnRestart`) or below one. Such a task waits for its definition instead of becoming `orphaned`.
3901
+ * A later abort request clears it.
3902
+ */
3903
+ readonly abortReason?: "restart";
3904
+ /** Set from `TaskOptions.abandonOnRestart`. Immutable. */
3905
+ readonly abandonOnRestart?: true;
3906
+ /**
3907
+ * Wall-clock milliseconds of the first change to `running`, stamped by the Session. Kept through waits and recovery,
3908
+ * so the span to `endedAt` includes them. Absent before the task first runs, and on records written by earlier
3909
+ * versions.
3910
+ */
3911
+ readonly startedAt?: number;
3912
+ /** Wall-clock milliseconds of the change to `terminal`, stamped by the Session; absent while live. */
3913
+ readonly endedAt?: number;
3914
+ /**
3915
+ * How many times in a row a crash, eviction, or reset cut the task off while it ran, without the task changing its
3916
+ * state since; open counts them, and a close does not. At `HarnessSettings.restartLimit` the task ends (the built-in
3917
+ * tasks end themselves, visibly; the scheduler faults any other kind), and a generation reads it to charge an
3918
+ * interrupted model request as a failed attempt.
3919
+ */
3920
+ readonly restarts?: number;
3921
+ };
3922
+ /** Complete replacement record for one durable task state machine. */
3923
+ type TaskRecord<I, S, R> = TaskRecordBase<I, R> & ({
3924
+ readonly state: Extract<TaskState<S, R>, {
3925
+ readonly status: "pending" | "running" | "waiting" | "sleeping";
3926
+ }>;
3927
+ /** Small first-writer-wins values retained while the task can run. */
3928
+ readonly memos?: Readonly<Record<string, JsonValue$1>>;
3929
+ } | {
3930
+ readonly state: Extract<TaskState<S, R>, {
3931
+ readonly status: "completing" | "terminal";
3932
+ }>;
3933
+ readonly memos?: never;
3934
+ });
3935
+ /** Persisted lifecycle record for one create-to-retire document incarnation. */
3936
+ type DocumentRecord = {
3937
+ /** Unique incarnation ID; never reused when the same logical document is recreated. */
3938
+ readonly id: DocumentId;
3939
+ /** Stable document definition kind. */
3940
+ readonly kind: string;
3941
+ /** Family member key; absent for singleton documents. */
3942
+ readonly key?: string;
3943
+ /** Commit that created the incarnation, stamped by storage. */
3944
+ readonly createdAt: Seq;
3945
+ /** Commit that retired the incarnation; absent while it is current. */
3946
+ readonly retiredAt?: Seq;
3947
+ } & ({
3948
+ readonly scope: {
3949
+ readonly kind: "session";
3950
+ };
3951
+ readonly history?: never;
3952
+ readonly fork?: never;
3953
+ } | ({
3954
+ readonly scope: {
3955
+ readonly kind: "conversation";
3956
+ readonly conversationId: ConversationId;
3957
+ };
3958
+ } & ({
3959
+ /** Retain only current state. */
3960
+ readonly history: "latest";
3961
+ /** Initialize a fork from current source state or the definition's initial value. */
3962
+ readonly fork: "current" | "initial";
3963
+ } | {
3964
+ /** Retain history needed for as-of reads. */
3965
+ readonly history: "rewindable";
3966
+ /** Initialize a fork at its cutoff, from current state, or from the initial value. */
3967
+ readonly fork: "asOf" | "current" | "initial";
3968
+ })) | {
3969
+ readonly scope: {
3970
+ readonly kind: "task";
3971
+ readonly taskId: TaskId;
3972
+ };
3973
+ readonly history?: never;
3974
+ readonly fork?: never;
3975
+ });
3976
+ /** Fields supplied when storage creates and stamps a new `DocumentRecord`. */
3977
+ type DocumentCreate = DocumentRecord extends infer Record ? Record extends DocumentRecord ? Omit<Record, "createdAt" | "retiredAt"> : never : never;
3978
+ /** One ordered scan result and its optional continuation state. */
3979
+ type Page<T, C> = {
3980
+ readonly items: readonly T[];
3981
+ readonly next?: C;
3982
+ };
3983
+ /**
3984
+ * Backend-owned JSON continuation state that callers only round-trip to the same scan. It carries the scan's order: a
3985
+ * scan given a cursor continues in that order, and rejects a different `order` in its query.
3986
+ */
3987
+ type Cursor = Readonly<Record<string, JsonValue$1>>;
3988
+ /** ID order of a scan: `ascending` is oldest first, `descending` newest first. */
3989
+ type ScanOrder = "ascending" | "descending";
3990
+ /** Optional filters for an ordered conversation scan. */
3991
+ type ConversationQuery = {
3992
+ readonly ownerConversationId?: ConversationId;
3993
+ readonly ownerTaskId?: TaskId;
3994
+ /** Default `ascending`; with a cursor, the cursor's order. */
3995
+ readonly order?: ScanOrder;
3996
+ };
3997
+ /** Inclusive ID bounds for a scan of one conversation's fork-aware history. */
3998
+ type EntryQuery = {
3999
+ readonly conversationId: ConversationId;
4000
+ /** Oldest entry ID that may be returned. */
4001
+ readonly minEntryId?: EntryId;
4002
+ /** Newest entry ID that may be returned. */
4003
+ readonly maxEntryId?: EntryId;
4004
+ /** Default `descending`; with a cursor, the cursor's order. */
4005
+ readonly order?: ScanOrder;
4006
+ };
4007
+ /** Optional filters for an ordered scan of durable task records. */
4008
+ type TaskQuery = {
4009
+ readonly conversationId?: ConversationId;
4010
+ readonly kind?: string;
4011
+ readonly status?: TaskState<JsonValue$1, JsonValue$1>["status"];
4012
+ readonly abortRequested?: boolean;
4013
+ readonly background?: boolean;
4014
+ /** Default `ascending`; with a cursor, the cursor's order. */
4015
+ readonly order?: ScanOrder;
4016
+ };
4017
+ /** Optional filters for an ordered scan of submission records. */
4018
+ type SubmissionQuery = {
4019
+ readonly conversationId?: ConversationId;
4020
+ readonly status?: SubmissionRecord["status"];
4021
+ /** Default `ascending`; with a cursor, the cursor's order. */
4022
+ readonly order?: ScanOrder;
4023
+ };
4024
+ /** Current state or one historical commit sequence used for document membership and content reads. */
4025
+ type DocumentPoint = Seq | "current";
4026
+ /** Exact logical identity of a singleton or one keyed family member. */
4027
+ type DocumentAddress = {
4028
+ readonly kind: string;
4029
+ readonly scope: DocumentRecord["scope"];
4030
+ /** Absent selects the singleton; present selects one family member. */
4031
+ readonly key?: string;
4032
+ };
4033
+ /** Ordered scan of document incarnations alive in one exact scope at one point. */
4034
+ type DocumentQuery = {
4035
+ readonly scope: DocumentRecord["scope"];
4036
+ readonly at: DocumentPoint;
4037
+ readonly kind?: string;
4038
+ };
4039
+ /** Complete checkpoint or Chord operation batch selected by the owning Session. */
4040
+ type DocumentContent = {
4041
+ readonly version: number;
4042
+ readonly kind: "base";
4043
+ readonly value: JsonObject;
4044
+ } | {
4045
+ readonly version: number;
4046
+ readonly kind: "delta";
4047
+ readonly ops: readonly Op[];
4048
+ };
4049
+ /** Exact persisted source selected for a definition-free document copy. */
4050
+ type DocumentCopySource = {
4051
+ readonly id: DocumentId;
4052
+ readonly at: DocumentPoint;
4053
+ };
4054
+ /** Detached materialized value and stored definition version at a selected point. */
4055
+ type StoredDocument = {
4056
+ readonly record: DocumentRecord;
4057
+ readonly version: number;
4058
+ readonly value: JsonObject;
4059
+ /** Deltas replayed after the selected base to materialize `value`. */
4060
+ readonly deltasSinceBase: number;
4061
+ };
4062
+ /** One record or document mutation in an atomic storage commit. */
4063
+ type StorageWrite = {
4064
+ readonly type: "conversation";
4065
+ readonly value: ConversationRecord;
4066
+ } | {
4067
+ readonly type: "entry";
4068
+ readonly value: EntryRecord;
4069
+ } | {
4070
+ readonly type: "task";
4071
+ readonly value: TaskRecord<JsonValue$1, JsonValue$1, JsonValue$1>;
4072
+ } | {
4073
+ readonly type: "submission";
4074
+ readonly value: SubmissionRecord;
4075
+ } | {
4076
+ readonly type: "document.create";
4077
+ readonly record: DocumentCreate;
4078
+ readonly content: Extract<DocumentContent, {
4079
+ readonly kind: "base";
4080
+ }>;
4081
+ } | {
4082
+ readonly type: "document.copy";
4083
+ readonly record: DocumentCreate;
4084
+ readonly source: DocumentCopySource;
4085
+ } | {
4086
+ readonly type: "document.change";
4087
+ readonly id: DocumentId;
4088
+ readonly content: DocumentContent;
4089
+ } | {
4090
+ readonly type: "document.retire";
4091
+ readonly id: DocumentId;
4092
+ };
4093
+ /**
4094
+ * Committed change of one document incarnation: `type: "document"` with `kind: "change"` (a creation or an update) or
4095
+ * `kind: "retire"` (this commit retired the incarnation), or a `document.copy`.
4096
+ */
4097
+ type DocumentCommitChange = {
4098
+ readonly type: "document";
4099
+ readonly kind: "change";
4100
+ readonly record: DocumentRecord;
4101
+ /** Conversation owning the document; task documents derive it from their task record. Undefined only for Session documents. */
4102
+ readonly conversationId: ConversationId | undefined;
4103
+ /** Definition version of `value`. */
4104
+ readonly version: number;
4105
+ /** Exact adopted immutable revision. */
4106
+ readonly value: JsonObject;
4107
+ /** Exact adopted operations for an ordinary update; empty for creation. */
4108
+ readonly ops: readonly Op[];
4109
+ } | {
4110
+ readonly type: "document";
4111
+ readonly kind: "retire";
4112
+ readonly record: DocumentRecord;
4113
+ /** Conversation owning the document; task documents derive it from their task record. Undefined only for Session documents. */
4114
+ readonly conversationId: ConversationId | undefined;
4115
+ } | {
4116
+ /** Definition-free child initialization; consumers hydrate through watch acquisition. */
4117
+ readonly type: "document.copy";
4118
+ readonly record: DocumentRecord;
4119
+ readonly conversationId: ConversationId;
4120
+ readonly source: DocumentCopySource;
4121
+ };
4122
+ /** Complete table record committed without another publication copy. */
4123
+ type TableCommitChange = Extract<StorageWrite, {
4124
+ readonly type: "conversation" | "entry" | "task" | "submission";
4125
+ }>;
4126
+ type CommitChange = TableCommitChange | DocumentCommitChange;
4127
+ /**
4128
+ * Every immutable change one Session storage transaction stored, with its `seq`. Change order is unspecified. A commit
4129
+ * held in memory (`CommitPersistence`) is published once it is stored: by the next commit that reads or writes its
4130
+ * document, alone (`seq` of its own), or with that commit, whose document change then carries the held operations
4131
+ * followed by its own.
4132
+ */
4133
+ type CommitPublication = {
4134
+ readonly seq: Seq;
4135
+ readonly changes: readonly CommitChange[];
4136
+ };
4137
+ /**
4138
+ * Transaction surface of one Session commit callback.
4139
+ * Table reads and creation results are trusted immutable values and may be shared with internal commit state; the
4140
+ * Session may freeze them (its caches and context ranges keep them), so mutating one can throw.
4141
+ */
4142
+ interface Tx {
4143
+ conversation(id: ConversationId): Promise<ConversationRecord | undefined>;
4144
+ entry(id: EntryId): Promise<EntryRecord | undefined>;
4145
+ /** Undefined when the entry is absent or has another kind. */
4146
+ entry<D extends JsonValue$1>(token: Entry<D>, id: EntryId): Promise<TypedEntry<D> | undefined>;
4147
+ task(id: TaskId): Promise<TaskRecord<JsonValue$1, JsonValue$1, JsonValue$1> | undefined>;
4148
+ scanConversations(query: ConversationQuery, limit: number, cursor?: Cursor): Promise<Page<ConversationRecord, Cursor>>;
4149
+ scanEntries(query: EntryQuery, limit: number, cursor?: Cursor): Promise<Page<EntryRecord, Cursor>>;
4150
+ /** Newest visible entry of the conversation that carries a `head`. */
4151
+ latestHeadMarker(conversationId: ConversationId): Promise<(EntryRecord & {
4152
+ readonly head: EntryId;
4153
+ }) | undefined>;
4154
+ /** ID of the newest entry visible from the conversation; `undefined` when it has none. */
4155
+ latestEntryId(conversationId: ConversationId): Promise<EntryId | undefined>;
4156
+ scanTasks(query: TaskQuery, limit: number, cursor?: Cursor): Promise<Page<TaskRecord<JsonValue$1, JsonValue$1, JsonValue$1>, Cursor>>;
4157
+ /** Committed submission record, such as one of `pi.live.run.inputs`; a placed input's `entry` is its transcript entry. */
4158
+ submission(id: SubmissionId): Promise<SubmissionRecord | undefined>;
4159
+ /** Committed submission with a conversation-scoped request ID. */
4160
+ submissionByRequest(conversationId: ConversationId, requestId: string): Promise<SubmissionRecord | undefined>;
4161
+ /** Create a conversation with explicitly selected ownership. */
4162
+ createConversation(options: {
4163
+ readonly ownership: ConversationOwnership;
4164
+ }): Promise<ConversationRecord>;
4165
+ /** Create a history fork at one concrete visible entry with explicitly selected ownership. */
4166
+ forkConversation(parentConversationId: ConversationId, at: EntryId, options: {
4167
+ readonly ownership: ConversationOwnership;
4168
+ }): Promise<ConversationRecord>;
4169
+ /** Returned records are Session-owned immutable values and may be shared with commit listeners. */
4170
+ appendEntry(conversationId: ConversationId, value: EntryDraft): Promise<EntryRecord>;
4171
+ /** The token supplies `kind` and types `data`. */
4172
+ appendEntry<D extends JsonValue$1>(token: Entry<D>, conversationId: ConversationId, value: TypedEntryDraft<NoInfer<D>>): Promise<TypedEntry<D>>;
4173
+ createTask<I, S extends {
4174
+ phase: string;
4175
+ }, R, H extends object>(task: Task<I, S, R, H>, input: I, options: TaskOptions): Promise<TaskId<R>>;
4176
+ /**
4177
+ * Create a raw submission record with a fresh ID. No admission rules apply: no busy check, no inbox queueing, no
4178
+ * placement. Use `Conversation.submit()` or a conversation handle unless the caller implements admission itself.
4179
+ */
4180
+ createSubmission(create: SubmissionCreate): Promise<SubmissionRecord>;
4181
+ /**
4182
+ * Settle a queued or placed submission; only a placed input or continue can be answered, and a settled submission stays
4183
+ * unchanged. Resolved against this transaction's latest record of the submission, so it works after table writes.
4184
+ * Run tasks settle the inputs they answer.
4185
+ */
4186
+ settleSubmission(id: SubmissionId, settlement: SubmissionSettlement): void;
4187
+ /**
4188
+ * Place a queued submission at `entry`: an input becomes `placed`, a write `done`. Resolved like
4189
+ * `settleSubmission()`. Inbox boundaries place the submissions they select.
4190
+ */
4191
+ placeSubmission(id: SubmissionId, entry: EntryId): void;
4192
+ /**
4193
+ * Deliver `value` to task `taskId` under `key`: stored in the task until a sleep on the key wakes on it, also when the
4194
+ * task does not sleep on it yet. Reads the task, so it throws `ReadAfterWrite` after the commit's first table write;
4195
+ * the result is provisional until the commit is stored. Checks nothing about the caller.
4196
+ */
4197
+ signal<T>(taskId: TaskId, token: SignalToken<T>, key: string, value: T): Promise<SignalResult>;
4198
+ doc<T extends JsonObject>(token: SessionDocToken<T>): Promise<Draft<T>>;
4199
+ doc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<Draft<T>>;
4200
+ doc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<Draft<T>>;
4201
+ doc<T extends JsonObject, I extends JsonValue$1>(token: SessionDocFamilyToken<T, I>, key: string, seed: I): Promise<Draft<T>>;
4202
+ doc<T extends JsonObject, I extends JsonValue$1>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, seed: I): Promise<Draft<T>>;
4203
+ doc<T extends JsonObject, I extends JsonValue$1>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, seed: I): Promise<Draft<T>>;
4204
+ retireDoc<T extends JsonObject>(token: SessionDocToken<T>): Promise<void>;
4205
+ retireDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<void>;
4206
+ retireDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<void>;
4207
+ retireDoc<T extends JsonObject, I extends JsonValue$1>(token: SessionDocFamilyToken<T, I>, key: string): Promise<void>;
4208
+ retireDoc<T extends JsonObject, I extends JsonValue$1>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string): Promise<void>;
4209
+ retireDoc<T extends JsonObject, I extends JsonValue$1>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string): Promise<void>;
4210
+ }
4211
+ /**
4212
+ * Watch of one document address (kind, scope, and key), from the incarnation found at acquisition on. A retirement is a
4213
+ * call with `retired` set, the last value the watch was given and no ops (a change made in the retiring commit itself
4214
+ * is not shown: that commit publishes the retirement only); the watch goes on, and a document created at the address
4215
+ * later arrives as `[["r", value]]`, folded with what is pending. It ends `ended` when its scope's owner ends: a task
4216
+ * document's watch once the retirement call of the commit that makes its task terminal returned, every watch at Session
4217
+ * close (a pending retirement dropped); `failed` with the error that failed the Session.
4218
+ */
4219
+ type DocumentWatch<T extends JsonObject> = WatchHandle<Readonly<T>>;
4220
+ /**
4221
+ * A synchronous observer of committed Durable state, for adapters such as a Chord source (`observeDoc()`,
4222
+ * `Harness.observeConversation()`, `Harness.observeTaskGraph()`), with the shapes of Chord's watch: `advance` gets a
4223
+ * `WatchCall`, `end` a `WatchEnd`. `advance` gets every change, unfolded, as memory adopts it: for a stored commit at its
4224
+ * publication once Storage stored it, for a deferred one before it is stored. A view or the graph gets at most one call
4225
+ * per commit, a document observer one per change at its address (two for a commit that retires and recreates it); the
4226
+ * task graph also advances outside any commit's publication, on the Session line, when a registry change or a failed
4227
+ * migration changes a
4228
+ * `blocked` reason. Durable's failures are final, so every call is a `value` call; a failure ends the observer. Calls
4229
+ * may come before the attaching promise resolves; their ops apply from `Observation.value`. `advance` must only record
4230
+ * the call, synchronously and quickly, never await, call the Session, or throw. A throw is reported as
4231
+ * `listener_error`, detaches the observer, and ends it `listener_error` with the error. `end` is called once: `ended`
4232
+ * when the observed scope's owner ends (a task document's task, after its retirement change, inside that commit's
4233
+ * `adopt`), `failed` with "session closed" when the Session closes (an adapter follows the next Session) or with the
4234
+ * error that failed the Session; never after `detach()`.
4235
+ */
4236
+ type Observer<T> = {
4237
+ advance(call: WatchCall<T>, context: Context$1): void;
4238
+ end(end: WatchEnd): void;
4239
+ };
4240
+ /**
4241
+ * A synchronous observer of stored commits (`Session.observeCommits()`): `advance` gets each `CommitPublication`, `end`
4242
+ * the Session's close (`failed` with "session closed", or with the error that failed the Session).
4243
+ */
4244
+ type CommitObserver = {
4245
+ advance(publication: CommitPublication, context: Context$1): void;
4246
+ end(end: WatchEnd): void;
4247
+ };
4248
+ /** An attached `CommitObserver`: how to detach it. Idempotent: no `advance` or `end` follows it. */
4249
+ type CommitObservation = {
4250
+ detach(): void;
4251
+ };
4252
+ /** An attached `Observer`: the value at attachment, which every later `advance` starts from, and how to detach it. */
4253
+ type Observation<T> = {
4254
+ readonly value: T;
4255
+ /** Idempotent: no `advance` or `end` follows it, not even for the rest of a commit underway. */
4256
+ detach(): void;
4257
+ };
4258
+ /** Committed document reads. */
4259
+ type DocumentReader = Pick<Session, "snapshot" | "snapshotAsOf">;
4260
+ /** Non-creating document watch acquisition shared by Session and later invocation APIs. */
4261
+ interface DocumentObserver {
4262
+ watchDoc<T extends JsonObject>(token: SessionDocToken<T>, context: Context$1): Promise<DocumentWatch<T> | undefined>;
4263
+ watchDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context$1): Promise<DocumentWatch<T> | undefined>;
4264
+ watchDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context$1): Promise<DocumentWatch<T> | undefined>;
4265
+ watchDoc<T extends JsonObject, I extends JsonValue$1>(token: SessionDocFamilyToken<T, I>, key: string, context: Context$1): Promise<DocumentWatch<T> | undefined>;
4266
+ watchDoc<T extends JsonObject, I extends JsonValue$1>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context$1): Promise<DocumentWatch<T> | undefined>;
4267
+ watchDoc<T extends JsonObject, I extends JsonValue$1>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context$1): Promise<DocumentWatch<T> | undefined>;
4268
+ }
4269
+ /** Why a Session ended, by `kind`: `close()`, or a failed Storage call, whose error it carries. */
4270
+ type SessionEnd = {
4271
+ readonly kind: "closed";
4272
+ } | {
4273
+ readonly kind: "failed";
4274
+ readonly error: unknown;
4275
+ };
4276
+ /**
4277
+ * When a commit reaches Storage. `immediate`, the default: before `commit()` resolves. `deferred`: when every write of
4278
+ * the commit changes an existing conversation document with `history: "latest"` and `fork: "initial"` (no creation,
4279
+ * migration, or retirement), the Session adopts it in memory, shows it to watches and views, and resolves, but stores it
4280
+ * later: with the next commit that reads (`tx.doc()`) or writes that document, before the document leaves memory or
4281
+ * retires, at `close()`, and at the latest about `withinMs` after the commit (default `settings.progress.persistWithinMs`,
4282
+ * 1,000 ms; `Infinity` waits for one of the others). A commit that writes anything else is immediate. A crash loses what
4283
+ * is held, so only state whose loss is acceptable, such as streamed progress, should be deferred, and nothing durable may
4284
+ * depend on it without reading it in a commit.
4285
+ */
4286
+ type CommitPersistence = {
4287
+ readonly kind: "immediate";
4288
+ } | {
4289
+ readonly kind: "deferred";
4290
+ readonly withinMs?: number;
4291
+ };
4292
+ /** Options of one Session commit. */
4293
+ type CommitOptions = {
4294
+ readonly persistence?: CommitPersistence;
4295
+ };
4296
+ /** Owner of one mutation line, its records, and its tracked documents. */
4297
+ interface Session extends DocumentObserver {
4298
+ /**
4299
+ * Run one atomic transaction on the Session mutation line. Inside the callback read only through `tx`: `snapshot()`, `watchDoc()`, `getTask()`, and the other Session and runtime reads may queue on the line the callback holds, and then never resolve.
4300
+ * `options.persistence` may defer storing it (`CommitPersistence`). The callback may run while an earlier commit is
4301
+ * being stored: at its first read or write of what an unpublished commit wrote, it waits until that commit is stored
4302
+ * and published; code before that runs early, so act on what it computes only once the commit resolves. Resolves
4303
+ * once the commit is stored and published, after every earlier commit's outcome.
4304
+ */
4305
+ commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context$1, options?: CommitOptions): Promise<T>;
4306
+ /** Seal admission, settle admitted commits, then close storage. */
4307
+ close(context: Context$1): Promise<void>;
4308
+ /**
4309
+ * Settles once the Session has closed, Storage included: after `close()`, or after the first failed Storage call,
4310
+ * which closes the Session itself. A failed Session is reopened from Storage; nothing else is left to clean up.
4311
+ */
4312
+ readonly closed: Promise<SessionEnd>;
4313
+ /**
4314
+ * Attach a synchronous `Observer` to one document address, atomically on the Session line, as `watchDoc()` acquires
4315
+ * a watch: the observation's value includes every commit before it, and `advance` gets every later one, retirements
4316
+ * and later incarnations included. `undefined` when the address is absent. `context` governs only the attachment:
4317
+ * cancelled while attaching, the promise rejects and nothing stays attached.
4318
+ */
4319
+ observeDoc<T extends JsonObject>(token: SessionDocToken<T>, observer: Observer<Readonly<T>>, context: Context$1): Promise<Observation<Readonly<T>> | undefined>;
4320
+ observeDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, observer: Observer<Readonly<T>>, context: Context$1): Promise<Observation<Readonly<T>> | undefined>;
4321
+ observeDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, observer: Observer<Readonly<T>>, context: Context$1): Promise<Observation<Readonly<T>> | undefined>;
4322
+ observeDoc<T extends JsonObject, I extends JsonValue$1>(token: SessionDocFamilyToken<T, I>, key: string, observer: Observer<Readonly<T>>, context: Context$1): Promise<Observation<Readonly<T>> | undefined>;
4323
+ observeDoc<T extends JsonObject, I extends JsonValue$1>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, observer: Observer<Readonly<T>>, context: Context$1): Promise<Observation<Readonly<T>> | undefined>;
4324
+ observeDoc<T extends JsonObject, I extends JsonValue$1>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, observer: Observer<Readonly<T>>, context: Context$1): Promise<Observation<Readonly<T>> | undefined>;
4325
+ /**
4326
+ * Observe stored commits, each with exactly what it stored, except that a document the commit retires is published
4327
+ * as its retirement only; a commit held in memory is published when it is stored (`CommitPublication`). Commits are
4328
+ * published in line order once Storage stored them, a macrotask apart; a publication queues one dispatch, which runs
4329
+ * a microtask later, before every wait the commit resolves and every abort it queues, and calls the observers
4330
+ * attached by then; a commit published while none was attached has no dispatch. There is no order relative to watch listeners. `advance` runs synchronously and must not block or
4331
+ * call Session APIs; a throw is reported as `listener_error`, detaches the observer, and ends it `listener_error`.
4332
+ * `end` is called once, when the Session closes (`ended`, after its last publication) or fails (`failed`), never
4333
+ * after `detach()`. Attaches synchronously; the observation has no `value`: commits are events, not a state, and the
4334
+ * Session does not know Storage's newest `seq` before its own first commit.
4335
+ */
4336
+ observeCommits(observer: CommitObserver): CommitObservation;
4337
+ /**
4338
+ * Observe close synchronously when it begins, also when a failed Storage call closes the Session. The listener must
4339
+ * not block or call Session APIs.
4340
+ */
4341
+ subscribeClose(listener: () => void): () => void;
4342
+ snapshot<T extends JsonObject>(token: SessionDocToken<T>, context: Context$1): Promise<Readonly<T> | undefined>;
4343
+ snapshot<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context$1): Promise<Readonly<T> | undefined>;
4344
+ snapshot<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context$1): Promise<Readonly<T> | undefined>;
4345
+ snapshot<T extends JsonObject, I extends JsonValue$1>(token: SessionDocFamilyToken<T, I>, key: string, context: Context$1): Promise<Readonly<T> | undefined>;
4346
+ snapshot<T extends JsonObject, I extends JsonValue$1>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context$1): Promise<Readonly<T> | undefined>;
4347
+ snapshot<T extends JsonObject, I extends JsonValue$1>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context$1): Promise<Readonly<T> | undefined>;
4348
+ snapshotAsOf<T extends JsonObject>(token: RewindableConversationDocToken<T>, conversationId: ConversationId, at: EntryId, context: Context$1): Promise<Readonly<T> | undefined>;
4349
+ snapshotAsOf<T extends JsonObject, I extends JsonValue$1>(token: RewindableConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, at: EntryId, context: Context$1): Promise<Readonly<T> | undefined>;
4350
+ }
4351
+ /** What `Storage.commit()` stored: the number of durable batches, and why the next one was refused, if one was. */
4352
+ type CommitResult = {
4353
+ readonly stored: number;
4354
+ readonly refused?: unknown;
4355
+ };
4356
+ /**
4357
+ * Atomic persistence boundary for Session records.
4358
+ *
4359
+ * Storage trusts the owning Session to supply semantically valid records, references,
4360
+ * ancestry, and transitions. Implementations enforce atomicity, global ID ownership,
4361
+ * immutable conversation/entry creation, document record consistency, and detached values;
4362
+ * Session serializes commits.
4363
+ *
4364
+ * An error a method throws is final: it fails the Session, which nothing retries, so retry transient failures inside
4365
+ * the method. Two errors of a read fail only that read: a `StorageRequestError` for an invalid request (an unknown
4366
+ * conversation, a foreign or malformed cursor, history a document does not keep), which must have no durable effect, and a
4367
+ * rejection because its caller's context was aborted. Any error from `commit()` or `mintId()` is fatal.
4368
+ */
4369
+ interface Storage {
4370
+ /**
4371
+ * Persist `batches` in order, each as one ordinary atomic commit with its own seq, checked against the state the
4372
+ * earlier ones left, in as few round trips as the backend can. Every batch has at least one write: a commit without
4373
+ * writes never reaches Storage, so the Session never sends an empty batch. Stops at the first batch Durable's own checks refuse
4374
+ * (global IDs, document actions, copy resolution): the batches before it are durable, it and the ones after are not.
4375
+ * Calls `receive(index, seq)` once per durable batch, in order, synchronously, after all of them are durable and
4376
+ * before the next commit starts. Resolves with the number of durable batches and the refusal, if any. Rejects for an
4377
+ * unknown outcome (connection lost, statement or commit failed); `receive` calls made before the rejection still
4378
+ * stand. `receive` is a durability receipt, not publication: the Session publishes later. Once it resolved, later
4379
+ * reads through this storage observe the stored batches.
4380
+ */
4381
+ commit(batches: readonly (readonly StorageWrite[])[], receive: (index: number, seq: Seq) => void, context: Context$1): Promise<CommitResult>;
4382
+ /**
4383
+ * Optional. Run `publish`, the Session's publication of one stored or held commit (its cache write-through,
4384
+ * adoption, and observers), inside this storage's own scope, such as a store's attached host batch, so what the
4385
+ * publication marks lands together. Call `publish` exactly once, now or soon after; the Session publishes the next
4386
+ * commit only once it ran. Without it, the Session publishes directly.
4387
+ */
4388
+ publishing?(publish: () => void, context: Context$1): void;
4389
+ /**
4390
+ * Return a fresh branded candidate from the Session-global numeric ID namespace, greater than every ID minted since
4391
+ * this storage was opened and every ID stored, also across reopen: scans order by ID as creation order, and the
4392
+ * Harness relies on it.
4393
+ */
4394
+ mintId<I extends Id<string>>(): Promise<I>;
4395
+ /** Look up one conversation by exact ID. */
4396
+ conversation(id: ConversationId, context: Context$1): Promise<ConversationRecord | undefined>;
4397
+ /** Scan conversations in `query.order` (default ascending) by ID. */
4398
+ scanConversations(query: ConversationQuery, limit: number, cursor: Cursor | undefined, context: Context$1): Promise<Page<ConversationRecord, Cursor>>;
4399
+ /** Look up one global entry and the sequence of the commit that persisted it. */
4400
+ entry(id: EntryId, context: Context$1): Promise<{
4401
+ readonly entry: EntryRecord;
4402
+ readonly commitSeq: Seq;
4403
+ } | undefined>;
4404
+ /** Look up one entry only when it is visible through the requested conversation's ancestry. */
4405
+ entry(conversationId: ConversationId, id: EntryId, context: Context$1): Promise<{
4406
+ readonly entry: EntryRecord;
4407
+ readonly commitSeq: Seq;
4408
+ } | undefined>;
4409
+ /**
4410
+ * Return the newest visible entry with a `head` at or below the optional inclusive cutoff.
4411
+ * The returned entry is the marker; its `head` value is the range's actual lower bound.
4412
+ */
4413
+ findLatestHeadMarker(conversationId: ConversationId, atOrBeforeEntryId: EntryId | undefined, context: Context$1): Promise<(EntryRecord & {
4414
+ readonly head: EntryId;
4415
+ }) | undefined>;
4416
+ /** Scan the inclusive visible range in `query.order` (default descending), returning at most `limit` entries. */
4417
+ scanEntries(query: EntryQuery, limit: number, cursor: Cursor | undefined, context: Context$1): Promise<Page<EntryRecord, Cursor>>;
4418
+ /** Look up the latest complete record for one task. */
4419
+ task(id: TaskId, context: Context$1): Promise<TaskRecord<JsonValue$1, JsonValue$1, JsonValue$1> | undefined>;
4420
+ /** Scan task records matching every supplied filter in `query.order` (default ascending) by ID. */
4421
+ scanTasks(query: TaskQuery, limit: number, cursor: Cursor | undefined, context: Context$1): Promise<Page<TaskRecord<JsonValue$1, JsonValue$1, JsonValue$1>, Cursor>>;
4422
+ /** Look up the latest complete record for one admitted submission. */
4423
+ submission(id: SubmissionId, context: Context$1): Promise<SubmissionRecord | undefined>;
4424
+ /** Scan submissions matching every supplied filter in `query.order` (default ascending) by ID. */
4425
+ scanSubmissions(query: SubmissionQuery, limit: number, cursor: Cursor | undefined, context: Context$1): Promise<Page<SubmissionRecord, Cursor>>;
4426
+ /** Find a submission by its conversation-scoped host deduplication key. */
4427
+ submissionByRequest(conversationId: ConversationId, requestId: string, context: Context$1): Promise<SubmissionRecord | undefined>;
4428
+ /** Resolve the incarnation occupying one exact logical address at the selected point. */
4429
+ findDocument(address: DocumentAddress, at: DocumentPoint, context: Context$1): Promise<DocumentRecord | undefined>;
4430
+ /** Materialize one specific incarnation by ID at the selected point without following a replacement at its address. */
4431
+ document(id: DocumentId, at: DocumentPoint, context: Context$1): Promise<StoredDocument | undefined>;
4432
+ /** Scan incarnations alive in one exact scope at the selected point. */
4433
+ scanDocuments(query: DocumentQuery, limit: number, cursor: Cursor | undefined, context: Context$1): Promise<Page<DocumentRecord, Cursor>>;
4434
+ /** Release backend resources; all later operations must reject. */
4435
+ close(context: Context$1): Promise<void>;
4436
+ }
4437
+
4438
+ /** Durable agent harness over one Session. */
4439
+ type Harness = Harness$1;
4440
+ declare const Harness: {
4441
+ /** Open a Harness over storage. The registry may keep changing while the Harness runs. */
4442
+ open<Tool extends ToolRegistration>(storage: Storage, options: HarnessOptions<Tool>, context: Context$1): Promise<Harness>;
4443
+ };
4444
+
4445
+ // @ts-ignore Standalone host installations omit the optional Pi Durable peer.
4446
+
4447
+
4448
+ type PiWatchEvent = WatchCall<ConversationView>;
4449
+
4450
+
4451
+ type RemoteInput = {
4452
+ type: 'input';
4453
+ content: string;
4454
+ requestId: string;
4455
+ whenBusy?: 'reject' | 'steer' | 'followUp';
4456
+ whenIdle?: 'reject';
4457
+ onAbort?: 'withdraw' | 'keep';
4458
+ };
4459
+ interface RemoteConversation {
4460
+ watch(context: Context$1, window?: ConversationWindow): Promise<ConversationWatch>;
4461
+ waitForIdle(context: Context$1): Promise<void>;
4462
+ abort(context: Context$1, options?: ConversationAbortOptions): Promise<void>;
4463
+ submit(draft: RemoteInput, context: Context$1): Promise<Submission>;
4464
+ submissionByRequest(requestId: string, context: Context$1): Promise<Submission | undefined>;
4465
+ stopSubmission(id: SubmissionId, context: Context$1): Promise<void>;
4466
+ entry(id: EntryId, context: Context$1): Promise<EntryRecord | undefined>;
4467
+ }
4468
+
4469
+ /** Resources owned by a Pi Durable runtime inside its sandbox. */
4470
+ interface ServedConversation {
4471
+ submit(draft: RemoteInput, context: Context$1): Promise<SubmissionId>;
4472
+ watch(context: Context$1, window?: ConversationWindow): Promise<ConversationWatch>;
4473
+ abort(context: Context$1, options?: ConversationAbortOptions): Promise<void>;
4474
+ waitForIdle(context: Context$1): Promise<void>;
4475
+ entry(id: EntryId, context: Context$1): Promise<EntryRecord | undefined>;
4476
+ submissionByRequest(requestId: string, context: Context$1): Promise<SubmissionId | undefined>;
4477
+ submission(id: SubmissionId, context: Context$1): Promise<Submission | undefined>;
4478
+ busy(context: Context$1): Promise<boolean>;
4479
+ stopSubmission(id: SubmissionId, context: Context$1): Promise<void>;
4480
+ close(): Promise<void>;
4481
+ }
4482
+
4483
+ interface HostSession {
4484
+ sessionId: string;
4485
+ conversation: Conversation;
4486
+ harness: Harness;
4487
+ executionEnv: ExecutionEnv;
4488
+ storage: Storage;
4489
+ close(): Promise<void>;
4490
+ }
4491
+
4492
+ type HostExecutionFactory = (session: { sessionId: string; storage: Storage }, context: Context$1) => Promise<{
4493
+ executionEnv: ExecutionEnv;
4494
+ resolve?: NonNullable<HarnessOptions['env']>;
4495
+ }>;
4496
+
4497
+ interface HostStartOptions {
4498
+ sessionId: string;
4499
+ storage: Storage;
4500
+ execution: ExecutionEnv | HostExecutionFactory;
4501
+ }
4502
+
4503
+ export type { Context$1 as Context, HostExecutionFactory, HostSession, HostStartOptions, PiWatchEvent, RemoteConversation, RemoteInput, ServedConversation };