@theokit/sdk 2.19.0 → 2.21.0

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 (89) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/dist/a2a/index.cjs +611 -274
  3. package/dist/a2a/index.cjs.map +1 -1
  4. package/dist/a2a/index.js +612 -275
  5. package/dist/a2a/index.js.map +1 -1
  6. package/dist/a2a/types.d.cts +7 -0
  7. package/dist/a2a/types.d.ts +7 -0
  8. package/dist/agent-builder.d.ts +2 -1
  9. package/dist/agent-generate.d.ts +12 -0
  10. package/dist/client/index.cjs.map +1 -1
  11. package/dist/client/index.d.cts +5 -0
  12. package/dist/client/index.d.ts +5 -0
  13. package/dist/client/index.js.map +1 -1
  14. package/dist/client/theokit-client.d.cts +6 -0
  15. package/dist/client/theokit-client.d.ts +6 -0
  16. package/dist/client/types.d.cts +2 -0
  17. package/dist/client/types.d.ts +2 -0
  18. package/dist/create-skill.d.ts +29 -0
  19. package/dist/{cron-D_wK1S-0.d.cts → cron-YrmsszEN.d.cts} +110 -3
  20. package/dist/{cron-Cep07kTz.d.ts → cron-dpvtRoro.d.ts} +110 -3
  21. package/dist/cron.cjs +660 -370
  22. package/dist/cron.cjs.map +1 -1
  23. package/dist/cron.d.cts +3 -2
  24. package/dist/cron.d.ts +3 -2
  25. package/dist/cron.js +661 -371
  26. package/dist/cron.js.map +1 -1
  27. package/dist/{errors-5lj1EWgs.d.ts → errors-C4vZPqXf.d.ts} +2 -2
  28. package/dist/{errors-CE-lMBi2.d.cts → errors-DrcpYVfZ.d.cts} +2 -2
  29. package/dist/errors.d.cts +3 -2
  30. package/dist/eval.cjs +660 -370
  31. package/dist/eval.cjs.map +1 -1
  32. package/dist/eval.js +660 -370
  33. package/dist/eval.js.map +1 -1
  34. package/dist/generate-object.d.ts +19 -4
  35. package/dist/index.cjs +867 -371
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.d.cts +274 -16
  38. package/dist/index.d.ts +274 -16
  39. package/dist/index.js +863 -373
  40. package/dist/index.js.map +1 -1
  41. package/dist/internal/agent-loop/loop-types.d.ts +2 -0
  42. package/dist/internal/agent-loop/tool-result-guard.d.ts +1 -0
  43. package/dist/internal/llm/tool-result-content.d.ts +40 -0
  44. package/dist/internal/llm/types.d.ts +6 -1
  45. package/dist/internal/persistence/conversation-storage-fs.d.cts +3 -1
  46. package/dist/internal/persistence/conversation-storage-fs.d.ts +3 -1
  47. package/dist/internal/persistence/conversation-storage-memory.d.cts +3 -1
  48. package/dist/internal/persistence/conversation-storage-memory.d.ts +3 -1
  49. package/dist/internal/persistence/session-meta.d.cts +13 -0
  50. package/dist/internal/persistence/session-meta.d.ts +13 -0
  51. package/dist/internal/runtime/model-selection.d.ts +14 -0
  52. package/dist/internal/structured-output-helpers.d.ts +1 -1
  53. package/dist/permission-engine.d.ts +32 -1
  54. package/dist/{run-BgfBWX-z.d.cts → run-BMo8yRwK.d.cts} +262 -19
  55. package/dist/{run-BgfBWX-z.d.ts → run-BMo8yRwK.d.ts} +262 -19
  56. package/dist/stream-object.d.ts +2 -1
  57. package/dist/tool-error.d.ts +30 -0
  58. package/dist/types/agent-prims.d.ts +10 -8
  59. package/dist/types/agent.d.ts +22 -1
  60. package/dist/types/content-blocks.d.ts +47 -0
  61. package/dist/types/conversation-storage.d.ts +38 -0
  62. package/dist/types/index.d.ts +1 -0
  63. package/dist/types/messages.d.ts +2 -9
  64. package/dist/types/run-events.d.ts +84 -0
  65. package/dist/types/run.d.ts +115 -1
  66. package/dist/types/session.d.ts +99 -0
  67. package/dist/types/workflow.d.ts +7 -0
  68. package/dist/workflow.cjs +7 -2
  69. package/dist/workflow.cjs.map +1 -1
  70. package/dist/workflow.d.cts +2 -0
  71. package/dist/workflow.d.ts +2 -0
  72. package/dist/workflow.js +7 -2
  73. package/dist/workflow.js.map +1 -1
  74. package/package.json +3 -23
  75. package/dist/internal/observability/context.d.cts +0 -23
  76. package/dist/internal/observability/context.d.ts +0 -23
  77. package/dist/internal/observability/index.cjs +0 -38
  78. package/dist/internal/observability/index.cjs.map +0 -1
  79. package/dist/internal/observability/index.d.cts +0 -8
  80. package/dist/internal/observability/index.d.ts +0 -8
  81. package/dist/internal/observability/index.js +0 -33
  82. package/dist/internal/observability/index.js.map +0 -1
  83. package/dist/internal/plugins/index.cjs +0 -363
  84. package/dist/internal/plugins/index.cjs.map +0 -1
  85. package/dist/internal/plugins/index.js +0 -357
  86. package/dist/internal/plugins/index.js.map +0 -1
  87. package/dist/internal/workflow/index.d.ts +0 -12
  88. package/dist/server/adapter/index.d.cts +0 -8
  89. package/dist/server/adapter/index.d.ts +0 -8
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-5lj1EWgs.js';
2
- export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, E as ErrorCode, m as ErrorMetadata, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors-5lj1EWgs.js';
3
- import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as ProviderProfile, m as Plugin, n as ConversationStorageAdapter, o as StoredMessage, B as BudgetTracker, p as MemoryProvider, q as MemoryId, r as PreToolCallDecision, s as SDKProvider } from './cron-Cep07kTz.js';
4
- export { t as ActiveMemoryPassArgs, u as ActiveMemoryPassResult, v as AgentMemory, w as BudgetCheck, x as BudgetTotal, y as BudgetUsageEvent, z as CloudEnv, D as CloudRepo, E as ContextBudget, F as ContextManagerKind, H as ContextSnapshot, I as ContextSource, J as ContextSourceStatus, K as Cron, N as CronCreateOptions, O as CronGetOptions, Q as CronJob, R as CronJobStatus, T as CronListOptions, U as CronOperationOptions, V as CronRunOptions, W as CronRuntime, X as CronSchedulerStatus, Y as CronStartOptions, Z as GoalEvent, _ as GoalOptions, $ as GoalResult, a0 as HookName, a1 as InvalidateCacheOptions, a2 as MemoryAdapter, a3 as MemoryAdapterCapabilities, a4 as MemoryContext, a5 as MemoryFact, a6 as MemoryProviderHandle, a7 as MemoryProviderInitOptions, a8 as MemoryRevision, a9 as MemoryToolSchema, aa as MemoryTurnMessage, ab as PersonalityPreset, ac as PluginContext, ad as PostAssistantReplyContext, ae as PreToolCallContext, af as PreUserSendContext, ag as PreUserSendResult, ah as ProviderCapability, ai as ProviderRoute, aj as RecordSessionSummaryArgs, ak as ResolvedProviderRoute, al as RunUntilIterator, am as SDKAgentPlugins, an as SDKAgentSkills, ao as SDKArtifact, ap as SDKContextManager, aq as SDKPluginMetadata, ar as SDKProvidersManager, as as SettingSource, at as SystemPromptContext, au as SystemPromptMemoryFact, av as SystemPromptSkillRef, aw as TelemetrySettings, ax as definePlugin } from './cron-Cep07kTz.js';
5
- import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-BgfBWX-z.js';
6
- export { A as AgentConversationTurn, c as AssistantMessage, d as ConversationStep, e as ConversationTurn, f as CostBreakdown, g as CostSource, h as CostStatus, D as DoomLoopThresholds, I as InteractionUpdate, i as McpAuthConfig, j as McpHttpServerConfig, k as McpOAuthConfig, l as McpStdioServerConfig, m as ModelParameterValue, P as PartialToolCallUpdate, n as RunErrorDetail, o as RunGitInfo, p as RunOperation, q as RunStatus, r as RunToCompletionOptions, s as RunToCompletionResult, t as SDKAssistantMessage, u as SDKImage, v as SDKImageDimension, w as SDKObjectDelta, x as SDKRequestMessage, y as SDKStatusMessage, z as SDKSystemMessage, B as SDKTaskMessage, E as SDKThinkingMessage, F as SDKToolUseMessage, G as SDKUserMessage, H as SDKUserMessageEvent, J as SendOptions, K as ShellCommand, L as ShellConversationTurn, N as ShellOutput, O as ShellOutputDeltaUpdate, Q as StepCompletedUpdate, T as StepStartedUpdate, U as StreamToCompletionResult, V as SummaryCompletedUpdate, W as SummaryStartedUpdate, X as SummaryUpdate, Y as TextBlock, Z as TextDeltaUpdate, _ as ThinkingCompletedUpdate, $ as ThinkingDeltaUpdate, a0 as ThinkingMessage, a1 as TokenDeltaUpdate, a2 as TokenUsage, a3 as ToolCall, a4 as ToolCallCompletedUpdate, a5 as ToolCallStartedUpdate, a6 as ToolResult, a7 as ToolResultGuardOptions, a8 as ToolUseBlock, a9 as TurnEndedUpdate, aa as UserMessage, ab as UserMessageAppendedUpdate } from './run-BgfBWX-z.js';
1
+ import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot, E as ErrorMetadata } from './errors-C4vZPqXf.js';
2
+ export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, m as ErrorCode, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors-C4vZPqXf.js';
3
+ import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as ProviderProfile, m as Plugin, n as ConversationStorageAdapter, o as StoredMessage, p as SessionMeta, q as SessionMetaPatch, B as BudgetTracker, r as MemoryProvider, s as MemoryId, t as PreToolCallDecision, u as SDKProvider } from './cron-dpvtRoro.js';
4
+ export { v as ActiveMemoryPassArgs, w as ActiveMemoryPassResult, x as AgentMemory, y as BudgetCheck, z as BudgetTotal, D as BudgetUsageEvent, E as CloudEnv, F as CloudRepo, H as ContextBudget, I as ContextManagerKind, J as ContextSnapshot, K as ContextSource, N as ContextSourceStatus, O as CreateSkillSpec, Q as Cron, R as CronCreateOptions, T as CronGetOptions, U as CronJob, V as CronJobStatus, W as CronListOptions, X as CronOperationOptions, Y as CronRunOptions, Z as CronRuntime, _ as CronSchedulerStatus, $ as CronStartOptions, a0 as GoalEvent, a1 as GoalOptions, a2 as GoalResult, a3 as HookName, a4 as InlineSkill, a5 as InvalidateCacheOptions, a6 as MemoryAdapter, a7 as MemoryAdapterCapabilities, a8 as MemoryContext, a9 as MemoryFact, aa as MemoryProviderHandle, ab as MemoryProviderInitOptions, ac as MemoryRevision, ad as MemoryToolSchema, ae as MemoryTurnMessage, af as PersonalityPreset, ag as PluginContext, ah as PostAssistantReplyContext, ai as PreToolCallContext, aj as PreUserSendContext, ak as PreUserSendResult, al as ProviderCapability, am as ProviderRoute, an as RecordSessionSummaryArgs, ao as ResolvedProviderRoute, ap as RunUntilIterator, aq as SDKAgentPlugins, ar as SDKAgentSkills, as as SDKArtifact, at as SDKContextManager, au as SDKPluginMetadata, av as SDKProvidersManager, aw as SettingSource, ax as SystemPromptContext, ay as SystemPromptMemoryFact, az as SystemPromptSkillRef, aA as TelemetrySettings, aB as createSkill, aC as definePlugin } from './cron-dpvtRoro.js';
5
+ import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage, c as MessageOrigin, T as ToolResultContentBlock } from './run-BMo8yRwK.js';
6
+ export { A as AgentConversationTurn, d as AssistantMessage, e as ConversationStep, f as ConversationTurn, g as CostBreakdown, h as CostSource, i as CostStatus, D as DoomLoopThresholds, G as GenerateOptions, j as GenerateRunResult, I as ImageBlock, k as InteractionUpdate, l as McpAuthConfig, m as McpHttpServerConfig, n as McpOAuthConfig, o as McpStdioServerConfig, p as ModelParameterValue, P as PartialToolCallUpdate, q as RunCompactBoundaryEvent, r as RunErrorDetail, s as RunEvent, t as RunEventSink, u as RunGitInfo, v as RunOperation, w as RunPermissionDeniedEvent, x as RunRateLimitEvent, y as RunStatus, z as RunTaskCompletedEvent, B as RunTaskStartedEvent, E as RunTaskUpdatedEvent, F as RunToCompletionOptions, H as RunToCompletionResult, J as RunToolProgressEvent, K as SDKAssistantMessage, L as SDKImage, N as SDKImageDimension, O as SDKObjectDelta, Q as SDKRequestMessage, U as SDKStatusMessage, V as SDKSystemMessage, W as SDKTaskMessage, X as SDKThinkingMessage, Y as SDKToolUseMessage, Z as SDKUserMessage, _ as SDKUserMessageEvent, $ as SendOptions, a0 as ShellCommand, a1 as ShellConversationTurn, a2 as ShellOutput, a3 as ShellOutputDeltaUpdate, a4 as StepCompletedUpdate, a5 as StepStartedUpdate, a6 as StreamToCompletionResult, a7 as SummaryCompletedUpdate, a8 as SummaryStartedUpdate, a9 as SummaryUpdate, aa as TextBlock, ab as TextDeltaUpdate, ac as ThinkingCompletedUpdate, ad as ThinkingDeltaUpdate, ae as ThinkingMessage, af as TokenDeltaUpdate, ag as TokenUsage, ah as ToolCall, ai as ToolCallCompletedUpdate, aj as ToolCallStartedUpdate, ak as ToolResult, al as ToolResultGuardOptions, am as ToolUseBlock, an as TurnEndedUpdate, ao as UserMessage, ap as UserMessageAppendedUpdate, aq as emitRunEvent } from './run-BMo8yRwK.js';
7
7
  import * as zod from 'zod';
8
8
  import { ZodType, z } from 'zod';
9
9
 
@@ -129,7 +129,8 @@ interface StreamObjectOptions<T extends ZodType> {
129
129
  schema: T;
130
130
  prompt: string;
131
131
  systemPrompt?: string;
132
- model: ModelSelection;
132
+ /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */
133
+ model: string | ModelSelection;
133
134
  apiKey?: string;
134
135
  local: LocalOptions;
135
136
  maxRetries?: number;
@@ -203,8 +204,16 @@ interface GenerateObjectOptions<T extends ZodType> {
203
204
  prompt: string;
204
205
  /** Optional system prompt steering the model. */
205
206
  systemPrompt?: string;
206
- /** Model selection. Required (transient agents need a model). */
207
- model: ModelSelection;
207
+ /** Model selection. Required (transient agents need a model). SE8 — accepts a
208
+ * bare-string id shorthand (`"openai/gpt-4o-mini"`) or a {@link ModelSelection}. */
209
+ model: string | ModelSelection;
210
+ /**
211
+ * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a
212
+ * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the
213
+ * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large
214
+ * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.
215
+ */
216
+ structuringModel?: string | ModelSelection;
208
217
  /** API key. Falls back to env (THEOKIT_API_KEY etc). */
209
218
  apiKey?: string;
210
219
  /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */
@@ -282,7 +291,8 @@ declare class AgentBuilder {
282
291
  private opts;
283
292
  private readonly deps;
284
293
  constructor(deps?: AgentBuilderDeps);
285
- model(m: ModelSelection): this;
294
+ /** SE8 — accepts a bare-string id shorthand (`"openai/gpt-4o-mini"`) or a {@link ModelSelection}. */
295
+ model(m: string | ModelSelection): this;
286
296
  apiKey(k: string): this;
287
297
  name(n: string): this;
288
298
  systemPrompt(p: string | SystemPromptResolver): this;
@@ -1018,6 +1028,8 @@ declare class FileSystemConversationStorage implements ConversationStorageAdapte
1018
1028
  limit?: number;
1019
1029
  }): Promise<readonly string[]>;
1020
1030
  compact(conversationId: string, maxTurns: number): Promise<void>;
1031
+ getSessionMeta(conversationId: string): Promise<SessionMeta | undefined>;
1032
+ setSessionMeta(conversationId: string, patch: SessionMetaPatch): Promise<void>;
1021
1033
  dispose(): Promise<void>;
1022
1034
  }
1023
1035
 
@@ -1049,6 +1061,8 @@ declare class InMemoryConversationStorage implements ConversationStorageAdapter
1049
1061
  listConversationIds(opts?: {
1050
1062
  limit?: number;
1051
1063
  }): Promise<readonly string[]>;
1064
+ getSessionMeta(conversationId: string): Promise<SessionMeta | undefined>;
1065
+ setSessionMeta(conversationId: string, patch: SessionMetaPatch): Promise<void>;
1052
1066
  dispose(): Promise<void>;
1053
1067
  }
1054
1068
 
@@ -1412,6 +1426,37 @@ declare function migrateSqliteToLance(options: MigrateOptions): Promise<MigrateR
1412
1426
  * the previous fail-open behavior with `{ defaultAction: "allow" }`.
1413
1427
  */
1414
1428
  type PermissionAction = "allow" | "deny" | "ask";
1429
+ /**
1430
+ * SE1 — a per-run permission MODE that adjusts the rule-engine verdict globally.
1431
+ * A PURE post-processor of the verdict (no tool-safety metadata needed, so it fits
1432
+ * a bring-your-own-tools runtime). Grounded in OpenCode (plan agent = deny-all,
1433
+ * `dangerously-skip-permissions`) + Codex (`AskForApproval`: `OnRequest` default,
1434
+ * `Never`, `UnlessTrusted`). See {@link applyMode} for the exact table.
1435
+ *
1436
+ * - `default` — verdict as-is (rules decide; unmatched ⇒ `ask`, fail-closed).
1437
+ * - `plan` — read-only: `allow` rules pass, everything else ⇒ `deny` (mutations blocked).
1438
+ * NOTE: `plan` gates on the resolved verdict, so an engine configured with
1439
+ * `{ defaultAction: "allow" }` still yields `allow` for UNMATCHED calls under
1440
+ * `plan` — pair `plan` with the default fail-closed engine (`defaultAction: "ask"`)
1441
+ * for full read-only behavior.
1442
+ * - `acceptEdits` — auto-approve the UNMATCHED verdict, but STILL honor an explicit
1443
+ * `ask` rule (a caller gates a risky tool with an ask rule). Codex `UnlessTrusted`.
1444
+ * - `bypass` — everything ⇒ `allow` EXCEPT an explicit `deny` rule. Never asks.
1445
+ * OpenCode `dangerously-skip-permissions` / Codex `Never`.
1446
+ */
1447
+ type PermissionMode = "default" | "plan" | "acceptEdits" | "bypass";
1448
+ /**
1449
+ * SE1 — apply a {@link PermissionMode} to a rule-engine verdict. Pure.
1450
+ *
1451
+ * `explicit` is `true` when the verdict came from a rule that matched by name (and
1452
+ * args), `false` when it is the fail-closed default for an unmatched call. The flag
1453
+ * is load-bearing for `acceptEdits`, which auto-approves the unmatched default but
1454
+ * keeps honoring an explicit `ask` rule (unlike `bypass`, which allows even that).
1455
+ *
1456
+ * INVARIANT (both OpenCode + Codex): an explicit `deny` is immune to EVERY
1457
+ * auto-approve mode — `bypass`/`acceptEdits` never un-deny.
1458
+ */
1459
+ declare function applyMode(verdict: PermissionAction, mode: PermissionMode, explicit: boolean): PermissionAction;
1415
1460
  /**
1416
1461
  * #55 — an argument matcher. A rule with `args` gates on the tool's argument
1417
1462
  * VALUES, not just its name: an exact string, a RegExp (tested against the
@@ -1454,7 +1499,7 @@ declare class PermissionEngine {
1454
1499
  * argument values, so the same tool name can resolve to different actions
1455
1500
  * depending on what it is asked to do.
1456
1501
  */
1457
- evaluate(toolName: string, args?: Record<string, unknown>): PermissionAction;
1502
+ evaluate(toolName: string, args?: Record<string, unknown>, mode?: PermissionMode): PermissionAction;
1458
1503
  }
1459
1504
 
1460
1505
  /**
@@ -1468,22 +1513,75 @@ declare class PermissionEngine {
1468
1513
  * @public
1469
1514
  */
1470
1515
 
1516
+ /**
1517
+ * SE1 — context passed to the {@link PermissionGate}. Intentionally minimal for
1518
+ * SE1; `agentId`/`runId` (for audit logging) are a documented follow-up — they are
1519
+ * available on the raw `pre_tool_call` context and can be threaded in a later slice.
1520
+ */
1521
+ interface PermissionGateContext {
1522
+ /** The tool being gated. */
1523
+ readonly toolName: string;
1524
+ /** The active permission mode for this run. */
1525
+ readonly mode: PermissionMode;
1526
+ }
1527
+ /**
1528
+ * SE1 — the resolution of an `"ask"` verdict by the host gate. Fail-closed: an
1529
+ * absent gate, a throwing gate, and a `"deny"` decision all block. Arg rewrite
1530
+ * (`updatedInput`) is intentionally NOT supported yet — the `pre_tool_call` seam
1531
+ * is veto-only (`{ block, message }`); a future enhancement can extend it.
1532
+ */
1533
+ type PermissionGateDecision = {
1534
+ readonly behavior: "allow";
1535
+ } | {
1536
+ readonly behavior: "deny";
1537
+ readonly message?: string;
1538
+ };
1539
+ /**
1540
+ * SE1 — the enriched `canUseTool` gate (the Anthropic-parity shape). Invoked ONLY
1541
+ * on an `"ask"` verdict, it receives the tool name, its input args, and the run
1542
+ * {@link PermissionGateContext}, and resolves to allow/deny. May be async (a real
1543
+ * gate can prompt a human — the `pre_tool_call` seam awaits it).
1544
+ */
1545
+ type PermissionGate = (toolName: string, input: Record<string, unknown>, ctx: PermissionGateContext) => PermissionGateDecision | Promise<PermissionGateDecision>;
1471
1546
  /** Options for {@link createPermissionPlugin}. */
1472
1547
  interface PermissionPluginOptions {
1473
1548
  /** Plugin name (default `"permission-engine"`). */
1474
1549
  readonly name?: string;
1475
1550
  /**
1476
- * Resolver for the `"ask"` verdict. Returns a veto (`{block,message}`) to deny
1477
- * or `undefined` to allow. Default: fail-closed (block with "requires approval").
1551
+ * SE1 the per-run {@link PermissionMode}. Threaded into `engine.evaluate`, so
1552
+ * `bypass` auto-allows the ask verdict (gate never consulted), `plan` blocks
1553
+ * mutations, etc. An explicit `deny` rule is immune to every mode. Default
1554
+ * `"default"` (rules decide; unmatched ⇒ fail-closed ask).
1555
+ */
1556
+ readonly mode?: PermissionMode;
1557
+ /**
1558
+ * SE1 — the enriched gate for the `"ask"` verdict. Preferred over {@link onAsk}.
1559
+ * Absent gate on an `ask` verdict ⇒ fail-closed block.
1560
+ */
1561
+ readonly canUseTool?: PermissionGate;
1562
+ /**
1563
+ * @deprecated since SE1 — use {@link canUseTool}, which receives `(toolName,
1564
+ * input, ctx)` and returns a typed decision. Honored only when `canUseTool` is
1565
+ * absent. Returns a veto (`{block,message}`) to deny or `undefined` to allow.
1478
1566
  */
1479
1567
  readonly onAsk?: (toolName: string) => PreToolCallDecision | undefined;
1480
1568
  }
1481
1569
  /**
1482
- * Build a `general` plugin that vetoes tool calls per the engine's verdict.
1483
- * Register it on an agent's plugin manager (same as the ACP permission plugin).
1570
+ * Build a `general` plugin that vetoes tool calls per the engine's verdict, under
1571
+ * the configured {@link PermissionMode}, resolving `ask` via the {@link canUseTool}
1572
+ * gate. Register it on an agent's plugin manager (same as the ACP permission plugin).
1484
1573
  */
1485
1574
  declare function createPermissionPlugin(engine: PermissionEngine, opts?: PermissionPluginOptions): Plugin;
1486
1575
 
1576
+ /** The internal JSON-Schema shape the synthetic `output` tool consumes. */
1577
+ type NormalizedJsonSchema = Record<string, unknown>;
1578
+ /**
1579
+ * Normalize any supported schema to the internal JSON Schema. Async because the Valibot path
1580
+ * dynamically imports its optional converter. Throws a clear, typed-message error for an unsupported
1581
+ * schema or a missing Valibot peer (error-handling.md).
1582
+ */
1583
+ declare function normalizeSchema(schema: unknown): Promise<NormalizedJsonSchema>;
1584
+
1487
1585
  /**
1488
1586
  * Public security namespace (T2.1, ADR D68).
1489
1587
  *
@@ -1552,6 +1650,130 @@ declare class Security {
1552
1650
  static addPattern(re: RegExp): void;
1553
1651
  }
1554
1652
 
1653
+ /**
1654
+ * SE4 — public types for the session-management surface (`createSessionManager`).
1655
+ *
1656
+ * A "session" is one conversation in a {@link ConversationStorageAdapter}. These
1657
+ * DTOs are deliberately LIGHT — derived display metadata, not raw store rows — so
1658
+ * a host (TheoKit) can build a session list/UI without reaching into storage
1659
+ * internals.
1660
+ *
1661
+ * @public
1662
+ */
1663
+
1664
+ /**
1665
+ * Light, display-oriented metadata for one session, derived from its transcript
1666
+ * plus any host-set title/tag. All fields except `id`/`messageCount` are optional
1667
+ * because a fresh or empty session may lack them.
1668
+ *
1669
+ * @public
1670
+ */
1671
+ interface SessionSummary {
1672
+ /** The conversation id (verbatim — includes any scope prefix like `user__`). */
1673
+ readonly id: string;
1674
+ /** Number of stored messages in the transcript. */
1675
+ readonly messageCount: number;
1676
+ /** Content of the first `user` message, when present — the opening prompt. */
1677
+ readonly firstPrompt?: string;
1678
+ /** Largest message timestamp (`StoredMessage.at`) seen, when any is stamped. */
1679
+ readonly lastModified?: number;
1680
+ /** Host-set title (via `renameSession`), when set. */
1681
+ readonly title?: string;
1682
+ /** Host-set tag (via `tagSession`), when set. */
1683
+ readonly tag?: string;
1684
+ /**
1685
+ * A short display preview: the `title` when set, otherwise the `firstPrompt`
1686
+ * (truncated). Undefined only when the session has neither a title nor a first
1687
+ * user prompt.
1688
+ */
1689
+ readonly summary?: string;
1690
+ }
1691
+ /**
1692
+ * Windowing for {@link SessionManager.listSessions}. `offset` counts from the
1693
+ * first listed session; `limit` bounds the returned count. Omitting both lists
1694
+ * all sessions (bounded only by the adapter's own `listConversationIds` limit).
1695
+ *
1696
+ * @public
1697
+ */
1698
+ interface SessionListOptions {
1699
+ readonly offset?: number;
1700
+ readonly limit?: number;
1701
+ }
1702
+ /**
1703
+ * Typed capability result — the graceful-degradation signal for operations an
1704
+ * adapter cannot perform (listing, or writing session metadata). Prefer this over
1705
+ * throwing on every call: a host inspects `supported` once and hides the
1706
+ * corresponding UI affordance. Mirrors the SDK's existing degradation precedent
1707
+ * (`ConversationStorageAdapter.listConversationIds` returning `undefined`,
1708
+ * `Run.unsupportedReason`).
1709
+ *
1710
+ * @public
1711
+ */
1712
+ type SessionCapabilityResult<T> = {
1713
+ readonly supported: true;
1714
+ readonly value: T;
1715
+ } | {
1716
+ readonly supported: false;
1717
+ readonly reason: string;
1718
+ };
1719
+ /**
1720
+ * The session-management surface returned by `createSessionManager`. Bound to a
1721
+ * single {@link ConversationStorageAdapter} instance (the same one a host passed
1722
+ * to `Agent.create({ conversationStorage })`).
1723
+ *
1724
+ * @public
1725
+ */
1726
+ interface SessionManager {
1727
+ /**
1728
+ * List sessions with light derived metadata. Returns an unsupported result
1729
+ * when the adapter cannot enumerate conversations (`listConversationIds`
1730
+ * absent or returning `undefined`).
1731
+ */
1732
+ listSessions(opts?: SessionListOptions): Promise<SessionCapabilityResult<readonly SessionSummary[]>>;
1733
+ /**
1734
+ * Read a session's stored transcript (passthrough to the adapter's mandatory
1735
+ * `getMessages`). Always supported. `{ offset, limit }` windows the result.
1736
+ */
1737
+ getSessionMessages(id: string, opts?: {
1738
+ offset?: number;
1739
+ limit?: number;
1740
+ }): Promise<readonly StoredMessage[]>;
1741
+ /**
1742
+ * Set a session's title. Unsupported when the adapter cannot write session
1743
+ * metadata (`setSessionMeta` absent).
1744
+ */
1745
+ renameSession(id: string, title: string): Promise<SessionCapabilityResult<void>>;
1746
+ /**
1747
+ * Set (`tag`) or clear (`null`) a session's tag. Unsupported when the adapter
1748
+ * cannot write session metadata (`setSessionMeta` absent).
1749
+ */
1750
+ tagSession(id: string, tag: string | null): Promise<SessionCapabilityResult<void>>;
1751
+ }
1752
+
1753
+ /**
1754
+ * SE4 — session-management surface over {@link ConversationStorageAdapter}.
1755
+ *
1756
+ * `createSessionManager(storage)` binds the four session operations
1757
+ * (list / get / rename / tag) to a storage adapter — the same instance a host
1758
+ * passed to `Agent.create({ conversationStorage })`. It derives LIGHT metadata
1759
+ * (firstPrompt, lastModified, messageCount) from the transcript, persists
1760
+ * title/tag via the adapter's optional `setSessionMeta`, and degrades to a typed
1761
+ * `{ supported: false }` result for adapters that cannot list or write metadata —
1762
+ * never a throw-on-every-call.
1763
+ *
1764
+ * Composition-LEGO precedent: mirrors `createSquad` / `createAgentFactory` — a
1765
+ * thin factory over an existing primitive, no new orchestration.
1766
+ *
1767
+ * @public
1768
+ */
1769
+
1770
+ /**
1771
+ * Build a {@link SessionManager} bound to `storage`.
1772
+ *
1773
+ * @public
1774
+ */
1775
+ declare function createSessionManager(storage: ConversationStorageAdapter): SessionManager;
1776
+
1555
1777
  /**
1556
1778
  * M3 #62 — scoped session state.
1557
1779
  *
@@ -1608,6 +1830,12 @@ interface AgentStep {
1608
1830
  readonly agent: SDKAgent;
1609
1831
  readonly promptTemplate: string | ((input: unknown) => string);
1610
1832
  readonly retry?: RetryPolicy;
1833
+ /**
1834
+ * SE3 — provenance stamped onto this step's `agent.send()` (forwarded to
1835
+ * `RunResult.origin`). Squad sets `{ kind: "peer", from: "agent-<i-1>" }` on
1836
+ * every step after the first so a peer-driven turn is attributable.
1837
+ */
1838
+ readonly origin?: MessageOrigin;
1611
1839
  }
1612
1840
  /** N concurrent branches, each its own mini-step-list. */
1613
1841
  interface ParallelStep {
@@ -2134,6 +2362,36 @@ declare class Theokit {
2134
2362
  };
2135
2363
  }
2136
2364
 
2365
+ /**
2366
+ * SE7 — `ToolError`: thrown FROM a tool `handler` to report a failure back to
2367
+ * the model with structured content (text and/or an image), not just a string.
2368
+ * Kept in its own module (not `errors.ts`) so the error taxonomy file stays
2369
+ * under the G8 LoC budget and this tool-shaped error lives next to the tool
2370
+ * surface it serves.
2371
+ *
2372
+ * @public
2373
+ */
2374
+
2375
+ /**
2376
+ * Thrown from a tool `handler` to surface a failure to the model. The SDK turns
2377
+ * it into a `tool_result` with `isError: true` carrying the content. A plain
2378
+ * `Error` thrown from a handler still works (its message becomes text);
2379
+ * `ToolError` is the opt-in for a clean message or a multimodal error (e.g. an
2380
+ * error screenshot).
2381
+ *
2382
+ * @public
2383
+ */
2384
+ declare class ToolError extends TheokitAgentError {
2385
+ readonly name: string;
2386
+ /** The error content surfaced to the model: a string, or text/image blocks. */
2387
+ readonly content: string | ToolResultContentBlock[];
2388
+ constructor(content: string | ToolResultContentBlock[], options?: {
2389
+ code?: string;
2390
+ cause?: unknown;
2391
+ metadata?: ErrorMetadata;
2392
+ });
2393
+ }
2394
+
2137
2395
  /**
2138
2396
  * Public types for ShareGPT trajectory export (ADR D139).
2139
2397
  *
@@ -2214,4 +2472,4 @@ declare function toShareGptTrajectory(result: BatchResult, options?: {
2214
2472
  model?: string;
2215
2473
  }): ShareGptTrajectory | null;
2216
2474
 
2217
- export { Agent, AgentBuilder, AgentDefinition, type AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, BudgetTracker, CloudOptions, ContextSettings, ConversationStorageAdapter, type CounterBudgetTrackerOptions, CustomTool, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, EventBus, type EvictReason, FileSystemConversationStorage, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, InMemoryConversationStorage, JobQueue, type JobQueueOptions, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryId, MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, type PermissionAction, PermissionEngine, type PermissionEngineOptions, type PermissionPluginOptions, type PermissionRule, Plugin, PluginsSettings, PreToolCallDecision, ProviderProfile, ProviderRoutingSettings, type ReplayHistoryOptions, Run, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type SessionScope, type ShareGptMessage, type ShareGptTrajectory, SkillsSettings, type Squad, type SquadOptions, type SquadRun, StoredMessage, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, Theokit, TheokitAgentError, type TheokitRequestOptions, UsageAccumulator, buildReplayHistory, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createPermissionPlugin, createSquad, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, scopedConversationId, sessionScopePrefix, toShareGptTrajectory, withCwdMutex };
2475
+ export { Agent, AgentBuilder, AgentDefinition, type AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, BudgetTracker, CloudOptions, ContextSettings, ConversationStorageAdapter, type CounterBudgetTrackerOptions, CustomTool, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, ErrorMetadata, EventBus, type EvictReason, FileSystemConversationStorage, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, InMemoryConversationStorage, JobQueue, type JobQueueOptions, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryId, MemoryProvider, MemorySettings, MessageOrigin, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, type NormalizedJsonSchema, type PermissionAction, PermissionEngine, type PermissionEngineOptions, type PermissionGate, type PermissionGateContext, type PermissionGateDecision, type PermissionMode, type PermissionPluginOptions, type PermissionRule, Plugin, PluginsSettings, PreToolCallDecision, ProviderProfile, ProviderRoutingSettings, type ReplayHistoryOptions, Run, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type SessionCapabilityResult, type SessionListOptions, type SessionManager, SessionMeta, SessionMetaPatch, type SessionScope, type SessionSummary, type ShareGptMessage, type ShareGptTrajectory, SkillsSettings, type Squad, type SquadOptions, type SquadRun, StoredMessage, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, Theokit, TheokitAgentError, type TheokitRequestOptions, ToolError, ToolResultContentBlock, UsageAccumulator, applyMode, buildReplayHistory, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createPermissionPlugin, createSessionManager, createSquad, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, preflightCheck, scopedConversationId, sessionScopePrefix, toShareGptTrajectory, withCwdMutex };