@theokit/sdk 4.19.1 → 4.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2309 @@
1
+ import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot, E as ErrorMetadata } from './errors-gE8612p9.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, 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-gE8612p9.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 Plugin$1, m as ProviderProfile, I as InlineSkill, n as GoalOptions, o as GoalEvent, p as GoalResult, B as BudgetTracker, q as MemoryProvider, r as MemoryId, s as PreToolCallDecision, t as StepResult, u as SDKProvider } from './cron-M2Xz7lq2.cjs';
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, J as ContextManagerKind, K as ContextSnapshot, N as ContextSource, O as ContextSourceStatus, Q as CreateSkillSpec, R as Cron, T as CronCreateOptions, U as CronGetOptions, V as CronJob, W as CronJobStatus, X as CronListOptions, Y as CronOperationOptions, Z as CronRunOptions, _ as CronRuntime, $ as CronSchedulerStatus, a0 as CronStartOptions, a1 as HookName, a2 as InvalidateCacheOptions, a3 as MemoryAdapter, a4 as MemoryAdapterCapabilities, a5 as MemoryContext, a6 as MemoryFact, a7 as MemoryProviderHandle, a8 as MemoryProviderInitOptions, a9 as MemoryRevision, aa as MemoryToolSchema, ab as MemoryTurnMessage, ac as PersonalityPreset, ad as PluginContext, ae as PostAssistantReplyContext, af as PreToolCallContext, ag as PreUserSendContext, ah as PreUserSendResult, ai as ProviderCapability, aj as ProviderRoute, ak as ProviderTransform, al as ProviderTransformContext, am as RecordSessionSummaryArgs, an as ResolvedProviderRoute, ao as RunUntilIterator, ap as SDKAgentPlugins, aq as SDKAgentSkillDetail, ar as SDKAgentSkills, as as SDKArtifact, at as SDKContextManager, au as SDKPluginMetadata, av as SDKProvidersManager, aw as SessionRecord, ax as SessionStore, ay as SettingSource, az as Skill, aA as SkillsResolver, aB as SkillsResolverContext, aC as SystemPromptContext, aD as SystemPromptMemoryFact, aE as SystemPromptSkillRef, aF as TelemetrySettings } from './cron-M2Xz7lq2.cjs';
5
+ import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, P as Processor, T as ToolResultContentBlock, c as PermissionMode, d as PermissionEngine, e as RunEventSink, S as SDKMessage } from './run-DFM1H2jW.cjs';
6
+ export { A as AgentConversationTurn, f as AssistantMessage, g as CompletionCheck, h as CompletionCheckResult, i as ConversationStep, j as ConversationTurn, k as CostBreakdown, l as CostSource, m as CostStatus, D as DoomLoopThresholds, G as GenerateOptions, n as GenerateRunResult, I as ImageBlock, o as InputProcessorContext, p as InteractionUpdate, q as McpAuthConfig, r as McpHttpServerConfig, s as McpOAuthConfig, t as McpStdioServerConfig, u as MessageOrigin, v as ModelParameterValue, O as OutputProcessorContext, w as PartialToolCallUpdate, x as PermissionAction, y as PermissionEngineOptions, z as PermissionRule, B as ProcessorControls, E as ProcessorTripwire, F as ProcessorViolation, H as RunCompactBoundaryEvent, J as RunCompletionCheckEvent, K as RunErrorDetail, L as RunEvent, N as RunGitInfo, Q as RunOperation, U as RunPermissionDeniedEvent, V as RunRateLimitEvent, W as RunStatus, X as RunTaskCompletedEvent, Y as RunTaskStartedEvent, Z as RunTaskUpdatedEvent, _ as RunToCompletionOptions, $ as RunToCompletionResult, a0 as RunToolProgressEvent, a1 as RunTripwireEvent, a2 as SDKAssistantMessage, a3 as SDKImage, a4 as SDKImageDimension, a5 as SDKObjectDelta, a6 as SDKRequestMessage, a7 as SDKStatusMessage, a8 as SDKSystemMessage, a9 as SDKTaskMessage, aa as SDKThinkingMessage, ab as SDKToolUseMessage, ac as SDKUserMessage, ad as SDKUserMessageEvent, ae as SendOptions, af as ShellCommand, ag as ShellConversationTurn, ah as ShellOutput, ai as ShellOutputDeltaUpdate, aj as StepCompletedUpdate, ak as StepStartedUpdate, al as StreamToCompletionResult, am as SummaryCompletedUpdate, an as SummaryStartedUpdate, ao as SummaryUpdate, ap as TextBlock, aq as TextDeltaUpdate, ar as ThinkingCompletedUpdate, as as ThinkingDeltaUpdate, at as ThinkingMessage, au as TokenDeltaUpdate, av as TokenUsage, aw as ToolCall, ax as ToolCallCompletedUpdate, ay as ToolCallStartedUpdate, az as ToolContextMessage, aA as ToolResult, aB as ToolResultGuardOptions, aC as ToolUseBlock, aD as TurnEndedUpdate, aE as UserMessage, aF as UserMessageAppendedUpdate, aG as applyMode, aH as emitRunEvent } from './run-DFM1H2jW.cjs';
7
+ import * as zod from 'zod';
8
+ import { ZodType, z } from 'zod';
9
+
10
+ /**
11
+ * Public compaction / context-management helpers (M2-1, extended V3-3).
12
+ *
13
+ * Promotes the SDK's compaction capability to a public surface so consumers can
14
+ * compact a transcript, mark/filter conversation checkpoints, and detect
15
+ * context-overflow — without reaching into `internal/`.
16
+ *
17
+ * Two recent-window modes (V3-3):
18
+ * - `keepRecent` (turn-count, default) — keeps the last N turns verbatim and
19
+ * always preserves leading system PROMPTS; reuses the internal
20
+ * `selectCompressionWindow` (no second algorithm).
21
+ * - `keepTokens` (token-budget) — keeps the trailing turns whose accumulated
22
+ * `estimateTokens` fits the budget (theocode `splitTranscript` semantics). In
23
+ * this mode leading system prompts are NOT special-cased (D6).
24
+ *
25
+ * Summarization is delegated to a caller-supplied callback (which receives the
26
+ * older window + the summary template). With `failSafe`, a thrown summarizer
27
+ * returns the ORIGINAL transcript + a structured warn (compaction is an
28
+ * optimization, never a cause of data loss); without it, the error propagates.
29
+ *
30
+ * Public from the `@theokit/sdk/compaction` sub-path.
31
+ */
32
+ /**
33
+ * Minimal message shape for compaction/compression input. THE canonical public origin (leaf type —
34
+ * rollup-plugin-dts cannot re-export types from internal modules into entry bundles; M42 lesson).
35
+ *
36
+ * @public
37
+ */
38
+ interface CompressibleMessage {
39
+ role: "user" | "assistant" | "system";
40
+ content: string;
41
+ }
42
+
43
+ /**
44
+ * M50 (agent-builder) — session-transcript compaction, Codex-faithful.
45
+ *
46
+ * Mirrors the vendored Codex mechanism (`codex-rs/core/src/compact.rs`):
47
+ * - the replacement history = recent USER messages verbatim (newest→oldest under a token budget;
48
+ * prior summaries filtered by marker) + ONE summary message with a textual marker prefix,
49
+ * injected as `role:"user"` (`build_compacted_history`, compact.rs:589-663);
50
+ * - persistence is APPEND-ONLY: a `compact_boundary` record becomes the new DAG root and the
51
+ * replacement messages are chained onto it — resume replays boundary→replacement→suffix
52
+ * (equivalent of `CompactedItem.replacement_history`, rollout is never truncated);
53
+ * - a failing summarizer leaves the transcript UNTOUCHED (typed error; no partial state).
54
+ *
55
+ * The summarizer is dependency-injected: tests pass a deterministic fake; the public
56
+ * `Agent.compact` wires the ADR-D440 compression summarizer (its first real caller).
57
+ */
58
+
59
+ interface CompactResult {
60
+ preTokens: number;
61
+ postTokens: number;
62
+ }
63
+
64
+ /**
65
+ * Public types for `Agent.batch` (ADRs D134-D140).
66
+ *
67
+ * Run N prompts in parallel with bounded concurrency. Each prompt gets
68
+ * a fresh agent (create → send → wait → dispose). Failures isolated
69
+ * per-prompt; the batch never aborts on a single failure.
70
+ *
71
+ * @public
72
+ */
73
+
74
+ /**
75
+ * Single prompt in a batch. Plain string is shorthand for `{ prompt }`.
76
+ *
77
+ * @public
78
+ */
79
+ interface BatchItem {
80
+ /** Prompt text sent to the agent. */
81
+ prompt: string;
82
+ /** Per-prompt system prompt override (wins over `BatchOptions.systemPrompt`). */
83
+ systemPrompt?: string;
84
+ /**
85
+ * Caller-supplied metadata, round-tripped to `BatchResult.metadata`.
86
+ * Passed by reference — do NOT mutate while the batch is in-flight (EC-I).
87
+ */
88
+ metadata?: Record<string, unknown>;
89
+ }
90
+ /**
91
+ * Options accepted by `Agent.batch`. Extends `AgentOptions` — every
92
+ * prompt gets an agent created with these options (ADR D138 isolation),
93
+ * plus the batch-specific knobs below.
94
+ *
95
+ * @public
96
+ */
97
+ interface BatchOptions extends AgentOptions {
98
+ /**
99
+ * Maximum parallel agents. Default 4 (ADR D136). Must be a positive
100
+ * integer. Capped to `prompts.length` to avoid spinning idle workers.
101
+ */
102
+ concurrency?: number;
103
+ /** Optional filter applied post-collection. Return `false` to discard. */
104
+ filter?: (result: BatchResult) => boolean;
105
+ /**
106
+ * Streaming callback fired once per completed prompt (success OR failure).
107
+ * Caller exceptions are caught + logged to stderr without poisoning
108
+ * the batch (EC-5).
109
+ */
110
+ onResult?: (result: BatchResult) => void | Promise<void>;
111
+ /** Progress callback fired after each result. */
112
+ onProgress?: (progress: BatchProgress) => void;
113
+ /**
114
+ * Cancel pending prompts (ADR D140). In-flight prompts continue to
115
+ * completion (Node `AbortSignal` semantics). When `signal.reason` is
116
+ * an Error, it propagates to `BatchResult.error`; otherwise a generic
117
+ * "aborted" error is used.
118
+ */
119
+ signal?: AbortSignal;
120
+ /**
121
+ * Opt-in Task wrapping (ADRs D363, D374). When set, the batch is
122
+ * registered as a `Task` (kind="batch") in the SDK's observable
123
+ * registry. The parent task transitions `finished` when every
124
+ * prompt is resolved (success OR failure).
125
+ *
126
+ * Use cases: surfacing a long-running batch in the `theokit tasks
127
+ * list` CLI, programmatic `Task.cancel(id)` aborting the batch, or
128
+ * binding a user-facing job dashboard. v1 does NOT yet emit one
129
+ * task PER prompt (single parent only); per-prompt tasks land in
130
+ * v0.2.
131
+ *
132
+ * Auto-generated id uses the `b-` reserved prefix (D368, EC-5).
133
+ *
134
+ * @public
135
+ */
136
+ task?: true | {
137
+ id?: string;
138
+ meta?: Record<string, unknown>;
139
+ };
140
+ }
141
+ /**
142
+ * Per-prompt outcome. Discriminated union — check `ok` before reading
143
+ * `result` or `error`.
144
+ *
145
+ * @public
146
+ */
147
+ type BatchResult = {
148
+ ok: true;
149
+ index: number;
150
+ prompt: string;
151
+ result: RunResult;
152
+ metadata?: Record<string, unknown>;
153
+ durationMs: number;
154
+ } | {
155
+ ok: false;
156
+ index: number;
157
+ prompt: string;
158
+ error: TheokitAgentError;
159
+ metadata?: Record<string, unknown>;
160
+ durationMs: number;
161
+ };
162
+ /**
163
+ * Live progress snapshot delivered to `onProgress`.
164
+ *
165
+ * @public
166
+ */
167
+ interface BatchProgress {
168
+ total: number;
169
+ completed: number;
170
+ failed: number;
171
+ pending: number;
172
+ inFlight: number;
173
+ }
174
+
175
+ /**
176
+ * Options accepted by {@link Agent.streamObject}. Same shape as
177
+ * `Agent.generateObject` with the addition that the result is an
178
+ * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.
179
+ *
180
+ * @public
181
+ */
182
+ interface StreamObjectOptions<T extends ZodType> {
183
+ schema: T;
184
+ prompt: string;
185
+ systemPrompt?: string;
186
+ /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */
187
+ model: string | ModelSelection;
188
+ apiKey?: string;
189
+ local: LocalOptions;
190
+ maxRetries?: number;
191
+ /**
192
+ * Optional provider routing forwarded to the transient agent. Required when
193
+ * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is
194
+ * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers
195
+ * provider from the prefix and may fail with `provider_unresolved` even
196
+ * when the right env key is set under a different provider name.
197
+ */
198
+ providers?: ProviderRoutingSettings;
199
+ }
200
+ /**
201
+ * Recursive partial — `T` where every nested field becomes optional.
202
+ *
203
+ * @public
204
+ */
205
+ type DeepPartial<T> = T extends (infer U)[] ? Array<DeepPartial<U>> : T extends object ? {
206
+ [K in keyof T]?: DeepPartial<T[K]>;
207
+ } : T;
208
+ /**
209
+ * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.
210
+ *
211
+ * - `partial` events fire zero or more times with monotonically increasing
212
+ * `attempt`, carrying best-effort schema-parsed snapshots of the model's
213
+ * accumulating output.
214
+ * - `complete` fires exactly once at the end, carrying the fully Zod-parsed
215
+ * object alongside usage and finishReason — semantically identical to a
216
+ * successful `Agent.generateObject()` return.
217
+ *
218
+ * @public
219
+ */
220
+ type StreamObjectEvent<T> = {
221
+ type: "partial";
222
+ partial: DeepPartial<T>;
223
+ attempt: number;
224
+ } | {
225
+ type: "complete";
226
+ object: T;
227
+ raw: unknown;
228
+ usage: {
229
+ inputTokens: number;
230
+ outputTokens: number;
231
+ };
232
+ finishReason: "tool_use" | "error";
233
+ };
234
+ /**
235
+ * Error thrown by {@link Agent.streamObject} when the model refuses to call
236
+ * the synthetic `output` tool or when all retries fail to produce a
237
+ * schema-valid object. Same code taxonomy as `GenerateObjectError`.
238
+ *
239
+ * @public
240
+ */
241
+ declare class StreamObjectError extends Error {
242
+ readonly name = "StreamObjectError";
243
+ readonly code: "no_tool_call" | "parse_failed";
244
+ readonly cause?: unknown;
245
+ constructor(code: "no_tool_call" | "parse_failed", message: string, cause?: unknown);
246
+ }
247
+
248
+ /**
249
+ * Options accepted by {@link Agent.generateObject}. Returns a typed object
250
+ * matching the supplied Zod schema. See ADR D33.
251
+ *
252
+ * @public
253
+ */
254
+ interface GenerateObjectOptions<T extends ZodType> {
255
+ /** Zod schema describing the expected object shape. */
256
+ schema: T;
257
+ /** User prompt — the model is asked to fill the schema given this prompt. */
258
+ prompt: string;
259
+ /** Optional system prompt steering the model. */
260
+ systemPrompt?: string;
261
+ /** Model selection. Required (transient agents need a model). SE8 — accepts a
262
+ * bare-string id shorthand (`"openai/gpt-4o-mini"`) or a {@link ModelSelection}. */
263
+ model: string | ModelSelection;
264
+ /**
265
+ * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a
266
+ * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the
267
+ * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large
268
+ * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.
269
+ */
270
+ structuringModel?: string | ModelSelection;
271
+ /** API key. Falls back to env (THEOKIT_API_KEY etc). */
272
+ apiKey?: string;
273
+ /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */
274
+ local: LocalOptions;
275
+ /**
276
+ * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).
277
+ * The transient agent is REUSED across retries so the registry sees a
278
+ * single entry (EC-3).
279
+ */
280
+ maxRetries?: number;
281
+ /**
282
+ * Optional provider routing forwarded to the transient agent. Required when
283
+ * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is
284
+ * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers
285
+ * provider from the prefix and may fail with `provider_unresolved` even
286
+ * when the right env key is set under a different provider name.
287
+ */
288
+ providers?: ProviderRoutingSettings;
289
+ /**
290
+ * What to do when the model's output fails schema validation after all
291
+ * retries are exhausted (M14):
292
+ * - `'throw'` (default) — throw {@link GenerateObjectError} `parse_failed`.
293
+ * - `'return-raw'` — resolve with the raw, UNVALIDATED input the model sent
294
+ * (`object` may not match the schema; inspect `raw` too).
295
+ * - `'return-partial'` — for object schemas, resolve with only the fields that
296
+ * individually validate (best-effort salvage); non-object schemas fall back
297
+ * to raw.
298
+ */
299
+ errorStrategy?: "throw" | "return-partial" | "return-raw";
300
+ }
301
+ /**
302
+ * Successful return from {@link Agent.generateObject}.
303
+ *
304
+ * @public
305
+ */
306
+ interface GenerateObjectResult<T> {
307
+ /** Typed object parsed via the Zod schema. */
308
+ object: T;
309
+ /** Raw input the model passed to the synthetic tool, before Zod parse. */
310
+ raw: unknown;
311
+ /** Token usage of the LLM call(s) that produced the result. */
312
+ usage: {
313
+ inputTokens: number;
314
+ outputTokens: number;
315
+ };
316
+ /** Stop reason of the underlying agent run. */
317
+ finishReason: "tool_use" | "error";
318
+ }
319
+ /**
320
+ * Typed error thrown by {@link Agent.generateObject} when the model refuses
321
+ * to call the synthetic `output` tool or when retries are exhausted.
322
+ *
323
+ * @public
324
+ */
325
+ declare class GenerateObjectError extends Error {
326
+ readonly name = "GenerateObjectError";
327
+ readonly code: "no_tool_call" | "parse_failed";
328
+ readonly cause?: unknown;
329
+ constructor(code: "no_tool_call" | "parse_failed", message: string, cause?: unknown);
330
+ }
331
+
332
+ /**
333
+ * Fluent builder for {@link AgentOptions}. Chainable setters mutate internal
334
+ * state and return `this`. Three terminals:
335
+ *
336
+ * - `.build()` — synchronous snapshot (shallow clone) of accumulated options.
337
+ * - `.create()` — calls the injected `create` (Agent.create).
338
+ * - `.getOrCreate(agentId)` — calls the injected `getOrCreate` (Agent.getOrCreate).
339
+ *
340
+ * Validation runs inside the terminals via `validateAgentOptions`. See ADR D25.
341
+ *
342
+ * @public
343
+ */
344
+ declare class AgentBuilder {
345
+ private opts;
346
+ private readonly deps;
347
+ constructor(deps?: AgentBuilderDeps);
348
+ /** SE8 — accepts a bare-string id shorthand (`"openai/gpt-4o-mini"`) or a {@link ModelSelection}. */
349
+ model(m: string | ModelSelection): this;
350
+ apiKey(k: string): this;
351
+ name(n: string): this;
352
+ systemPrompt(p: string | SystemPromptResolver): this;
353
+ local(l: LocalOptions): this;
354
+ cloud(c: CloudOptions): this;
355
+ memory(m: MemorySettings): this;
356
+ tools(t: CustomTool[]): this;
357
+ mcpServers(s: Record<string, McpServerConfig>): this;
358
+ agents(a: Record<string, AgentDefinition>): this;
359
+ context(c: ContextSettings): this;
360
+ providers(p: ProviderRoutingSettings): this;
361
+ plugins(p: PluginsSettings): this;
362
+ skills(s: SkillsSettings): this;
363
+ agentId(id: string): this;
364
+ /**
365
+ * Synchronous snapshot of the accumulated options. Returns a SHALLOW CLONE
366
+ * so external mutation of the result doesn't pollute the builder state (EC-2).
367
+ */
368
+ build(): AgentOptions;
369
+ /**
370
+ * Validate + create a fresh agent. Delegates to `Agent.create` via the
371
+ * injected `deps.create`. Throws if the builder was instantiated without
372
+ * deps (i.e., direct `new AgentBuilder()` instead of `Agent.builder()`).
373
+ */
374
+ create(): Promise<SDKAgent>;
375
+ /**
376
+ * Resume an existing agent or create one if the ID is unknown. Delegates to
377
+ * `Agent.getOrCreate` via the injected `deps.getOrCreate` (ADR D22).
378
+ */
379
+ getOrCreate(agentId: string): Promise<SDKAgent>;
380
+ }
381
+
382
+ /**
383
+ * Live-agent cache for production deploys (Production-Readiness #2, ADRs D307-D310).
384
+ *
385
+ * Caches `SDKAgent` instances by id with LRU eviction (when `size > maxAgents`)
386
+ * and an idle-timeout sweep (configurable interval, default 60s). Solves the
387
+ * "OOM at some point" failure mode of long-running Node servers that keep
388
+ * spawning fresh agents per conversation.
389
+ *
390
+ * **Distinct from `agent-registry.ts`** (the metadata registry that persists
391
+ * `RegisteredAgent` to `registry.json` per cwd). That module is the "address
392
+ * book"; this module is the "live cache". Conflating them violates SRP — see
393
+ * ADR D307.
394
+ *
395
+ * Defaults (ADR D308): `maxAgents: 100`, `idleTimeoutMs: 30 min`, sweep `60s`.
396
+ * Calibrated for indie/small-team Node deploys; high-traffic SaaS should
397
+ * `configure({ maxAgents: 1000 })`.
398
+ *
399
+ * @public (singleton exposed via `Agent.registry`)
400
+ */
401
+
402
+ type EvictReason = "lru" | "idle" | "explicit";
403
+ interface AgentRegistryOptions {
404
+ /**
405
+ * Maximum number of agents kept alive simultaneously. LRU eviction when
406
+ * exceeded. Default: 100.
407
+ *
408
+ * Setting `0` disables the cache entirely — every `Agent.getOrCreate`
409
+ * re-initializes (high cost, but predictable memory).
410
+ */
411
+ maxAgents?: number;
412
+ /**
413
+ * Idle timeout in milliseconds. Agents not used for this duration are
414
+ * evicted on the next sweep tick. Default: 1_800_000 (30 minutes).
415
+ * Set `0` to disable idle eviction.
416
+ */
417
+ idleTimeoutMs?: number;
418
+ /**
419
+ * Sweep interval in milliseconds. Default: 60_000 (60s).
420
+ * Lower = more responsive eviction but more CPU. Higher = staler entries.
421
+ */
422
+ sweepIntervalMs?: number;
423
+ /**
424
+ * Called whenever an agent is evicted. Listener errors are swallowed
425
+ * with a one-shot stderr warn (do not crash the eviction loop).
426
+ */
427
+ onEvict?: (id: string, reason: EvictReason) => void;
428
+ }
429
+ declare class LiveAgentRegistry {
430
+ #private;
431
+ /**
432
+ * Reconfigure registry behavior. Process-wide singleton (D310) — last
433
+ * configure call wins for all subsequent operations.
434
+ */
435
+ configure(opts: AgentRegistryOptions): void;
436
+ /**
437
+ * Lookup a cached agent. `get` is a use — refreshes `lastUsedAt` so the
438
+ * entry survives LRU eviction.
439
+ */
440
+ get(id: string): SDKAgent | undefined;
441
+ /**
442
+ * Insert or overwrite an agent in the cache. Triggers fire-and-forget LRU
443
+ * eviction when `size > maxAgents`.
444
+ *
445
+ * EC-4: when `id` already maps to a DIFFERENT agent instance, dispose the
446
+ * old one before overwriting (race protection against two `getOrCreate`
447
+ * calls creating two agents but only the second being cached — the first
448
+ * would leak file handles + lifecycle controllers).
449
+ */
450
+ set(id: string, agent: SDKAgent): void;
451
+ /**
452
+ * Explicitly evict an agent by id. Returns `true` when the entry was
453
+ * present (false = already gone). Calls `agent.dispose()` + `onEvict`
454
+ * with reason `"explicit"`.
455
+ */
456
+ evict(id: string): Promise<boolean>;
457
+ /**
458
+ * Evict every cached agent. Used by graceful shutdown (`process.on('SIGTERM')`)
459
+ * or end-of-test cleanup.
460
+ */
461
+ evictAll(): Promise<void>;
462
+ /** Number of currently cached agents. */
463
+ size(): number;
464
+ /** Ids of cached agents, newest first (by lastUsedAt). */
465
+ ids(): readonly string[];
466
+ }
467
+
468
+ /**
469
+ * Result of a one-shot {@link Agent.prompt} call.
470
+ *
471
+ * @public
472
+ */
473
+ type AgentPromptResult = RunResult;
474
+ /**
475
+ * Static façade for creating and managing Theo agents.
476
+ *
477
+ * @public
478
+ */
479
+ declare class Agent {
480
+ private constructor();
481
+ /**
482
+ * Live-agent cache for production deploys (Production-Readiness #2, ADRs D307-D310).
483
+ *
484
+ * Caches `SDKAgent` instances by id with LRU eviction (when `size > maxAgents`)
485
+ * and an idle-timeout sweep. Solves the OOM failure mode for long-running
486
+ * Node servers spawning fresh agents per conversation.
487
+ *
488
+ * Defaults: `maxAgents: 100`, `idleTimeoutMs: 30 min`, sweep `60s`.
489
+ * Configure for high-traffic SaaS:
490
+ *
491
+ * ```ts
492
+ * Agent.registry.configure({ maxAgents: 1000, idleTimeoutMs: 15 * 60_000 });
493
+ * process.on("SIGTERM", () => Agent.registry.evictAll());
494
+ * ```
495
+ *
496
+ * Cache hits are automatic in `Agent.getOrCreate` (T2.6). Disable the cache
497
+ * entirely via `configure({ maxAgents: 0 })` — every getOrCreate then
498
+ * re-initializes.
499
+ *
500
+ * @public
501
+ */
502
+ static readonly registry: LiveAgentRegistry;
503
+ /**
504
+ * Create a new agent. Pass either `local` or `cloud` to pick a runtime.
505
+ *
506
+ * @public
507
+ */
508
+ static create(options: AgentOptions): Promise<SDKAgent>;
509
+ /**
510
+ * One-shot prompt: create an agent, send a single message, wait, dispose.
511
+ *
512
+ * When `options.throwOnError === true`, rejects with `AgentRunError` if
513
+ * the run terminates with `status: 'error'` (instead of resolving with the
514
+ * error wrapped in the RunResult). Cancelled runs still resolve normally.
515
+ *
516
+ * @public
517
+ */
518
+ static prompt(message: string, options: AgentOptions): Promise<AgentPromptResult>;
519
+ /**
520
+ * Reattach to an existing agent by ID.
521
+ *
522
+ * @public
523
+ */
524
+ static resume(agentId: string, options?: Partial<AgentOptions>): Promise<SDKAgent>;
525
+ /**
526
+ * Start building an {@link AgentOptions} via fluent chain. See ADR D25.
527
+ * Terminals: `.build()`, `.create()`, `.getOrCreate(id)`.
528
+ *
529
+ * The builder receives `create` + `getOrCreate` as injected callbacks so
530
+ * that `agent-builder.ts` doesn't need a static import of `Agent` — keeps
531
+ * the module graph acyclic (G6).
532
+ *
533
+ * @public
534
+ */
535
+ static builder(): AgentBuilder;
536
+ /**
537
+ * Generate a typed object matching a Zod schema via a synthetic forced
538
+ * tool call (ADR D33). One-shot: create transient agent → send prompt →
539
+ * model calls `output` tool → parse args via Zod → return typed.
540
+ *
541
+ * @public
542
+ */
543
+ static generateObject<T extends zod.ZodType>(options: GenerateObjectOptions<T>): Promise<GenerateObjectResult<zod.z.infer<T>>>;
544
+ /**
545
+ * Stream a structured output object alongside intermediate `partial`
546
+ * deltas as the model accumulates its response (ADR D39). Returns an
547
+ * `AsyncIterator<StreamObjectEvent<T>>` that yields zero or more
548
+ * `partial` events and exactly one `complete` event at the end.
549
+ *
550
+ * The `complete` event carries the same `object: z.infer<T>` you would get
551
+ * from `Agent.generateObject` — same prompt + schema + model produces
552
+ * the same final object.
553
+ *
554
+ * @public
555
+ */
556
+ static streamObject<T extends zod.ZodType>(options: StreamObjectOptions<T>): AsyncGenerator<StreamObjectEvent<zod.z.infer<T>>, void, void>;
557
+ /**
558
+ * Run N prompts in parallel with bounded concurrency (ADRs D134-D140).
559
+ *
560
+ * Each prompt gets a fresh agent (create → send → wait → dispose). Failures
561
+ * are isolated per-prompt; the batch never throws on a single failure —
562
+ * inspect `result.ok` to discriminate success vs error. Default
563
+ * concurrency is 4. When `options.providers.apiKeys` has ≥2 keys per
564
+ * provider, all in-flight agents share a single credential pool via
565
+ * `AsyncLocalStorage` (EC-A) so rate-limit cooldowns are observed once
566
+ * instead of duplicated per agent.
567
+ *
568
+ * Streaming progress is opt-in via `onResult` / `onProgress`. `AbortSignal`
569
+ * cancels pending prompts; in-flight ones continue to completion (Node
570
+ * AbortSignal semantics). `signal.reason` propagates to `error` when set.
571
+ *
572
+ * @public
573
+ */
574
+ static batch(prompts: ReadonlyArray<string | BatchItem>, options: BatchOptions): Promise<BatchResult[]>;
575
+ /**
576
+ * Get an existing agent by ID, or create one with the supplied options if
577
+ * the ID is not yet registered. Eliminates the resume-vs-create boilerplate
578
+ * common to chat bots and other long-running agent consumers. See ADR D22.
579
+ *
580
+ * Resolution:
581
+ * 1. Try `Agent.resume(agentId, options)`. Return on success.
582
+ * 2. On `UnknownAgentError`, fall through to `Agent.create({ ...options, agentId })`.
583
+ * 3. On same-process race (`ConfigurationError(code: "agent_id_already_exists")`
584
+ * during step 2), retry `Agent.resume` once and return the winner's handle.
585
+ * 4. Any other error propagates verbatim.
586
+ *
587
+ * Caveats:
588
+ * - The function-level `agentId` always wins over `options.agentId`.
589
+ * - Options differ between calls? Last-call-wins for this handle (matches `Agent.resume`).
590
+ * - Disposed agents are NOT auto-deleted from the registry. To force a fresh
591
+ * agent, call `Agent.delete(agentId)` first.
592
+ *
593
+ * @public
594
+ */
595
+ static getOrCreate(agentId: string, options: AgentOptions): Promise<SDKAgent>;
596
+ /**
597
+ * List agents (local or cloud).
598
+ *
599
+ * @public
600
+ */
601
+ static list(options?: ListAgentsOptions): Promise<ListResult<SDKAgentInfo>>;
602
+ /**
603
+ * Get metadata for a single agent.
604
+ *
605
+ * @public
606
+ */
607
+ static get(agentId: string, _options?: GetAgentOptions): Promise<SDKAgentInfo>;
608
+ /**
609
+ * List runs for an agent.
610
+ *
611
+ * @public
612
+ */
613
+ static listRuns(agentId: string, _options?: ListRunsOptions): Promise<ListResult<Run>>;
614
+ /**
615
+ * Get a single run.
616
+ *
617
+ * @public
618
+ */
619
+ static getRun(runId: string, options?: GetRunOptions): Promise<Run>;
620
+ /**
621
+ * Archive a cloud agent.
622
+ *
623
+ * @public
624
+ */
625
+ static archive(agentId: string, _options?: AgentOperationOptions): Promise<void>;
626
+ /**
627
+ * Restore an archived cloud agent.
628
+ *
629
+ * @public
630
+ */
631
+ static unarchive(agentId: string, _options?: AgentOperationOptions): Promise<void>;
632
+ /**
633
+ * Set the human-facing `name` of a registered agent (the label `Agent.list()` returns). The registry
634
+ * already carries a `name` field; this is the missing public mutator for it. Runtime-agnostic (mutates
635
+ * the local per-cwd registry for local agents; the cloud registry for cloud agents).
636
+ *
637
+ * @public
638
+ */
639
+ static rename(agentId: string, name: string, _options?: AgentOperationOptions): Promise<void>;
640
+ /**
641
+ * M50 — compact a LOCAL agent's persisted session transcript (Codex `/compact` parity): the
642
+ * history is summarized (recent user messages preserved verbatim + one marker'd summary) and an
643
+ * append-only `compact_boundary` + replacement chain is written — resume replays only the
644
+ * replacement + later turns. The summarizer defaults to the compression subsystem's aux-LLM
645
+ * (its first real caller); tests/consumers may inject their own.
646
+ *
647
+ * @public
648
+ */
649
+ static compact(agentId: string, options?: {
650
+ trigger?: "manual" | "auto";
651
+ summarize?: (messages: readonly CompressibleMessage[]) => Promise<string>;
652
+ }): Promise<CompactResult>;
653
+ /**
654
+ * M51 — inject a SYNTHETIC user+assistant pair into a LOCAL session's persisted transcript WITHOUT
655
+ * running an LLM turn (the Codex review-exit mechanism: the parent thread "learns" a result — e.g.
656
+ * review findings — so follow-ups work). Appends onto the DAG leaf and invalidates the in-memory
657
+ * cache; serialized on the per-agent write chain.
658
+ *
659
+ * @public
660
+ */
661
+ static injectSessionTurn(agentId: string, turn: {
662
+ userText: string;
663
+ assistantText: string;
664
+ }): Promise<void>;
665
+ /**
666
+ * Permanently delete a cloud agent.
667
+ *
668
+ * @public
669
+ */
670
+ static delete(agentId: string, _options?: AgentOperationOptions): Promise<void>;
671
+ }
672
+
673
+ /**
674
+ * Handle returned by {@link createAgentFactory}. See ADR D23 for merge
675
+ * semantics.
676
+ *
677
+ * @public
678
+ */
679
+ interface AgentFactory {
680
+ /**
681
+ * Create a fresh agent for this session. Equivalent to `Agent.create(merged)`
682
+ * where `merged` is `common` ⊕ `overrides` ⊕ `{ agentId }`.
683
+ */
684
+ forSession(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;
685
+ /**
686
+ * Resume an existing agent for this session, or create one if the ID is
687
+ * unknown. Equivalent to `Agent.getOrCreate(agentId, merged)`.
688
+ */
689
+ getOrCreate(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;
690
+ }
691
+ /** SE36 — `AgentFactory.create` replaces `createAgentFactory` (ADR 0015). Merges with the `AgentFactory` interface. @public */
692
+ declare class AgentFactory {
693
+ private constructor();
694
+ static create(common: Partial<AgentOptions>): AgentFactory;
695
+ }
696
+
697
+ /**
698
+ * computeCost — apply pricing entries to a TokenUsage and produce a
699
+ * CostBreakdown (ADRs D377, D378).
700
+ *
701
+ * Edge cases absorbed:
702
+ * - EC-13: negative pricing → status="unknown" + note.
703
+ * - EC-14: reasoning tokens fall back to outputCostPerMillion when
704
+ * dedicated reasoning rate is undefined.
705
+ * - EC-12: money precision via microcent normalization (× 1e6).
706
+ * - "subscription_included" routes (Codex CLI, future Claude Pro) →
707
+ * return $0 with status="included".
708
+ * - Provider unknown / pricing missing → status="unknown" with
709
+ * undefined amountUsd (NÃO retorna 0 falso).
710
+ *
711
+ * @internal
712
+ */
713
+ interface ComputeArgs {
714
+ readonly usage: TokenUsage;
715
+ readonly provider: string;
716
+ readonly model: string;
717
+ readonly baseUrl?: string;
718
+ }
719
+ /**
720
+ * Returns CostBreakdown with `status="estimated"`, `"unknown"`, or
721
+ * `"included"`. Never throws; never returns 0 when pricing is missing.
722
+ */
723
+ declare function computeCost(args: ComputeArgs): CostBreakdown;
724
+
725
+ /**
726
+ * Budget enforcement (ADRs D383, D386, EC-7/8/9).
727
+ *
728
+ * - `preflightCheck(name, estimatedUsd)` — em `block` mode, throw
729
+ * `BudgetExceededError` antes da LLM call se qualquer limit seria
730
+ * excedido (EC-9 — caller chama dentro do mutex section).
731
+ * - `chargeAndCheckThresholds(name, actualUsd)` — apply charge ao
732
+ * ledger + invoca onThreshold/onExceed callbacks isolated em
733
+ * try/catch (EC-8).
734
+ *
735
+ * @internal
736
+ */
737
+ /**
738
+ * Throws BudgetExceededError if `mode === "block"` and any limit
739
+ * would be exceeded. No-op for audit/warn modes (post-charge checks
740
+ * handle those).
741
+ *
742
+ * Caller invokes this BEFORE the LLM call.
743
+ */
744
+ declare function preflightCheck(name: string, estimatedUsd: number): void;
745
+ /**
746
+ * Charge the budget + dispatch threshold/exceed callbacks (EC-8 isolated).
747
+ *
748
+ * - In `audit` mode: charge only, no callbacks.
749
+ * - In `warn` mode: charge + onThreshold (80/95) + onExceed (100). No throw.
750
+ * - In `block` mode: charge + onThreshold + onExceed. No throw post-call
751
+ * (preflightCheck already prevented exceed for the upcoming call;
752
+ * this protects against simultaneous-call races where multiple sends
753
+ * each pass preflight independently — last one to charge may still
754
+ * tip a limit. We document the case rather than retroactively throw).
755
+ */
756
+ declare function chargeAndCheckThresholds(name: string, actualUsd: number): Promise<void>;
757
+
758
+ /**
759
+ * normalizeUsage — convert provider-shaped raw `usage` object to
760
+ * canonical `TokenUsage`. Ports Hermes Agent's `normalize_usage`
761
+ * (referencia/peer-agent/agent/usage_pricing.py:672-742).
762
+ *
763
+ * Handles 3 API shapes:
764
+ * - Anthropic Messages: 4 explicit buckets (input/output/cache_read/cache_creation).
765
+ * - OpenAI Chat Completions: prompt_tokens INCLUDES cache; subtract cached_tokens.
766
+ * - OpenAI Responses (Codex): input_tokens INCLUDES cache; same subtraction.
767
+ *
768
+ * Edge cases:
769
+ * - a peer#10266 — OpenAI-compat proxies (OpenRouter, a peer vendor AI Gateway,
770
+ * a peer) routing Claude expose Anthropic-style top-level fields
771
+ * (cache_read_input_tokens / cache_creation_input_tokens). Both
772
+ * locations are checked with top-level fallback.
773
+ * - Null/undefined fields → 0 via `int()` coerce.
774
+ * - String token counts → parsed via int.
775
+ * - Negative values → clamped to 0 (defensive against proxy bugs).
776
+ *
777
+ * @internal
778
+ */
779
+ type ApiMode = "anthropic_messages" | "openai_chat_completions" | "openai_responses";
780
+ declare function inferApiMode(provider: string): ApiMode;
781
+ declare function normalizeUsage(rawUsage: unknown, opts: {
782
+ provider: string;
783
+ apiMode?: ApiMode;
784
+ }): TokenUsage;
785
+
786
+ /**
787
+ * Pricing registry — bundled snapshot of LiteLLM JSON (ADR D379) with
788
+ * lazy load + alias normalization (EC-2).
789
+ *
790
+ * Snapshot lives in `pricing-data.json` (hand-curated 2026-05; refresh
791
+ * via `scripts/refresh-pricing.mjs`). All rates in USD per 1_000_000
792
+ * tokens (D378).
793
+ *
794
+ * Lookup precedence (EC-2):
795
+ * 1. Direct `provider/model` key
796
+ * 2. Strip date suffix (-YYYYMMDD or -YYYY-MM-DD)
797
+ * 3. Anthropic dot-to-dash normalization (claude-opus-4.7 → claude-opus-4-7)
798
+ * 4. Strip `openrouter/` prefix
799
+ *
800
+ * @internal
801
+ */
802
+ interface PricingEntry {
803
+ readonly provider: string;
804
+ readonly model: string;
805
+ readonly inputCostPerMillion: number;
806
+ readonly outputCostPerMillion: number;
807
+ readonly cacheReadCostPerMillion?: number;
808
+ readonly cacheWriteCostPerMillion?: number;
809
+ readonly reasoningCostPerMillion?: number;
810
+ readonly pricingVersion: string;
811
+ }
812
+ /**
813
+ * Returns the pricing entry for a given `{provider, model}` route.
814
+ * Tries direct lookup, then 3 alias normalizations (EC-2).
815
+ */
816
+ declare function getPricingEntry(opts: {
817
+ provider: string;
818
+ model: string;
819
+ baseUrl?: string;
820
+ }): PricingEntry | undefined;
821
+
822
+ /**
823
+ * UsageAccumulator — aggregate multi-step `LlmFinish` token counts
824
+ * into a canonical `TokenUsage` (ADR D376, mirror a peer SDK
825
+ * `Usage.add`).
826
+ *
827
+ * Each `add(step)` merges in a per-step finish; `toTokenUsage()`
828
+ * produces the aggregated public shape with `requests[]` populated
829
+ * when there were ≥2 steps.
830
+ *
831
+ * @internal
832
+ */
833
+ interface StepUsage {
834
+ inputTokens?: number;
835
+ outputTokens?: number;
836
+ cacheReadTokens?: number;
837
+ cacheWriteTokens?: number;
838
+ reasoningTokens?: number;
839
+ }
840
+ declare class UsageAccumulator {
841
+ private input;
842
+ private output;
843
+ private cacheRead;
844
+ private cacheWrite;
845
+ private reasoning;
846
+ private readonly requests;
847
+ add(step: StepUsage): void;
848
+ /** Did we observe any usage at all? */
849
+ hasAny(): boolean;
850
+ toTokenUsage(): TokenUsage;
851
+ }
852
+
853
+ /**
854
+ * `Budget` — token cost enforcement primitive (Adoption Roadmap #1
855
+ * post-Tasks, ADRs D375-D388).
856
+ *
857
+ * Static facade delegating to the in-process registry + ledger.
858
+ * 3 modes: `audit` (log-only), `warn` (callbacks + log), `block`
859
+ * (preflight throw before LLM call).
860
+ *
861
+ * @public
862
+ *
863
+ * @deprecated since SDK 2.0 (iter 18+) — import this facade from
864
+ * `@theokit/sdk-budget` instead. The sources backing this facade have
865
+ * been physically extracted to `@theokit/sdk-budget/internal/` per
866
+ * ADR-008. The sdk-core copies are retained for the v1.x sync API
867
+ * contract; consumers MUST migrate before sdk-core v3.0.
868
+ *
869
+ * Migration:
870
+ *
871
+ * ```ts
872
+ * // Before (sdk-core, deprecated):
873
+ * import { Budget, computeCost } from "@theokit/sdk";
874
+ *
875
+ * // After (sdk-budget, authoritative):
876
+ * import {
877
+ * chargeAndCheckThresholds,
878
+ * createBudget,
879
+ * computeUsdCost, // replaces computeCost
880
+ * createUsdBudgetTracker,
881
+ * } from "@theokit/sdk-budget";
882
+ * ```
883
+ */
884
+
885
+ declare class Budget {
886
+ private constructor();
887
+ /**
888
+ * Create a budget. `name` must match `^[a-z0-9][a-z0-9_-]*$` (EC-7).
889
+ * Throws `ConfigurationError` if name is invalid OR already exists
890
+ * (EC-16: duplicate surface caller bug).
891
+ *
892
+ * `limits` is stacked (D384) — ANY exceeded triggers enforcement.
893
+ * Empty `limits[]` is valid: pure tracking, no thresholds/exceed
894
+ * callbacks fire (EC-19).
895
+ *
896
+ * Default `mode` is `"warn"` (D383). For emergency stop, use
897
+ * `mode: "block", limits: [{ window: "1d", limitUsd: 0 }]` (EC-18).
898
+ */
899
+ static create(options: BudgetOptions): BudgetHandle;
900
+ /** Returns the handle for an active budget, or `undefined`. */
901
+ static get(name: string): BudgetHandle | undefined;
902
+ /** Returns all active budgets. */
903
+ static list(): readonly BudgetHandle[];
904
+ /**
905
+ * Deletes a budget from the registry. Returns `true` if it existed.
906
+ * In-flight `agent.send` calls referencing the name treat the
907
+ * subsequent charge as a silent no-op + stderr warn (EC-20).
908
+ */
909
+ static delete(name: string): boolean;
910
+ /**
911
+ * Returns per-window spend snapshot for all active budgets. Each
912
+ * entry has `{ name, window, spentUsd, limitUsd, ratio }`.
913
+ */
914
+ static snapshot(): readonly BudgetSnapshot[];
915
+ }
916
+
917
+ /**
918
+ * SE25 — deterministic, no-LLM guardrail processors built on the SE24
919
+ * {@link Processor} seam. Cheap and churn-free (no provider/model deltas), so
920
+ * they are safe to own in-core — unlike the LLM-classifier processors, which are
921
+ * delegated (see the guardrails ADR). All are OPT-IN: add them to
922
+ * `AgentOptions.inputProcessors` / `outputProcessors`.
923
+ *
924
+ * @public
925
+ */
926
+
927
+ /**
928
+ * Approximate token count from string length. This is an ESTIMATE
929
+ * (≈ UTF-16-code-units / 4, NOT Unicode code points, NOT an exact per-model
930
+ * tokenizer count) — good enough for a coarse cap, and dependency-free.
931
+ */
932
+ declare function estimateTokens(text: string): number;
933
+ /** Options for {@link createUnicodeNormalizer}. @public */
934
+ interface UnicodeNormalizerOptions {
935
+ /** Remove C0 + C1 control chars + DEL (keeps tab / newline / carriage-return). Default `false`. */
936
+ stripControlChars?: boolean;
937
+ /** Collapse runs of intra-line whitespace to one space, 3+ blank lines to one, and trim. Default `false`. Uses legacy `\s`; Unicode-only whitespace (U+00A0 NBSP, U+FEFF BOM, U+2000–U+200A) is NOT collapsed. */
938
+ collapseWhitespace?: boolean;
939
+ }
940
+ /** Options for {@link createTokenLimiter}. @public */
941
+ interface TokenLimiterOptions {
942
+ /** Positive integer token budget (estimate — see {@link estimateTokens}). */
943
+ limit: number;
944
+ /** Over the limit: `"truncate"` (default, cut to fit) or `"block"` (abort with a tripwire). */
945
+ strategy?: "truncate" | "block";
946
+ }
947
+ /** SE36 — `TokenLimiter.create` replaces `createTokenLimiter` (ADR 0015). @public */
948
+ declare class TokenLimiter {
949
+ private constructor();
950
+ static create(opts: TokenLimiterOptions): Processor;
951
+ }
952
+ /** SE36 — `UnicodeNormalizer.create` replaces `createUnicodeNormalizer` (ADR 0015). @public */
953
+ declare class UnicodeNormalizer {
954
+ private constructor();
955
+ static create(opts?: UnicodeNormalizerOptions): Processor;
956
+ }
957
+
958
+ /**
959
+ * Plugin contract — RUNTIME value + type re-exports (T1.1, ADRs D97-D101).
960
+ *
961
+ * SE45/SE46 — the pure `Plugin` *type* and its type companions now live in
962
+ * `types/plugin.ts` (above the DIP boundary, because `Plugin` is public
963
+ * contract). This module keeps the RUNTIME value (`definePlugin` /
964
+ * `Plugin.create`) and re-exports the types so every existing
965
+ * `../plugins/types.js` importer (and the `index.ts` barrel) resolves the same
966
+ * names unchanged.
967
+ *
968
+ * @public
969
+ */
970
+
971
+ /**
972
+ * Identity helper for plugin authors. TS-only convenience — preserves
973
+ * inferred type without forcing manual `Plugin` annotation.
974
+ *
975
+ * @public
976
+ */
977
+ declare function definePlugin<P extends Plugin>(p: P): P;
978
+ type Plugin = Plugin$1;
979
+ /** SE36 — `Plugin.create` replaces `definePlugin` (ADR 0015). Const-companion (the `Plugin` type alias blocks a class of the same name); `create` is the generic `definePlugin`. @public */
980
+ declare const Plugin: {
981
+ create: typeof definePlugin;
982
+ };
983
+
984
+ /**
985
+ * Options for {@link defineProvider}.
986
+ *
987
+ * @public
988
+ */
989
+ interface DefineProviderOptions {
990
+ /** Plugin version surfaced in diagnostics. Default `"1.0.0"`. */
991
+ version?: string;
992
+ }
993
+ /** SE36 — uniform namespace API. `Provider.create` replaces `defineProvider` (ADR 0015). @public */
994
+ declare class Provider {
995
+ private constructor();
996
+ static create(profile: ProviderProfile, opts?: DefineProviderOptions): Plugin;
997
+ /**
998
+ * Every first-party builtin provider (anthropic, openai, openrouter, gemini, ollama, the ChatGPT/Codex
999
+ * `openai-chatgpt`, …) as model-provider plugins, ready to hand to `Agent.create({ plugins })` or any
1000
+ * runtime that consumes model-provider plugins (e.g. the `theokit` agent server / `@theokit/agents`, whose
1001
+ * own model resolution does NOT share this registry). Enables a consumer to route to ANY SDK builtin —
1002
+ * including one added later in a single SDK file — with ZERO provider-specific code: just
1003
+ * `.plugins(Provider.builtins())` once, then pick a `provider/model` id. @public
1004
+ */
1005
+ static builtins(): Plugin[];
1006
+ }
1007
+
1008
+ /**
1009
+ * SE23 — `defineSkillReadTool`: an OPT-IN factory that gives the MODEL on-demand
1010
+ * access to a skill's full body + references via a `skill_read` tool.
1011
+ *
1012
+ * TheoKit discloses skills eagerly through the `<skills>` system-prompt block
1013
+ * (name + description only). This factory is the LAZY read path: the consumer
1014
+ * explicitly adds the returned {@link CustomTool} to `tools`, and when the model
1015
+ * calls it with a skill name, it gets that skill's `instructions` (+ SE21
1016
+ * `references`). The SDK NEVER auto-injects it — bring-your-own-tools stays
1017
+ * intact (sibling of `defineSubAgent` / `workflowAsTool`). See ADR 0007.
1018
+ *
1019
+ * import { Agent, createSkill, defineSkillReadTool } from "@theokit/sdk";
1020
+ *
1021
+ * const skills = [createSkill({ name: "release", description: "…", instructions: "…" })];
1022
+ * const agent = await Agent.create({
1023
+ * model: { id: "openai/gpt-4o-mini" },
1024
+ * skills: { inline: skills },
1025
+ * tools: [defineSkillReadTool(skills)],
1026
+ * });
1027
+ *
1028
+ * @public
1029
+ */
1030
+
1031
+ /** SE36 — `SkillReadTool.create` replaces `defineSkillReadTool` (ADR 0015). @public */
1032
+ declare class SkillReadTool {
1033
+ private constructor();
1034
+ static create(skills: ReadonlyArray<InlineSkill>): CustomTool;
1035
+ }
1036
+
1037
+ /**
1038
+ * Options for {@link sanitizeToolInput}. Trim is the only default-on rung — coercion and JSON
1039
+ * repair change a value's representation, so they are opt-in (the SDK's "values are strings; Zod
1040
+ * coerces" boundary; see `define-tool.ts` doc-comment).
1041
+ *
1042
+ * @public
1043
+ */
1044
+ interface SanitizeOptions {
1045
+ /** Trim leading/trailing whitespace from string values. Default `true`. */
1046
+ trim?: boolean;
1047
+ /** Coerce string values to typed values (`"5"`→`5`, `"true"`→`true`, `"null"`→`null`, JSON). Default `false`. */
1048
+ coerce?: boolean;
1049
+ /** Repair-then-parse malformed JSON-looking string values (via `jsonrepair`). Default `false`. */
1050
+ repairJson?: boolean;
1051
+ /**
1052
+ * Optional Zod schema. When it is a `z.object(...)`, coercion is schema-aware: each TOP-LEVEL
1053
+ * field is coerced only toward a candidate its field-schema accepts (so a `z.string()` field
1054
+ * keeps `"5"` as a string). Non-object schemas (union/record) fall back to heuristic coercion.
1055
+ * Note: with `deep: true`, nested fields always use heuristic coercion (the schema is not
1056
+ * descended into).
1057
+ */
1058
+ schema?: ZodType;
1059
+ /** Recurse into nested objects/arrays. Default `false` (shallow). */
1060
+ deep?: boolean;
1061
+ /** Max recursion depth when `deep` is set. Default `8`. */
1062
+ maxDepth?: number;
1063
+ }
1064
+
1065
+ /**
1066
+ * Spec accepted by {@link defineTool}. `inputSchema` is a Zod schema; the
1067
+ * `handler` argument type is inferred via `z.infer<T>` — no `as` casts.
1068
+ *
1069
+ * @public
1070
+ */
1071
+ /**
1072
+ * SE16 — the handler's return type. With no `outputSchema` the tool returns a
1073
+ * plain `string` (pre-SE16 shape). With an `outputSchema` the handler returns the
1074
+ * STRUCTURED output inferred from it (validated + serialized to the tool result).
1075
+ * The `[O]` tuple wrap prevents distribution so `never` maps cleanly to `string`.
1076
+ */
1077
+ type ToolHandlerReturn<O extends ZodType> = [O] extends [never] ? string : z.infer<O>;
1078
+ interface DefineToolSpec<T extends ZodType, O extends ZodType = never> {
1079
+ /** Tool name surfaced to the LLM. Same constraints as {@link CustomTool.name}. */
1080
+ name: string;
1081
+ /** Description surfaced to the LLM. */
1082
+ description: string;
1083
+ /** Zod schema describing the input. Must be `z.object(...)` at the root for the LLM tool contract. */
1084
+ inputSchema: T;
1085
+ /**
1086
+ * SE16 — optional Zod schema describing the OUTPUT. When set, the handler
1087
+ * returns the structured value inferred from it; the value is validated against
1088
+ * this schema and serialized to the tool result (a string stays as-is, an object
1089
+ * is JSON-stringified). A validation failure raises `ZodError`, converted to a
1090
+ * `tool_result(isError)`. Absent ⇒ the handler returns a plain string (unchanged).
1091
+ */
1092
+ outputSchema?: O;
1093
+ /**
1094
+ * Handler invoked with the parsed input. Type is inferred via `z.infer<T>`; the
1095
+ * return type is `z.infer<O>` when `outputSchema` is set, else `string`.
1096
+ * #65 — an optional 2nd `ToolContext` argument carries the run's `AbortSignal`,
1097
+ * so a cooperative handler can stop early when the run is cancelled. Existing
1098
+ * single-argument handlers are unaffected.
1099
+ */
1100
+ handler: (input: z.infer<T>, ctx?: {
1101
+ signal?: AbortSignal;
1102
+ context?: unknown;
1103
+ threadId?: string;
1104
+ }) => ToolHandlerReturn<O> | Promise<ToolHandlerReturn<O>>;
1105
+ /**
1106
+ * SE17 — map the handler's (validated) output to the compact / multimodal
1107
+ * representation the MODEL sees in the tool_result. The handler keeps returning
1108
+ * the FULL result (validated by `outputSchema`); `toModelOutput` shapes only what
1109
+ * reaches the model, so app-facing detail is not forced into model context.
1110
+ * Returns a string OR SE7 `ToolResultContentBlock[]` (text + image). Absent ⇒
1111
+ * the tool_result is the serialized handler output (SE16 / pre-SE17 behavior).
1112
+ * The split is REAL: the model's `tool_result` carries this compact value, while
1113
+ * observability (`onToolEnd.result`) receives the FULL raw handler output
1114
+ * (serialized) — so the app keeps the complete result. ONE handler execution
1115
+ * feeds both channels.
1116
+ */
1117
+ toModelOutput?: (output: ToolHandlerReturn<O>) => string | ToolResultContentBlock[];
1118
+ /**
1119
+ * Sanitize the raw model-emitted args BEFORE schema validation (`@theokit/sdk/sanitize`).
1120
+ * `true` trims whitespace; an object opts into coercion / JSON-repair. Coercion is schema-aware
1121
+ * against this tool's `inputSchema`. Absent ⇒ args reach validation untouched. Sanitize is
1122
+ * hygiene, not a validity bypass — a genuinely invalid arg still raises `ZodError`.
1123
+ */
1124
+ sanitize?: boolean | SanitizeOptions;
1125
+ }
1126
+ /**
1127
+ * SE36 — the uniform `X.create()` namespace API. `Tool.create(spec)` is the sole public
1128
+ * constructor for a {@link CustomTool}; it wraps the internal builder so behavior is identical
1129
+ * (ADR 0015). A `private constructor` makes `Tool` a namespace, not an instantiable value —
1130
+ * `new Tool()` is a compile error. Mirrors `Agent.create` / `Cron.create`.
1131
+ *
1132
+ * @public
1133
+ */
1134
+ declare class Tool {
1135
+ private constructor();
1136
+ static create<T extends ZodType, O extends ZodType = never>(spec: DefineToolSpec<T, O>): CustomTool;
1137
+ }
1138
+
1139
+ /**
1140
+ * `EventBus` — typed EventEmitter wrapper.
1141
+ *
1142
+ * Provides type-safe publish/subscribe with automatic unsubscribe cleanup.
1143
+ * Each handler is try-caught (EC-2) so one failing handler cannot break others.
1144
+ */
1145
+ type EventHandler<T> = (payload: T) => void;
1146
+ declare class EventBus<Events extends Record<string, unknown>> {
1147
+ #private;
1148
+ private handlers;
1149
+ /** M3 #64 — number of handler invocations that threw (and were logged). */
1150
+ get handlerErrorCount(): number;
1151
+ /**
1152
+ * Subscribe to an event. Returns an unsubscribe function.
1153
+ */
1154
+ subscribe<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void;
1155
+ /**
1156
+ * Publish an event to all subscribers. EC-2: try-catch per handler.
1157
+ */
1158
+ publish<K extends keyof Events>(event: K, payload: Events[K]): void;
1159
+ /**
1160
+ * Subscribe to an event for a single firing. Returns an unsubscribe function.
1161
+ */
1162
+ once<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void;
1163
+ }
1164
+
1165
+ /**
1166
+ * Judge call primitive (T2.2, ADRs D119-D121).
1167
+ *
1168
+ * Instantiates a short-lived auxiliary agent that evaluates whether a
1169
+ * goal is satisfied. The auxiliary judge runs with `tools: []` and a
1170
+ * cheap model (default `openai/gpt-4o-mini`) — see ADR D119. The judge
1171
+ * model needs only API access; we read `OPENROUTER_API_KEY` directly
1172
+ * from the environment (EC-A — single source of truth) and let the
1173
+ * caller override via {@link JudgeOptions.apiKey} for Anthropic or
1174
+ * direct-OpenAI environments.
1175
+ *
1176
+ * NOTE: judge aux agents created from inside a `forkAgent` context will
1177
+ * inherit the parent fork's whitelist via AsyncLocalStorage (EC-J).
1178
+ * `tools: []` keeps this benign today; future callers that add tools to
1179
+ * a judge should be aware.
1180
+ *
1181
+ * @internal
1182
+ */
1183
+ /** Inputs to the judge — pure data. */
1184
+ interface JudgeContext {
1185
+ goal: string;
1186
+ lastResponse: string;
1187
+ subgoals?: string[];
1188
+ }
1189
+ /** Caller-supplied tuning knobs for the judge call. */
1190
+ interface JudgeOptions {
1191
+ /** Judge model identifier. Default `"openai/gpt-4o-mini"` (ADR D119). */
1192
+ judgeModel?: string;
1193
+ /** Override env. Default `process.env.OPENROUTER_API_KEY` (EC-A). */
1194
+ apiKey?: string;
1195
+ }
1196
+
1197
+ /**
1198
+ * Public types for the judge subsystem (T2.1, ADR D120).
1199
+ *
1200
+ * @internal
1201
+ */
1202
+ /** Outcome of {@link parseVerdict} / {@link judgeCallImpl}. */
1203
+ interface JudgeResult {
1204
+ verdict: Verdict;
1205
+ reason: string;
1206
+ /**
1207
+ * `true` when the underlying text did not start with one of the three
1208
+ * canonical prefixes. The verdict is set to `"continue"` (fail-safe,
1209
+ * ADR D121) to avoid stopping prematurely; callers track consecutive
1210
+ * failures and bail via `maxConsecutiveJudgeFailures`.
1211
+ */
1212
+ parseFailed: boolean;
1213
+ }
1214
+
1215
+ /**
1216
+ * Goal-driven Ralph loop (T3.2, ADRs D115-D121).
1217
+ *
1218
+ * `runUntilImpl` is an `AsyncGenerator<GoalEvent, GoalResult, void>`:
1219
+ * yields events as the loop progresses, returns the final result when
1220
+ * the goal completes, fails, or is paused. The auxiliary judge model is
1221
+ * injected via `deps.judge` so the generator stays free of the `Agent`
1222
+ * façade import.
1223
+ *
1224
+ * EC-C fix: pre-aborted signals emit only `[paused]`, not `[active, paused]`.
1225
+ * EC-D: `maxTurns: 0` is supported (vacuous yield active → failed).
1226
+ *
1227
+ * @internal
1228
+ */
1229
+
1230
+ /** DI contract: the judge is the only external touchpoint. */
1231
+ interface RunUntilDeps {
1232
+ judge: (ctx: JudgeContext, opts?: JudgeOptions) => Promise<JudgeResult>;
1233
+ }
1234
+
1235
+ /**
1236
+ * M56 (agent-builder goal transparency) — PUBLIC goal-loop driver for CUSTOM agent surfaces.
1237
+ *
1238
+ * `LocalAgent.runUntil` binds the goal loop to a registered local agent. Surfaces that route turns
1239
+ * through their OWN transport (e.g. a TUI store facade, so every goal turn renders in the same
1240
+ * timeline as a manual turn) need the SAME loop over a minimal `send → wait` shape. This export
1241
+ * gives them exactly that: the canonical `runUntilImpl` (judge + continuation + token budget +
1242
+ * Codex states) with the default judge wired from the DI registry.
1243
+ *
1244
+ * @public
1245
+ */
1246
+
1247
+ /**
1248
+ * Stable marker on the FIRST LINE of every goal-continuation prompt. Surfaces detect it to render the
1249
+ * turn collapsed, exclude it from backtrack windows, and skip it in compaction preservation.
1250
+ */
1251
+ declare const GOAL_CONTINUATION_MARKER = "[[theokit:goal-continuation]]";
1252
+
1253
+ /** The minimal surface the goal loop drives — anything that can send a prompt and wait for it. */
1254
+ interface GoalLoopAgent {
1255
+ send(prompt: string): Promise<{
1256
+ wait(): Promise<{
1257
+ result?: string;
1258
+ usage?: {
1259
+ totalTokens?: number;
1260
+ };
1261
+ }>;
1262
+ }>;
1263
+ }
1264
+ /**
1265
+ * Run the goal-driven loop (`send → judge → continuation`) over ANY `send → wait` surface.
1266
+ * Identical semantics to `Agent.runUntil` (ADRs D115-D121 + M55 token budget / states).
1267
+ * `depsOverride` is a test seam for injecting a fake judge.
1268
+ */
1269
+ declare function runGoalLoop(agent: GoalLoopAgent, goal: string, options?: GoalOptions, depsOverride?: RunUntilDeps): AsyncGenerator<GoalEvent, GoalResult, void>;
1270
+
1271
+ /**
1272
+ * Reference `BudgetTracker` impl — pure token + iteration counter
1273
+ * (SDK 2.0 Phase 2 / T2.1 — ADR D1 reference implementation).
1274
+ *
1275
+ * Counts tokens per type (input/output) + iteration count. Enforces
1276
+ * optional `maxTokens` / `maxIterations` ceilings via `check()`.
1277
+ *
1278
+ * Does NOT compute USD cost — leaves that to richer impls in
1279
+ * `@theokit/sdk-budget` (post-Phase-2). This file is intentionally
1280
+ * minimal so consumers can:
1281
+ * - use it as-is for simple guard-rails;
1282
+ * - read it as a worked example before authoring a custom tracker;
1283
+ * - rely on it as a fallback before sdk-budget ships.
1284
+ *
1285
+ * @public — surface-level reference impl.
1286
+ */
1287
+
1288
+ /** Options for `createCounterBudgetTracker`. */
1289
+ interface CounterBudgetTrackerOptions {
1290
+ /** Hard ceiling on total tokens (input + output). When reached, `check()` returns `allowed: false`. */
1291
+ readonly maxTokens?: number;
1292
+ /** Hard ceiling on iterations counted by `nextIteration()`. */
1293
+ readonly maxIterations?: number;
1294
+ }
1295
+ /**
1296
+ * Build a fresh tracker. The returned object is independent — call
1297
+ * `createCounterBudgetTracker()` per Agent instance.
1298
+ *
1299
+ * The tracker exposes the `BudgetTracker` contract PLUS a `nextIteration()`
1300
+ * helper for impls that want explicit iteration counting (the agent loop
1301
+ * calls it once per turn). Without `nextIteration()` calls, the iteration
1302
+ * cap is never reached.
1303
+ */
1304
+ declare function createCounterBudgetTracker(options?: CounterBudgetTrackerOptions): BudgetTracker & {
1305
+ nextIteration(): void;
1306
+ };
1307
+
1308
+ declare function withCwdMutex<T>(key: string, fn: () => Promise<T>): Promise<T>;
1309
+
1310
+ /**
1311
+ * Reference `MemoryProvider` impl — no-op fallback (SDK 2.0 Phase 1 /
1312
+ * T1.2 reference implementation, mirrors `createCounterBudgetTracker`).
1313
+ *
1314
+ * Every method is a degenerate identity:
1315
+ * - `init()` returns a handle wrapping a no-op `MemoryAdapter`.
1316
+ * - `buildTools()` returns `[]` (no memory tools surfaced to the LLM).
1317
+ * - `runActivePass()` returns `{ facts: [] }` (no recall fires).
1318
+ * - `dispose()` is a no-op.
1319
+ *
1320
+ * Why ship this:
1321
+ * - Default safety net before `@theokit/sdk-memory` is installed.
1322
+ * - Worked reference for authors of custom providers.
1323
+ * - Enables `Agent.create({ memoryProvider: createNoopMemoryProvider() })`
1324
+ * unit tests without pulling memory infrastructure.
1325
+ *
1326
+ * NOT a substitute for the existing `Memory` class — the legacy class
1327
+ * stays authoritative until the subsystem fully ports to providers
1328
+ * (Phase 1 / T1.6).
1329
+ *
1330
+ * @public — surface-level reference impl.
1331
+ */
1332
+
1333
+ /** SE36 — `NoopMemoryProvider.create` replaces `createNoopMemoryProvider` (ADR 0015). @public */
1334
+ declare class NoopMemoryProvider {
1335
+ private constructor();
1336
+ static create(): MemoryProvider;
1337
+ }
1338
+
1339
+ /**
1340
+ * `JobQueue` — background job queue with status tracking, cancellation, and an
1341
+ * optional concurrency bound.
1342
+ *
1343
+ * EC-1: all enqueued functions are wrapped in Promise.resolve().then() so
1344
+ * synchronous throws become rejections.
1345
+ *
1346
+ * #58: each job runs under an `AbortController` whose signal is passed to the
1347
+ * job fn, so `cancel()` actually interrupts a running job (not just a status
1348
+ * flip); an optional `maxConcurrency` bounds how many jobs run at once.
1349
+ */
1350
+ type JobStatus = "pending" | "running" | "completed" | "failed" | "cancelled";
1351
+ interface Job<T> {
1352
+ id: string;
1353
+ status: JobStatus;
1354
+ result?: T;
1355
+ error?: string;
1356
+ }
1357
+ /** #58 — construction options. */
1358
+ interface JobQueueOptions {
1359
+ /**
1360
+ * Max jobs running concurrently. Omit for unbounded (previous behavior).
1361
+ * Values < 1 are clamped to 1 (an invalid bound must not deadlock).
1362
+ */
1363
+ maxConcurrency?: number;
1364
+ }
1365
+ declare class JobQueue {
1366
+ #private;
1367
+ private jobs;
1368
+ private controllers;
1369
+ private readonly maxConcurrency;
1370
+ private running;
1371
+ private readonly waiting;
1372
+ constructor(options?: JobQueueOptions);
1373
+ /**
1374
+ * Enqueue a background function. Returns the job ID immediately. The function
1375
+ * receives an `AbortSignal` that fires when the job is cancelled (#58) — a
1376
+ * cooperative job should observe it to stop early. Existing `() => Promise<T>`
1377
+ * callers are unaffected (the signal argument is simply ignored).
1378
+ */
1379
+ enqueue<T>(fn: (signal: AbortSignal) => Promise<T>): string;
1380
+ getJob(id: string): Job<unknown> | undefined;
1381
+ list(): Job<unknown>[];
1382
+ /**
1383
+ * Cancel a pending or running job. Returns true if cancelled. #58 — aborts the
1384
+ * job's `AbortSignal` so a cooperative running job is actually interrupted.
1385
+ */
1386
+ cancel(id: string): boolean;
1387
+ }
1388
+
1389
+ /**
1390
+ * Public handle to an open memory index. Mirrors the internal `MemoryIndex`
1391
+ * contract structurally; defined here (NOT re-exported from internal/) so
1392
+ * the public DTS surface does not pull the internal/runtime cycle that
1393
+ * trips rollup-plugin-dts.
1394
+ *
1395
+ * @public
1396
+ */
1397
+ interface MemoryIndexHandle {
1398
+ sync(): Promise<{
1399
+ filesScanned: number;
1400
+ filesUpdated: number;
1401
+ chunksWritten: number;
1402
+ chunksEmbedded: number;
1403
+ }>;
1404
+ search(query: string, options?: {
1405
+ maxResults?: number;
1406
+ minScore?: number;
1407
+ sources?: ReadonlyArray<"memory" | "sessions" | "wiki">;
1408
+ }): Promise<ReadonlyArray<{
1409
+ path: string;
1410
+ startLine: number;
1411
+ endLine: number;
1412
+ score: number;
1413
+ textScore: number;
1414
+ vectorScore?: number;
1415
+ snippet: string;
1416
+ source: "memory" | "sessions" | "wiki";
1417
+ citation: string;
1418
+ }>>;
1419
+ status(): {
1420
+ backend: "fts-only" | "hybrid";
1421
+ filesIndexed: number;
1422
+ chunksIndexed: number;
1423
+ lastSyncMs?: number;
1424
+ };
1425
+ close(): Promise<void> | void;
1426
+ }
1427
+ /**
1428
+ * Public `Memory` namespace.
1429
+ *
1430
+ * Exposes operations users can run outside of `agent.send()` — most notably
1431
+ * the dreaming sweep (consolidation of facts via dedup + clustering).
1432
+ *
1433
+ * @public
1434
+ */
1435
+ interface DreamingSweepOptions {
1436
+ /** Workspace cwd holding `.theokit/memory/`. */
1437
+ cwd: string;
1438
+ /**
1439
+ * Embedding provider for semantic dedup + clustering. Required — dreaming
1440
+ * relies on real embeddings to score cosine similarity. Supported providers:
1441
+ * `"openai"`, `"mistral"`, `"openrouter"`, `"voyage"`, `"deepinfra"`,
1442
+ * `"ollama"` (local, ADR D183).
1443
+ */
1444
+ embedding: {
1445
+ provider: "openai" | "mistral" | "openrouter" | "voyage" | "deepinfra" | "ollama";
1446
+ model?: string;
1447
+ };
1448
+ /** Cosine-similarity threshold for the dedup phase. Default `0.95`. */
1449
+ dedupThreshold?: number;
1450
+ /** Cosine-similarity threshold for the clustering phase. Default `0.75`. */
1451
+ clusterThreshold?: number;
1452
+ }
1453
+ interface DreamingSweepResult {
1454
+ status: "ok" | "skipped" | "error";
1455
+ factsBefore: number;
1456
+ factsAfter: number;
1457
+ duplicatesRemoved: number;
1458
+ clustersCreated: number;
1459
+ notesWritten: number;
1460
+ }
1461
+ /**
1462
+ * Options for `Memory.openIndex`. Mirrors the internal `OpenIndexOptions`
1463
+ * but using only public types from the SDK surface.
1464
+ *
1465
+ * @public
1466
+ */
1467
+ interface OpenMemoryIndexOptions {
1468
+ /** Workspace cwd holding `.theokit/memory/`. */
1469
+ cwd: string;
1470
+ /** Override storage file path (SQLite) OR storage directory (Lance). */
1471
+ filePath?: string;
1472
+ /**
1473
+ * Embedding runtime — REQUIRED for `backend: "lance"`, optional for
1474
+ * `"sqlite-vec"` (when omitted, SQLite runs FTS-only without vector
1475
+ * recall).
1476
+ */
1477
+ embedding?: {
1478
+ provider: "openai" | "mistral" | "openrouter" | "voyage" | "deepinfra" | "ollama";
1479
+ model?: string;
1480
+ };
1481
+ /** Default `"sqlite-vec"`. Set to `"lance"` to opt into LanceDB (peer dep). */
1482
+ backend?: "sqlite-vec" | "lance";
1483
+ }
1484
+ declare const Memory: {
1485
+ /**
1486
+ * Open a memory index. Dispatches to SQLite-vec (default, zero deps) or
1487
+ * LanceDB (opt-in via `backend: "lance"`, requires `@lancedb/lancedb`
1488
+ * peer dep + an embedding runtime).
1489
+ *
1490
+ * Returns a `MemoryIndex` with `sync()`, `search(query, opts?)`,
1491
+ * `status()`, and `close()`. Use this when you want a direct index
1492
+ * handle outside of `Agent.create({ memory: ... })`.
1493
+ *
1494
+ * @throws ConfigurationError({code:"invalid_memory_backend"}) for typos
1495
+ * like `"lancedb"`.
1496
+ * @throws ConfigurationError({code:"lance_requires_embedding"}) when
1497
+ * `backend: "lance"` is requested without `embedding`.
1498
+ * @throws ConfigurationError({code:"lance_backend_unavailable"}) when
1499
+ * `backend: "lance"` is requested but the peer dep is absent.
1500
+ *
1501
+ * @public
1502
+ */
1503
+ openIndex(opts: OpenMemoryIndexOptions): Promise<MemoryIndexHandle>;
1504
+ /**
1505
+ * Run a dreaming sweep: dedup near-duplicate facts, cluster thematically
1506
+ * related ones, and write a consolidated note + diary entry.
1507
+ *
1508
+ * @public
1509
+ */
1510
+ runDreamingSweep(opts: DreamingSweepOptions): Promise<DreamingSweepResult>;
1511
+ };
1512
+
1513
+ /**
1514
+ * Runtime helpers for `MemoryAdapter` (T1.1, ADR D141).
1515
+ *
1516
+ * Kept separate from `types/memory-adapter.ts` so the types module
1517
+ * stays import-free of runtime code (dep-cruise rule
1518
+ * `types-dont-import-runtime`). Adapter authors call `mkMemoryId` to
1519
+ * construct a branded id and `extractRawId` to unwrap with cross-adapter
1520
+ * safety (EC-B).
1521
+ *
1522
+ * @public
1523
+ */
1524
+
1525
+ /**
1526
+ * Construct a branded `MemoryId` for an adapter. Embeds the adapter
1527
+ * identifier so `extractRawId` can reject ids minted by other adapters.
1528
+ *
1529
+ * @public
1530
+ */
1531
+ declare function mkMemoryId(adapterId: string, rawId: string): MemoryId;
1532
+ /**
1533
+ * Extract the raw provider id from a `MemoryId`, enforcing that the
1534
+ * prefix matches `expectedAdapterId`. Throws `MemoryAdapterError(code:
1535
+ * "invalid_input")` on mismatch — prevents `mem0.delete(supermemoryId)`
1536
+ * from accidentally deleting unrelated data (EC-B).
1537
+ *
1538
+ * @public
1539
+ */
1540
+ declare function extractRawId(id: MemoryId, expectedAdapterId: string): string;
1541
+
1542
+ /**
1543
+ * Options for {@link migrateSqliteToLance}.
1544
+ *
1545
+ * @public
1546
+ */
1547
+ interface MigrateOptions {
1548
+ cwd: string;
1549
+ dryRun?: boolean;
1550
+ batchSize?: number;
1551
+ logger?: (msg: string) => void;
1552
+ }
1553
+ /**
1554
+ * Outcome of {@link migrateSqliteToLance}.
1555
+ *
1556
+ * @public
1557
+ */
1558
+ interface MigrateResult {
1559
+ countSqlite: number;
1560
+ countLance: number;
1561
+ validated: boolean;
1562
+ sampleComparisons: ReadonlyArray<{
1563
+ id: string;
1564
+ match: boolean;
1565
+ }>;
1566
+ lancePath: string;
1567
+ committed: boolean;
1568
+ }
1569
+ /**
1570
+ * Migrate the Memory index from SQLite to LanceDB. ADR D44.
1571
+ *
1572
+ * @public
1573
+ */
1574
+ declare function migrateSqliteToLance(options: MigrateOptions): Promise<MigrateResult>;
1575
+
1576
+ /**
1577
+ * M7-5 — `createPermissionPlugin`: wire a {@link PermissionEngine} into the
1578
+ * `definePlugin` `pre_tool_call` veto seam. This is the canonical exemplar that
1579
+ * gives `PermissionEngine` a real caller (it was previously exported-but-unwired):
1580
+ * on each tool call the engine's verdict maps to the veto contract —
1581
+ * `"deny"` -> block, `"ask"` -> the caller's `onAsk` resolver (or block, fail-closed),
1582
+ * `"allow"` -> pass.
1583
+ *
1584
+ * @public
1585
+ */
1586
+
1587
+ /**
1588
+ * SE1 — context passed to the {@link PermissionGate}. Intentionally minimal for
1589
+ * SE1; `agentId`/`runId` (for audit logging) are a documented follow-up — they are
1590
+ * available on the raw `pre_tool_call` context and can be threaded in a later slice.
1591
+ */
1592
+ interface PermissionGateContext {
1593
+ /** The tool being gated. */
1594
+ readonly toolName: string;
1595
+ /** The active permission mode for this run. */
1596
+ readonly mode: PermissionMode;
1597
+ }
1598
+ /**
1599
+ * SE1 — the resolution of an `"ask"` verdict by the host gate. Fail-closed: an
1600
+ * absent gate, a throwing gate, and a `"deny"` decision all block. Arg rewrite
1601
+ * (`updatedInput`) is intentionally NOT supported yet — the `pre_tool_call` seam
1602
+ * is veto-only (`{ block, message }`); a future enhancement can extend it.
1603
+ */
1604
+ type PermissionGateDecision = {
1605
+ readonly behavior: "allow";
1606
+ } | {
1607
+ readonly behavior: "deny";
1608
+ readonly message?: string;
1609
+ };
1610
+ /**
1611
+ * SE1 — the enriched `canUseTool` gate (the Anthropic-parity shape). Invoked ONLY
1612
+ * on an `"ask"` verdict, it receives the tool name, its input args, and the run
1613
+ * {@link PermissionGateContext}, and resolves to allow/deny. May be async (a real
1614
+ * gate can prompt a human — the `pre_tool_call` seam awaits it).
1615
+ */
1616
+ type PermissionGate = (toolName: string, input: Record<string, unknown>, ctx: PermissionGateContext) => PermissionGateDecision | Promise<PermissionGateDecision>;
1617
+ /** Options for {@link createPermissionPlugin}. */
1618
+ interface PermissionPluginOptions {
1619
+ /** Plugin name (default `"permission-engine"`). */
1620
+ readonly name?: string;
1621
+ /**
1622
+ * SE1 — the per-run {@link PermissionMode}. Threaded into `engine.evaluate`, so
1623
+ * `bypass` auto-allows the ask verdict (gate never consulted), `plan` blocks
1624
+ * mutations, etc. An explicit `deny` rule is immune to every mode. Default
1625
+ * `"default"` (rules decide; unmatched ⇒ fail-closed ask).
1626
+ */
1627
+ readonly mode?: PermissionMode;
1628
+ /**
1629
+ * SE1 — the enriched gate for the `"ask"` verdict. Preferred over {@link onAsk}.
1630
+ * Absent gate on an `ask` verdict ⇒ fail-closed block.
1631
+ */
1632
+ readonly canUseTool?: PermissionGate;
1633
+ /**
1634
+ * @deprecated since SE1 — use {@link canUseTool}, which receives `(toolName,
1635
+ * input, ctx)` and returns a typed decision. Honored only when `canUseTool` is
1636
+ * absent. Returns a veto (`{block,message}`) to deny or `undefined` to allow.
1637
+ */
1638
+ readonly onAsk?: (toolName: string) => PreToolCallDecision | undefined;
1639
+ }
1640
+ /** SE36 — `PermissionPlugin.create` replaces `createPermissionPlugin` (ADR 0015). @public */
1641
+ declare class PermissionPlugin {
1642
+ private constructor();
1643
+ static create(engine: PermissionEngine, opts?: PermissionPluginOptions): Plugin;
1644
+ }
1645
+
1646
+ /** The internal JSON-Schema shape the synthetic `output` tool consumes. */
1647
+ type NormalizedJsonSchema = Record<string, unknown>;
1648
+ /**
1649
+ * Normalize any supported schema to the internal JSON Schema. Async because the Valibot path
1650
+ * dynamically imports its optional converter. Throws a clear, typed-message error for an unsupported
1651
+ * schema or a missing Valibot peer (error-handling.md).
1652
+ */
1653
+ declare function normalizeSchema(schema: unknown): Promise<NormalizedJsonSchema>;
1654
+
1655
+ /**
1656
+ * Public security namespace (T2.1, ADR D68).
1657
+ *
1658
+ * Two entry points:
1659
+ *
1660
+ * - `Security.redact(text, opts?)` — apply the canonical redactor to
1661
+ * arbitrary text. Useful when a consumer app (or example) writes its
1662
+ * own logs / metrics / paste-share artifacts that the SDK's wired
1663
+ * sinks (error metadata, telemetry, transcript, migration) don't
1664
+ * cover.
1665
+ * - `Security.addPattern(re)` — register a custom credential pattern
1666
+ * on top of the 12 builtins (OpenAI, Anthropic, GitHub PAT classic +
1667
+ * fine, GitLab, AWS, Google, Slack, Sentry, Stripe live + restricted)
1668
+ * plus the parametric `key=value` + `Bearer <token>` matchers.
1669
+ *
1670
+ * Redaction is ON by default. Disable with `THEOKIT_REDACT_SECRETS=false`
1671
+ * (a warning is emitted on stderr so the operator knows the SDK process
1672
+ * is vulnerable). The env var is snapshotted at module init — runtime
1673
+ * mutation cannot disable it, defending against prompt injection that
1674
+ * tries to flip the flag mid-run.
1675
+ */
1676
+ declare class Security {
1677
+ private constructor();
1678
+ /**
1679
+ * Redact known credential patterns from `text` and return the masked
1680
+ * string. Use this at any consumer output boundary the SDK does not
1681
+ * directly own (custom stdout loggers, app-level metrics, debug-share
1682
+ * artifacts, etc.).
1683
+ *
1684
+ * Coerces non-strings (objects via JSON.stringify, null/undefined → "").
1685
+ * Two-bucket masking: tokens shorter than 18 chars → `***`; longer
1686
+ * tokens preserve `prefix...suffix` for debuggability without revealing
1687
+ * the secret middle.
1688
+ *
1689
+ * @param text - The value to redact. Strings, objects, primitives all OK.
1690
+ * @param opts.codeFile - When `true`, skips the parametric `key=value`
1691
+ * matcher so file content like `.env.example` placeholders is left
1692
+ * intact. Built-in pattern matches still apply.
1693
+ *
1694
+ * @example
1695
+ * console.log(`[bot] received: ${Security.redact(userText)}`);
1696
+ * // → "[bot] received: please remember sk-abc...xyz1"
1697
+ */
1698
+ static redact(text: unknown, opts?: {
1699
+ codeFile?: boolean;
1700
+ }): string;
1701
+ /**
1702
+ * Register a custom redaction pattern. Additive — built-in patterns
1703
+ * (OpenAI, Anthropic, GitHub PAT, AWS, etc.) cannot be removed.
1704
+ *
1705
+ * @param re - RegExp with `/g` flag. Throws if `/g` is missing
1706
+ * (without /g, only first match is replaced and the rest
1707
+ * leaks).
1708
+ *
1709
+ * Process-global mutable state. The SDK is designed for single-tenant
1710
+ * processes (Theo PaaS user runtime, local CLI). Multi-tenant
1711
+ * deployments running multiple SDK consumers in the same Node process
1712
+ * share this list — patterns added by tenant A apply to tenant B's
1713
+ * redactions. Acceptable for v1; future isolate-aware refactor would
1714
+ * thread patterns through a context if needed.
1715
+ *
1716
+ * @example
1717
+ * Security.addPattern(/MYORG-[A-Z0-9]{32}/g);
1718
+ * // → text containing "MYORG-AAAA...AAAA" now masks like a builtin.
1719
+ */
1720
+ static addPattern(re: RegExp): void;
1721
+ }
1722
+
1723
+ /**
1724
+ * M3 #62 — scoped session state.
1725
+ *
1726
+ * A conversation id can be namespaced by SCOPE so a consumer keeps app-durable,
1727
+ * user-durable, and ephemeral (temp) session data separated in the same store:
1728
+ *
1729
+ * - `app:` — durable state shared across users (app-level memory).
1730
+ * - `user:` — durable state for one user.
1731
+ * - `temp:` — ephemeral state a consumer prunes on logout / session end.
1732
+ *
1733
+ * The scope is a prefix on the conversation id (`"<scope>__<id>"`). The `__`
1734
+ * separator is path-safe (unlike `:`, which the identifier guard rejects), so a
1735
+ * host can partition sessions by scope over the native transcript store.
1736
+ *
1737
+ * @public
1738
+ */
1739
+ /** M3 #62 — session state scope. */
1740
+ type SessionScope = "app" | "user" | "temp";
1741
+ /** M3 #62 — build a scope-namespaced conversation id (`"<scope>__<id>"`). */
1742
+ declare function scopedConversationId(scope: SessionScope, id: string): string;
1743
+ /** M3 #62 — the id prefix (`"<scope>__"`) used to match a scope's conversations. */
1744
+ declare function sessionScopePrefix(scope: SessionScope): string;
1745
+
1746
+ /**
1747
+ * `createSquad` — a sequential team of agents.
1748
+ *
1749
+ * A Squad is a thin convenience that COMPOSES `Workflow` + `agentStep` — it
1750
+ * adds NO new orchestration logic. Agents run in array order; each agent's
1751
+ * output is threaded into the next agent's prompt. For branching/parallel/
1752
+ * foreach teams use `Workflow` directly; for manager→worker delegation use
1753
+ * subagents or `@theokit/sdk-handoff`.
1754
+ *
1755
+ * Mirrors the `createAgentFactory` composition-LEGO precedent (a factory over
1756
+ * existing primitives, not a new subsystem).
1757
+ *
1758
+ * @public
1759
+ */
1760
+
1761
+ /**
1762
+ * Options for {@link createSquad}.
1763
+ *
1764
+ * @public
1765
+ */
1766
+ interface SquadOptions {
1767
+ /** Agents run in array order (sequential pipeline). Must be non-empty. */
1768
+ agents: ReadonlyArray<SDKAgent>;
1769
+ /**
1770
+ * Orchestration process. Only `"sequential"` is supported (the default).
1771
+ * `"hierarchical"` is accepted by the type but rejected at runtime with
1772
+ * guidance — use subagents or `@theokit/sdk-handoff` for manager→worker
1773
+ * delegation (those already cover it).
1774
+ */
1775
+ process?: "sequential" | "hierarchical";
1776
+ /** Optional squad name (surfaced on the underlying workflow). Default `"squad"`. */
1777
+ name?: string;
1778
+ }
1779
+ /**
1780
+ * Result of a {@link Squad.run}. `result` is the final (last agent's) output;
1781
+ * `steps` is the per-agent trace from the underlying workflow run.
1782
+ *
1783
+ * @public
1784
+ */
1785
+ interface SquadRun {
1786
+ readonly result: unknown;
1787
+ readonly status: "running" | "completed" | "failed" | "suspended" | "cancelled";
1788
+ readonly steps: ReadonlyArray<StepResult>;
1789
+ }
1790
+ /**
1791
+ * A sequential agent team produced by {@link createSquad}.
1792
+ *
1793
+ * @public
1794
+ */
1795
+ interface Squad {
1796
+ /** Run the team over `input`, threading each agent's output to the next. */
1797
+ run(input: unknown): Promise<SquadRun>;
1798
+ }
1799
+ /** SE36 — `Squad.create` replaces `createSquad` (ADR 0015). Merges with the `Squad` interface. @public */
1800
+ declare class Squad {
1801
+ private constructor();
1802
+ static create(options: SquadOptions): Squad;
1803
+ }
1804
+
1805
+ /**
1806
+ * Public type contract for the Task observability registry (ADRs D361-D374).
1807
+ *
1808
+ * Tasks are an opt-in observability layer over async work in the SDK
1809
+ * (`Agent.send`, `Agent.batch`, `Workflow.run`, `Cron` fires). They have
1810
+ * a closed 5-state lifecycle (D362), discriminated events (D366), and a
1811
+ * pluggable store (D364). The `Task` facade in `task.ts` is the public
1812
+ * surface; consumers import these types from `@theokit/sdk`.
1813
+ *
1814
+ * @public
1815
+ */
1816
+ /**
1817
+ * Closed enum of the 5 lifecycle states (D362).
1818
+ *
1819
+ * Transitions are acyclic:
1820
+ * queued → running → (finished | error | cancelled)
1821
+ * queued → cancelled (direct, no run started)
1822
+ */
1823
+ type TaskState = "queued" | "running" | "finished" | "error" | "cancelled";
1824
+ /** Discriminator of the runtime that produced a task (D374). */
1825
+ type TaskKind = "run" | "batch" | "workflow" | "cron" | "custom";
1826
+ /** Discriminated union of task lifecycle events (D366). */
1827
+ type TaskEvent = {
1828
+ readonly type: "submitted";
1829
+ readonly taskId: string;
1830
+ readonly kind: TaskKind;
1831
+ readonly submittedAt: number;
1832
+ readonly meta?: Record<string, unknown>;
1833
+ /** D372 — flag set on the first yielded event when the ring buffer was at cap. */
1834
+ readonly truncated?: boolean;
1835
+ } | {
1836
+ readonly type: "started";
1837
+ readonly taskId: string;
1838
+ readonly startedAt: number;
1839
+ } | {
1840
+ readonly type: "progress";
1841
+ readonly taskId: string;
1842
+ readonly at: number;
1843
+ readonly payload: unknown;
1844
+ } | {
1845
+ readonly type: "finished";
1846
+ readonly taskId: string;
1847
+ readonly finishedAt: number;
1848
+ readonly result: unknown;
1849
+ } | {
1850
+ readonly type: "errored";
1851
+ readonly taskId: string;
1852
+ readonly erroredAt: number;
1853
+ readonly error: {
1854
+ readonly code: string;
1855
+ readonly message: string;
1856
+ };
1857
+ } | {
1858
+ readonly type: "cancelled";
1859
+ readonly taskId: string;
1860
+ readonly cancelledAt: number;
1861
+ readonly reason?: string;
1862
+ };
1863
+ /** Public read-only view of a task entry in the registry. */
1864
+ interface TaskHandle {
1865
+ readonly id: string;
1866
+ readonly kind: TaskKind;
1867
+ readonly state: TaskState;
1868
+ readonly submittedAt: number;
1869
+ readonly startedAt?: number;
1870
+ readonly finishedAt?: number;
1871
+ readonly cancelledAt?: number;
1872
+ readonly erroredAt?: number;
1873
+ readonly result?: unknown;
1874
+ readonly error?: {
1875
+ readonly code: string;
1876
+ readonly message: string;
1877
+ };
1878
+ readonly meta?: Record<string, unknown>;
1879
+ /**
1880
+ * EC-7 — cross-process best-effort cancel flag. Set by CLI
1881
+ * `theokit tasks cancel` via JsonFileTaskStore. The owning process
1882
+ * polls at checkpoints and honors via AbortController. Always
1883
+ * `undefined` for in-process cancel paths (which go directly through
1884
+ * AbortController).
1885
+ */
1886
+ readonly cancelRequested?: boolean;
1887
+ }
1888
+ /** Query filter for `Task.list`. */
1889
+ interface TaskFilter {
1890
+ readonly state?: TaskState | readonly TaskState[];
1891
+ readonly kind?: TaskKind | readonly TaskKind[];
1892
+ readonly submittedAfter?: number;
1893
+ readonly submittedBefore?: number;
1894
+ /** Defaults to 100. JsonFileTaskStore hard-caps loaded entries at 256 (D364). */
1895
+ readonly limit?: number;
1896
+ }
1897
+ /** Options for `Task.submit`. */
1898
+ interface TaskSubmitOptions {
1899
+ /**
1900
+ * Optional user-supplied ID. Must match grammar `^[a-z0-9][a-z0-9_-]*$`
1901
+ * and MUST NOT start with the reserved prefixes `wf-` / `b-` / `cron-`
1902
+ * (D368, EC-5). When omitted, `crypto.randomUUID()` is used.
1903
+ */
1904
+ readonly id?: string;
1905
+ readonly meta?: Record<string, unknown>;
1906
+ /**
1907
+ * Optional caller-provided AbortSignal. If already aborted at submit
1908
+ * time, the registry short-circuits to `cancelled` without acquiring
1909
+ * a semaphore slot (EC-4).
1910
+ */
1911
+ readonly signal?: AbortSignal;
1912
+ /**
1913
+ * SE2 — an opt-in {@link import("./run-events.js").RunEventSink}. The task's
1914
+ * lifecycle is forwarded to it as typed `task_started` / `task_updated` /
1915
+ * `task_completed` RunEvents, so a caller that spawned the task can observe it
1916
+ * through the same `onRunEvent` channel as the rest of the run. Best-effort (a
1917
+ * throwing sink never breaks the task). The dedicated `Task.subscribe(id)`
1918
+ * channel is unaffected.
1919
+ */
1920
+ readonly onRunEvent?: RunEventSink;
1921
+ }
1922
+ /** Options shape for `TaskStore` factory (D364). */
1923
+ type TaskStoreOptions = {
1924
+ readonly backend: "memory";
1925
+ } | {
1926
+ readonly backend: "json";
1927
+ readonly dir: string;
1928
+ };
1929
+ /** Result of `Task.cancel` (D365 — idempotent). */
1930
+ interface TaskCancelResult {
1931
+ readonly cancelled: boolean;
1932
+ readonly alreadyTerminal: boolean;
1933
+ }
1934
+ /**
1935
+ * Validates a task ID against the public grammar + reserved prefixes.
1936
+ * Throws `InvalidTaskIdError` from `../errors.js` on rejection.
1937
+ *
1938
+ * Adapter callers (workflow/batch/cron) MUST set `allowReserved: true`
1939
+ * to register their own IDs; user-facing surfaces (`Task.submit`,
1940
+ * `agent.send({ task: { id } })`) leave it false.
1941
+ */
1942
+ declare function isValidTaskId(id: string, allowReserved: boolean): boolean;
1943
+ /** Re-exported for adapter implementations + tests. */
1944
+ declare const TASK_RESERVED_PREFIXES: readonly string[];
1945
+
1946
+ /**
1947
+ * `Task` — observable async work registry (Adoption Roadmap gap #2,
1948
+ * ADRs D361-D374).
1949
+ *
1950
+ * Static facade delegating to the in-process `TaskRegistry` singleton.
1951
+ * The lifecycle of any task is the 5-state machine `queued | running |
1952
+ * finished | error | cancelled` (D362). Wrapping `Agent.send` /
1953
+ * `Agent.batch` / `Workflow.run` / `Cron` fires is opt-in via the
1954
+ * `{ task: true }` option on each (D363).
1955
+ *
1956
+ * @public
1957
+ */
1958
+
1959
+ interface TaskWorkContext {
1960
+ readonly signal: AbortSignal;
1961
+ emit(payload: unknown): void;
1962
+ }
1963
+ type TaskWorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;
1964
+ /**
1965
+ * Registry-level configuration. May only be applied BEFORE the first
1966
+ * `Task.submit` of the process — see EC-13. Subsequent calls emit a
1967
+ * single stderr line and become no-ops.
1968
+ */
1969
+ interface TaskConfigureOptions {
1970
+ readonly store?: TaskStoreOptions;
1971
+ readonly maxConcurrent?: number;
1972
+ readonly retentionMs?: number;
1973
+ }
1974
+ declare class Task {
1975
+ private constructor();
1976
+ /**
1977
+ * Configure the registry. **Must be called before the first `submit`**
1978
+ * (EC-13). Available knobs: pluggable store (D364), concurrency cap
1979
+ * (D369), and retention (D373).
1980
+ */
1981
+ static configure(opts: TaskConfigureOptions): void;
1982
+ /**
1983
+ * Submit a unit of asynchronous work to the registry.
1984
+ *
1985
+ * The `work` function receives `{ signal, emit }` — `signal` is the
1986
+ * AbortSignal honored on cancel; `emit(payload)` produces a
1987
+ * `progress` event observable via `Task.subscribe`.
1988
+ *
1989
+ * Returns a `TaskHandle` in `state: "queued"`. Subsequent state
1990
+ * transitions are observable via `Task.subscribe(handle.id)` OR
1991
+ * polled via `Task.get(handle.id)`.
1992
+ *
1993
+ * **Idempotency (D367):** submitting twice with the same `id` returns
1994
+ * the existing handle without re-invoking work.
1995
+ *
1996
+ * **Grammar (D368):** user-supplied ids must match
1997
+ * `^[a-z0-9][a-z0-9_-]*$` and must not start with reserved prefixes
1998
+ * `wf-` / `b-` / `cron-`. Otherwise `InvalidTaskIdError` is thrown.
1999
+ *
2000
+ * **Pre-aborted signal (EC-4):** if `options.signal` is already
2001
+ * aborted, the task short-circuits to `cancelled` without acquiring
2002
+ * a semaphore slot and without invoking `work`.
2003
+ */
2004
+ static submit<T>(kind: TaskKind, work: TaskWorkFn<T>, options?: TaskSubmitOptions): Promise<TaskHandle>;
2005
+ /** Returns matching handles, capped at `filter.limit ?? 100`. */
2006
+ static list(filter?: TaskFilter): Promise<TaskHandle[]>;
2007
+ /** Returns a single handle by id, or `undefined` if unknown / evicted. */
2008
+ static get(id: string): Promise<TaskHandle | undefined>;
2009
+ /**
2010
+ * Idempotent cancel (D365). Returns:
2011
+ * - `{ cancelled: true, alreadyTerminal: false }` — transitioned
2012
+ * queued/running task to `cancelled`.
2013
+ * - `{ cancelled: false, alreadyTerminal: true }` — task already
2014
+ * terminal.
2015
+ * - `{ cancelled: false, alreadyTerminal: false }` — task unknown.
2016
+ *
2017
+ * Never throws.
2018
+ */
2019
+ static cancel(id: string, reason?: string): Promise<TaskCancelResult>;
2020
+ /**
2021
+ * Subscribe to a task's event stream. The returned `AsyncIterable<TaskEvent>`
2022
+ * starts by replaying buffered events (ring buffer cap 64, D372) and
2023
+ * then yields live events until a terminal event (finished / errored
2024
+ * / cancelled) is emitted, at which point it closes automatically.
2025
+ *
2026
+ * Calling `.return()` on the iterator (or `break` in a `for await`)
2027
+ * cleans up the subscriber callback (EC-10).
2028
+ *
2029
+ * Throws `TaskNotFoundError` if the id is unknown or has been evicted.
2030
+ */
2031
+ static subscribe(id: string): AsyncIterable<TaskEvent>;
2032
+ }
2033
+
2034
+ /**
2035
+ * Dynamic provider catalog loader (T10.1, ADR D447).
2036
+ *
2037
+ * Loads provider metadata from `provider-catalog.json` at runtime.
2038
+ * Malformed entries are skipped with WARN (EC-1) — never crash.
2039
+ *
2040
+ * @internal
2041
+ */
2042
+
2043
+ interface ProviderCapabilities {
2044
+ supportsToolUse: boolean;
2045
+ supportsVision: boolean;
2046
+ supportsStructuredOutput: boolean;
2047
+ supportsStreaming: boolean;
2048
+ supportsCacheControl: boolean;
2049
+ maxContextTokens?: number;
2050
+ maxOutputTokens?: number;
2051
+ }
2052
+
2053
+ /**
2054
+ * Account-level user info returned by `Theokit.me()`.
2055
+ *
2056
+ * @public
2057
+ */
2058
+ interface SDKUser {
2059
+ apiKeyName: string;
2060
+ userEmail?: string;
2061
+ createdAt: string;
2062
+ }
2063
+ /**
2064
+ * Per-model parameter definition discovered from `Theokit.models.list()`.
2065
+ *
2066
+ * @public
2067
+ */
2068
+ interface ModelParameterDefinition {
2069
+ id: string;
2070
+ displayName?: string;
2071
+ values: Array<{
2072
+ value: string;
2073
+ displayName?: string;
2074
+ }>;
2075
+ }
2076
+ /**
2077
+ * Preset variant for a model — pre-filled parameter combinations.
2078
+ *
2079
+ * @public
2080
+ */
2081
+ interface ModelVariant {
2082
+ params: Array<{
2083
+ id: string;
2084
+ value: string;
2085
+ }>;
2086
+ displayName: string;
2087
+ description?: string;
2088
+ isDefault?: boolean;
2089
+ }
2090
+ /**
2091
+ * Single model entry in the catalog.
2092
+ *
2093
+ * @public
2094
+ */
2095
+ interface ModelListItem {
2096
+ id: string;
2097
+ /** Short, plain-text model name. Mirrors `displayName` for typical SDKs. */
2098
+ name?: string;
2099
+ displayName: string;
2100
+ description?: string;
2101
+ parameters?: ModelParameterDefinition[];
2102
+ variants?: ModelVariant[];
2103
+ }
2104
+ /** @public */
2105
+ type SDKModel = ModelListItem;
2106
+ /**
2107
+ * GitHub repository connected to the team. Cloud-only.
2108
+ *
2109
+ * @public
2110
+ */
2111
+ interface SDKRepository {
2112
+ url: string;
2113
+ }
2114
+
2115
+ /**
2116
+ * Options shared by every `Theokit.*` request.
2117
+ *
2118
+ * @public
2119
+ */
2120
+ interface TheokitRequestOptions {
2121
+ /** Override the `THEOKIT_API_KEY` env var for this call. */
2122
+ apiKey?: string;
2123
+ /**
2124
+ * Target a specific provider for catalog reads. When set to a provider
2125
+ * with `authType: "none"` (e.g. `"ollama"`, `"lmstudio"`, `"llamacpp"`),
2126
+ * `Theokit.models.list({ provider })` reads from the provider's local
2127
+ * `/v1/models` endpoint instead of the TheoCloud catalog. ADR D184.
2128
+ *
2129
+ * @public
2130
+ */
2131
+ provider?: string;
2132
+ }
2133
+ /**
2134
+ * Account-level and catalog reads. All methods accept an optional `apiKey`
2135
+ * and otherwise fall back to the `THEOKIT_API_KEY` environment variable.
2136
+ *
2137
+ * @public
2138
+ */
2139
+ declare class Theokit {
2140
+ private constructor();
2141
+ /**
2142
+ * Return the user behind the current API key.
2143
+ *
2144
+ * @public
2145
+ */
2146
+ static me(options?: TheokitRequestOptions): Promise<SDKUser>;
2147
+ /**
2148
+ * Model catalog reads.
2149
+ *
2150
+ * @public
2151
+ */
2152
+ static readonly models: {
2153
+ list: (options?: TheokitRequestOptions) => Promise<SDKModel[]>;
2154
+ capabilities: (providerOrModelId: string) => ProviderCapabilities | undefined;
2155
+ };
2156
+ /**
2157
+ * Connected GitHub repositories for the calling user's team. Cloud only.
2158
+ *
2159
+ * @public
2160
+ */
2161
+ static readonly repositories: {
2162
+ list: (options?: TheokitRequestOptions) => Promise<SDKRepository[]>;
2163
+ };
2164
+ /**
2165
+ * Provider catalog. Lists every provider known to the platform, including
2166
+ * plugin-registered ones, with capability and availability metadata.
2167
+ *
2168
+ * @public
2169
+ */
2170
+ static readonly providers: {
2171
+ list: (options?: TheokitRequestOptions) => Promise<SDKProvider[]>;
2172
+ };
2173
+ /**
2174
+ * Local introspection of bundled SDK assets (ADR D201). Unlike the
2175
+ * cloud-catalog `providers.list()` (which hits the TheoCloud HTTP API),
2176
+ * `inspect.*` reads the SDK's own bundled registries — useful for
2177
+ * tooling (e.g. `@theokit/cli`'s `theokit inspect`) that needs to know
2178
+ * what's available WITHOUT a network round-trip.
2179
+ *
2180
+ * @public
2181
+ */
2182
+ static readonly inspect: {
2183
+ builtinProviders: () => Array<{
2184
+ readonly name: string;
2185
+ readonly apiMode: string;
2186
+ readonly authType: string;
2187
+ readonly baseUrl: string;
2188
+ readonly aliases?: ReadonlyArray<string>;
2189
+ readonly envVars: ReadonlyArray<string>;
2190
+ }>;
2191
+ embeddingAdapters: () => Array<{
2192
+ readonly id: string;
2193
+ readonly transport: string;
2194
+ readonly defaultModel: string;
2195
+ }>;
2196
+ };
2197
+ }
2198
+
2199
+ /**
2200
+ * SE7 — `ToolError`: thrown FROM a tool `handler` to report a failure back to
2201
+ * the model with structured content (text and/or an image), not just a string.
2202
+ * Kept in its own module (not `errors.ts`) so the error taxonomy file stays
2203
+ * under the G8 LoC budget and this tool-shaped error lives next to the tool
2204
+ * surface it serves.
2205
+ *
2206
+ * @public
2207
+ */
2208
+
2209
+ /**
2210
+ * Thrown from a tool `handler` to surface a failure to the model. The SDK turns
2211
+ * it into a `tool_result` with `isError: true` carrying the content. A plain
2212
+ * `Error` thrown from a handler still works (its message becomes text);
2213
+ * `ToolError` is the opt-in for a clean message or a multimodal error (e.g. an
2214
+ * error screenshot).
2215
+ *
2216
+ * @public
2217
+ */
2218
+ declare class ToolError extends TheokitAgentError {
2219
+ readonly name: string;
2220
+ /** The error content surfaced to the model: a string, or text/image blocks. */
2221
+ readonly content: string | ToolResultContentBlock[];
2222
+ constructor(content: string | ToolResultContentBlock[], options?: {
2223
+ code?: string;
2224
+ cause?: unknown;
2225
+ metadata?: ErrorMetadata;
2226
+ });
2227
+ }
2228
+
2229
+ /**
2230
+ * Public types for ShareGPT trajectory export (ADR D139).
2231
+ *
2232
+ * Output format for fine-tuning datasets — consumed by HuggingFace, Axolotl,
2233
+ * LLaMA-Factory, and most modern fine-tuning toolchains. Pure data shape;
2234
+ * no runtime dependency.
2235
+ *
2236
+ * @public
2237
+ */
2238
+ /**
2239
+ * One ShareGPT message in a conversation. `from` identifies the role and
2240
+ * `value` carries the textual content. Tool calls live in `tool_calls`
2241
+ * (assistant-only) and tool results re-enter as `from: "tool"` entries.
2242
+ *
2243
+ * @public
2244
+ */
2245
+ interface ShareGptMessage {
2246
+ /** "human" for user, "gpt" for assistant, "tool" for tool result, "system" for system. */
2247
+ from: "human" | "gpt" | "tool" | "system";
2248
+ /** The message text. Empty string is valid (preserves turn boundary). */
2249
+ value: string;
2250
+ /** Optional tool calls — only emitted when `from === "gpt"`. */
2251
+ tool_calls?: Array<{
2252
+ name: string;
2253
+ arguments: Record<string, unknown>;
2254
+ }>;
2255
+ }
2256
+ /**
2257
+ * One full ShareGPT-format trajectory — a single conversation plus
2258
+ * metadata. JSONL-friendly (one trajectory per line when serialized).
2259
+ *
2260
+ * @public
2261
+ */
2262
+ interface ShareGptTrajectory {
2263
+ conversations: ShareGptMessage[];
2264
+ metadata?: {
2265
+ model?: string;
2266
+ timestamp: string;
2267
+ durationMs: number;
2268
+ promptIndex: number;
2269
+ };
2270
+ /** `true` when the source `BatchResult.ok === true`. Always `true` in current shape. */
2271
+ completed: boolean;
2272
+ /** Token usage when surfaced by the underlying RunResult (provider-specific). */
2273
+ usage?: {
2274
+ inputTokens: number;
2275
+ outputTokens: number;
2276
+ };
2277
+ }
2278
+
2279
+ /**
2280
+ * `toShareGptTrajectory` — opt-in BatchResult → ShareGPT converter (ADR D139).
2281
+ *
2282
+ * Pure transformation. Returns `null` for failed results so callers can
2283
+ * filter via `.map(toShareGptTrajectory).filter(Boolean)`. Tool calls and
2284
+ * tool results are preserved when an SDKMessage trace is provided; otherwise
2285
+ * a minimal `human → gpt` trajectory is emitted from the final text.
2286
+ *
2287
+ * @public
2288
+ */
2289
+
2290
+ /**
2291
+ * Convert a successful `BatchResult` to ShareGPT-format trajectory.
2292
+ *
2293
+ * Behavior:
2294
+ * - `result.ok === false` → returns `null` (EC-11).
2295
+ * - First entry is always `{from: "human", value: result.prompt}`.
2296
+ * - When `options.messages` is supplied, each SDKMessage maps to one or
2297
+ * more ShareGPT entries (assistant text → gpt, tool_use → gpt + tool).
2298
+ * - Without `options.messages`, fall back to a single `{from: "gpt"}`
2299
+ * entry carrying `result.result.result` (the final text) when present.
2300
+ * - Malformed message entries are silently skipped (EC-F / EC-14).
2301
+ *
2302
+ * @public
2303
+ */
2304
+ declare function toShareGptTrajectory(result: BatchResult, options?: {
2305
+ messages?: SDKMessage[];
2306
+ model?: string;
2307
+ }): ShareGptTrajectory | null;
2308
+
2309
+ export { Agent, AgentBuilder, AgentDefinition, AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, BudgetTracker, CloudOptions, ContextSettings, type CounterBudgetTrackerOptions, CustomTool, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, ErrorMetadata, EventBus, type EvictReason, GOAL_CONTINUATION_MARKER, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, GoalEvent, type GoalLoopAgent, GoalOptions, GoalResult, InlineSkill, JobQueue, type JobQueueOptions, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryId, MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, NoopMemoryProvider, type NormalizedJsonSchema, PermissionEngine, type PermissionGate, type PermissionGateContext, type PermissionGateDecision, PermissionMode, PermissionPlugin, type PermissionPluginOptions, Plugin, PluginsSettings, PreToolCallDecision, Processor, Provider, ProviderProfile, ProviderRoutingSettings, Run, RunEventSink, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type SessionScope, type ShareGptMessage, type ShareGptTrajectory, SkillReadTool, SkillsSettings, Squad, type SquadOptions, type SquadRun, 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, TokenLimiter, type TokenLimiterOptions, Tool, ToolError, ToolResultContentBlock, UnicodeNormalizer, type UnicodeNormalizerOptions, UsageAccumulator, chargeAndCheckThresholds, computeCost, createCounterBudgetTracker, estimateTokens, extractRawId, getPricingEntry, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, preflightCheck, runGoalLoop, scopedConversationId, sessionScopePrefix, toShareGptTrajectory, withCwdMutex };