@theokit/sdk 2.15.2 → 2.18.1

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 (75) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/dist/a2a/index.cjs +875 -198
  3. package/dist/a2a/index.cjs.map +1 -1
  4. package/dist/a2a/index.js +876 -199
  5. package/dist/a2a/index.js.map +1 -1
  6. package/dist/{cron-BxLSz1UH.d.cts → cron-Bbg0mBOv.d.ts} +33 -3
  7. package/dist/{cron-DcaoP7aW.d.ts → cron-ZLSKbDbB.d.cts} +33 -3
  8. package/dist/cron.cjs +840 -187
  9. package/dist/cron.cjs.map +1 -1
  10. package/dist/cron.d.cts +2 -2
  11. package/dist/cron.d.ts +2 -2
  12. package/dist/cron.js +840 -187
  13. package/dist/cron.js.map +1 -1
  14. package/dist/define-tool.d.ts +9 -2
  15. package/dist/{errors-Bart0ptP.d.cts → errors-1tVcX3Fq.d.cts} +1 -1
  16. package/dist/{errors-DJuuubJK.d.ts → errors-qyVYfk9H.d.ts} +1 -1
  17. package/dist/errors.d.cts +2 -2
  18. package/dist/eval.cjs +846 -189
  19. package/dist/eval.cjs.map +1 -1
  20. package/dist/eval.js +846 -189
  21. package/dist/eval.js.map +1 -1
  22. package/dist/event-bus.d.ts +3 -0
  23. package/dist/index.cjs +977 -215
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +122 -27
  26. package/dist/index.d.ts +122 -27
  27. package/dist/index.js +977 -217
  28. package/dist/index.js.map +1 -1
  29. package/dist/internal/agent-loop/tool-dispatch.d.ts +3 -1
  30. package/dist/internal/agent-loop/tool-result-guard.d.ts +24 -0
  31. package/dist/internal/agent-loop/tool-timeout.d.ts +23 -0
  32. package/dist/internal/llm/openai.d.ts +4 -0
  33. package/dist/internal/llm/sse.d.ts +13 -1
  34. package/dist/internal/mcp/client.d.ts +1 -1
  35. package/dist/internal/memory/active-memory.d.ts +1 -1
  36. package/dist/internal/persistence/conversation-storage-fs.d.cts +7 -1
  37. package/dist/internal/persistence/conversation-storage-fs.d.ts +7 -1
  38. package/dist/internal/persistence/conversation-storage-memory.d.cts +7 -1
  39. package/dist/internal/persistence/conversation-storage-memory.d.ts +7 -1
  40. package/dist/internal/persistence/pagination.d.cts +8 -0
  41. package/dist/internal/persistence/pagination.d.ts +8 -0
  42. package/dist/internal/plugins/index.cjs +135 -0
  43. package/dist/internal/plugins/index.cjs.map +1 -1
  44. package/dist/internal/plugins/index.js +135 -0
  45. package/dist/internal/plugins/index.js.map +1 -1
  46. package/dist/internal/plugins/manager.d.cts +21 -1
  47. package/dist/internal/plugins/manager.d.ts +21 -1
  48. package/dist/internal/plugins/types.d.cts +40 -0
  49. package/dist/internal/plugins/types.d.ts +40 -0
  50. package/dist/internal/{memory → resilience}/circuit-breaker.d.ts +5 -1
  51. package/dist/internal/runtime/hooks/hooks-frontmatter.d.ts +1 -1
  52. package/dist/internal/runtime/lifecycle/env-policy.d.ts +30 -0
  53. package/dist/internal/runtime/session/agent-session-store.d.ts +1 -0
  54. package/dist/internal/telemetry/span-names.d.ts +7 -1
  55. package/dist/job-queue.d.ts +29 -7
  56. package/dist/permission-engine.d.ts +32 -7
  57. package/dist/{run-DXy_MVwz.d.cts → run-pE-34AAo.d.cts} +64 -3
  58. package/dist/{run-DXy_MVwz.d.ts → run-pE-34AAo.d.ts} +64 -3
  59. package/dist/sandbox/index.cjs +53 -2
  60. package/dist/sandbox/index.cjs.map +1 -1
  61. package/dist/sandbox/index.js +53 -2
  62. package/dist/sandbox/index.js.map +1 -1
  63. package/dist/sandbox/local-sandbox.d.cts +11 -3
  64. package/dist/sandbox/local-sandbox.d.ts +11 -3
  65. package/dist/sandbox/types.d.cts +7 -0
  66. package/dist/sandbox/types.d.ts +7 -0
  67. package/dist/types/agent-prims.d.ts +6 -2
  68. package/dist/types/conversation-storage.d.ts +32 -2
  69. package/dist/types/mcp.d.ts +20 -0
  70. package/dist/types/run.d.ts +17 -0
  71. package/dist/workflow.cjs +6 -3
  72. package/dist/workflow.cjs.map +1 -1
  73. package/dist/workflow.js +6 -3
  74. package/dist/workflow.js.map +1 -1
  75. package/package.json +14 -14
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
1
- import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-Bart0ptP.cjs';
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-Bart0ptP.cjs';
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-BxLSz1UH.cjs';
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-BxLSz1UH.cjs';
5
- import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-DXy_MVwz.cjs';
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 ToolUseBlock, a8 as TurnEndedUpdate, a9 as UserMessage, aa as UserMessageAppendedUpdate } from './run-DXy_MVwz.cjs';
1
+ import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-1tVcX3Fq.cjs';
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-1tVcX3Fq.cjs';
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-ZLSKbDbB.cjs';
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-ZLSKbDbB.cjs';
5
+ import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-pE-34AAo.cjs';
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-pE-34AAo.cjs';
7
7
  import * as zod from 'zod';
8
8
  import { ZodType, z } from 'zod';
9
9
 
@@ -904,8 +904,15 @@ interface DefineToolSpec<T extends ZodType> {
904
904
  description: string;
905
905
  /** Zod schema describing the input. Must be `z.object(...)` at the root for the LLM tool contract. */
906
906
  inputSchema: T;
907
- /** Handler invoked with the parsed input. Type is inferred via `z.infer<T>`. */
908
- handler: (input: z.infer<T>) => string | Promise<string>;
907
+ /**
908
+ * Handler invoked with the parsed input. Type is inferred via `z.infer<T>`.
909
+ * #65 — an optional 2nd `ToolContext` argument carries the run's `AbortSignal`,
910
+ * so a cooperative handler can stop early when the run is cancelled. Existing
911
+ * single-argument handlers are unaffected.
912
+ */
913
+ handler: (input: z.infer<T>, ctx?: {
914
+ signal?: AbortSignal;
915
+ }) => string | Promise<string>;
909
916
  /**
910
917
  * Sanitize the raw model-emitted args BEFORE schema validation (`@theokit/sdk/sanitize`).
911
918
  * `true` trims whitespace; an object opts into coercion / JSON-repair. Coercion is schema-aware
@@ -940,7 +947,10 @@ declare function defineTool<T extends ZodType>(spec: DefineToolSpec<T>): CustomT
940
947
  */
941
948
  type EventHandler<T> = (payload: T) => void;
942
949
  declare class EventBus<Events extends Record<string, unknown>> {
950
+ #private;
943
951
  private handlers;
952
+ /** M3 #64 — number of handler invocations that threw (and were logged). */
953
+ get handlerErrorCount(): number;
944
954
  /**
945
955
  * Subscribe to an event. Returns an unsubscribe function.
946
956
  */
@@ -983,9 +993,15 @@ declare class FileSystemConversationStorage implements ConversationStorageAdapte
983
993
  constructor(opts?: FileSystemConversationStorageOptions);
984
994
  /** Exposed for tests + diagnostics. The path is sanitized at use sites. */
985
995
  get root(): string;
986
- getMessages(conversationId: string): Promise<readonly StoredMessage[]>;
996
+ getMessages(conversationId: string, opts?: {
997
+ offset?: number;
998
+ limit?: number;
999
+ }): Promise<readonly StoredMessage[]>;
987
1000
  appendMessage(conversationId: string, message: StoredMessage): Promise<void>;
1001
+ appendMessages(conversationId: string, messages: readonly StoredMessage[]): Promise<void>;
1002
+ truncateConversation(conversationId: string, keepCount: number): Promise<number>;
988
1003
  deleteConversation(conversationId: string): Promise<void>;
1004
+ deleteScope(prefix: string): Promise<number>;
989
1005
  listConversationIds(opts?: {
990
1006
  limit?: number;
991
1007
  }): Promise<readonly string[]>;
@@ -1009,9 +1025,15 @@ declare class FileSystemConversationStorage implements ConversationStorageAdapte
1009
1025
 
1010
1026
  declare class InMemoryConversationStorage implements ConversationStorageAdapter {
1011
1027
  #private;
1012
- getMessages(conversationId: string): Promise<readonly StoredMessage[]>;
1028
+ getMessages(conversationId: string, opts?: {
1029
+ offset?: number;
1030
+ limit?: number;
1031
+ }): Promise<readonly StoredMessage[]>;
1013
1032
  appendMessage(conversationId: string, message: StoredMessage): Promise<void>;
1033
+ appendMessages(conversationId: string, messages: readonly StoredMessage[]): Promise<void>;
1034
+ truncateConversation(conversationId: string, keepCount: number): Promise<number>;
1014
1035
  deleteConversation(conversationId: string): Promise<void>;
1036
+ deleteScope(prefix: string): Promise<number>;
1015
1037
  listConversationIds(opts?: {
1016
1038
  limit?: number;
1017
1039
  }): Promise<readonly string[]>;
@@ -1132,10 +1154,15 @@ declare function buildReplayHistory(base: readonly StoredMessage[], events: read
1132
1154
  declare function createNoopMemoryProvider(): MemoryProvider;
1133
1155
 
1134
1156
  /**
1135
- * `JobQueue` — background job queue with status tracking.
1157
+ * `JobQueue` — background job queue with status tracking, cancellation, and an
1158
+ * optional concurrency bound.
1159
+ *
1160
+ * EC-1: all enqueued functions are wrapped in Promise.resolve().then() so
1161
+ * synchronous throws become rejections.
1136
1162
  *
1137
- * EC-1: all enqueued functions are wrapped in Promise.resolve().then()
1138
- * to ensure synchronous throws become rejections.
1163
+ * #58: each job runs under an `AbortController` whose signal is passed to the
1164
+ * job fn, so `cancel()` actually interrupts a running job (not just a status
1165
+ * flip); an optional `maxConcurrency` bounds how many jobs run at once.
1139
1166
  */
1140
1167
  type JobStatus = "pending" | "running" | "completed" | "failed" | "cancelled";
1141
1168
  interface Job<T> {
@@ -1144,17 +1171,34 @@ interface Job<T> {
1144
1171
  result?: T;
1145
1172
  error?: string;
1146
1173
  }
1147
- declare class JobQueue {
1148
- private jobs;
1174
+ /** #58 construction options. */
1175
+ interface JobQueueOptions {
1149
1176
  /**
1150
- * Enqueue a background function. Returns the job ID immediately.
1151
- * EC-1: wraps fn in Promise.resolve().then() so sync throws are caught.
1177
+ * Max jobs running concurrently. Omit for unbounded (previous behavior).
1178
+ * Values < 1 are clamped to 1 (an invalid bound must not deadlock).
1152
1179
  */
1153
- enqueue<T>(fn: () => Promise<T>): string;
1180
+ maxConcurrency?: number;
1181
+ }
1182
+ declare class JobQueue {
1183
+ #private;
1184
+ private jobs;
1185
+ private controllers;
1186
+ private readonly maxConcurrency;
1187
+ private running;
1188
+ private readonly waiting;
1189
+ constructor(options?: JobQueueOptions);
1190
+ /**
1191
+ * Enqueue a background function. Returns the job ID immediately. The function
1192
+ * receives an `AbortSignal` that fires when the job is cancelled (#58) — a
1193
+ * cooperative job should observe it to stop early. Existing `() => Promise<T>`
1194
+ * callers are unaffected (the signal argument is simply ignored).
1195
+ */
1196
+ enqueue<T>(fn: (signal: AbortSignal) => Promise<T>): string;
1154
1197
  getJob(id: string): Job<unknown> | undefined;
1155
1198
  list(): Job<unknown>[];
1156
1199
  /**
1157
- * Cancel a pending or running job. Returns true if cancelled.
1200
+ * Cancel a pending or running job. Returns true if cancelled. #58 — aborts the
1201
+ * job's `AbortSignal` so a cooperative running job is actually interrupted.
1158
1202
  */
1159
1203
  cancel(id: string): boolean;
1160
1204
  }
@@ -1349,31 +1393,56 @@ declare function migrateSqliteToLance(options: MigrateOptions): Promise<MigrateR
1349
1393
  /**
1350
1394
  * `PermissionEngine` — first-match permission rules for tool invocations.
1351
1395
  *
1352
- * Evaluates a tool name against an ordered list of rules. First matching rule
1353
- * wins; when no rule matches the `defaultAction` is returned (M7-4 — default
1354
- * `"allow"`, opt into default-deny via `{ defaultAction: "deny" }`).
1396
+ * Evaluates a tool name (and optional arguments, #55) against an ordered list
1397
+ * of rules. First matching rule wins; when no rule matches the `defaultAction`
1398
+ * is returned. #55 — the default is now `"ask"` (FAIL-CLOSED): a permission
1399
+ * engine that cannot positively allow must not silently allow. Opt back into
1400
+ * the previous fail-open behavior with `{ defaultAction: "allow" }`.
1355
1401
  */
1356
1402
  type PermissionAction = "allow" | "deny" | "ask";
1403
+ /**
1404
+ * #55 — an argument matcher. A rule with `args` gates on the tool's argument
1405
+ * VALUES, not just its name: an exact string, a RegExp (tested against the
1406
+ * stringified value), or a predicate. Every declared arg must match for the
1407
+ * rule to apply — so `{ tool: "shell", args: { command: /rm\s+-rf/ } }` denies
1408
+ * a destructive shell call while leaving `ls` to fall through.
1409
+ */
1410
+ type ArgMatcher = string | RegExp | ((value: unknown) => boolean);
1357
1411
  interface PermissionRule {
1358
1412
  /** Tool name (exact string) or pattern (RegExp). */
1359
1413
  tool: string | RegExp;
1414
+ /**
1415
+ * #55 — optional per-argument matchers. When present, the rule matches only
1416
+ * if the tool name matches AND every declared arg predicate matches the
1417
+ * corresponding call argument. A missing/undefined arg fails its predicate
1418
+ * (the rule does not match) — never throws.
1419
+ */
1420
+ args?: Record<string, ArgMatcher>;
1360
1421
  /** Action to take when rule matches. */
1361
1422
  action: PermissionAction;
1362
1423
  }
1363
1424
  /** Options for {@link PermissionEngine}. */
1364
1425
  interface PermissionEngineOptions {
1365
- /** Action when no rule matches. Default `"allow"` (backward-compatible). M7-4. */
1426
+ /**
1427
+ * Action when no rule matches. #55 — default is now `"ask"` (fail-closed): a
1428
+ * permission engine that cannot positively allow must not silently allow.
1429
+ * Pass `"allow"` to restore the previous fail-open behavior.
1430
+ */
1366
1431
  readonly defaultAction?: PermissionAction;
1367
1432
  }
1368
1433
  declare class PermissionEngine {
1434
+ #private;
1369
1435
  private readonly rules;
1370
1436
  private readonly defaultAction;
1371
1437
  constructor(rules: PermissionRule[], options?: PermissionEngineOptions);
1372
1438
  /**
1373
- * Evaluate a tool name against the rules. First match wins; falls back to the
1374
- * configured `defaultAction` (default `"allow"`) when no rule matches.
1439
+ * Evaluate a tool name (and optional arguments) against the rules. First
1440
+ * match wins; falls back to the configured `defaultAction` (default `"ask"`,
1441
+ * fail-closed) when no rule matches. #55 — a rule with `args` gates on the
1442
+ * argument values, so the same tool name can resolve to different actions
1443
+ * depending on what it is asked to do.
1375
1444
  */
1376
- evaluate(toolName: string): PermissionAction;
1445
+ evaluate(toolName: string, args?: Record<string, unknown>): PermissionAction;
1377
1446
  }
1378
1447
 
1379
1448
  /**
@@ -1471,6 +1540,32 @@ declare class Security {
1471
1540
  static addPattern(re: RegExp): void;
1472
1541
  }
1473
1542
 
1543
+ /**
1544
+ * M3 #62 — scoped session state.
1545
+ *
1546
+ * A conversation id can be namespaced by SCOPE so a consumer keeps app-durable,
1547
+ * user-durable, and ephemeral (temp) session data separated in the same store:
1548
+ *
1549
+ * - `app:` — durable state shared across users (app-level memory).
1550
+ * - `user:` — durable state for one user.
1551
+ * - `temp:` — ephemeral state; prune it with `adapter.deleteScope("temp")` on
1552
+ * logout / session end so it never accumulates.
1553
+ *
1554
+ * The scope is a prefix on the conversation id (`"<scope>__<id>"`), so it works
1555
+ * with any {@link ConversationStorageAdapter} — no new storage surface required.
1556
+ * The `__` separator is path-safe (unlike `:`, which the FS adapter's identifier
1557
+ * guard rejects). `deleteScope(prefix)` (optional on the adapter) removes every
1558
+ * conversation with that prefix in one call.
1559
+ *
1560
+ * @public
1561
+ */
1562
+ /** M3 #62 — session state scope. */
1563
+ type SessionScope = "app" | "user" | "temp";
1564
+ /** M3 #62 — build a scope-namespaced conversation id (`"<scope>__<id>"`). */
1565
+ declare function scopedConversationId(scope: SessionScope, id: string): string;
1566
+ /** M3 #62 — the id prefix (`"<scope>__"`) used to match a scope's conversations. */
1567
+ declare function sessionScopePrefix(scope: SessionScope): string;
1568
+
1474
1569
  /**
1475
1570
  * Public type contract for `Workflow.create / .run / .resume` (Adoption
1476
1571
  * Roadmap #5; ADRs D230-D248).
@@ -2107,4 +2202,4 @@ declare function toShareGptTrajectory(result: BatchResult, options?: {
2107
2202
  model?: string;
2108
2203
  }): ShareGptTrajectory | null;
2109
2204
 
2110
- 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, 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 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, toShareGptTrajectory, withCwdMutex };
2205
+ 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 };
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-DJuuubJK.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-DJuuubJK.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-DcaoP7aW.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-DcaoP7aW.js';
5
- import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-DXy_MVwz.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 ToolUseBlock, a8 as TurnEndedUpdate, a9 as UserMessage, aa as UserMessageAppendedUpdate } from './run-DXy_MVwz.js';
1
+ import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-qyVYfk9H.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-qyVYfk9H.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-Bbg0mBOv.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-Bbg0mBOv.js';
5
+ import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-pE-34AAo.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-pE-34AAo.js';
7
7
  import * as zod from 'zod';
8
8
  import { ZodType, z } from 'zod';
9
9
 
@@ -904,8 +904,15 @@ interface DefineToolSpec<T extends ZodType> {
904
904
  description: string;
905
905
  /** Zod schema describing the input. Must be `z.object(...)` at the root for the LLM tool contract. */
906
906
  inputSchema: T;
907
- /** Handler invoked with the parsed input. Type is inferred via `z.infer<T>`. */
908
- handler: (input: z.infer<T>) => string | Promise<string>;
907
+ /**
908
+ * Handler invoked with the parsed input. Type is inferred via `z.infer<T>`.
909
+ * #65 — an optional 2nd `ToolContext` argument carries the run's `AbortSignal`,
910
+ * so a cooperative handler can stop early when the run is cancelled. Existing
911
+ * single-argument handlers are unaffected.
912
+ */
913
+ handler: (input: z.infer<T>, ctx?: {
914
+ signal?: AbortSignal;
915
+ }) => string | Promise<string>;
909
916
  /**
910
917
  * Sanitize the raw model-emitted args BEFORE schema validation (`@theokit/sdk/sanitize`).
911
918
  * `true` trims whitespace; an object opts into coercion / JSON-repair. Coercion is schema-aware
@@ -940,7 +947,10 @@ declare function defineTool<T extends ZodType>(spec: DefineToolSpec<T>): CustomT
940
947
  */
941
948
  type EventHandler<T> = (payload: T) => void;
942
949
  declare class EventBus<Events extends Record<string, unknown>> {
950
+ #private;
943
951
  private handlers;
952
+ /** M3 #64 — number of handler invocations that threw (and were logged). */
953
+ get handlerErrorCount(): number;
944
954
  /**
945
955
  * Subscribe to an event. Returns an unsubscribe function.
946
956
  */
@@ -983,9 +993,15 @@ declare class FileSystemConversationStorage implements ConversationStorageAdapte
983
993
  constructor(opts?: FileSystemConversationStorageOptions);
984
994
  /** Exposed for tests + diagnostics. The path is sanitized at use sites. */
985
995
  get root(): string;
986
- getMessages(conversationId: string): Promise<readonly StoredMessage[]>;
996
+ getMessages(conversationId: string, opts?: {
997
+ offset?: number;
998
+ limit?: number;
999
+ }): Promise<readonly StoredMessage[]>;
987
1000
  appendMessage(conversationId: string, message: StoredMessage): Promise<void>;
1001
+ appendMessages(conversationId: string, messages: readonly StoredMessage[]): Promise<void>;
1002
+ truncateConversation(conversationId: string, keepCount: number): Promise<number>;
988
1003
  deleteConversation(conversationId: string): Promise<void>;
1004
+ deleteScope(prefix: string): Promise<number>;
989
1005
  listConversationIds(opts?: {
990
1006
  limit?: number;
991
1007
  }): Promise<readonly string[]>;
@@ -1009,9 +1025,15 @@ declare class FileSystemConversationStorage implements ConversationStorageAdapte
1009
1025
 
1010
1026
  declare class InMemoryConversationStorage implements ConversationStorageAdapter {
1011
1027
  #private;
1012
- getMessages(conversationId: string): Promise<readonly StoredMessage[]>;
1028
+ getMessages(conversationId: string, opts?: {
1029
+ offset?: number;
1030
+ limit?: number;
1031
+ }): Promise<readonly StoredMessage[]>;
1013
1032
  appendMessage(conversationId: string, message: StoredMessage): Promise<void>;
1033
+ appendMessages(conversationId: string, messages: readonly StoredMessage[]): Promise<void>;
1034
+ truncateConversation(conversationId: string, keepCount: number): Promise<number>;
1014
1035
  deleteConversation(conversationId: string): Promise<void>;
1036
+ deleteScope(prefix: string): Promise<number>;
1015
1037
  listConversationIds(opts?: {
1016
1038
  limit?: number;
1017
1039
  }): Promise<readonly string[]>;
@@ -1132,10 +1154,15 @@ declare function buildReplayHistory(base: readonly StoredMessage[], events: read
1132
1154
  declare function createNoopMemoryProvider(): MemoryProvider;
1133
1155
 
1134
1156
  /**
1135
- * `JobQueue` — background job queue with status tracking.
1157
+ * `JobQueue` — background job queue with status tracking, cancellation, and an
1158
+ * optional concurrency bound.
1159
+ *
1160
+ * EC-1: all enqueued functions are wrapped in Promise.resolve().then() so
1161
+ * synchronous throws become rejections.
1136
1162
  *
1137
- * EC-1: all enqueued functions are wrapped in Promise.resolve().then()
1138
- * to ensure synchronous throws become rejections.
1163
+ * #58: each job runs under an `AbortController` whose signal is passed to the
1164
+ * job fn, so `cancel()` actually interrupts a running job (not just a status
1165
+ * flip); an optional `maxConcurrency` bounds how many jobs run at once.
1139
1166
  */
1140
1167
  type JobStatus = "pending" | "running" | "completed" | "failed" | "cancelled";
1141
1168
  interface Job<T> {
@@ -1144,17 +1171,34 @@ interface Job<T> {
1144
1171
  result?: T;
1145
1172
  error?: string;
1146
1173
  }
1147
- declare class JobQueue {
1148
- private jobs;
1174
+ /** #58 construction options. */
1175
+ interface JobQueueOptions {
1149
1176
  /**
1150
- * Enqueue a background function. Returns the job ID immediately.
1151
- * EC-1: wraps fn in Promise.resolve().then() so sync throws are caught.
1177
+ * Max jobs running concurrently. Omit for unbounded (previous behavior).
1178
+ * Values < 1 are clamped to 1 (an invalid bound must not deadlock).
1152
1179
  */
1153
- enqueue<T>(fn: () => Promise<T>): string;
1180
+ maxConcurrency?: number;
1181
+ }
1182
+ declare class JobQueue {
1183
+ #private;
1184
+ private jobs;
1185
+ private controllers;
1186
+ private readonly maxConcurrency;
1187
+ private running;
1188
+ private readonly waiting;
1189
+ constructor(options?: JobQueueOptions);
1190
+ /**
1191
+ * Enqueue a background function. Returns the job ID immediately. The function
1192
+ * receives an `AbortSignal` that fires when the job is cancelled (#58) — a
1193
+ * cooperative job should observe it to stop early. Existing `() => Promise<T>`
1194
+ * callers are unaffected (the signal argument is simply ignored).
1195
+ */
1196
+ enqueue<T>(fn: (signal: AbortSignal) => Promise<T>): string;
1154
1197
  getJob(id: string): Job<unknown> | undefined;
1155
1198
  list(): Job<unknown>[];
1156
1199
  /**
1157
- * Cancel a pending or running job. Returns true if cancelled.
1200
+ * Cancel a pending or running job. Returns true if cancelled. #58 — aborts the
1201
+ * job's `AbortSignal` so a cooperative running job is actually interrupted.
1158
1202
  */
1159
1203
  cancel(id: string): boolean;
1160
1204
  }
@@ -1349,31 +1393,56 @@ declare function migrateSqliteToLance(options: MigrateOptions): Promise<MigrateR
1349
1393
  /**
1350
1394
  * `PermissionEngine` — first-match permission rules for tool invocations.
1351
1395
  *
1352
- * Evaluates a tool name against an ordered list of rules. First matching rule
1353
- * wins; when no rule matches the `defaultAction` is returned (M7-4 — default
1354
- * `"allow"`, opt into default-deny via `{ defaultAction: "deny" }`).
1396
+ * Evaluates a tool name (and optional arguments, #55) against an ordered list
1397
+ * of rules. First matching rule wins; when no rule matches the `defaultAction`
1398
+ * is returned. #55 — the default is now `"ask"` (FAIL-CLOSED): a permission
1399
+ * engine that cannot positively allow must not silently allow. Opt back into
1400
+ * the previous fail-open behavior with `{ defaultAction: "allow" }`.
1355
1401
  */
1356
1402
  type PermissionAction = "allow" | "deny" | "ask";
1403
+ /**
1404
+ * #55 — an argument matcher. A rule with `args` gates on the tool's argument
1405
+ * VALUES, not just its name: an exact string, a RegExp (tested against the
1406
+ * stringified value), or a predicate. Every declared arg must match for the
1407
+ * rule to apply — so `{ tool: "shell", args: { command: /rm\s+-rf/ } }` denies
1408
+ * a destructive shell call while leaving `ls` to fall through.
1409
+ */
1410
+ type ArgMatcher = string | RegExp | ((value: unknown) => boolean);
1357
1411
  interface PermissionRule {
1358
1412
  /** Tool name (exact string) or pattern (RegExp). */
1359
1413
  tool: string | RegExp;
1414
+ /**
1415
+ * #55 — optional per-argument matchers. When present, the rule matches only
1416
+ * if the tool name matches AND every declared arg predicate matches the
1417
+ * corresponding call argument. A missing/undefined arg fails its predicate
1418
+ * (the rule does not match) — never throws.
1419
+ */
1420
+ args?: Record<string, ArgMatcher>;
1360
1421
  /** Action to take when rule matches. */
1361
1422
  action: PermissionAction;
1362
1423
  }
1363
1424
  /** Options for {@link PermissionEngine}. */
1364
1425
  interface PermissionEngineOptions {
1365
- /** Action when no rule matches. Default `"allow"` (backward-compatible). M7-4. */
1426
+ /**
1427
+ * Action when no rule matches. #55 — default is now `"ask"` (fail-closed): a
1428
+ * permission engine that cannot positively allow must not silently allow.
1429
+ * Pass `"allow"` to restore the previous fail-open behavior.
1430
+ */
1366
1431
  readonly defaultAction?: PermissionAction;
1367
1432
  }
1368
1433
  declare class PermissionEngine {
1434
+ #private;
1369
1435
  private readonly rules;
1370
1436
  private readonly defaultAction;
1371
1437
  constructor(rules: PermissionRule[], options?: PermissionEngineOptions);
1372
1438
  /**
1373
- * Evaluate a tool name against the rules. First match wins; falls back to the
1374
- * configured `defaultAction` (default `"allow"`) when no rule matches.
1439
+ * Evaluate a tool name (and optional arguments) against the rules. First
1440
+ * match wins; falls back to the configured `defaultAction` (default `"ask"`,
1441
+ * fail-closed) when no rule matches. #55 — a rule with `args` gates on the
1442
+ * argument values, so the same tool name can resolve to different actions
1443
+ * depending on what it is asked to do.
1375
1444
  */
1376
- evaluate(toolName: string): PermissionAction;
1445
+ evaluate(toolName: string, args?: Record<string, unknown>): PermissionAction;
1377
1446
  }
1378
1447
 
1379
1448
  /**
@@ -1471,6 +1540,32 @@ declare class Security {
1471
1540
  static addPattern(re: RegExp): void;
1472
1541
  }
1473
1542
 
1543
+ /**
1544
+ * M3 #62 — scoped session state.
1545
+ *
1546
+ * A conversation id can be namespaced by SCOPE so a consumer keeps app-durable,
1547
+ * user-durable, and ephemeral (temp) session data separated in the same store:
1548
+ *
1549
+ * - `app:` — durable state shared across users (app-level memory).
1550
+ * - `user:` — durable state for one user.
1551
+ * - `temp:` — ephemeral state; prune it with `adapter.deleteScope("temp")` on
1552
+ * logout / session end so it never accumulates.
1553
+ *
1554
+ * The scope is a prefix on the conversation id (`"<scope>__<id>"`), so it works
1555
+ * with any {@link ConversationStorageAdapter} — no new storage surface required.
1556
+ * The `__` separator is path-safe (unlike `:`, which the FS adapter's identifier
1557
+ * guard rejects). `deleteScope(prefix)` (optional on the adapter) removes every
1558
+ * conversation with that prefix in one call.
1559
+ *
1560
+ * @public
1561
+ */
1562
+ /** M3 #62 — session state scope. */
1563
+ type SessionScope = "app" | "user" | "temp";
1564
+ /** M3 #62 — build a scope-namespaced conversation id (`"<scope>__<id>"`). */
1565
+ declare function scopedConversationId(scope: SessionScope, id: string): string;
1566
+ /** M3 #62 — the id prefix (`"<scope>__"`) used to match a scope's conversations. */
1567
+ declare function sessionScopePrefix(scope: SessionScope): string;
1568
+
1474
1569
  /**
1475
1570
  * Public type contract for `Workflow.create / .run / .resume` (Adoption
1476
1571
  * Roadmap #5; ADRs D230-D248).
@@ -2107,4 +2202,4 @@ declare function toShareGptTrajectory(result: BatchResult, options?: {
2107
2202
  model?: string;
2108
2203
  }): ShareGptTrajectory | null;
2109
2204
 
2110
- 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, 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 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, toShareGptTrajectory, withCwdMutex };
2205
+ 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 };