@arnilo/prism 0.1.3 → 0.1.5

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 (43) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/agent-approval.d.ts +49 -0
  3. package/dist/agent-approval.js +178 -0
  4. package/dist/agent-run-lifecycle.d.ts +5 -1
  5. package/dist/agent-run-lifecycle.js +211 -3
  6. package/dist/agent-session.d.ts +98 -0
  7. package/dist/agent-session.js +1811 -0
  8. package/dist/agent-tool-dispatch.d.ts +13 -0
  9. package/dist/agent-tool-dispatch.js +92 -0
  10. package/dist/agents.d.ts +16 -9
  11. package/dist/agents.js +14 -2267
  12. package/dist/cli-init.d.ts +0 -2
  13. package/dist/cli-init.js +0 -2
  14. package/dist/cli-runner.js +1 -1
  15. package/dist/contracts-core.d.ts +1396 -0
  16. package/dist/contracts-core.js +119 -0
  17. package/dist/contracts-protocol.d.ts +594 -0
  18. package/dist/contracts-protocol.js +2 -0
  19. package/dist/contracts-run-state.d.ts +285 -0
  20. package/dist/contracts-run-state.js +77 -0
  21. package/dist/contracts.d.ts +7 -2269
  22. package/dist/contracts.js +7 -192
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/rpc.js +2 -1
  26. package/docs/agent-loops.md +1 -1
  27. package/docs/agent-session-runtime.md +4 -2
  28. package/docs/browser-automation.md +13 -9
  29. package/docs/coding-agent-tools.md +1 -2
  30. package/docs/compaction-observational-memory.md +5 -6
  31. package/docs/index.md +4 -4
  32. package/docs/migration.md +114 -1
  33. package/docs/performance.md +10 -0
  34. package/docs/provider-conformance.md +2 -2
  35. package/docs/provider-layer.md +1 -1
  36. package/docs/provider-packages.md +1 -1
  37. package/docs/provider-primitives.md +1 -1
  38. package/docs/public-contracts.md +4 -2
  39. package/docs/release-and-install.md +64 -0
  40. package/docs/tool-execution-primitives.md +3 -3
  41. package/docs/tools.md +2 -2
  42. package/docs/use-case-model-selection.md +12 -11
  43. package/package.json +2 -2
@@ -1,2274 +1,12 @@
1
- import type { AudioContent, DocumentContent, FileContent } from "./content.js";
2
- import type { ContributionRegistries } from "./contributions.js";
3
- import type { AgentInput } from "./input.js";
4
- import type { ManifestContributionDeclaration } from "./manifests.js";
5
- import type { Middleware, MiddlewareHookName, MiddlewareRegistry } from "./middleware.js";
6
- import type { SecretRedactor } from "./redaction.js";
7
- import type { PermissionPolicy, TrustPolicy } from "./security.js";
8
- import type { ToolValidator } from "./tools.js";
9
- export type JsonPrimitive = string | number | boolean | null;
10
- export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
11
- export interface JsonObject {
12
- readonly [key: string]: JsonValue;
13
- }
14
- export interface ErrorInfo {
15
- readonly name?: string;
16
- readonly message: string;
17
- readonly code?: string | number;
18
- /** Provider backpressure hint (e.g. from a `Retry-After` header); retry policies
19
- * honor it capped at their own `maxDelayMs`. */
20
- readonly retryAfterMs?: number;
21
- readonly cause?: unknown;
22
- }
23
- export type { AudioContent, DocumentContent, FileContent } from "./content.js";
24
- export type ContentBlock = TextContent | ImageContent | AudioContent | FileContent | DocumentContent | ThinkingContent | ToolCallDeltaContent | ToolCallContent | ToolResultContent;
25
- export interface TextContent {
26
- readonly type: "text";
27
- readonly text: string;
28
- }
29
- export interface ImageContent {
30
- readonly type: "image";
31
- readonly mimeType?: string;
32
- readonly data?: string;
33
- readonly url?: string;
34
- readonly resourceUri?: string;
35
- readonly name?: string;
36
- readonly metadata?: Readonly<Record<string, unknown>>;
37
- }
38
- export interface ThinkingContent {
39
- readonly type: "thinking";
40
- readonly text: string;
41
- readonly signature?: string;
42
- }
43
- export interface ToolCallDeltaContent {
44
- readonly type: "tool_call_delta";
45
- readonly index: number;
46
- readonly id?: string;
47
- readonly name?: string;
48
- readonly argumentsText?: string;
49
- /** Who executes the call. `"provider-hosted"` = the provider runs it server-side;
50
- * the host must NOT dispatch it or send a `tool_result`. Defaults to `"host"`. */
51
- readonly authority?: ToolCallAuthority;
52
- }
53
- export type ToolCallAuthority = "host" | "provider-hosted";
54
- export interface ToolCallContent {
55
- readonly type: "tool_call";
56
- readonly id: string;
57
- readonly name: string;
58
- readonly arguments: JsonObject;
59
- /** Set when streamed arguments failed JSON parse; dispatch blocks without execute(). */
60
- readonly argumentsError?: ErrorInfo;
61
- /** Who executes the call. `"provider-hosted"` = the provider already ran it
62
- * server-side; the host must NOT dispatch it or append a `tool_result`. The
63
- * assistant response text already incorporates the call's effect. */
64
- readonly authority?: ToolCallAuthority;
65
- }
66
- export interface ToolResultContent {
67
- readonly type: "tool_result";
68
- readonly toolCallId: string;
69
- readonly name: string;
70
- readonly result?: unknown;
71
- readonly error?: ErrorInfo;
72
- }
73
- export interface Message {
74
- readonly id?: string;
75
- readonly role: "system" | "user" | "assistant" | "tool";
76
- readonly content: readonly ContentBlock[];
77
- readonly metadata?: Readonly<Record<string, unknown>>;
78
- }
79
- export interface ModelConfig {
80
- readonly provider: string;
81
- readonly model: string;
82
- readonly displayName?: string;
83
- readonly capabilities?: ModelCapabilities;
84
- readonly limits?: ModelLimits;
85
- readonly cost?: ModelCost;
86
- readonly cache?: ModelCacheCapabilities;
87
- readonly compat?: JsonObject;
88
- readonly parameters?: Readonly<Record<string, unknown>>;
89
- readonly metadata?: Readonly<Record<string, unknown>>;
90
- }
91
- export interface ModelCapabilities {
92
- /** Known values include `text`, `image`, `audio`, `file`, and `document`. */
93
- readonly input?: readonly string[];
94
- readonly output?: readonly string[];
95
- readonly reasoning?: boolean;
96
- readonly tools?: boolean;
97
- readonly streaming?: boolean;
98
- /** Native JSON-schema structured output support for this model. */
99
- readonly structuredOutput?: boolean | "json_schema";
100
- }
101
- export interface ModelLimits {
102
- readonly contextWindow?: number;
103
- readonly maxOutputTokens?: number;
104
- }
105
- export interface ModelCost {
106
- readonly input?: number;
107
- readonly output?: number;
108
- readonly cacheRead?: number;
109
- readonly cacheWrite?: number;
110
- readonly currency?: string;
111
- readonly unit?: string;
112
- }
113
- export interface Usage {
114
- readonly inputTokens?: number;
115
- readonly outputTokens?: number;
116
- readonly totalTokens?: number;
117
- readonly cacheReadTokens?: number;
118
- readonly cacheWriteTokens?: number;
119
- readonly cost?: number;
120
- readonly currency?: string;
121
- }
122
- export interface RunLimits {
123
- readonly maxTurns?: number;
124
- readonly maxProviderAttempts?: number;
125
- readonly maxToolRounds?: number;
126
- readonly maxToolCalls?: number;
127
- readonly maxWallTimeMs?: number;
128
- readonly maxRequestBytes?: number;
129
- readonly maxResponseBytes?: number;
130
- readonly maxInputTokens?: number;
131
- readonly maxOutputTokens?: number;
132
- readonly maxTotalTokens?: number;
133
- readonly maxCost?: {
134
- readonly amount: number;
135
- readonly currency: string;
136
- };
137
- }
138
- export type RunLimitName = keyof Required<RunLimits>;
139
- export interface RunLimitCounters {
140
- readonly turns: number;
141
- readonly providerAttempts: number;
142
- readonly toolRounds: number;
143
- readonly toolCalls: number;
144
- readonly wallTimeMs: number;
145
- readonly requestBytes: number;
146
- readonly responseBytes: number;
147
- readonly inputTokens: number;
148
- readonly outputTokens: number;
149
- readonly totalTokens: number;
150
- readonly cost: number;
151
- }
152
- export interface RunLimitBreach {
153
- readonly limit: RunLimitName;
154
- readonly maximum: number;
155
- readonly observed: number;
156
- readonly currency?: string;
157
- }
158
- export type GuardrailStage = "input" | "output" | "tool_input" | "tool_output";
159
- export type GuardrailAction = "allow" | "block" | "tripwire" | "interrupt";
160
- export type GuardrailValue<S extends GuardrailStage> = S extends "input" ? readonly Message[] : S extends "output" ? ProviderTurnResult : S extends "tool_input" ? ToolCallContent : ToolResult;
161
- export interface GuardrailContext<S extends GuardrailStage> {
162
- readonly stage: S;
163
- readonly value: GuardrailValue<S>;
164
- readonly sessionId: string;
165
- readonly runId: string;
166
- readonly toolCallId?: string;
167
- readonly toolName?: string;
168
- readonly metadata: Readonly<Record<string, unknown>>;
169
- readonly signal: AbortSignal;
170
- }
171
- export interface GuardrailDecision {
172
- readonly action: GuardrailAction;
173
- readonly reason?: string;
174
- /** Public data only; Prism JSON-normalizes, bounds, and redacts it before emission. */
175
- readonly metadata?: Readonly<Record<string, unknown>>;
176
- }
177
- export interface Guardrail<S extends GuardrailStage = GuardrailStage> {
178
- readonly name: string;
179
- readonly stage: S;
180
- /** Host-authored stable identity for durable definitions; unused by ordinary runs. */
181
- readonly revision?: string;
182
- evaluate(context: GuardrailContext<S>): GuardrailDecision | Promise<GuardrailDecision>;
183
- }
184
- export interface GuardrailRecord {
185
- readonly guardrail: string;
186
- readonly stage: GuardrailStage;
187
- readonly action: GuardrailAction;
188
- readonly reason?: string;
189
- readonly metadata?: Readonly<Record<string, unknown>>;
190
- }
191
- export interface Guardrails {
192
- readonly input?: readonly Guardrail<"input">[];
193
- readonly output?: readonly Guardrail<"output">[];
194
- readonly toolInput?: readonly Guardrail<"tool_input">[];
195
- readonly toolOutput?: readonly Guardrail<"tool_output">[];
196
- /** Defaults to sequential; at most 16 stage evaluations run at once. */
197
- readonly maxConcurrency?: number;
198
- }
199
- export type CacheRetention = "none" | "short" | "long";
200
- export type PromptCacheKind = "implicit" | "openai_key" | "cache_control" | "provider_specific" | "none";
201
- export interface ModelCacheCapabilities {
202
- readonly kind?: PromptCacheKind;
203
- readonly maxKeyLength?: number;
204
- readonly maxBreakpoints?: number;
205
- readonly minCacheableTokens?: number;
206
- readonly longRetention?: boolean;
207
- }
208
- export type PromptCacheMode = "auto" | "on" | "off";
209
- export type PromptCacheBreakpointLocation = "system_prompt" | "tools" | "stable_context" | "last_stable_message" | "last_user_message" | "message_id";
210
- export type PromptCacheBreakpointTtl = "short" | "long";
211
- export interface PromptCacheBreakpoint {
212
- readonly location: PromptCacheBreakpointLocation;
213
- readonly messageId?: string;
214
- readonly ttl?: PromptCacheBreakpointTtl;
215
- }
216
- export interface PromptCacheHints {
217
- readonly mode?: PromptCacheMode;
218
- readonly key?: string;
219
- readonly retention?: CacheRetention;
220
- readonly breakpoints?: readonly PromptCacheBreakpoint[];
221
- }
222
- export interface StructuredOutputOptions {
223
- readonly name: string;
224
- readonly schema: JsonObject;
225
- readonly strict?: boolean;
226
- }
227
- export interface ProviderRequestOptions {
228
- readonly sessionId?: string;
229
- readonly cacheRetention?: CacheRetention;
230
- readonly cacheKey?: string;
231
- readonly cache?: PromptCacheHints;
232
- readonly headers?: Readonly<Record<string, string>>;
233
- /** @deprecated Provider-level timeout is inert in first-party providers; pass an AbortSignal/RunOptions.signal instead. */
234
- readonly timeoutMs?: number;
235
- /** @deprecated Provider-level retry is inert in first-party providers; use AgentConfig.retry/RunOptions.retry instead. */
236
- readonly maxRetries?: number;
237
- /** @deprecated Provider-level retry is inert in first-party providers; use AgentConfig.retry/RunOptions.retry instead. */
238
- readonly maxRetryDelayMs?: number;
239
- readonly compat?: JsonObject;
240
- readonly extra?: JsonObject;
241
- /** Provider-neutral JSON-schema structured output request. Requires model `capabilities.structuredOutput`. */
242
- readonly structuredOutput?: StructuredOutputOptions;
243
- /** Opaque provider continuation cursor (e.g. OpenAI `previous_response_id`). When set,
244
- * the provider resumes from this cursor instead of re-sending full history. */
245
- readonly continuation?: {
246
- readonly cursor: string;
247
- };
248
- }
249
- export interface ProviderRequest {
250
- readonly model: ModelConfig;
251
- readonly messages: readonly Message[];
252
- readonly tools?: readonly ToolDefinition[];
253
- readonly context?: readonly ContextBlock[];
254
- readonly options?: ProviderRequestOptions;
255
- readonly metadata?: Readonly<Record<string, unknown>>;
256
- readonly signal?: AbortSignal;
257
- }
258
- export type ProviderEvent = {
259
- readonly type: "message_start";
260
- readonly messageId?: string;
261
- } | {
262
- readonly type: "content_delta";
263
- readonly content: ContentBlock;
264
- } | {
265
- readonly type: "tool_call_delta";
266
- readonly index: number;
267
- readonly id?: string;
268
- readonly name?: string;
269
- readonly argumentsText?: string;
270
- readonly authority?: ToolCallAuthority;
271
- } | {
272
- readonly type: "tool_call";
273
- readonly call: ToolCallContent;
274
- } | {
275
- readonly type: "usage";
276
- readonly usage: Usage;
277
- } | {
278
- readonly type: "continuation_required";
279
- readonly cursor: string;
280
- readonly reason?: string;
281
- } | {
282
- readonly type: "done";
283
- readonly usage?: Usage;
284
- } | {
285
- readonly type: "error";
286
- readonly error: ErrorInfo;
287
- };
288
- export interface AIProvider {
289
- readonly id: string;
290
- generate(request: ProviderRequest): AsyncIterable<ProviderEvent>;
291
- }
292
- export type ProviderResolver = (model: ModelConfig) => AIProvider | undefined;
293
- /** Realtime audio/session event. Realtime is a bidirectional session, not a request/response
294
- * stream, so it is a separate neutral seam from `AIProvider.generate()`. Credentials are
295
- * bound to the session handshake only and never appear in events. */
296
- export type RealtimeEvent = {
297
- readonly type: "session_started";
298
- readonly sessionId?: string;
299
- } | {
300
- readonly type: "audio_delta";
301
- readonly audio: Uint8Array;
302
- } | {
303
- readonly type: "transcript_delta";
304
- readonly text: string;
305
- readonly role: "user" | "assistant";
306
- } | {
307
- readonly type: "tool_call";
308
- readonly call: ToolCallContent;
309
- } | {
310
- readonly type: "interrupted";
311
- } | {
312
- readonly type: "session_closed";
313
- readonly reason?: string;
314
- } | {
315
- readonly type: "error";
316
- readonly error: ErrorInfo;
317
- };
318
- /** Neutral bidirectional realtime session seam. The provider owns the transport
319
- * (e.g. WebSocket); the host owns audio capture/playback and session lifecycle. */
320
- export interface RealtimeSession {
321
- readonly id: string;
322
- readonly provider: string;
323
- /** Send an audio chunk (PCM/Opus; provider-specific format set at creation). */
324
- sendAudio(chunk: Uint8Array, options?: {
325
- readonly signal?: AbortSignal;
326
- }): Promise<void>;
327
- /** Inbound events (audio out, transcripts, hosted tool calls, interruption, close, error). */
328
- events(): AsyncIterable<RealtimeEvent>;
329
- /** Request the provider stop the current response mid-stream. */
330
- interrupt(options?: {
331
- readonly signal?: AbortSignal;
332
- }): Promise<void>;
333
- /** Close the session and release the transport. Idempotent. */
334
- close(reason?: string, options?: {
335
- readonly signal?: AbortSignal;
336
- }): Promise<void>;
337
- }
338
- /** Factory a provider exposes for realtime sessions; not part of `AIProvider`. */
339
- export type RealtimeSessionFactory = (options: RealtimeSessionOptions) => RealtimeSession;
340
- export interface RealtimeSessionOptions {
341
- readonly model: ModelConfig;
342
- readonly signal?: AbortSignal;
343
- /** Provider-specific caps override; providers enforce finite defaults. */
344
- readonly caps?: RealtimeCaps;
345
- }
346
- export interface RealtimeCaps {
347
- readonly maxAudioEventsPerSecond?: number;
348
- readonly maxBytesPerSecond?: number;
349
- readonly maxWallMs?: number;
350
- }
351
- export type InputAssemblyLayout = "legacy" | "cache_aware";
352
- export interface RunOptions {
353
- readonly signal?: AbortSignal;
354
- readonly model?: ModelConfig;
355
- readonly providerSource?: ProviderResolver;
356
- /** @deprecated Use `limits.maxToolRounds`. */
357
- readonly maxToolRounds?: number;
358
- /** Run-scoped ceilings. When an agent config also sets limits, these can only narrow it. */
359
- readonly limits?: RunLimits;
360
- readonly providerOptions?: ProviderRequestOptions;
361
- readonly providerRequestPolicies?: ProviderRequestPolicy | readonly ProviderRequestPolicy[];
362
- readonly systemPrompt?: SystemPromptConfig;
363
- readonly compaction?: false | CompactionOptions;
364
- readonly retry?: false | RetryOptions;
365
- readonly metadata?: Readonly<Record<string, unknown>>;
366
- readonly redactor?: SecretRedactor;
367
- readonly runLedger?: RunLedger;
368
- /** Optional durable recovery store. Per-run value overrides this agent default. */
369
- readonly effectStore?: ToolEffectStore;
370
- readonly ownership?: OwnershipScope;
371
- /** Host-verified identity; when set, must project onto `ownership` without widening. */
372
- readonly identity?: import("./identity.js").AgentIdentity;
373
- readonly idempotencyKey?: string;
374
- readonly validate?: ToolValidator;
375
- readonly activeSkills?: readonly string[];
376
- readonly skills?: readonly Skill[];
377
- /** Migration opt-in: activate every skill in a configured `SkillRegistry` when `activeSkills` / `skills` are unset. */
378
- readonly activateAllSkills?: true;
379
- /** Progressive: catalog (name+description) unless loaded; eager: full instructions every turn. Default progressive. */
380
- readonly skillsDisclosure?: import("./skill-disclosure.js").SkillsDisclosure;
381
- /** Opt-in projection-only fold for aged large tool results in provider view; store untouched. */
382
- readonly toolResultFold?: import("./tool-result-fold.js").ToolResultFoldOptions;
383
- readonly instructionInjectors?: readonly InstructionInjector[];
384
- readonly inputLayout?: InputAssemblyLayout;
385
- readonly loop?: AgentLoopStrategy | AgentLoopOptions;
386
- /** Appended to agent-level guardrails for this run. */
387
- readonly guardrails?: Guardrails;
388
- /** Opt-in durable interruption/checkpointing. */
389
- readonly runState?: AgentRunStateOptions;
390
- }
391
- export interface AgentDefinition {
392
- readonly name: string;
393
- readonly description?: string;
394
- /** Direct model config, or a model id resolved from `registries.models`. */
395
- readonly model?: ModelConfig | string;
396
- /** Tool names to activate from the active tool registry / `registries.tools`. */
397
- readonly tools?: readonly string[];
398
- /** Skill names resolved through `resolveActiveSkills()`; `toolNames` enforcement applies. */
399
- readonly skills?: readonly string[];
400
- /** Context provider names from `registries.contextProviders`. */
401
- readonly context?: readonly string[];
402
- readonly systemPrompt?: SystemPromptConfig;
403
- readonly instructions?: string;
404
- readonly loop?: AgentLoopStrategy | AgentLoopOptions;
405
- readonly metadata?: Readonly<Record<string, unknown>>;
406
- /** Optional escape hatch. When present, overrides declarative resolution. */
407
- create?(config?: AgentConfig): Promise<Agent> | Agent;
408
- }
409
- /** Input to {@link resolveAgentDefinition}. All fields are optional; the host
410
- * controls scope by which registries it passes. */
411
- export interface AgentDefinitionResolutionContext {
412
- readonly registries?: ContributionRegistries;
413
- readonly providerSource?: ProviderResolver;
414
- readonly tools?: ToolRegistry | readonly ToolDefinition[];
415
- readonly skillsRegistry?: SkillRegistry;
416
- /** Migration-only: omitted `tools`/`skills` activate every in-scope tool/skill. Defaults to fail-closed. */
417
- readonly activateAllCapabilities?: true;
418
- readonly overrides?: Partial<AgentConfig>;
419
- }
420
- export interface AgentConfig {
421
- readonly id?: string;
422
- readonly name?: string;
423
- readonly instructions?: string;
424
- readonly model: ModelConfig;
425
- readonly provider?: AIProvider;
426
- readonly providerSource?: ProviderResolver;
427
- readonly tools?: ToolRegistry | readonly ToolDefinition[];
428
- readonly context?: readonly ContextProvider[];
429
- readonly skills?: SkillRegistry | readonly Skill[];
430
- /** Migration opt-in: activate every registry skill by default when run options do not narrow activation. */
431
- readonly activateAllSkills?: true;
432
- /** Progressive: catalog (name+description) unless loaded; eager: full instructions every turn. Default progressive. */
433
- readonly skillsDisclosure?: import("./skill-disclosure.js").SkillsDisclosure;
434
- /** Opt-in projection-only fold for aged large tool results in provider view; store untouched. */
435
- readonly toolResultFold?: import("./tool-result-fold.js").ToolResultFoldOptions;
436
- readonly inputBuilder?: InputBuilder;
437
- readonly promptBuilder?: PromptBuilder;
438
- readonly middleware?: MiddlewareRegistry;
439
- readonly resourceLoader?: ResourceLoader;
440
- readonly store?: SessionStore;
441
- readonly permission?: PermissionPolicy;
442
- /** Optional trust check for tool and resource targets. */
443
- readonly trust?: TrustPolicy;
444
- readonly providerOptions?: ProviderRequestOptions;
445
- readonly providerRequestPolicies?: ProviderRequestPolicy | readonly ProviderRequestPolicy[];
446
- readonly systemPrompt?: SystemPromptConfig;
447
- readonly redactor?: SecretRedactor;
448
- readonly runLedger?: RunLedger;
449
- /** Optional durable recovery store. */
450
- readonly effectStore?: ToolEffectStore;
451
- readonly ownership?: OwnershipScope;
452
- /** Host-verified identity default for sessions created from this agent. */
453
- readonly identity?: import("./identity.js").AgentIdentity;
454
- readonly idempotencyKey?: string;
455
- readonly compaction?: false | CompactionOptions;
456
- readonly retry?: false | RetryOptions;
457
- /** Agent-wide ceilings; per-run limits may only narrow these values. */
458
- readonly limits?: RunLimits;
459
- readonly metadata?: Readonly<Record<string, unknown>>;
460
- readonly validator?: ToolValidator;
461
- readonly instructionInjectors?: readonly InstructionInjector[];
462
- readonly inputLayout?: InputAssemblyLayout;
463
- readonly loop?: AgentLoopStrategy | AgentLoopOptions;
464
- readonly guardrails?: Guardrails;
465
- /** Opt-in durable interruption/checkpointing default for this agent. */
466
- readonly runState?: AgentRunStateOptions;
467
- /** Internal marker set by createSecureAgent(); makes security defaults immutable per run. */
468
- readonly secure?: true;
469
- }
470
- /** Opt-in fail-closed composition over the normal explicit AgentConfig API. */
471
- export interface SecureAgentOptions extends Omit<AgentConfig, "tools" | "validator" | "redactor" | "permission" | "trust" | "ownership" | "identity" | "limits" | "runState" | "secure"> {
472
- readonly id: string;
473
- readonly tools: readonly ToolDefinition[];
474
- readonly toolArgumentValidator: import("./tools.js").ToolArgumentValidator;
475
- readonly redactor: SecretRedactor;
476
- readonly permission: PermissionPolicy;
477
- readonly trust: TrustPolicy;
478
- readonly ownership: OwnershipScope;
479
- /** Optional host-verified identity; when set must match `ownership`. */
480
- readonly identity?: import("./identity.js").AgentIdentity;
481
- readonly limits: RunLimits;
482
- readonly definitionRevision: string;
483
- readonly runState: Omit<AgentRunStateOptions, "definitionRevision" | "interruptBeforeTool">;
484
- }
485
- export interface Agent {
486
- readonly config: AgentConfig;
487
- createSession(config?: AgentSessionConfig): AgentSession;
488
- }
489
- export interface AgentSessionConfig {
490
- readonly id?: string;
491
- readonly agent?: Agent;
492
- readonly store?: SessionStore;
493
- readonly leafId?: string;
494
- readonly metadata?: Readonly<Record<string, unknown>>;
495
- }
496
- export interface AgentSessionForkOptions {
497
- readonly leafId?: string;
498
- }
499
- export interface AgentSessionCloneOptions {
500
- readonly id?: string;
501
- readonly leafId?: string;
502
- }
503
- export type SubscriberOverflowPolicy = "close" | "drop_oldest" | "drop_newest";
504
- export interface SubscribeOptions {
505
- /** Maximum queued events for a subscriber that is not actively awaiting `next()`. Defaults to 1024. */
506
- readonly maxQueuedEvents?: number;
507
- /** What to do when `maxQueuedEvents` is reached. Defaults to `close`. */
508
- readonly overflow?: SubscriberOverflowPolicy;
509
- }
510
- export type AgentRunStatus = "succeeded" | "failed" | "aborted" | "suspended" | "denied";
511
- export type AgentRunInterruptionKind = "input_guardrail" | "tool_approval" | "elicitation";
512
- export type ApprovalOutcome = "allow_once" | "allow_for_run" | "reject_once" | "reject_for_run";
513
- export type PendingDecisionKind = "tool_approval" | "elicitation";
514
- /** Redacted match scope for one pending or sticky decision; never contains raw tool arguments. */
515
- export interface DecisionScope {
516
- readonly toolName?: string;
517
- readonly effectKind?: ToolEffectKind;
518
- /** Redacted principal reference (tenant/kind/id); never a credential. */
519
- readonly identity?: string;
520
- /** Bounded argument-value constraints; deep-equal matched per key. */
521
- readonly actionConstraints?: Readonly<Record<string, JsonValue>>;
522
- /** SHA-256 of canonical JSON arguments; present instead of raw arguments. */
523
- readonly argumentsHash?: string;
524
- }
525
- /** One redacted, unresolved approval request inside a suspended durable run. */
526
- export interface PendingDecision {
527
- /** Unique within the run; nested runs use supervisor-prefixed ids. */
528
- readonly approvalId: string;
529
- readonly kind: PendingDecisionKind;
530
- readonly toolCallId?: string;
531
- readonly scope: DecisionScope;
532
- /** Bounded, redacted. */
533
- readonly reason: string;
534
- /** Typed payload contract for elicitation decisions. */
535
- readonly elicitationSchema?: JsonObject;
536
- /** Delegation chain, root-first; core-written, never client-supplied. */
537
- readonly attribution?: {
538
- readonly path: readonly string[];
539
- };
540
- }
541
- /** Redacted safe-boundary descriptor; never contains tool arguments. */
542
- export interface AgentRunInterruption {
543
- readonly kind: AgentRunInterruptionKind;
544
- readonly reason: string;
545
- readonly toolCallId?: string;
546
- readonly toolName?: string;
547
- /** All unresolved approval requests of this suspension; absent for legacy single approvals. */
548
- readonly pendingDecisions?: readonly PendingDecision[];
549
- }
550
- /** One host decision applied to one pending approval request. */
551
- export interface RunDecision {
552
- readonly approvalId: string;
553
- readonly outcome: ApprovalOutcome;
554
- /** Bounded to 2 KiB; redacted. */
555
- readonly reason?: string;
556
- /** Revalidated (schema, guardrails, policy) before dispatch; produces a new arguments hash. */
557
- readonly modifiedArguments?: JsonObject;
558
- /** Elicitation payload; validated against the pending decision's elicitationSchema. */
559
- readonly elicitation?: JsonObject;
560
- }
561
- /** Run-scoped sticky decision; exact scope match, rechecked against policy, dropped at run end. */
562
- export interface StickyDecision {
563
- readonly scope: DecisionScope;
564
- readonly outcome: "allow_for_run" | "reject_for_run";
565
- readonly reason?: string;
566
- readonly decidedAt: string;
567
- /** Delegation path when the sticky was created for a nested-run decision. */
568
- readonly attribution?: {
569
- readonly path: readonly string[];
570
- };
571
- }
572
- /** Root-visible link between one nested approval and the child-run approval id. */
573
- export interface NestedRunApproval {
574
- /** Root-visible approval id (hashed, non-enumerating across runs). */
575
- readonly id: string;
576
- /** Approval id as the nested run recorded it. */
577
- readonly childApprovalId: string;
578
- }
579
- /** Root-visible link between a suspended nested run and the tool call that hosted it. */
580
- export interface NestedRunRef {
581
- readonly runId: string;
582
- readonly sessionId?: string;
583
- readonly toolCallId: string;
584
- /** Redacted delegation path (child ids, root first). */
585
- readonly path: readonly string[];
586
- readonly approvals: readonly NestedRunApproval[];
587
- /** Decisions persisted by a partial batch, keyed by root-visible approval id. */
588
- readonly decisions?: Readonly<Record<string, RunDecision>>;
589
- }
590
- /** Outcome of resuming a nested run through the host-supplied hook. */
591
- export type NestedRunOutcome = {
592
- readonly status: "suspended";
593
- readonly pendingDecisions: readonly PendingDecision[];
594
- } | {
595
- readonly status: "completed";
596
- readonly value?: JsonValue;
597
- } | {
598
- readonly status: "failed";
599
- readonly code: string;
600
- readonly message: string;
601
- };
602
1
  /**
603
- * Host hook that resumes a nested run (supervisor child) with child-visible decisions.
604
- * Used both when a nested suspension first surfaces (sticky auto-apply) and when root
605
- * decisions route back to the child on resume.
2
+ * Contracts barrel (0.1.4 god-module split): re-exports the full public
3
+ * contracts surface from the three concern-split modules
4
+ * (contracts-core / contracts-run-state / contracts-protocol) so the
5
+ * import surface of `./contracts.js` is unchanged.
606
6
  */
607
- export type ResumeNestedRun = (nested: {
608
- readonly ref: AgentRunRef;
609
- readonly toolCallId: string;
610
- readonly path: readonly string[];
611
- }, decisions: readonly RunDecision[]) => Promise<NestedRunOutcome>;
612
- /**
613
- * Thrown by a delegated-run host (e.g. the supervisor) when a nested run suspends on
614
- * pending decisions inside a tool execution. Core converts it into a root suspension
615
- * with attributed, root-visible approval ids; the dispatching wrapper attaches `toolCall`.
616
- */
617
- export declare class AgentDelegationSuspendedError extends Error {
618
- readonly ref: AgentRunRef;
619
- readonly pendingDecisions: readonly PendingDecision[];
620
- /** Redacted delegation path (child ids) used when decisions carry no attribution. */
621
- readonly path?: readonly string[] | undefined;
622
- readonly code = "ERR_PRISM_DELEGATION_SUSPENDED";
623
- toolCall?: ToolCallContent;
624
- constructor(ref: AgentRunRef, pendingDecisions: readonly PendingDecision[],
625
- /** Redacted delegation path (child ids) used when decisions carry no attribution. */
626
- path?: readonly string[] | undefined);
627
- }
628
- /** Shared decision-contract violations. Unknown and foreign approval ids share one non-enumerating error. */
629
- export declare class AgentDecisionError extends Error {
630
- readonly code: "ERR_PRISM_DECISION_STALE" | "ERR_PRISM_DECISION_UNKNOWN" | "ERR_PRISM_DECISION_DUPLICATE" | "ERR_PRISM_DECISION_SCOPE" | "ERR_PRISM_DECISION_INVALID" | "ERR_PRISM_DECISION_LIMIT";
631
- constructor(code: "ERR_PRISM_DECISION_STALE" | "ERR_PRISM_DECISION_UNKNOWN" | "ERR_PRISM_DECISION_DUPLICATE" | "ERR_PRISM_DECISION_SCOPE" | "ERR_PRISM_DECISION_INVALID" | "ERR_PRISM_DECISION_LIMIT", message: string, options?: {
632
- readonly cause?: unknown;
633
- });
634
- }
635
- export declare const DEFAULT_MAX_PENDING_DECISIONS = 32;
636
- export declare const HARD_MAX_PENDING_DECISIONS = 128;
637
- export declare const DEFAULT_MAX_STICKY_DECISIONS = 64;
638
- export declare const HARD_MAX_STICKY_DECISIONS = 256;
639
- export declare const MAX_DECISION_REASON_BYTES: number;
640
- export declare const HARD_MAX_DECISION_REASON_BYTES: number;
641
- export declare const MAX_ELICITATION_BYTES: number;
642
- export declare const HARD_MAX_ELICITATION_BYTES: number;
643
- export declare const MAX_ACTION_CONSTRAINTS = 32;
644
- export declare const HARD_MAX_ACTION_CONSTRAINTS = 64;
645
- /** Maximum delegation attribution depth for surfaced nested pending decisions. */
646
- export declare const MAX_ATTRIBUTION_DEPTH = 8;
647
- export declare const MAX_ACTION_CONSTRAINT_BYTES: number;
648
- export declare const HARD_MAX_ACTION_CONSTRAINT_BYTES: number;
649
- export interface AgentRunStateOptions {
650
- readonly checkpoints: CheckpointStore;
651
- /** Host-authored immutable revision required for durable runs. */
652
- readonly definitionRevision: string;
653
- /** Suspend every tool call before its side effect. */
654
- readonly interruptBeforeTool?: boolean;
655
- readonly maxStateBytes?: number;
656
- readonly fencingToken?: number;
657
- /** Enables sticky auto-apply when a nested suspension first surfaces during this run. */
658
- readonly resumeNestedRun?: ResumeNestedRun;
659
- /**
660
- * Opt-in (plan 015 Task 4): persist the session's loaded-skill names in the run-state
661
- * checkpoint and restore them on resume. Names only — bodies reload via `load_skill`.
662
- * Default off: checkpoint shape is identical to 0.1.2.
663
- */
664
- readonly persistSessionState?: boolean;
665
- }
666
- /** Versioned, redacted checkpoint payload. Treat as opaque except status/version/interruption. */
667
- export interface AgentRunState {
668
- readonly schemaVersion: 1;
669
- readonly agentId: string;
670
- readonly definitionRevision: string;
671
- readonly fingerprint: string;
672
- readonly runId: string;
673
- readonly sessionId: string;
674
- readonly leafId?: string;
675
- readonly model: ModelConfig;
676
- readonly status: AgentRunStatus | "running";
677
- readonly interruption?: AgentRunInterruption;
678
- readonly version?: number;
679
- }
680
- export interface AgentRunResume {
681
- readonly expectedVersion: number;
682
- /** Legacy single-approval path; `approve` allows all pending once, `deny` terminates the run denied. */
683
- readonly decision?: "approve" | "deny";
684
- /** Batch decision path; exactly one of decision/decisions. Applied as one atomic CAS transition. */
685
- readonly decisions?: readonly RunDecision[];
686
- }
687
- export interface AgentRunResumeOptions {
688
- readonly checkpoints: CheckpointStore;
689
- /** Current host-authored revision; must exactly match the checkpoint. */
690
- readonly definitionRevision: string;
691
- readonly ownership?: OwnershipScope;
692
- readonly fencingToken?: number;
693
- /** Routes root decisions for nested-run approvals back to the child (e.g. supervisor). */
694
- readonly resumeNestedRun?: ResumeNestedRun;
695
- /** Opt-in (plan 015 Task 4): restore persisted loaded-skill names into the resumed session catalog. */
696
- readonly persistSessionState?: boolean;
697
- }
698
- /** Bounded, abortable options for `resumeAgentRunStream()`. */
699
- export interface AgentRunResumeStreamOptions extends AgentRunResumeOptions, SubscribeOptions {
700
- readonly signal?: AbortSignal;
701
- }
702
- export interface AgentRunRef {
703
- readonly runId: string;
704
- readonly sessionId?: string;
705
- }
706
- export interface AgentRunStatusResult {
707
- readonly state: AgentRunState;
708
- readonly version: number;
709
- }
710
- export declare class AgentRunStateError extends Error {
711
- readonly code = "ERR_PRISM_AGENT_RUN_STATE";
712
- constructor(message: string);
713
- }
714
- /** Durable-loop contract violations: hook-less custom strategy on a durable run, invalid snapshot, or revision drift. */
715
- export declare class AgentLoopStateError extends Error {
716
- readonly code: "ERR_PRISM_LOOP_NOT_DURABLE" | "ERR_PRISM_LOOP_SNAPSHOT" | "ERR_PRISM_LOOP_REVISION";
717
- constructor(code: "ERR_PRISM_LOOP_NOT_DURABLE" | "ERR_PRISM_LOOP_SNAPSHOT" | "ERR_PRISM_LOOP_REVISION", message: string, options?: {
718
- readonly cause?: unknown;
719
- });
720
- }
721
- /** Terminal result of `session.run()` / `session.prompt()`. Failed and aborted runs throw {@link AgentRunError} with this shape attached. */
722
- export interface AgentRunResult {
723
- readonly sessionId: string;
724
- readonly runId: string;
725
- readonly status: AgentRunStatus;
726
- /** Branch leaf after the run settles. */
727
- readonly leafId?: string;
728
- /** Concatenated text blocks from the final assistant message, or `""` when none. */
729
- readonly text: string;
730
- /** Content blocks from the final assistant message, or `[]` when none. */
731
- readonly content: readonly ContentBlock[];
732
- /** Final assistant message when the run produced one. */
733
- readonly message?: Message;
734
- /** Aggregate usage across provider turns (`run_total` scope). */
735
- readonly usage?: Usage;
736
- /** Present when the run hit a configured resource ceiling. */
737
- readonly limit?: RunLimitBreach;
738
- /** Present when `status` is `"failed"` or when a failed attempt still produced partial output. */
739
- readonly error?: ErrorInfo;
740
- /** String form of the abort reason when `status` is `"aborted"`. */
741
- readonly abortReason?: string;
742
- /** Present for durable suspended/terminal runs. Payload is redacted and bounded. */
743
- readonly runState?: AgentRunState;
744
- /** Present only while awaiting an operator decision. */
745
- readonly interruption?: AgentRunInterruption;
746
- }
747
- export declare class AgentRunError extends Error {
748
- readonly result: AgentRunResult;
749
- constructor(result: AgentRunResult, options?: {
750
- readonly cause?: unknown;
751
- });
752
- }
753
- /** Mid-run steer queue: default pending message count (fail closed at this cap). */
754
- export declare const DEFAULT_MAX_PENDING_STEERS = 8;
755
- /** Absolute pending steer count ceiling if hosts later expose overrides. */
756
- export declare const HARD_MAX_PENDING_STEERS = 32;
757
- /** Mid-run steer queue: default total UTF-8 byte budget across pending messages. */
758
- export declare const DEFAULT_MAX_PENDING_STEER_BYTES: number;
759
- /** Absolute pending steer byte ceiling if hosts later expose overrides. */
760
- export declare const HARD_MAX_PENDING_STEER_BYTES: number;
761
- export interface SteerOptions {
762
- /**
763
- * When true, abort the in-flight provider stream and continue the same run after
764
- * injecting steered user text. Default false: inject before the next provider turn
765
- * (after the current tool batch completes).
766
- */
767
- readonly softInterrupt?: boolean;
768
- }
769
- export interface AgentSession {
770
- readonly id: string;
771
- /** Current branch leaf entry id; advances on every append/run and is re-pointed by `checkout`.
772
- * Undefined until the first entry lands (a fresh session with no history). */
773
- readonly leafId: string | undefined;
774
- run(input: string | Message | readonly Message[], options?: RunOptions): Promise<AgentRunResult>;
775
- prompt(input: string, options?: RunOptions): Promise<AgentRunResult>;
776
- /**
777
- * Enqueue user text into an active run. Default injects before the next provider turn.
778
- * `softInterrupt: true` aborts the current provider stream, then continues the same run.
779
- * Fails closed when no run is active or the pending queue exceeds caps.
780
- */
781
- steer(input: string | Message | readonly Message[], options?: SteerOptions): void;
782
- /** Subscribe first, then start exactly one run and yield only that run's events until it terminates. */
783
- stream(input: string | Message | readonly Message[], options?: RunOptions & SubscribeOptions): AsyncIterable<AgentEvent>;
784
- compact(options?: CompactionOptions): Promise<CompactionResult>;
785
- subscribe(options?: SubscribeOptions): AsyncIterable<AgentEvent>;
786
- abort(reason?: unknown): void;
787
- entries(): Promise<readonly SessionEntry[]>;
788
- checkout(leafId?: string): Promise<void>;
789
- fork(options?: AgentSessionForkOptions): AgentSession;
790
- clone(options?: AgentSessionCloneOptions): Promise<AgentSession>;
791
- }
792
- export interface ProviderTurnMetadata {
793
- readonly providerId: string;
794
- readonly model: ModelConfig;
795
- readonly requestId?: string;
796
- readonly latencyMs?: number;
797
- readonly attempt?: number;
798
- readonly httpStatus?: number;
799
- readonly rateLimitRemaining?: number;
800
- readonly rateLimitResetMs?: number;
801
- }
802
- export interface ToolExecutionMetadata {
803
- readonly durationMs: number;
804
- readonly status: ToolCallStatus;
805
- }
806
- export type AgentEvent = {
807
- readonly type: "agent_started";
808
- readonly sessionId: string;
809
- readonly runId: string;
810
- } | {
811
- readonly type: "agent_finished";
812
- readonly sessionId: string;
813
- readonly runId: string;
814
- readonly usage?: Usage;
815
- } | {
816
- readonly type: "agent_suspended";
817
- readonly sessionId: string;
818
- readonly runId: string;
819
- readonly interruption: AgentRunInterruption;
820
- readonly version: number;
821
- } | {
822
- readonly type: "agent_resumed";
823
- readonly sessionId: string;
824
- readonly runId: string;
825
- readonly version: number;
826
- } | {
827
- readonly type: "agent_denied";
828
- readonly sessionId: string;
829
- readonly runId: string;
830
- readonly interruption: AgentRunInterruption;
831
- readonly version: number;
832
- } | {
833
- readonly type: "turn_started";
834
- readonly sessionId: string;
835
- readonly runId: string;
836
- readonly turn: number;
837
- } | {
838
- readonly type: "turn_finished";
839
- readonly sessionId: string;
840
- readonly runId: string;
841
- readonly turn: number;
842
- } | {
843
- readonly type: "provider_turn_started";
844
- readonly sessionId: string;
845
- readonly runId: string;
846
- readonly turn: number;
847
- readonly metadata: ProviderTurnMetadata;
848
- } | {
849
- readonly type: "provider_turn_finished";
850
- readonly sessionId: string;
851
- readonly runId: string;
852
- readonly turn: number;
853
- readonly metadata: ProviderTurnMetadata;
854
- readonly usage?: Usage;
855
- readonly error?: ErrorInfo;
856
- } | {
857
- readonly type: "message_started";
858
- readonly sessionId: string;
859
- readonly runId: string;
860
- readonly message: Message;
861
- } | {
862
- readonly type: "message_delta";
863
- readonly sessionId: string;
864
- readonly runId: string;
865
- readonly content: ContentBlock;
866
- } | {
867
- readonly type: "message_finished";
868
- readonly sessionId: string;
869
- readonly runId: string;
870
- readonly message: Message;
871
- } | {
872
- readonly type: "tool_execution_started";
873
- readonly sessionId: string;
874
- readonly runId: string;
875
- readonly call: ToolCallContent;
876
- } | {
877
- readonly type: "tool_execution_progress";
878
- readonly sessionId: string;
879
- readonly runId: string;
880
- readonly toolCallId: string;
881
- readonly name: string;
882
- readonly progress?: unknown;
883
- readonly metadata?: Readonly<Record<string, unknown>>;
884
- } | {
885
- readonly type: "tool_execution_finished";
886
- readonly sessionId: string;
887
- readonly runId: string;
888
- readonly result: ToolResult;
889
- readonly metadata: ToolExecutionMetadata;
890
- } | {
891
- readonly type: "tool_execution_error";
892
- readonly sessionId: string;
893
- readonly runId: string;
894
- readonly call: ToolCallContent;
895
- readonly error: ErrorInfo;
896
- readonly metadata: ToolExecutionMetadata;
897
- } | {
898
- readonly type: "tool_execution_blocked";
899
- readonly sessionId: string;
900
- readonly runId: string;
901
- readonly toolCallId: string;
902
- readonly name: string;
903
- readonly reason: string;
904
- readonly error: ErrorInfo;
905
- readonly metadata: ToolExecutionMetadata;
906
- } | {
907
- readonly type: "guardrail_decision";
908
- readonly sessionId: string;
909
- readonly runId: string;
910
- readonly toolCallId?: string;
911
- readonly toolName?: string;
912
- readonly record: GuardrailRecord;
913
- } | {
914
- readonly type: "run_limit_exceeded";
915
- readonly sessionId: string;
916
- readonly runId: string;
917
- readonly breach: RunLimitBreach;
918
- } | {
919
- readonly type: "queue_updated";
920
- readonly sessionId: string;
921
- readonly runId: string;
922
- readonly size: number;
923
- } | {
924
- /** A steered message was dropped by a terminal input guardrail; the run continues without it. */
925
- readonly type: "steer_rejected";
926
- readonly sessionId: string;
927
- readonly runId: string;
928
- readonly message: Message;
929
- readonly record: GuardrailRecord;
930
- } | {
931
- readonly type: "event_subscriber_overflow";
932
- readonly sessionId: string;
933
- readonly runId?: string;
934
- readonly droppedEvents: number;
935
- readonly maxQueuedEvents: number;
936
- readonly overflow: SubscriberOverflowPolicy;
937
- } | {
938
- readonly type: "compaction_started";
939
- readonly sessionId: string;
940
- readonly runId?: string;
941
- } | {
942
- readonly type: "compaction_finished";
943
- readonly sessionId: string;
944
- readonly runId?: string;
945
- readonly summary: string;
946
- } | {
947
- readonly type: "retry_scheduled";
948
- readonly sessionId: string;
949
- readonly runId: string;
950
- readonly attempt: number;
951
- readonly delayMs: number;
952
- readonly error: ErrorInfo;
953
- } | {
954
- readonly type: "error";
955
- readonly sessionId?: string;
956
- readonly runId?: string;
957
- readonly error: ErrorInfo;
958
- } | {
959
- readonly type: "artifact_validation_started";
960
- readonly sessionId: string;
961
- readonly runId: string;
962
- readonly turn: number;
963
- readonly attempt: number;
964
- } | {
965
- readonly type: "artifact_validation_finished";
966
- readonly sessionId: string;
967
- readonly runId: string;
968
- readonly turn: number;
969
- readonly attempt: number;
970
- readonly result: ArtifactValidation;
971
- } | {
972
- readonly type: "artifact_revision_started";
973
- readonly sessionId: string;
974
- readonly runId: string;
975
- readonly turn: number;
976
- readonly attempt: number;
977
- readonly failure: ArtifactValidation;
978
- } | {
979
- readonly type: "artifact_finished";
980
- readonly sessionId: string;
981
- readonly runId: string;
982
- readonly turn: number;
983
- readonly attempt: number;
984
- readonly result: ArtifactValidation;
985
- } | {
986
- readonly type: "artifact_failed";
987
- readonly sessionId: string;
988
- readonly runId: string;
989
- readonly turn: number;
990
- readonly attempt: number;
991
- readonly result: ArtifactValidation;
992
- };
993
- export type ToolEffectKind = "none" | "local_mutation" | "external_mutation";
994
- export type ToolEffectIdempotency = "none" | "optional" | "required" | "tool_managed" | "unsupported";
995
- /** Static or validated-argument classification of one tool call's side-effect behavior. */
996
- export interface ToolEffectDeclaration {
997
- readonly kind: ToolEffectKind;
998
- readonly idempotency: ToolEffectIdempotency;
999
- }
1000
- /** Runs after argument validation. It must be synchronous, deterministic, bounded, and side-effect-free. */
1001
- export type ToolEffectClassifier = (args: JsonObject, context: ToolExecutionContext) => ToolEffectDeclaration;
1002
- /**
1003
- * Elicitation contract declared by a tool. When a durable gated run suspends on this tool,
1004
- * the pending decision has kind `elicitation` and carries this schema as its payload contract;
1005
- * the resume decision's `elicitation` payload resolves the call without executing it.
1006
- */
1007
- export interface ToolElicitationRequest {
1008
- /** Typed payload contract; bounded to HARD_MAX_ELICITATION_BYTES when serialized. */
1009
- readonly schema: JsonObject;
1010
- /** Human-facing reason (e.g. the question); bounded to MAX_DECISION_REASON_BYTES. */
1011
- readonly reason?: string;
1012
- /** Answer-shape validation beyond structural schema checks; throw to reject the payload. */
1013
- readonly validate?: (payload: JsonObject) => void;
1014
- }
1015
- export interface ToolDefinition {
1016
- readonly name: string;
1017
- readonly description?: string;
1018
- readonly parameters?: JsonObject;
1019
- /** Force any provider turn containing this tool to dispatch sequentially. */
1020
- readonly exclusive?: boolean;
1021
- /** Optional side-effect declaration. Omitted tools retain legacy unmanaged dispatch. */
1022
- readonly effect?: ToolEffectDeclaration | ToolEffectClassifier;
1023
- /** Optional elicitation contract for durable gating; return undefined to fall back to plain tool approval. */
1024
- readonly elicitation?: (args: JsonObject, context: ToolExecutionContext) => ToolElicitationRequest | undefined;
1025
- execute(args: JsonObject, context: ToolExecutionContext): Promise<ToolResult> | ToolResult;
1026
- }
1027
- export interface ToolRegistry {
1028
- register(tool: ToolDefinition): void;
1029
- get(name: string): ToolDefinition | undefined;
1030
- resolve(name: string): ToolDefinition;
1031
- list(): readonly ToolDefinition[];
1032
- }
1033
- export interface ToolExecutionContext {
1034
- readonly sessionId: string;
1035
- readonly runId: string;
1036
- readonly toolCallId: string;
1037
- readonly signal?: AbortSignal;
1038
- readonly metadata?: Readonly<Record<string, unknown>>;
1039
- /** Host-verified identity for this tool invocation, when enterprise identity is active. */
1040
- readonly identity?: import("./identity.js").AgentIdentity;
1041
- /** Core-derived stable effect key. Never accept a model-supplied key as authority. */
1042
- readonly idempotencyKey?: string;
1043
- progress?(progress?: unknown, metadata?: Readonly<Record<string, unknown>>): void | Promise<void>;
1044
- }
1045
- export interface ToolResult {
1046
- readonly toolCallId: string;
1047
- readonly name: string;
1048
- readonly content?: readonly ContentBlock[];
1049
- readonly value?: unknown;
1050
- readonly error?: ErrorInfo;
1051
- readonly metadata?: Readonly<Record<string, unknown>>;
1052
- }
1053
- export type ToolEffectStatus = "pending" | "dispatched" | "completed" | "failed_retryable" | "failed_terminal" | "unknown";
1054
- export interface ToolEffectRecord extends OwnershipScope {
1055
- readonly key: string;
1056
- readonly sessionId: string;
1057
- readonly runId: string;
1058
- readonly toolCallId: string;
1059
- readonly toolName: string;
1060
- readonly argumentsHash: string;
1061
- readonly status: ToolEffectStatus;
1062
- readonly attempt: number;
1063
- readonly version: number;
1064
- readonly claimToken?: string;
1065
- readonly result?: ToolResult;
1066
- readonly resultRef?: string;
1067
- readonly failure?: {
1068
- readonly code: string;
1069
- readonly reference?: string;
1070
- };
1071
- readonly createdAt: string;
1072
- readonly updatedAt: string;
1073
- readonly expiresAt?: string;
1074
- }
1075
- export interface ToolEffectKey {
1076
- readonly identity: import("./identity.js").AgentIdentity;
1077
- readonly ownership: OwnershipScope;
1078
- readonly key: string;
1079
- readonly sessionId: string;
1080
- readonly runId: string;
1081
- readonly toolCallId: string;
1082
- readonly toolName: string;
1083
- readonly argumentsHash: string;
1084
- readonly signal?: AbortSignal;
1085
- }
1086
- export interface ToolEffectTransition extends ToolEffectKey {
1087
- readonly claimToken: string;
1088
- readonly expectedVersion: number;
1089
- }
1090
- /** Durable claim/CAS store for recoverable tool effects. */
1091
- export interface ToolEffectStore {
1092
- get(input: ToolEffectKey): Promise<ToolEffectRecord | undefined>;
1093
- begin(input: ToolEffectKey & {
1094
- readonly claimTtlMs?: number;
1095
- readonly maxAttempts?: number;
1096
- }): Promise<{
1097
- readonly outcome: "acquired" | "existing";
1098
- readonly record: ToolEffectRecord;
1099
- }>;
1100
- markDispatched(input: ToolEffectTransition): Promise<ToolEffectRecord>;
1101
- complete(input: ToolEffectTransition & {
1102
- readonly result?: ToolResult;
1103
- readonly resultRef?: string;
1104
- }): Promise<ToolEffectRecord>;
1105
- fail(input: ToolEffectTransition & {
1106
- readonly status: "failed_retryable" | "failed_terminal";
1107
- readonly failure: {
1108
- readonly code: string;
1109
- readonly reference?: string;
1110
- };
1111
- }): Promise<ToolEffectRecord>;
1112
- markUnknown(input: ToolEffectTransition & {
1113
- readonly failure?: {
1114
- readonly code: string;
1115
- readonly reference?: string;
1116
- };
1117
- }): Promise<ToolEffectRecord>;
1118
- resolveUnknown(input: ToolEffectKey & {
1119
- readonly expectedVersion: number;
1120
- readonly status: "completed" | "failed_retryable" | "failed_terminal";
1121
- readonly result?: ToolResult;
1122
- readonly resultRef?: string;
1123
- readonly failure?: {
1124
- readonly code: string;
1125
- readonly reference?: string;
1126
- };
1127
- }): Promise<ToolEffectRecord>;
1128
- cleanup(input: {
1129
- readonly ownership: OwnershipScope;
1130
- readonly before: string;
1131
- readonly limit?: number;
1132
- readonly signal?: AbortSignal;
1133
- }): Promise<{
1134
- readonly deleted: number;
1135
- }>;
1136
- }
1137
- export interface CommandDefinition {
1138
- readonly name: string;
1139
- readonly description?: string;
1140
- readonly parameters?: JsonObject;
1141
- execute(args: JsonObject, context: CommandExecutionContext): Promise<CommandResult> | CommandResult;
1142
- readonly metadata?: Readonly<Record<string, unknown>>;
1143
- }
1144
- export interface CommandExecutionContext {
1145
- readonly sessionId?: string;
1146
- readonly runId?: string;
1147
- readonly signal?: AbortSignal;
1148
- readonly metadata?: Readonly<Record<string, unknown>>;
1149
- }
1150
- export interface CommandResult {
1151
- readonly name: string;
1152
- readonly content?: readonly ContentBlock[];
1153
- readonly value?: unknown;
1154
- readonly error?: ErrorInfo;
1155
- readonly metadata?: Readonly<Record<string, unknown>>;
1156
- }
1157
- export interface ContextBlock {
1158
- readonly id?: string;
1159
- readonly title?: string;
1160
- readonly content: string | readonly ContentBlock[];
1161
- readonly priority?: number;
1162
- readonly metadata?: Readonly<Record<string, unknown>>;
1163
- }
1164
- export interface ContextProvider {
1165
- readonly name: string;
1166
- resolve(context: ContextResolutionContext): Promise<readonly ContextBlock[]> | readonly ContextBlock[];
1167
- }
1168
- export interface ContextResolutionContext {
1169
- readonly sessionId?: string;
1170
- readonly runId?: string;
1171
- readonly messages: readonly Message[];
1172
- readonly metadata?: Readonly<Record<string, unknown>>;
1173
- readonly signal?: AbortSignal;
1174
- }
1175
- /** When an {@link InstructionInjector} contributes to the assembled provider input. */
1176
- export type InstructionTiming = "first_turn" | "every_turn" | "on_input";
1177
- /** Runtime turn scope handed to an {@link InstructionInjector}. Mirrors {@link LoopContext}
1178
- * scope using already-redacted input/history so predicates cannot recover secrets. */
1179
- export interface InstructionContext {
1180
- readonly sessionId: string;
1181
- readonly runId: string;
1182
- readonly turn: number;
1183
- readonly input: readonly Message[];
1184
- readonly history: readonly Message[];
1185
- readonly metadata: Readonly<Record<string, unknown>>;
1186
- readonly signal: AbortSignal;
1187
- }
1188
- /** Output of an {@link InstructionInjector}. Only `instructions` and `contextBlocks` are
1189
- * honored; other fields grant nothing (no tools, skills, or permissions). */
1190
- export interface InstructionContribution {
1191
- readonly instructions?: string;
1192
- readonly contextBlocks?: readonly ContextBlock[];
1193
- readonly when: InstructionTiming;
1194
- /** Used only when `when === "on_input"`; absent predicate means apply every turn. */
1195
- readonly predicate?: (ctx: InstructionContext) => boolean;
1196
- }
1197
- /** Additive instruction/context contribution that a package registers through
1198
- * {@link ExtensionAPI.registerInstructionInjector} and the host selects on
1199
- * {@link AgentConfig.instructionInjectors} / {@link RunOptions.instructionInjectors}.
1200
- * Inert until selected; cannot grant privileges beyond text/context blocks. */
1201
- export interface InstructionInjector {
1202
- readonly name: string;
1203
- readonly description?: string;
1204
- apply(ctx: InstructionContext): InstructionContribution;
1205
- }
1206
- export interface InputBuilder {
1207
- readonly name: string;
1208
- build(input: string | Message | readonly Message[], context?: InputBuildContext): Promise<readonly Message[]> | readonly Message[];
1209
- readonly metadata?: Readonly<Record<string, unknown>>;
1210
- }
1211
- export interface InputBuildContext {
1212
- readonly inputLayout?: InputAssemblyLayout;
1213
- readonly sessionId?: string;
1214
- readonly runId?: string;
1215
- readonly metadata?: Readonly<Record<string, unknown>>;
1216
- readonly signal?: AbortSignal;
1217
- readonly permission?: PermissionPolicy;
1218
- readonly trust?: TrustPolicy;
1219
- }
1220
- export interface PromptBuilder {
1221
- readonly name: string;
1222
- build(request: PromptBuildRequest): Promise<readonly Message[]> | readonly Message[];
1223
- readonly metadata?: Readonly<Record<string, unknown>>;
1224
- }
1225
- export interface PromptBuildRequest {
1226
- readonly messages: readonly Message[];
1227
- readonly context?: readonly ContextBlock[];
1228
- readonly skills?: readonly Skill[];
1229
- readonly skillsDisclosure?: import("./skill-disclosure.js").SkillsDisclosure;
1230
- readonly loadedSkills?: import("./skill-disclosure.js").LoadedSkillSet;
1231
- /** Skills demoted to catalog-only by context budget this turn. */
1232
- readonly demotedSkillBodies?: readonly string[];
1233
- readonly tools?: readonly ToolDefinition[];
1234
- /** Model being prompted; lets builders adapt composition to declared capabilities
1235
- * (e.g. the default builder omits the `Available tools:` text for tool-capable models). */
1236
- readonly model?: ModelConfig;
1237
- readonly metadata?: Readonly<Record<string, unknown>>;
1238
- readonly signal?: AbortSignal;
1239
- }
1240
- export interface Skill {
1241
- readonly name: string;
1242
- readonly description?: string;
1243
- readonly instructions?: string;
1244
- readonly context?: readonly ContextProvider[];
1245
- readonly toolNames?: readonly string[];
1246
- readonly metadata?: Readonly<Record<string, unknown>>;
1247
- }
1248
- export interface SkillRegistry {
1249
- register(skill: Skill): void;
1250
- get(name: string): Skill | undefined;
1251
- resolve(name: string): Skill;
1252
- list(): readonly Skill[];
1253
- }
1254
- /** Directory-name spelling for discovered contribution kinds. Maps to a
1255
- * {@link ManifestContributionDeclaration} kind for non-skill kinds:
1256
- * `context` → `contextProvider`, `instructions` → `systemPromptContribution`. */
1257
- export type ContributionFileKind = "skill" | "tool" | "context" | "instructions";
1258
- /** Inert envelope emitted by the host/CLI discovery scanner. Carries the
1259
- * realized {@link Skill} for skill kinds and a manifest-referenced
1260
- * {@link ManifestContributionDeclaration} for other kinds; the host owns
1261
- * any executable behavior. Contains no code, no credential. */
1262
- export interface DiscoveredContribution {
1263
- readonly kind: ContributionFileKind;
1264
- readonly name: string;
1265
- readonly origin: "global" | "workspace";
1266
- readonly path: string;
1267
- /** Present when `kind === "skill"`. */
1268
- readonly skill?: Skill;
1269
- /** Present for non-skill kinds. */
1270
- readonly declaration?: ManifestContributionDeclaration;
1271
- readonly metadata?: Readonly<Record<string, unknown>>;
1272
- }
1273
- export type ExtensionLifecycleEventName = "resource_discovery" | "session_start" | "session_shutdown" | "before_agent_start" | "turn" | "context" | "provider_request" | "tool_call" | "tool_result" | "compaction" | "retry";
1274
- export interface ExtensionEvent {
1275
- readonly type: ExtensionLifecycleEventName | "extension_error" | string;
1276
- readonly payload?: unknown;
1277
- readonly extension?: string;
1278
- readonly error?: ErrorInfo;
1279
- readonly metadata?: Readonly<Record<string, unknown>>;
1280
- }
1281
- export interface Extension {
1282
- readonly name: string;
1283
- setup(api: ExtensionAPI): void | Promise<void>;
1284
- /** Host-attested signature/digest for `ExtensionLoadPolicy.verifySignature`. */
1285
- readonly signature?: string;
1286
- readonly metadata?: Readonly<Record<string, unknown>>;
1287
- }
1288
- export interface ProviderPackage {
1289
- readonly name: string;
1290
- readonly version?: string;
1291
- readonly description?: string;
1292
- readonly docs?: ProviderPackageDocs;
1293
- setup(api: ProviderPackageAPI): void | Promise<void>;
1294
- readonly metadata?: Readonly<Record<string, unknown>>;
1295
- }
1296
- export interface ProviderPackageDocs {
1297
- readonly description?: string;
1298
- readonly links?: readonly string[];
1299
- readonly metadata?: Readonly<Record<string, unknown>>;
1300
- }
1301
- export interface ProviderPackageAPI extends ExtensionAPI {
1302
- }
1303
- export type AuthMethod = ApiKeyAuthMethod | OAuthAuthMethod | CustomAuthMethod;
1304
- export interface ApiKeyAuthMethod {
1305
- readonly kind: "api_key";
1306
- readonly provider: string;
1307
- readonly name?: string;
1308
- readonly credentialName?: string;
1309
- readonly metadata?: Readonly<Record<string, unknown>>;
1310
- }
1311
- export interface OAuthAuthMethod {
1312
- readonly kind: "oauth";
1313
- readonly provider: string;
1314
- readonly name?: string;
1315
- readonly oauth?: OAuthProvider;
1316
- readonly metadata?: Readonly<Record<string, unknown>>;
1317
- }
1318
- export interface OAuthLoginCallbacks {
1319
- onAuth?(url: string): void | Promise<void>;
1320
- onDeviceCode?(code: {
1321
- readonly userCode: string;
1322
- readonly verificationUri: string;
1323
- readonly expiresAt?: string;
1324
- }): void | Promise<void>;
1325
- onPrompt?(message: string): string | undefined | Promise<string | undefined>;
1326
- onSelect?(prompt: {
1327
- readonly message: string;
1328
- readonly choices: readonly string[];
1329
- }): string | undefined | Promise<string | undefined>;
1330
- /** Aborts OAuth login flows and device-code polling when signaled. */
1331
- readonly signal?: AbortSignal;
1332
- }
1333
- export interface OAuthCredentials {
1334
- readonly access?: string;
1335
- readonly refresh?: string;
1336
- readonly expires?: string | number;
1337
- readonly accountId?: string;
1338
- readonly metadata?: Readonly<Record<string, unknown>>;
1339
- }
1340
- export interface OAuthProvider {
1341
- readonly id: string;
1342
- login(callbacks?: OAuthLoginCallbacks): Promise<OAuthCredentials> | OAuthCredentials;
1343
- refresh?(credentials: OAuthCredentials): Promise<OAuthCredentials> | OAuthCredentials;
1344
- /** Best-effort upstream revocation; the store delete is what fails closed locally. */
1345
- revoke?(credentials: OAuthCredentials): Promise<void> | void;
1346
- getCredential?(credentials: OAuthCredentials): Promise<Credential | undefined> | Credential | undefined;
1347
- readonly metadata?: Readonly<Record<string, unknown>>;
1348
- }
1349
- export interface CustomAuthMethod {
1350
- readonly kind: "custom" | string;
1351
- readonly provider: string;
1352
- readonly name?: string;
1353
- readonly metadata?: Readonly<Record<string, unknown>>;
1354
- }
1355
- export interface ProviderRequestPolicy {
1356
- readonly name: string;
1357
- apply(context: ProviderRequestPolicyContext): Promise<ProviderRequest | ProviderRequestPolicyResult> | ProviderRequest | ProviderRequestPolicyResult;
1358
- readonly metadata?: Readonly<Record<string, unknown>>;
1359
- }
1360
- export interface ProviderRequestPolicyContext {
1361
- readonly request: ProviderRequest;
1362
- readonly sessionId?: string;
1363
- readonly runId?: string;
1364
- readonly metadata?: Readonly<Record<string, unknown>>;
1365
- readonly signal?: AbortSignal;
1366
- }
1367
- export interface ProviderRequestPolicyResult {
1368
- readonly request: ProviderRequest;
1369
- readonly secrets?: readonly (string | undefined)[];
1370
- }
1371
- export type SystemPromptMode = "append" | "prepend" | "replace" | "disable";
1372
- export type SystemPromptSource = "package" | "app" | "user" | "run" | string;
1373
- export interface SystemPromptContribution {
1374
- readonly id: string;
1375
- readonly source?: SystemPromptSource;
1376
- readonly mode?: SystemPromptMode;
1377
- readonly text: string;
1378
- readonly metadata?: Readonly<Record<string, unknown>>;
1379
- }
1380
- export type SystemPromptConfig = false | SystemPromptContribution | readonly SystemPromptContribution[];
1381
- export interface ExtensionAPI {
1382
- readonly registries: ContributionRegistries;
1383
- readonly middleware: MiddlewareRegistry;
1384
- on(type: ExtensionLifecycleEventName | string, handler: (event: ExtensionEvent) => void | Promise<void>): () => void;
1385
- emit(event: ExtensionEvent): Promise<void>;
1386
- use<T>(hook: MiddlewareHookName | string, middleware: Middleware<T>): () => void;
1387
- registerProvider(provider: AIProvider): void;
1388
- registerModel(model: ModelConfig): void;
1389
- registerTool(tool: ToolDefinition): void;
1390
- registerContextProvider(provider: ContextProvider): void;
1391
- registerSkill(skill: Skill): void;
1392
- registerCommand(command: CommandDefinition): void;
1393
- registerAgent(agent: AgentDefinition): void;
1394
- registerInputBuilder(builder: InputBuilder): void;
1395
- registerPromptBuilder(builder: PromptBuilder): void;
1396
- registerCompactionStrategy(strategy: CompactionStrategy): void;
1397
- registerRetryPolicy(policy: RetryPolicy): void;
1398
- registerStoreFactory(factory: StoreFactory): void;
1399
- registerResourceLoader(key: string, loader: ResourceLoader): void;
1400
- registerSettingsProvider(key: string, provider: SettingsProvider): void;
1401
- registerCredentialResolver(key: string, resolver: CredentialResolver): void;
1402
- registerProviderPackage(providerPackage: ProviderPackage): void;
1403
- registerAuthMethod(method: AuthMethod): void;
1404
- registerProviderRequestPolicy(policy: ProviderRequestPolicy): void;
1405
- registerSystemPromptContribution(contribution: SystemPromptContribution): void;
1406
- registerInstructionInjector(injector: InstructionInjector): void;
1407
- }
1408
- export type SessionEntryKind = "message" | "event" | "summary" | "metadata" | "model_change" | "label" | "custom" | "compaction";
1409
- export declare const SESSION_ENTRY_KINDS: readonly SessionEntryKind[];
1410
- export declare const SESSION_ENTRY_SCHEMA_VERSION = 1;
1411
- export declare function isSessionEntryKind(value: unknown): value is SessionEntryKind;
1412
- export interface SessionEntry {
1413
- readonly id: string;
1414
- readonly parentId?: string;
1415
- readonly sessionId: string;
1416
- readonly timestamp: string;
1417
- readonly kind: SessionEntryKind;
1418
- readonly schemaVersion?: 1;
1419
- readonly runId?: string;
1420
- readonly message?: Message;
1421
- readonly event?: AgentEvent;
1422
- readonly model?: ModelConfig;
1423
- readonly previousModel?: ModelConfig;
1424
- readonly label?: string;
1425
- readonly summary?: string;
1426
- readonly data?: unknown;
1427
- readonly metadata?: Readonly<Record<string, unknown>>;
1428
- }
1429
- export interface SessionStore {
1430
- append(entry: SessionEntry, options?: SessionAppendOptions): Promise<void>;
1431
- list(sessionId: string): Promise<readonly SessionEntry[]>;
1432
- get?(id: string): Promise<SessionEntry | undefined>;
1433
- /** DB-friendly branch read: return one branch's ancestor chain as a page so adapters
1434
- * avoid `list(sessionId)` (full-session scan) + in-memory rebuild. Optional — the
1435
- * built-in memory/JSONL stores omit it and the runtime falls back to `list()`. */
1436
- readBranchPath?(query: SessionBranchRead): Promise<PersistencePage<SessionEntry>>;
1437
- /**
1438
- * Optional bounded session search. Prefer implementing this **or** returning a companion
1439
- * `SessionIndex` from the adapter factory — hosts must not need both. Call
1440
- * `resolveSessionSearchQuery` before scan/query. Memory defaults to capped linear
1441
- * search (`sessionSearchMode: "unsupported"` throws). JSONL throws unsupported.
1442
- */
1443
- searchSessions?(query: SessionSearchQuery): Promise<PersistencePage<SessionSearchHit>>;
1444
- }
1445
- /** Host-written `SessionRecord.metadata` / session metadata key for workspace filtering. */
1446
- export declare const SESSION_SEARCH_WORKSPACE_METADATA_KEY: "workspaceRoot";
1447
- export declare const DEFAULT_SESSION_SEARCH_LIMIT = 20;
1448
- export declare const HARD_MAX_SESSION_SEARCH_LIMIT = 100;
1449
- export declare const DEFAULT_MAX_SESSION_SEARCH_QUERY_BYTES: number;
1450
- export declare const HARD_MAX_SESSION_SEARCH_QUERY_BYTES: number;
1451
- export declare const DEFAULT_MAX_SESSION_SEARCH_SNIPPET_BYTES = 512;
1452
- export declare const HARD_MAX_SESSION_SEARCH_SNIPPET_BYTES: number;
1453
- export declare const DEFAULT_MAX_SESSION_SEARCH_CURSOR_BYTES: number;
1454
- export declare const HARD_MAX_SESSION_SEARCH_CURSOR_BYTES: number;
1455
- export declare const DEFAULT_MAX_SESSION_SEARCH_LINEAR_SESSIONS = 1000;
1456
- export declare const HARD_MAX_SESSION_SEARCH_LINEAR_SESSIONS = 5000;
1457
- export declare const DEFAULT_MAX_SESSION_SEARCH_LINEAR_ENTRIES = 10000;
1458
- export declare const HARD_MAX_SESSION_SEARCH_LINEAR_ENTRIES = 50000;
1459
- export declare const DEFAULT_MAX_SESSION_SEARCH_LINEAR_BYTES: number;
1460
- export declare const HARD_MAX_SESSION_SEARCH_LINEAR_BYTES: number;
1461
- export declare const DEFAULT_MAX_SESSION_SEARCH_FTS_CANDIDATES = 1000;
1462
- export declare const HARD_MAX_SESSION_SEARCH_FTS_CANDIDATES = 5000;
1463
- /** Bounded session search filters. Workspace matches host-written `metadata.workspaceRoot`. */
1464
- export interface SessionSearchQuery extends PersistenceQuery, OwnershipScope {
1465
- readonly workspaceRoot?: string;
1466
- /** Optional full-text / message+summary query (adapter-defined matching). */
1467
- readonly query?: string;
1468
- readonly provider?: string;
1469
- readonly model?: string;
1470
- readonly label?: string;
1471
- readonly summary?: string;
1472
- readonly fromUpdatedAt?: string;
1473
- readonly toUpdatedAt?: string;
1474
- readonly signal?: AbortSignal;
1475
- }
1476
- /**
1477
- * Safe search hit for resume/checkout. Never includes credentials or raw full transcripts.
1478
- * `leafId` is the branch tip for `session.checkout` when known.
1479
- */
1480
- export interface SessionSearchHit {
1481
- readonly sessionId: string;
1482
- readonly leafId?: string;
1483
- readonly updatedAt?: string;
1484
- readonly label?: string;
1485
- readonly summary?: string;
1486
- readonly snippet?: string;
1487
- /** Safe display fields only (e.g. workspaceRoot); never credentials. */
1488
- readonly metadata?: Readonly<Record<string, unknown>>;
1489
- }
1490
- /** Narrow search seam; adapters may implement this instead of `SessionStore.searchSessions`. */
1491
- export interface SessionIndex {
1492
- search(query: SessionSearchQuery): Promise<PersistencePage<SessionSearchHit>>;
1493
- }
1494
- /** Validated search query with finite `limit` / `order` filled in. */
1495
- export interface ResolvedSessionSearchQuery extends SessionSearchQuery {
1496
- readonly limit: number;
1497
- readonly order: "asc" | "desc";
1498
- }
1499
- /**
1500
- * O(1) validation before any scan/query. Applies default page limit; rejects NaN,
1501
- * non-positive limits, oversize query/cursor/filter strings, and invalid order.
1502
- */
1503
- export declare function resolveSessionSearchQuery(query: SessionSearchQuery): ResolvedSessionSearchQuery;
1504
- export declare const SESSION_SEARCH_UNSUPPORTED_CODE: "session_search_unsupported";
1505
- /** Thrown when a store opts out of `searchSessions` (memory `unsupported`, JSONL). */
1506
- export declare class SessionSearchUnsupportedError extends Error {
1507
- readonly code: "session_search_unsupported";
1508
- constructor(message?: string);
1509
- }
1510
- export declare function isSessionSearchUnsupported(error: unknown): error is SessionSearchUnsupportedError;
1511
- /** Query for a single branch's ancestor chain (DB-friendly: one recursive/ancestor query
1512
- * instead of a full-session scan). Honored by `SessionStore.readBranchPath` and the pure
1513
- * branch helpers' reader overload. `leafId` is optional (omit for the latest leaf). */
1514
- export interface SessionBranchRead {
1515
- readonly sessionId: string;
1516
- readonly leafId?: string;
1517
- readonly cursor?: string;
1518
- readonly limit?: number;
1519
- }
1520
- /** Database-neutral callable returning one branch's ancestor chain as a page. Implementations
1521
- * issue a single recursive CTE / ancestor walk; the pure helpers follow `nextCursor` to
1522
- * completion. Returns redacted `SessionEntry` values only (stores already persist redacted
1523
- * entries; the runtime redacts before append). */
1524
- export type BranchReader = (query: SessionBranchRead) => Promise<PersistencePage<SessionEntry>>;
1525
- /**
1526
- * Options for `SessionStore.append`. Stores that honor them reject dangling
1527
- * `expectedParentId` values and deduplicate exact retries by `idempotencyKey` +
1528
- * parent. Production stores may add stricter branch-tip CAS and report
1529
- * `currentLeafId` in `SessionAppendConflictError`. `idempotencyKey` is an opaque
1530
- * host string; stores redact it like metadata when persisted. Carries no
1531
- * credentials, credential resolvers, provider instances, or unredacted secrets.
1532
- */
1533
- export interface SessionAppendOptions {
1534
- /** Parent entry the new entry should attach to. Must exist when provided. */
1535
- readonly expectedParentId?: string;
1536
- /** Opaque host idempotency key; exact retries for one parent deduplicate. */
1537
- readonly idempotencyKey?: string;
1538
- }
1539
- /**
1540
- * Durable pointer to a branch tip. One session may own many handles (one per
1541
- * leaf). `BranchRecord.leafEntryId` is the persistence-side equivalent.
1542
- */
1543
- export interface SessionBranchHandle {
1544
- readonly sessionId: string;
1545
- readonly leafId: string;
1546
- }
1547
- /** Stable error code carried by `SessionAppendConflictError`. */
1548
- export declare const SESSION_APPEND_CONFLICT_CODE: "session_append_conflict";
1549
- /** Conflict details carried by `SessionAppendConflictError`. Carries no secrets. */
1550
- export interface SessionAppendConflict {
1551
- readonly code: typeof SESSION_APPEND_CONFLICT_CODE;
1552
- readonly expectedParentId?: string;
1553
- readonly currentLeafId?: string;
1554
- readonly idempotencyDuplicate?: boolean;
1555
- }
1556
- /**
1557
- * Thrown when `SessionStore.append` rejects an entry under `SessionAppendOptions`
1558
- * (dangling/stale `expectedParentId`, stricter adapter CAS failure, or duplicate
1559
- * idempotency key for the same parent). Recognize via the stable `code` and
1560
- * `isSessionAppendConflict`, not message text.
1561
- */
1562
- export declare class SessionAppendConflictError extends Error {
1563
- readonly conflict: SessionAppendConflict;
1564
- readonly code: "session_append_conflict";
1565
- constructor(conflict: SessionAppendConflict);
1566
- }
1567
- /** Type guard keyed off the stable `code` (works across bundles; not message text). */
1568
- export declare function isSessionAppendConflict(error: unknown): error is SessionAppendConflictError;
1569
- export interface StoreFactory {
1570
- readonly name: string;
1571
- create(config?: JsonObject): Promise<SessionStore> | SessionStore;
1572
- readonly metadata?: Readonly<Record<string, unknown>>;
1573
- }
1574
- /** Ownership scope identifiers. Hosts may use these for multi-tenant isolation. */
1575
- export interface OwnershipScope {
1576
- readonly tenantId?: string;
1577
- readonly accountId?: string;
1578
- readonly userId?: string;
1579
- }
1580
- /** Cursor-paginated result page. */
1581
- export interface PersistencePage<T> {
1582
- readonly items: readonly T[];
1583
- readonly nextCursor?: string;
1584
- readonly total?: number;
1585
- }
1586
- /** Common query controls for cursor-based pagination. */
1587
- export interface PersistenceQuery {
1588
- readonly cursor?: string;
1589
- readonly limit?: number;
1590
- readonly order?: "asc" | "desc";
1591
- }
1592
- /** Generic versioned checkpoint key. Namespaces prevent consumer collisions. */
1593
- export interface CheckpointKey extends OwnershipScope {
1594
- readonly namespace: string;
1595
- readonly key: string;
1596
- readonly signal?: AbortSignal;
1597
- }
1598
- /** Input for an optimistic checkpoint write. Versions must strictly increase. */
1599
- export interface CheckpointSaveInput extends CheckpointKey {
1600
- readonly version: number;
1601
- /** Exact current version required before update; use 0 for create-only. */
1602
- readonly expectedVersion?: number;
1603
- /** Monotonic lease fence. Lower or absent worker fences cannot replace a fenced record. */
1604
- readonly fencingToken?: number;
1605
- readonly value: unknown;
1606
- readonly category?: string;
1607
- readonly metadata?: Readonly<Record<string, unknown>>;
1608
- }
1609
- /** Durable generic checkpoint record. */
1610
- export interface CheckpointRecord extends OwnershipScope {
1611
- readonly namespace: string;
1612
- readonly key: string;
1613
- readonly version: number;
1614
- readonly fencingToken?: number;
1615
- readonly value: unknown;
1616
- readonly category?: string;
1617
- readonly createdAt: string;
1618
- readonly updatedAt: string;
1619
- readonly metadata?: Readonly<Record<string, unknown>>;
1620
- }
1621
- /** Bounded checkpoint query. */
1622
- export interface CheckpointQuery extends PersistenceQuery, OwnershipScope {
1623
- readonly namespace?: string;
1624
- readonly keyPrefix?: string;
1625
- readonly category?: string | readonly string[];
1626
- readonly signal?: AbortSignal;
1627
- }
1628
- /** Generic versioned checkpoint capability for persistence adapters. */
1629
- export interface CheckpointStore {
1630
- saveCheckpoint(input: CheckpointSaveInput): Promise<CheckpointRecord>;
1631
- loadCheckpoint(input: CheckpointKey): Promise<CheckpointRecord | null>;
1632
- listCheckpoints(query?: CheckpointQuery): Promise<PersistencePage<CheckpointRecord>>;
1633
- deleteCheckpoint(input: CheckpointKey): Promise<boolean>;
1634
- }
1635
- /** Generic lease key. Ownership fields are part of the trust boundary. */
1636
- export interface LeaseKey extends OwnershipScope {
1637
- readonly namespace: string;
1638
- readonly key: string;
1639
- readonly signal?: AbortSignal;
1640
- }
1641
- export interface LeaseAcquireInput extends LeaseKey {
1642
- readonly ownerId: string;
1643
- readonly ttlMs: number;
1644
- }
1645
- export interface LeaseClaimInput extends LeaseKey {
1646
- readonly ownerId: string;
1647
- readonly token: string;
1648
- readonly ttlMs?: number;
1649
- }
1650
- export interface LeaseRecord extends OwnershipScope {
1651
- readonly namespace: string;
1652
- readonly key: string;
1653
- readonly ownerId: string;
1654
- readonly token: string;
1655
- readonly fencingToken: number;
1656
- readonly acquiredAt: string;
1657
- readonly expiresAt: string;
1658
- readonly updatedAt: string;
1659
- }
1660
- /** Atomic distributed lease capability. Expired rows retain fencing counters. */
1661
- export interface LeaseStore {
1662
- tryAcquireLease(input: LeaseAcquireInput): Promise<LeaseRecord | null>;
1663
- renewLease(input: LeaseClaimInput & {
1664
- readonly ttlMs: number;
1665
- }): Promise<LeaseRecord | null>;
1666
- releaseLease(input: LeaseClaimInput): Promise<boolean>;
1667
- getLease(input: LeaseKey): Promise<LeaseRecord | null>;
1668
- }
1669
- /** Stored session record. Does not include provider objects or credentials. */
1670
- export interface SessionRecord extends OwnershipScope {
1671
- readonly id: string;
1672
- readonly parentSessionId?: string;
1673
- readonly agentDefinitionId?: string;
1674
- readonly agentDefinitionVersion?: string;
1675
- readonly createdAt: string;
1676
- readonly updatedAt: string;
1677
- readonly expiresAt?: string;
1678
- readonly retentionPolicyId?: string;
1679
- readonly metadata?: Readonly<Record<string, unknown>>;
1680
- }
1681
- /** Stored branch handle / leaf pointer. The leaf is the current entry id for the branch. */
1682
- export interface BranchRecord {
1683
- readonly id: string;
1684
- readonly sessionId: string;
1685
- readonly name?: string;
1686
- readonly rootEntryId?: string;
1687
- readonly parentBranchId?: string;
1688
- /** Durable leaf entry id for this branch (the persistence-side branch tip). */
1689
- readonly leafEntryId?: string;
1690
- readonly createdAt: string;
1691
- readonly metadata?: Readonly<Record<string, unknown>>;
1692
- }
1693
- export type RunStatus = "queued" | "running" | "suspended" | "denied" | "succeeded" | "failed" | "aborted";
1694
- /** Stored run record. */
1695
- export interface RunRecord extends OwnershipScope {
1696
- readonly id: string;
1697
- readonly sessionId: string;
1698
- readonly branchId?: string;
1699
- readonly agentDefinitionId?: string;
1700
- readonly agentDefinitionVersion?: string;
1701
- readonly model?: ModelConfig;
1702
- readonly provider?: string;
1703
- readonly idempotencyKey?: string;
1704
- readonly status?: RunStatus;
1705
- readonly startedAt: string;
1706
- readonly finishedAt?: string;
1707
- readonly abortReason?: string;
1708
- readonly error?: ErrorInfo;
1709
- readonly metadata?: Readonly<Record<string, unknown>>;
1710
- }
1711
- export type AgentEventType = AgentEvent["type"];
1712
- /** Stored agent event ledger row. The `event` payload should be redacted before storage when secrets are present. */
1713
- export interface AgentEventRecord extends OwnershipScope {
1714
- readonly id: string;
1715
- readonly sessionId: string;
1716
- readonly runId?: string;
1717
- /** Durable sources allocate positive, strictly increasing per-run positions. */
1718
- readonly sequence?: number;
1719
- readonly entryId?: string;
1720
- readonly type: AgentEventType;
1721
- readonly timestamp: string;
1722
- readonly event: AgentEvent;
1723
- readonly redacted: boolean;
1724
- readonly metadata?: Readonly<Record<string, unknown>>;
1725
- }
1726
- /** An event record returned by an {@link AgentEventSource}. */
1727
- export interface DurableAgentEventRecord extends AgentEventRecord {
1728
- readonly runId: string;
1729
- readonly sequence: number;
1730
- }
1731
- export interface AgentEventEnvelope {
1732
- readonly record: DurableAgentEventRecord;
1733
- /** Opaque cursor immediately after `record`. */
1734
- readonly cursor: string;
1735
- }
1736
- export interface AgentEventSourcePage {
1737
- readonly items: readonly AgentEventEnvelope[];
1738
- readonly nextCursor?: string;
1739
- /** True only after every event preceding a terminal event has been returned. */
1740
- readonly terminal: boolean;
1741
- }
1742
- /** Exact-owned, per-run durable event read. `after` is exclusive. */
1743
- export interface AgentEventSourceRead {
1744
- readonly ownership: OwnershipScope;
1745
- readonly sessionId: string;
1746
- readonly runId: string;
1747
- readonly after?: string;
1748
- readonly limit?: number;
1749
- readonly signal?: AbortSignal;
1750
- }
1751
- export interface AgentEventSourceCleanup {
1752
- readonly ownership: OwnershipScope;
1753
- readonly before: string;
1754
- readonly limit?: number;
1755
- readonly signal?: AbortSignal;
1756
- }
1757
- export interface AgentEventSourceOptions {
1758
- readonly maxEventBytes?: number;
1759
- readonly maxPageSize?: number;
1760
- readonly maxCursorBytes?: number;
1761
- readonly maxQueuedEvents?: number;
1762
- readonly maxSubscribers?: number;
1763
- readonly pollIntervalMs?: number;
1764
- readonly reconnectInitialMs?: number;
1765
- readonly reconnectMaxMs?: number;
1766
- readonly maxRetainedEventsPerRun?: number;
1767
- readonly maxRetentionAgeMs?: number;
1768
- }
1769
- /** Optional durable event capability. `RunLedger` remains a write-only contract. */
1770
- export interface AgentEventSource {
1771
- append(record: AgentEventRecord): Promise<DurableAgentEventRecord>;
1772
- page(input: AgentEventSourceRead): Promise<AgentEventSourcePage>;
1773
- subscribe(input: AgentEventSourceRead): AsyncIterable<AgentEventEnvelope>;
1774
- cleanup(input: AgentEventSourceCleanup): Promise<{
1775
- readonly deleted: number;
1776
- }>;
1777
- }
1778
- export type ToolCallStatus = "started" | "finished" | "error" | "blocked";
1779
- /** Stored tool-call row. The `result` payload should be redacted before storage when secrets are present. */
1780
- export interface ToolCallRecord extends OwnershipScope {
1781
- readonly id: string;
1782
- readonly sessionId: string;
1783
- readonly runId?: string;
1784
- readonly entryId?: string;
1785
- readonly toolCallId: string;
1786
- readonly name: string;
1787
- readonly arguments: JsonObject;
1788
- readonly result?: ToolResult;
1789
- readonly status?: ToolCallStatus;
1790
- readonly reason?: string;
1791
- readonly progress?: unknown;
1792
- readonly progressMetadata?: Readonly<Record<string, unknown>>;
1793
- readonly progressAt?: string;
1794
- readonly startedAt: string;
1795
- readonly finishedAt?: string;
1796
- readonly redacted: boolean;
1797
- readonly metadata?: Readonly<Record<string, unknown>>;
1798
- }
1799
- export type UsageScope = "provider_turn" | "run_total";
1800
- /** Stored usage row. `scope` prevents provider-turn and aggregate totals from being summed together. */
1801
- export interface UsageRecord extends OwnershipScope {
1802
- readonly id: string;
1803
- readonly sessionId: string;
1804
- readonly runId?: string;
1805
- readonly entryId?: string;
1806
- readonly scope: UsageScope;
1807
- readonly turn?: number;
1808
- readonly attempt?: number;
1809
- readonly usage: Usage;
1810
- readonly recordedAt: string;
1811
- readonly metadata?: Readonly<Record<string, unknown>>;
1812
- }
1813
- /** Host-implemented write-side ledger for runs, events, tool calls, and usage. */
1814
- export interface RunLedger {
1815
- appendRun(record: RunRecord): Promise<void> | void;
1816
- appendEvent(record: AgentEventRecord): Promise<void> | void;
1817
- appendToolCall(record: ToolCallRecord): Promise<void> | void;
1818
- appendUsage(record: UsageRecord): Promise<void> | void;
1819
- }
1820
- /** Union of records that may be handed to a {@link RunLedger}. */
1821
- export type RunLedgerRecord = RunRecord | AgentEventRecord | ToolCallRecord | UsageRecord;
1822
- export type RunLedgerDurability = "write_through" | "flush_on_terminal" | "buffered";
1823
- export interface RunLedgerFlushResult {
1824
- readonly accepted: number;
1825
- readonly flushed: number;
1826
- readonly buffered: number;
1827
- }
1828
- /** Optional durability seam implemented by bounded ledger adapters. */
1829
- export interface FlushableRunLedger extends RunLedger {
1830
- readonly durability: RunLedgerDurability;
1831
- flush(): Promise<RunLedgerFlushResult>;
1832
- status(): RunLedgerFlushResult;
1833
- dispose(options?: {
1834
- readonly flush?: boolean;
1835
- }): Promise<void>;
1836
- }
1837
- /** Immutable human feedback linked to an existing owned run/trace and optional evaluations. */
1838
- export interface RunFeedbackRecord extends OwnershipScope {
1839
- readonly id: string;
1840
- readonly runId: string;
1841
- readonly sessionId: string;
1842
- readonly traceId?: string;
1843
- readonly rating?: number;
1844
- readonly comment?: string;
1845
- readonly tags: readonly string[];
1846
- readonly scorerIds: readonly string[];
1847
- readonly evaluationIds: readonly string[];
1848
- readonly createdAt: string;
1849
- readonly createdBy?: string;
1850
- readonly metadata?: Readonly<Record<string, unknown>>;
1851
- }
1852
- export interface AppendRunFeedbackInput extends OwnershipScope {
1853
- readonly id: string;
1854
- readonly runId: string;
1855
- readonly sessionId?: string;
1856
- readonly traceId?: string;
1857
- readonly rating?: number;
1858
- readonly comment?: string;
1859
- readonly tags?: readonly string[];
1860
- readonly scorerIds?: readonly string[];
1861
- readonly evaluationIds?: readonly string[];
1862
- readonly createdAt?: string;
1863
- readonly createdBy?: string;
1864
- readonly metadata?: Readonly<Record<string, unknown>>;
1865
- readonly signal?: AbortSignal;
1866
- }
1867
- /** Cursor-paginated, ownership-scoped feedback query. */
1868
- export interface RunFeedbackQuery extends PersistenceQuery, OwnershipScope {
1869
- readonly runId?: string;
1870
- readonly sessionId?: string;
1871
- readonly traceId?: string;
1872
- readonly rating?: number;
1873
- readonly scorerId?: string;
1874
- readonly evaluationId?: string;
1875
- readonly tag?: string;
1876
- readonly fromCreatedAt?: string;
1877
- readonly toCreatedAt?: string;
1878
- readonly signal?: AbortSignal;
1879
- }
1880
- export interface DeleteRunFeedbackInput extends OwnershipScope {
1881
- readonly id: string;
1882
- readonly signal?: AbortSignal;
1883
- }
1884
- /** Feedback storage seam. Records are append-only; correction uses a new record and deletion is explicit. */
1885
- export interface RunFeedbackStore {
1886
- append(input: AppendRunFeedbackInput): Promise<RunFeedbackRecord>;
1887
- query(query: RunFeedbackQuery): Promise<PersistencePage<RunFeedbackRecord>>;
1888
- delete(input: DeleteRunFeedbackInput): Promise<boolean>;
1889
- }
1890
- /** Stored agent definition version. Does not include provider credentials/resolvers/provider instances. */
1891
- export interface AgentDefinitionRecord extends OwnershipScope {
1892
- readonly id: string;
1893
- readonly name: string;
1894
- readonly version: string;
1895
- readonly source?: string;
1896
- readonly agentDefinition: AgentDefinition;
1897
- readonly createdAt: string;
1898
- readonly createdBy?: string;
1899
- readonly metadata?: Readonly<Record<string, unknown>>;
1900
- }
1901
- /** Stored retention policy. */
1902
- export interface RetentionPolicy extends OwnershipScope {
1903
- readonly id: string;
1904
- readonly name?: string;
1905
- readonly maxAgeDays?: number;
1906
- readonly maxEntriesPerSession?: number;
1907
- readonly maxTotalBytes?: number;
1908
- readonly archiveStore?: string;
1909
- readonly appliedKinds?: readonly SessionEntryKind[];
1910
- readonly createdAt: string;
1911
- readonly metadata?: Readonly<Record<string, unknown>>;
1912
- }
1913
- /** Stored migration record. */
1914
- export interface MigrationRecord {
1915
- readonly id: string;
1916
- readonly name: string;
1917
- readonly version: string;
1918
- readonly appliedAt: string;
1919
- readonly appliedBy?: string;
1920
- readonly checksum?: string;
1921
- readonly metadata?: Readonly<Record<string, unknown>>;
1922
- }
1923
- /** Query for sessions. */
1924
- export interface SessionQuery extends PersistenceQuery, OwnershipScope {
1925
- readonly id?: string;
1926
- readonly parentSessionId?: string;
1927
- readonly agentDefinitionId?: string;
1928
- readonly agentDefinitionVersion?: string;
1929
- readonly retentionPolicyId?: string;
1930
- /** Match sessions whose `metadata` object contains this top-level key (e.g. conversation marker). */
1931
- readonly metadataKey?: string;
1932
- readonly fromCreatedAt?: string;
1933
- readonly toCreatedAt?: string;
1934
- readonly fromUpdatedAt?: string;
1935
- readonly toUpdatedAt?: string;
1936
- readonly hasExpired?: boolean;
1937
- }
1938
- /** Validate a top-level `SessionRecord.metadata` key used by `SessionQuery.metadataKey` filters. */
1939
- export declare function assertSessionMetadataKey(key: string): string;
1940
- /** Query for session entries. */
1941
- export interface SessionEntryQuery extends PersistenceQuery, OwnershipScope {
1942
- readonly sessionId?: string;
1943
- readonly runId?: string;
1944
- readonly parentId?: string;
1945
- /** Filter to entries on the branch ending at this leaf id. */
1946
- readonly leafId?: string;
1947
- readonly kind?: SessionEntryKind | readonly SessionEntryKind[];
1948
- readonly fromTimestamp?: string;
1949
- readonly toTimestamp?: string;
1950
- }
1951
- /** Query for branch handles/leaves. */
1952
- export interface BranchQuery extends PersistenceQuery {
1953
- readonly sessionId?: string;
1954
- readonly name?: string;
1955
- readonly parentBranchId?: string;
1956
- readonly hasLeaf?: boolean;
1957
- }
1958
- /** Query for runs. */
1959
- export interface RunQuery extends PersistenceQuery, OwnershipScope {
1960
- readonly sessionId?: string;
1961
- readonly branchId?: string;
1962
- readonly agentDefinitionId?: string;
1963
- readonly agentDefinitionVersion?: string;
1964
- readonly status?: RunStatus | readonly RunStatus[];
1965
- readonly fromStartedAt?: string;
1966
- readonly toStartedAt?: string;
1967
- readonly fromFinishedAt?: string;
1968
- readonly toFinishedAt?: string;
1969
- readonly isFinished?: boolean;
1970
- }
1971
- /** Query for agent event ledger rows. */
1972
- export interface AgentEventQuery extends PersistenceQuery, OwnershipScope {
1973
- readonly sessionId?: string;
1974
- readonly runId?: string;
1975
- readonly entryId?: string;
1976
- readonly type?: AgentEventType | readonly AgentEventType[];
1977
- readonly fromTimestamp?: string;
1978
- readonly toTimestamp?: string;
1979
- readonly redacted?: boolean;
1980
- }
1981
- /** Query for tool-call rows. */
1982
- export interface ToolCallQuery extends PersistenceQuery, OwnershipScope {
1983
- readonly sessionId?: string;
1984
- readonly runId?: string;
1985
- readonly entryId?: string;
1986
- readonly name?: string;
1987
- readonly status?: ToolCallStatus | readonly ToolCallStatus[];
1988
- readonly fromStartedAt?: string;
1989
- readonly toStartedAt?: string;
1990
- readonly fromFinishedAt?: string;
1991
- readonly toFinishedAt?: string;
1992
- readonly redacted?: boolean;
1993
- }
1994
- /** Query for usage rows. */
1995
- export interface UsageQuery extends PersistenceQuery, OwnershipScope {
1996
- readonly sessionId?: string;
1997
- readonly runId?: string;
1998
- readonly entryId?: string;
1999
- readonly scope?: UsageScope;
2000
- readonly turn?: number;
2001
- readonly attempt?: number;
2002
- readonly fromRecordedAt?: string;
2003
- readonly toRecordedAt?: string;
2004
- }
2005
- /** Query for agent definition versions. */
2006
- export interface AgentDefinitionQuery extends PersistenceQuery, OwnershipScope {
2007
- readonly name?: string;
2008
- readonly version?: string;
2009
- readonly source?: string;
2010
- readonly fromCreatedAt?: string;
2011
- readonly toCreatedAt?: string;
2012
- }
2013
- /** Query for retention policies. */
2014
- export interface RetentionPolicyQuery extends PersistenceQuery, OwnershipScope {
2015
- readonly name?: string;
2016
- readonly archiveStore?: string;
2017
- }
2018
- /** Query for migration records. */
2019
- export interface MigrationQuery extends PersistenceQuery {
2020
- readonly name?: string;
2021
- readonly version?: string;
2022
- readonly fromAppliedAt?: string;
2023
- readonly toAppliedAt?: string;
2024
- }
2025
- /**
2026
- * Production database-neutral persistence store contract.
2027
- * Hosts implement this interface to provide durable, paginated storage
2028
- * for sessions, entries, runs, events, tool calls, usage, agent definitions,
2029
- * and migrations, with optional generic checkpoint and atomic lease capabilities. No SQL client, ORM, host file storage, or network dependency is
2030
- * required by the contract.
2031
- */
2032
- export interface ProductionPersistenceStore {
2033
- readonly name?: string;
2034
- /** Optional generic write capability for resumable consumers such as workflows. */
2035
- readonly checkpoints?: CheckpointStore;
2036
- /** Optional atomic distributed lease capability for coordinators and workers. */
2037
- readonly leases?: LeaseStore;
2038
- /** Optional immutable run/trace feedback storage capability. */
2039
- readonly feedback?: RunFeedbackStore;
2040
- /** Optional durable, cross-replica-capable event source. */
2041
- readonly events?: AgentEventSource;
2042
- querySessions(query: SessionQuery): Promise<PersistencePage<SessionRecord>>;
2043
- queryBranches(query: BranchQuery): Promise<PersistencePage<BranchRecord>>;
2044
- queryEntries(query: SessionEntryQuery): Promise<PersistencePage<SessionEntry>>;
2045
- queryRuns(query: RunQuery): Promise<PersistencePage<RunRecord>>;
2046
- queryEvents(query: AgentEventQuery): Promise<PersistencePage<AgentEventRecord>>;
2047
- queryToolCalls(query: ToolCallQuery): Promise<PersistencePage<ToolCallRecord>>;
2048
- queryUsage(query: UsageQuery): Promise<PersistencePage<UsageRecord>>;
2049
- queryAgentDefinitions(query: AgentDefinitionQuery): Promise<PersistencePage<AgentDefinitionRecord>>;
2050
- queryRetentionPolicies(query: RetentionPolicyQuery): Promise<PersistencePage<RetentionPolicy>>;
2051
- queryMigrations(query: MigrationQuery): Promise<PersistencePage<MigrationRecord>>;
2052
- /** Optional session-record write capability (conversation threads, host-managed sessions).
2053
- * Upserts by id; ownership columns are set on create, `metadata`/`updatedAt` on update. */
2054
- appendSession?(record: SessionRecord): Promise<void>;
2055
- /** DB-friendly branch read (mirrors `SessionStore.readBranchPath`): one ancestor-chain
2056
- * query instead of `queryEntries({ sessionId })` + in-memory walk. Optional. */
2057
- readBranchPath?(query: SessionBranchRead): Promise<PersistencePage<SessionEntry>>;
2058
- /**
2059
- * Optional Phase 8 retention / legal-hold / export / tenant-quota lifecycle.
2060
- * Prefer attaching `createMemoryPersistenceLifecycle()` or adapter-native methods.
2061
- */
2062
- readonly lifecycle?: import("./persistence-lifecycle.js").PersistenceLifecycleStore;
2063
- readonly metadata?: Readonly<Record<string, unknown>>;
2064
- }
2065
- export interface CompactionStrategy {
2066
- readonly name: string;
2067
- compact(context: CompactionContext): Promise<CompactionResult> | CompactionResult;
2068
- readonly metadata?: Readonly<Record<string, unknown>>;
2069
- }
2070
- export interface CompactionContext {
2071
- readonly sessionId: string;
2072
- readonly entries: readonly SessionEntry[];
2073
- readonly keepRecentEntries?: number;
2074
- readonly trigger?: "manual" | "auto" | string;
2075
- readonly secrets?: readonly (string | undefined)[];
2076
- readonly metadata?: Readonly<Record<string, unknown>>;
2077
- readonly signal?: AbortSignal;
2078
- }
2079
- export interface CompactionResult {
2080
- readonly summary: string;
2081
- readonly entries?: readonly SessionEntry[];
2082
- readonly metadata?: Readonly<Record<string, unknown>>;
2083
- }
2084
- export interface CompactionOptions {
2085
- readonly strategy?: CompactionStrategy;
2086
- readonly thresholdEntries?: number;
2087
- readonly keepRecentEntries?: number;
2088
- readonly maxSummaryChars?: number;
2089
- readonly secrets?: readonly (string | undefined)[];
2090
- readonly metadata?: Readonly<Record<string, unknown>>;
2091
- readonly signal?: AbortSignal;
2092
- }
2093
- export interface CompactionMiddlewarePayload {
2094
- readonly context: CompactionContext;
2095
- readonly result: CompactionResult;
2096
- }
2097
- export interface CompactionEntryData {
2098
- readonly throughEntryId?: string;
2099
- readonly keepEntryIds?: readonly string[];
2100
- readonly strategy?: string;
2101
- readonly trigger?: "manual" | "auto" | string;
2102
- }
2103
- export interface RetryPolicy {
2104
- readonly name: string;
2105
- decide(context: RetryContext): Promise<RetryDecision> | RetryDecision;
2106
- readonly metadata?: Readonly<Record<string, unknown>>;
2107
- }
2108
- export interface RetryContext {
2109
- readonly sessionId: string;
2110
- readonly runId: string;
2111
- readonly attempt: number;
2112
- readonly error: ErrorInfo;
2113
- readonly metadata?: Readonly<Record<string, unknown>>;
2114
- readonly signal?: AbortSignal;
2115
- }
2116
- export interface RetryDecision {
2117
- readonly retry: boolean;
2118
- readonly delayMs?: number;
2119
- readonly metadata?: Readonly<Record<string, unknown>>;
2120
- }
2121
- export interface RetryOptions {
2122
- readonly policy?: RetryPolicy;
2123
- readonly maxAttempts?: number;
2124
- readonly baseDelayMs?: number;
2125
- readonly maxDelayMs?: number;
2126
- readonly secrets?: readonly (string | undefined)[];
2127
- readonly metadata?: Readonly<Record<string, unknown>>;
2128
- }
2129
- export interface RetryMiddlewarePayload {
2130
- readonly context: RetryContext;
2131
- readonly decision: RetryDecision;
2132
- }
2133
- export interface Resource {
2134
- readonly uri: string;
2135
- readonly mediaType?: string;
2136
- readonly text?: string;
2137
- readonly data?: Uint8Array;
2138
- readonly metadata?: Readonly<Record<string, unknown>>;
2139
- }
2140
- export interface ResourceLoader {
2141
- load(uri: string, context?: ResourceLoadContext): Promise<Resource>;
2142
- list?(context?: ResourceLoadContext): Promise<readonly Resource[]>;
2143
- }
2144
- export interface ResourceLoadContext {
2145
- readonly signal?: AbortSignal;
2146
- readonly metadata?: Readonly<Record<string, unknown>>;
2147
- readonly permission?: PermissionPolicy;
2148
- readonly trust?: TrustPolicy;
2149
- }
2150
- export interface SettingsProvider {
2151
- get<T = unknown>(key: string): Promise<T | undefined> | T | undefined;
2152
- }
2153
- export interface CredentialRequest {
2154
- readonly name: string;
2155
- readonly provider?: string;
2156
- readonly metadata?: Readonly<Record<string, unknown>>;
2157
- }
2158
- export interface Credential {
2159
- readonly type: "bearer" | "api_key" | "basic" | "custom";
2160
- readonly value: string;
2161
- readonly metadata?: Readonly<Record<string, unknown>>;
2162
- }
2163
- export interface CredentialResolver {
2164
- resolve(request: CredentialRequest): Promise<Credential | undefined> | Credential | undefined;
2165
- }
2166
- export interface CredentialResolverSource {
2167
- readonly name: string;
2168
- readonly resolver: CredentialResolver;
2169
- }
2170
- export interface OAuthCredentialStore {
2171
- set(provider: string, credentials: OAuthCredentials): void | Promise<void>;
2172
- }
2173
- export interface ProviderTurnResult {
2174
- readonly content: readonly ContentBlock[];
2175
- readonly calls: readonly ToolCallContent[];
2176
- readonly messageId?: string;
2177
- readonly started: boolean;
2178
- readonly usage?: Usage;
2179
- }
2180
- export interface LoopContext {
2181
- readonly sessionId: string;
2182
- readonly runId: string;
2183
- readonly metadata: Readonly<Record<string, unknown>>;
2184
- readonly signal: AbortSignal;
2185
- readonly history: Message[];
2186
- readonly input: AgentInput;
2187
- readonly inputMessages: readonly Message[];
2188
- readonly maxToolRounds: number;
2189
- /** Maximum independent tool calls dispatched concurrently per provider turn. Default `1`. */
2190
- readonly toolConcurrency: number;
2191
- assemble(nextInput: AgentInput, toolResults?: readonly ToolResult[], turn?: number): Promise<ProviderRequest>;
2192
- /**
2193
- * Charges a complete tool round before any call in it can start. On durable interrupt
2194
- * runs this is also the round-level approval gate: it collects every gated call of the
2195
- * round into one suspension. Loops must await it; dispatch without it falls back to
2196
- * per-call single-decision suspensions.
2197
- */
2198
- chargeToolRound?(calls: readonly ToolCallContent[]): void | Promise<void>;
2199
- generate(request: ProviderRequest): Promise<ProviderTurnResult>;
2200
- dispatchToolCall(call: ToolCallContent): Promise<ToolResult>;
2201
- isToolCallExclusive?(call: ToolCallContent): boolean;
2202
- appendMessage(message: Message): Promise<void>;
2203
- emit(event: AgentEvent): void;
2204
- /** True when mid-run steers are queued for the next provider turn. */
2205
- hasPendingSteers?(): boolean;
2206
- /** Drain pending steers into history/session. Returns true when any were applied. */
2207
- applyPendingSteers?(): Promise<boolean>;
2208
- /** Snapshot captured at the last suspension when the strategy declared snapshot/restore. Present only on resume. */
2209
- readonly restoredLoopState?: JsonValue;
2210
- }
2211
- export interface AgentLoopStrategy {
2212
- readonly name: string;
2213
- /** Host-authored loop revision. Joins the durable-run fingerprint when snapshot hooks are present. */
2214
- readonly revision?: string;
2215
- run(ctx: LoopContext): Promise<Usage | undefined>;
2216
- /**
2217
- * Capture loop-local resumable state at suspension. Must return a JSON-compatible value;
2218
- * core bounds and redacts it inside the durable run-state envelope. Declare together with
2219
- * `restore`; a custom strategy without both hooks is rejected before any provider call on
2220
- * durable runs (`AgentLoopStateError` / `ERR_PRISM_LOOP_NOT_DURABLE`).
2221
- */
2222
- snapshot?(): JsonValue;
2223
- /** Rehydrate from a previously captured snapshot; must throw on drift. Called before `run` on resume. */
2224
- restore?(snapshot: JsonValue): void;
2225
- }
2226
- export type AgentLoopOptions = {
2227
- readonly strategy: "single-shot";
2228
- /** Independent tool calls per turn run concurrently up to this limit. Default `1` (sequential). */
2229
- readonly toolConcurrency?: number;
2230
- } | {
2231
- readonly strategy: "generate-validate-revise";
2232
- readonly validator: ArtifactValidator<unknown>;
2233
- readonly parser?: ArtifactParser<unknown>;
2234
- readonly repairer?: ArtifactRepairer<unknown>;
2235
- readonly maxRevisions?: number;
2236
- /** Dispatch provider tool calls in artifact turns. Default `"disabled"`; `"bounded"` uses RunOptions.maxToolRounds sequentially. */
2237
- readonly toolCalls?: "disabled" | "bounded";
2238
- /** Native provider JSON-schema output. Ignored when `structuredOutputMode` is `artifact-loop`. */
2239
- readonly structuredOutput?: StructuredOutputOptions;
2240
- /** `native` maps schema to capable providers; `artifact-loop` keeps repair turns only. */
2241
- readonly structuredOutputMode?: "native" | "artifact-loop";
2242
- /**
2243
- * When to attach native `structuredOutput` under `toolCalls: "bounded"`.
2244
- * `every-turn` (default): schema on every provider request (legacy).
2245
- * `final-turn-only`: tool-eligible turns omit schema; artifact/revision turns send schema and withdraw tools.
2246
- */
2247
- readonly structuredOutputTiming?: "every-turn" | "final-turn-only";
2248
- };
2249
- export interface ArtifactValidation {
2250
- readonly ok: boolean;
2251
- readonly errors?: readonly {
2252
- readonly path?: string;
2253
- readonly message: string;
2254
- }[];
2255
- readonly metadata?: Readonly<Record<string, unknown>>;
2256
- }
2257
- export interface ArtifactContext {
2258
- readonly sessionId: string;
2259
- readonly runId: string;
2260
- readonly turn: number;
2261
- readonly signal: AbortSignal;
2262
- readonly metadata: Readonly<Record<string, unknown>>;
2263
- }
2264
- export interface ArtifactParseResult<T> {
2265
- readonly ok: boolean;
2266
- readonly value?: T;
2267
- readonly error?: string;
2268
- }
2269
- export type ArtifactParser<T> = (text: string, ctx: ArtifactContext) => ArtifactParseResult<T> | Promise<ArtifactParseResult<T>>;
2270
- export type ArtifactValidator<T> = (value: T, ctx: ArtifactContext) => ArtifactValidation | Promise<ArtifactValidation>;
2271
- export type ArtifactRepairer<T> = (value: T | undefined, failure: ArtifactValidation, ctx: ArtifactContext) => AgentInput | Promise<AgentInput>;
7
+ export * from "./contracts-core.js";
8
+ export * from "./contracts-run-state.js";
9
+ export * from "./contracts-protocol.js";
2272
10
  /** Alias re-exports so `dist/contracts.d.ts` exposes implementer contract names. */
2273
11
  export type AgentIdentity = import("./identity.js").AgentIdentity;
2274
12
  export type Principal = import("./identity.js").Principal;