@theokit/agents 16.0.0 → 16.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +47 -1
  3. package/dist/{agent-compiler-BMpuJFAI.d.ts → agent-compiler-JSYkHpa7.d.ts} +2 -2
  4. package/dist/{delegation-scoring-CURe4oSL.d.ts → agent-orchestrator-BFWg2URC.d.ts} +11 -426
  5. package/dist/agent-runner-BUJKNNuI.d.ts +364 -0
  6. package/dist/agent-sse-handler-BRp9vHrb.d.ts +348 -0
  7. package/dist/{bridge-entry-BxJWDpQP.d.ts → bridge-entry-BNWDrPzg.d.ts} +8 -422
  8. package/dist/bridge.d.ts +8 -5
  9. package/dist/bridge.js +19 -15
  10. package/dist/{chunk-4PHZ25JN.js → chunk-3TE4PJZL.js} +62 -1137
  11. package/dist/chunk-3TE4PJZL.js.map +1 -0
  12. package/dist/{chunk-FIGLHWR2.js → chunk-4SXVNI5O.js} +7 -7
  13. package/dist/chunk-A2UVVEB3.js +799 -0
  14. package/dist/chunk-A2UVVEB3.js.map +1 -0
  15. package/dist/chunk-Z5SYU6Z6.js +353 -0
  16. package/dist/chunk-Z5SYU6Z6.js.map +1 -0
  17. package/dist/delegation-scoring-Cn5eM4lQ.d.ts +79 -0
  18. package/dist/evals.d.ts +84 -0
  19. package/dist/evals.js +191 -0
  20. package/dist/evals.js.map +1 -0
  21. package/dist/handoff.d.ts +91 -0
  22. package/dist/handoff.js +268 -0
  23. package/dist/handoff.js.map +1 -0
  24. package/dist/index.d.ts +19 -369
  25. package/dist/index.js +36 -32
  26. package/dist/index.js.map +1 -1
  27. package/dist/mcp-health.d.ts +1 -1
  28. package/dist/sdk-adapter-DQnKx7bA.d.ts +435 -0
  29. package/dist/testing.d.ts +2 -2
  30. package/dist/tools.d.ts +5 -3
  31. package/dist/tools.js +10 -6
  32. package/dist/tools.js.map +1 -1
  33. package/dist/{types-DdltPCj2.d.ts → types-D5cHmSLi.d.ts} +1 -1
  34. package/docs/capability-map.md +31 -1
  35. package/package.json +12 -2
  36. package/dist/chunk-4PHZ25JN.js.map +0 -1
  37. /package/dist/{chunk-FIGLHWR2.js.map → chunk-4SXVNI5O.js.map} +0 -0
@@ -1,15 +1,17 @@
1
1
  import { ExecutionContext } from '@theokit/http';
2
- import { c as AgentOptions, T as ToolOptions, P as ProjectContextOptions, H as HumanInTheLoopOptions, R as ReasoningEffort, M as McpServersMap } from './types-DdltPCj2.js';
3
- import { C as CompiledAgentOptions, A as AgentDefinition, a as CompiledTool, G as Guardrail, m as SkillsSelection, s as SubagentAgentDefinition, H as HookApprovalGate, t as CodePlugin } from './agent-compiler-BMpuJFAI.js';
4
- import { SkillsSettings, ContextSettings, SystemPromptResolver, ModelSelection, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition as AgentDefinition$1, BudgetTracker, CustomTool, RunEventSink, MemorySettings, TelemetrySettings, PermissionRule } from '@theokit/sdk';
5
- import { S as StreamEvent, f as ApprovalRequiredEvent, a5 as MaskError } from './delegation-scoring-CURe4oSL.js';
6
- import { RetryOptions } from '@theokit/sdk/retry';
2
+ import { c as AgentOptions, T as ToolOptions, P as ProjectContextOptions, R as ReasoningEffort, H as HumanInTheLoopOptions, a as McpServersMap } from './types-D5cHmSLi.js';
3
+ import { a as CompiledAgentOptions, G as Guardrail, m as SkillsSelection, s as SubagentAgentDefinition, H as HookApprovalGate, t as CodePlugin, A as AgentDefinition } from './agent-compiler-JSYkHpa7.js';
4
+ import { SkillsSettings, ContextSettings, SystemPromptResolver, ModelSelection, CustomTool, MemorySettings, TelemetrySettings, PermissionRule, Plugin } from '@theokit/sdk';
5
+ import { S as StreamEvent, M as MaskError } from './agent-sse-handler-BRp9vHrb.js';
6
+ import { R as RuntimeOverrides, f as HitlWiring } from './sdk-adapter-DQnKx7bA.js';
7
7
  import { SandboxPosture } from '@theokit/sdk/sandbox';
8
8
  import { z } from 'zod';
9
9
  import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
10
10
  import { S as SettingSourcesSelection } from './setting-sources-gate-BJJiKq33.js';
11
11
  import { WireChunk } from '@theokit/presenter/wire';
12
12
  import { TheokitAgentError } from '@theokit/sdk/errors';
13
+ import './agent-orchestrator-BFWg2URC.js';
14
+ import './delegation-scoring-Cn5eM4lQ.js';
13
15
 
14
16
  /**
15
17
  * AgentExecutionContext — extends http-decorators' ExecutionContext with agent-specific methods.
@@ -171,422 +173,6 @@ interface AgentRouteContext {
171
173
  /** Generate HTTP routes for a single agent. Returns Web Standard handlers. */
172
174
  declare function generateAgentRoutes(ctx: AgentRouteContext): AgentRoute[];
173
175
 
174
- /**
175
- * M4 (theokit-ai-first) — the HITL producer: a `pre_tool_call` plugin that pauses the SDK run
176
- * for a human-in-the-loop tool approval.
177
- *
178
- * ADR 0038: this is the ADAPTER seam — it makes the shipped-but-dead `@HumanInTheLoop` decorator
179
- * FUNCTIONAL by wiring the SDK's OWN async `pre_tool_call` veto hook (which the SDK loop `await`s,
180
- * so returning a pending Promise genuinely PAUSES the run) to a human approval. It calls no LLM,
181
- * dispatches no tool, and runs no second loop — the SDK owns all of that.
182
- *
183
- * Flow: gated tool about to run → emit an `ApprovalRequiredEvent` (which the translator maps to
184
- * the ai-sdk `tool-approval-request` chunk) → `await awaitApproval(approvalId)` (resolved by the
185
- * out-of-band approve route) → allow (`undefined`) or veto (`{ block, message }`, which the SDK
186
- * surfaces as a tool result the model self-corrects on).
187
- */
188
-
189
- /**
190
- * M20 — a settled HITL decision. Structural mirror of the harness's `ApprovalDecision` (the agents
191
- * package must not import from `theokit` — dependency direction). `awaitApproval` may resolve a bare
192
- * boolean (legacy) OR this object; the plugin normalizes both.
193
- */
194
- interface HitlDecision {
195
- approved: boolean;
196
- reason?: string;
197
- payload?: unknown;
198
- /**
199
- * What settled this, when it was not a person (usetheokit/theokit#393).
200
- *
201
- * Mirrors `ApprovalDecision.settledBy` in `theokit`, for the reason the comment above this
202
- * interface gives: this package must not import from `theokit`. Absent means the decision came
203
- * through the approve route; `'timeout'` means the window closed with nobody deciding.
204
- */
205
- settledBy?: 'timeout';
206
- }
207
- /** Injected wiring — the harness (mount-agent) supplies these; the plugin stays pure. */
208
- interface HitlWiring {
209
- /** Tool name → its `@HumanInTheLoop` config. A tool absent here is NOT gated. */
210
- gated: Map<string, HumanInTheLoopOptions>;
211
- /** Push the approval-required event into the agent stream (the translator emits the chunk). */
212
- emit: (event: ApprovalRequiredEvent) => void;
213
- /**
214
- * Await the human decision for `approvalId`; resolves approve/deny (or timeout). M20 — may resolve
215
- * a bare boolean (legacy) OR a {@link HitlDecision} carrying an approver `reason` + `payload`.
216
- */
217
- awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions, toolName: string) => Promise<boolean | HitlDecision>;
218
- /**
219
- * OPTIONAL — reach the owner off the stream (usetheokit/theokit#458).
220
- *
221
- * `emit` above puts the pause into the run's own event stream, and that was the only egress: a
222
- * caller not currently consuming it never learned the run was waiting, so the framework's
223
- * asynchronous promise held exactly as long as someone was watching.
224
- *
225
- * This receives the same facts the stream carries and does whatever the APPLICATION does — Slack,
226
- * email, a row in a table. Deliberately not a `@theokit/gateway` dependency: this package must not
227
- * import from it, and picking a channel is a policy decision the framework does not get to make.
228
- *
229
- * Fire-and-forget by contract. The run does not wait for it and does not fail on it: a dispatch
230
- * outage must not decide whether a gated tool runs, and must not delay the pause it announces.
231
- */
232
- onApprovalRequired?: (request: ApprovalRequest) => void | Promise<void>;
233
- }
234
- /** What an application is told when a gated tool pauses. The stream's facts, off the stream. */
235
- interface ApprovalRequest {
236
- approvalId: string;
237
- toolName: string;
238
- question: string;
239
- input: unknown;
240
- /** Relative, exactly as the stream carries it — the app knows its own base URL; this does not. */
241
- callbackUrl: string;
242
- timeoutMs: number;
243
- }
244
-
245
- /**
246
- * M96 U1 — the approval posture: what a surface does when a gated tool asks for approval.
247
- *
248
- * ## Why a closed type, and why mandatory
249
- *
250
- * The defect this module closes was one of TYPE, not of behaviour. The "no HITL" posture was not
251
- * representable as a value, so it was expressed as ABSENCE — and an absence has no exhaustive
252
- * `match`, appears in no log, and fails no test. `toAgentFactory` compiled the `compiled.hitl` map
253
- * that `.approvals({…})` produces and threw it away, with the discard admitted in writing in the
254
- * JSDoc, while the sibling bridge REFUSED for the same definition.
255
- *
256
- * The permissive posture remains entirely expressible — as a NAMED VALUE, with a written reason.
257
- * What stops existing is the omission.
258
- *
259
- * ## Os peers
260
- *
261
- * `codex` models the posture as a four-variant `enum AskForApproval` in the protocol crate, and
262
- * makes forgetting it a compile error through the `ToolRuntime: Approvable + Sandboxable` supertrait;
263
- * a mandatory field is the closest this type system gets to that.
264
- *
265
- * Omission resolves in the safe direction — never auto-approved — and the human's stand-in is named
266
- * rather than inferred from the absence of one.
267
- */
268
-
269
- /** The map of gated tools that `compileAgentDefinition` produces (`compiled.hitl`). */
270
- type GatedTools = ReadonlyMap<string, HumanInTheLoopOptions>;
271
- /**
272
- * What this surface does when a gated tool asks for approval. Four variants, none of them
273
- * "omission" — each with a concrete consumer and a written reason.
274
- */
275
- type ApprovalPosture = {
276
- /** There is a human: the request is EMITTED and execution pauses until the decision arrives. */
277
- kind: 'interactive';
278
- /**
279
- * Pushes the `ApprovalRequiredEvent` into the surface's stream. MANDATORY: `toAgentFactory`
280
- * returns a raw handle, with no stream and no translator, so the sink comes from whoever passes
281
- * the posture — which is precisely the surface that owns the stream. A no-op default would
282
- * bring the silent discard back through the back door: the request would be "emitted" nowhere.
283
- */
284
- emit: (event: ApprovalRequiredEvent) => void;
285
- /** Resolves the human decision; execution stays paused until this settles. */
286
- awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions, toolName: string) => Promise<boolean | HitlDecision>;
287
- } | {
288
- /** Nobody asks and the tool runs. Legitimate only when something else confines the execution. */
289
- kind: 'auto-approve';
290
- /**
291
- * M77 — the EVIDENCE that something else confines the execution. Not optional, and not a
292
- * string.
293
- *
294
- * This is the most consequential decision a coding agent makes — "run commands without
295
- * asking" — and until M77 its type asked only for a `reason: string`. A string is
296
- * unverifiable at the seam: nothing could tell "confined by bwrap, kernel-enforced" from
297
- * "I'm sure it's fine". So the consumer implemented the refusal itself, TWICE
298
- * (`shouldAutoApprove` in the TUI, `resolveHeadlessApproval` in the headless path), with the
299
- * same rule in both — an absent posture counts as unconfined. A security rule duplicated
300
- * across two call sites is a rule that will eventually disagree with itself (G12).
301
- *
302
- * `SandboxPosture` is the SDK's own honest answer to "am I kernel-enforced right now?", and
303
- * it carries `detail` so a refusal can say WHY rather than just "unconfined". Requiring it
304
- * makes the unconfined case unrepresentable at the type level; {@link applyPosture} refuses
305
- * it at runtime for the caller who casts past the type.
306
- */
307
- confinedBy: SandboxPosture;
308
- reason: string;
309
- } | {
310
- /** Nobody asks and the tool does NOT run — the safe reading of omission (codex `GranularApprovalConfig`). */
311
- kind: 'auto-reject';
312
- reason: string;
313
- } | {
314
- /**
315
- * The gate is driven by the SERVING SURFACE (the ACP client, through the protocol itself), so
316
- * the layer installs no plugin at all. It is a bypass — but a NAMED bypass, with a written
317
- * reason, that shows up in the `match`, shows up in logs and can be counted by a gate. What it
318
- * replaces is worse: today the same effect happens by omission, with none of that.
319
- */
320
- kind: 'owned-by-surface';
321
- reason: string;
322
- };
323
- /**
324
- * Writes the plugins the posture requires into `extra` — the object `toAgentFactory` spreads AFTER
325
- * `m8` into the `Agent.create` options, and which therefore wins. Plugins already present (from the
326
- * agent, via `m8`, and from an override, via `extra`) are preserved: running them over is the M14
327
- * regression that `buildExtraCreateOptions` already carries a guard against.
328
- *
329
- * The legacy `plugins` shape (an `{ enabled }` object) cannot carry both, so a posture that needs to
330
- * install a plugin alongside it is refused LOUD AND CLEAR, rather than resolved by dropping one of
331
- * them: silently dropping the approval gate is exactly the class of defect this milestone closes
332
- * (Rule 8, fail-closed).
333
- */
334
- declare function applyPosture(extra: Record<string, unknown>, m8: {
335
- plugins?: unknown;
336
- }, posturePolicy: ApprovalPosture, gated: GatedTools | undefined): void;
337
-
338
- /**
339
- * A definition, or a THUNK that produces one per session.
340
- *
341
- * M91 — the `apiKey` line just below has accepted a thunk since M74, added for **exactly** this
342
- * reason. The asymmetry was one line wide and cost a lot: with the object shape, trust, hooks, skills
343
- * and MCP are frozen at module load. In a `theokit acp` process an IDE keeps open for hours, that
344
- * reintroduces the staleness M67 removed by moving construction to the entry point.
345
- */
346
- type DefinitionOrThunk = AgentDefinition | ((sessionId: string) => AgentDefinition | Promise<AgentDefinition>);
347
-
348
- /**
349
- * SDK Adapter — bridges @theokit/agents decorators → @theokit/sdk runtime.
350
- *
351
- * Per rule sdk-runtime.md (UNBREAKABLE): @theokit/sdk is the ONLY agent runtime.
352
- * This adapter replaces llm-runner.ts (which called OpenRouter API directly).
353
- *
354
- * Flow: @Agent decorator → compileAgent() → createSdkAgentStream() → SDK Agent.create() → Run.stream()
355
- */
356
-
357
- /**
358
- * Per-request overrides forwarded into `Agent.create` (V4-L.2 + V4-L.3). Bundled into
359
- * one object (rather than positional params) so the per-request surface can grow without
360
- * a parameter explosion. Each field is Axis-A SWAP — a value the app holds at call time.
361
- */
362
- /**
363
- * A multimodal image for a send turn — the SDK's `SDKImage` shape, typed locally because `@theokit/sdk`
364
- * is an optional peer (dynamic import). Either a URL or inline base64 `{ data, mimeType }`.
365
- */
366
- type BridgeImage = {
367
- url: string;
368
- } | {
369
- data: string;
370
- mimeType: string;
371
- };
372
- interface RuntimeOverrides {
373
- /** Overrides the model for this call (`?? compiled.model ?? default`). */
374
- model?: string | ModelSelection;
375
- /**
376
- * M35 (multimodal) — images to send alongside the text. When present, the SDK send switches from the
377
- * plain-string form to the structured `{ text, images }` form (`SDKUserMessage`). Absent ⇒ the
378
- * string path is byte-unchanged (back-compat).
379
- */
380
- images?: readonly BridgeImage[];
381
- /**
382
- * Per-run extended-thinking effort (`?? compiled.reasoningEffort`). Mapped to the SDK
383
- * `ModelSelection.params` so the provider produces reasoning (surfaced as `thinking` StreamEvents).
384
- */
385
- reasoningEffort?: ReasoningEffort;
386
- /**
387
- * Per-run opt-in (`?? compiled.parseThinkTags`): when true, wrap the event stream with the M2
388
- * `<think>`-tag extractor so inline `<think>…</think>` text becomes `thinking` StreamEvents.
389
- */
390
- parseThinkTags?: boolean;
391
- /**
392
- * Per-run opt-in (`?? compiled.stripToolDialect`): when true, strip a leaked Hermes
393
- * `<function=…></tool_call>` tool-call dialect out of the assistant text stream (theocode#32).
394
- */
395
- stripToolDialect?: boolean;
396
- /**
397
- * Per-run opt-in (`?? compiled.recoverLeakedToolCalls`): when true, enable the SDK chat route's
398
- * `extractToolCallsFromContent` so a leaked Hermes `<function=…></tool_call>` dialect is recovered
399
- * and EXECUTED (theokit#58). Sibling of {@link stripToolDialect}; has effect only when {@link providers}
400
- * routes a provider.
401
- */
402
- recoverLeakedToolCalls?: boolean;
403
- /** Per-run cwd → `Agent.create({ local: { cwd } })` → `SystemPromptContext.cwd`. */
404
- cwd?: string;
405
- /**
406
- * M7 — per-run run-context override (`?? compiled.runContext`). Injected into every tool
407
- * handler's `ctx.context` by `buildSdkTools`. Lets a single request override the agent-level
408
- * `defineAgent({ context })` (mirrors `model`/`cwd`).
409
- */
410
- runContext?: Record<string, unknown>;
411
- /**
412
- * Per-run plugins (e.g. permission gate selected by request mode). Accepts EITHER
413
- * named-plugin discovery settings (`{ enabled: [...] }`) OR an array of code `Plugin`
414
- * objects, forwarded RAW through the duck-typed `Agent.create` bridge (mirrors the
415
- * @theokit/sdk `AgentOptions.plugins` widen).
416
- */
417
- plugins?: PluginsSettings | readonly Plugin[];
418
- /** Per-run provider routing. */
419
- providers?: ProviderRoutingSettings;
420
- /** Per-run sub-agent definitions (opts-only; `compiled.agents` stays deferred — ADR D3). */
421
- agents?: Record<string, AgentDefinition$1>;
422
- /** Per-run SDK budget tracker (inner tool-loop cap; distinct from the loop's USD `budget`). */
423
- budgetTracker?: BudgetTracker;
424
- /**
425
- * SDK 4.0 (SE40) — root of the native Claude-shaped `.jsonl` session transcript the SDK writes
426
- * automatically (`<root>/projects/<encoded-cwd>/<agentId>.jsonl`). The framework threads the
427
- * app's project root here (see `mount-agent`) so sessions persist per-app; unset ⇒ SDK default
428
- * (`~/.theokit`). Replaces the removed pluggable `conversationStorage` — persistence is now the
429
- * SDK's native transcript, not a swappable adapter.
430
- *
431
- * Forwarded to the SDK as `local.baseDir`, which that package deprecated in its own #301 in favour
432
- * of `sessionDir`. It stays `baseDir` on purpose: `sessionDir` does not exist at `^4.52.1`, the
433
- * floor this package declares, so switching would type-error on the floor and — worse — silently
434
- * send the transcript to the SDK default `~/.theokit` for any consumer resolving there, losing
435
- * per-app persistence. Migrating the name is a floor bump, not a rename, and the deprecated field
436
- * is still honoured. Attempted and reverted rather than assumed: the typecheck gate caught it.
437
- *
438
- * **Setting this also relocates the agent's durable MEMORY**, which the SDK's own docstring for
439
- * the field denies ("Only transcripts are written here"). `MEMORY.md` moves from
440
- * `<cwd>/.theokit/memory/` to `<root>/projects/<encoded-cwd>/memory/`, while `.index/` and
441
- * `sessions/` stay behind — so the store looks alive and the capture looks broken. Since the
442
- * mount sets this unconditionally, it applies to every agent the framework serves.
443
- *
444
- * Measured against `@theokit/sdk` 4.62.0 and filed as usetheokit/theokit-sdk#463; the downstream
445
- * report is usetheokit/theokit#557. Documented here rather than worked around because one SDK
446
- * field governs both roots — there is no way to place them separately from this side.
447
- */
448
- baseDir?: string;
449
- /**
450
- * V4-Q: pre-built SDK `CustomTool[]` forwarded RAW to `Agent.create.tools` (appended after the
451
- * compiled tools), bypassing `defineTool` (which requires a Zod schema). Lets an app whose tools
452
- * come from imperative SDK factories supply them without the `@Tool` compile path.
453
- */
454
- sdkTools?: readonly CustomTool[];
455
- /**
456
- * theokit#132 — sink for the SDK's typed `RunEvent`s (`tool_progress`, `rate_limit`,
457
- * `permission_denied`, `task_*`, `compact_boundary`, `tripwire`, `completion_check`), threaded
458
- * straight to `SendOptions.onRunEvent`.
459
- *
460
- * Threaded, NOT multiplexed into the UIMessage stream. These are run diagnostics for an observer —
461
- * theokit-studio's event inspector is the demand that opened the issue — and folding them into the
462
- * message protocol would force every consumer of the chat stream to know about frames it has no
463
- * use for. Threading leaves the chat path byte-identical for anyone who does not opt in, which is
464
- * why the key is omitted entirely rather than set to `undefined` when absent.
465
- */
466
- onRunEvent?: RunEventSink;
467
- /**
468
- * theokit#474 — per-turn transient retry, opt-in.
469
- *
470
- * When set, the START of the turn (the SDK handshake plus its first event, before anything is
471
- * yielded) is wrapped in the SDK `Retry`, so a 429/5xx/network blip that kills the turn before it
472
- * produced anything is recovered instead of ending it. Absent ⇒ a single attempt, and the key is
473
- * omitted from every downstream call, so the stream is byte-identical to before.
474
- *
475
- * See `turn-retry.ts` for why a rejection-shaped retry would have been inert on this path, and
476
- * for the invariant that closes the retry window on the first event.
477
- */
478
- retry?: RetryOptions;
479
- /**
480
- * theokit#475 — expose the run's REAL token usage to tool handlers as `ctx.usage`, opt-in.
481
- *
482
- * When true, the adapter installs a {@link RunUsageMeter} as the run's `budgetTracker` (wrapping
483
- * the caller's own, when there is one) and hands every tool handler a snapshot of what the
484
- * provider has reported so far. A tool can then answer "how much context is left?" from a
485
- * measurement instead of a character-count estimate. See `usage/run-usage.ts`.
486
- *
487
- * Opt-in rather than always-on because installing a `budgetTracker` changes what `Agent.create`
488
- * receives for every run that never asked for it, and the back-compat floor here is a floor, not
489
- * a preference. Absent ⇒ handlers are wrapped exactly as before (`ctx.usage` does not exist) and
490
- * the SDK receives no tracker it was not already given.
491
- */
492
- exposeUsageToTools?: boolean;
493
- }
494
- declare function createSdkAgentStream(compiled: CompiledAgentOptions, compiledTools: CompiledTool[], apiKey: string | (() => string | Promise<string>), overrides?: RuntimeOverrides): ((message: string, sessionId: string, factoryOpts?: {
495
- disableTools?: boolean;
496
- }) => AsyncIterable<StreamEvent>) & {
497
- resolvedModel: string | ModelSelection;
498
- };
499
- /**
500
- * The minimal `SDKAgent` surface a serving host needs (ACP checks `agentId: string` + `send: fn`).
501
- * `Agent.getOrCreate` returns the real SDK agent — this alias just types what {@link toAgentFactory}
502
- * hands back without re-exporting the full `@theokit/sdk` `Agent` type.
503
- */
504
- /**
505
- * The minimum a turn returns. Structural on purpose (M91's ADR-2).
506
- *
507
- * Re-exporting the SDK's type would tie this layer's public signature to theirs — the opposite of
508
- * what the boundary exists to do, and the same reason `SdkAgentHandle` was already an alias rather
509
- * than a
510
- * re-export.
511
- */
512
- interface SdkTurnHandle {
513
- wait: () => Promise<{
514
- result?: string;
515
- usage?: {
516
- totalTokens?: number;
517
- };
518
- }>;
519
- }
520
- /** Per-turn options. Open for now — the SDK accepts more than the layer needs to declare. */
521
- type SdkSendOptions = Record<string, unknown>;
522
- interface SdkAgentHandle {
523
- readonly agentId: string;
524
- /**
525
- * B-062 — a tool-using run that returns schema-validated output.
526
- *
527
- * The SDK's `agent.generate(input, { output })` "runs the agent's NORMAL tool loop (the user's
528
- * tools run first) and then coerces the final answer into a Zod schema". It existed and this
529
- * handle did not declare it, so a consumer of `@theokit/agents` could reach it only by importing
530
- * `@theokit/sdk` directly — the one thing this layer's doctrine forbids.
531
- *
532
- * The survey that filed this concluded the capability was absent, having measured `generateObject`
533
- * — which is the TOOLLESS path by design: it builds a transient agent whose only tool is the
534
- * synthetic output tool. Both paths exist and answer different questions.
535
- *
536
- * OPTIONAL, because a caller-injected handle (tests, a custom transport) need not implement it,
537
- * and requiring it would break every such double to add a method most of them never call.
538
- *
539
- * BOTH wrappers below forward it. A wrapper that rebuilds the handle silently removes every method
540
- * it does not name, and the consumer meets the loss at runtime as "the handle has no `generate`"
541
- * after the types said it had one. Each forward is pinned by its own mutation.
542
- *
543
- * It is NOT put through the output guards, stated rather than assumed: `generate` resolves to a
544
- * validated OBJECT and those guards moderate TEXT, so running them over a serialised object would
545
- * moderate a shape no guard was written against. Guarding the structured path needs its own
546
- * decision about what a redaction means to a schema, and inventing one would be the gate that
547
- * reports without gating this module already refuses to build.
548
- */
549
- readonly generate?: (message: string, options: {
550
- output: unknown;
551
- [key: string]: unknown;
552
- }) => Promise<unknown>;
553
- /**
554
- * M91 — era `(msg: string, opts?: unknown) => unknown`.
555
- *
556
- * The `unknown` return cost the consumer a whole module: `agents/lib/goal/runner-facade.ts`, 38
557
- * lines whose only job was to re-narrow this return into the `send → wait` contract the goal loop
558
- * requires. That module's docstring records that, before it, the caller wrote `as never` — and that
559
- * **it was under that cover that the goal surface diverged from the real agent for several
560
- * milestones**. The layer always knew the shape; it simply did not declare it.
561
- *
562
- * The shape is **asynchronous**: `SDKAgent.send` returns `Promise<Run>`, and the SDK's
563
- * `GoalLoopAgent` declares `send(prompt): Promise<{ wait(): Promise<…> }>`. This milestone's first
564
- * attempt typed it as synchronous and the consumer's `tsc` would not have caught it — the facade's
565
- * `as never` absorbed the difference. It is literally the divergence the facade's docstring
566
- * described, met again while trying to remove it.
567
- */
568
- send: (msg: string, opts?: SdkSendOptions) => Promise<SdkTurnHandle>;
569
- dispose: () => Promise<void>;
570
- }
571
- /**
572
- * #12 — bridge a builder/`defineAgent` {@link TheokitAgentDefinition} to a real `SDKAgent` FACTORY,
573
- * so surfaces that require an `SDKAgent` (or `(sessionId) => SDKAgent`) — notably `theokit acp`,
574
- * whose entry default-export must be one — can serve an agent defined with the `AgentBuilder.create()` chain.
575
- *
576
- * The factory reuses the SAME projection the streaming path uses (`compileAgentDefinition` → tools /
577
- * model / `assembleM8CreateOptions`), so the served agent has identical tools, model, system prompt,
578
- * skills, and `mcpServers`. Keyed per `sessionId` via `Agent.getOrCreate` (matches the run path).
579
- *
580
- * M96 — the surface DECLARES its {@link ApprovalPosture} and the factory installs the plugin the
581
- * variant requires. Before, the `compiled.hitl` map was compiled and DISCARDED here. Rationale in
582
- * `./approval-posture.ts`.
583
- */
584
- declare function toAgentFactory(def: DefinitionOrThunk, opts: {
585
- apiKey: string | (() => string | Promise<string>);
586
- approvals: ApprovalPosture;
587
- overrides?: RuntimeOverrides;
588
- }): (sessionId: string) => Promise<SdkAgentHandle>;
589
-
590
176
  /**
591
177
  * T2.1 — "may I auto-approve this tool right now?", as a symbol a surface can call.
592
178
  *
@@ -1746,4 +1332,4 @@ declare function agentsPlugin(opts: AgentsPluginOptions): {
1746
1332
  register(app: PluginApp): void;
1747
1333
  };
1748
1334
 
1749
- export { compileContextWindow as $, type AgentManifestEntry as A, type BeforeToolCallContext as B, type ContextWindowOptions as C, type DefinitionOrThunk as D, type EphemeralAgent as E, type McpSelection as F, type ProcessInputContext as G, type HitlDecision as H, type SdkAgentHandle as I, type SdkMessage as J, type SdkSendOptions as K, type LLMCallContext as L, type McpApprovalSpec as M, type SdkTurnHandle as N, type Segment as O, type PermissionsPluginOptions as P, type ShouldAutoApproveOptions as Q, type RuntimeOverrides as R, type SkillsOptions as S, type ToolCallVeto as T, type ToolHooks as U, type ToolHooksPlugin as V, WRITE_SCOPED_TOOLS as W, agentsPlugin as X, applyPosture as Y, buildModelSelection as Z, compileAgentModule as _, type ApprovalPosture as a, compileLoadedAgentModule as a0, compileProjectContext as a1, compileSkills as a2, createAgentExecutionContext as a3, createApiErrorHandler as a4, createPermissionsPlugin as a5, createSdkAgentStream as a6, createThinkTagExtractor as a7, createToolHooksPlugin as a8, extractThinkTagStream as a9, generateAgentManifest as aa, generateAgentRoutes as ab, isAgentContext as ac, loadMcpJson as ad, loadPersonalMcpServers as ae, mcpRegistry as af, mcpToolApprovals as ag, projectContextMetadataOnlyKnobs as ah, reasoningEffortOf as ai, resolveMcpServers as aj, runWithApiErrorHandling as ak, shouldAutoApprove as al, toAgentFactory as am, translateSdkEvent as an, withClockCap as ao, withEphemeralAgent as ap, type AgentModule as b, APPROVAL_MODES as c, type AfterToolCallContext as d, AgentBuilder as e, AgentDefinitionError as f, type AgentExecutionContext as g, type AgentManifest as h, type AgentManifestSource as i, type AgentManifestTool as j, type AgentRoute as k, type AgentRouteContext as l, type AgentRunInfo as m, type AgentsPluginOptions as n, type ApiErrorContext as o, type ApiErrorDecision as p, type ApiErrorPolicy as q, type ApprovalMode as r, streamAgentUIMessages as s, type ApprovalRequest as t, type CompiledContextWindow as u, ContextualTool as v, DelegationTimeoutError as w, McpFileError as x, type McpRegistryConfig as y, type McpRequestContext as z };
1335
+ export { extractThinkTagStream as $, type AgentManifestEntry as A, type BeforeToolCallContext as B, type ContextWindowOptions as C, DelegationTimeoutError as D, type EphemeralAgent as E, type Segment as F, type ShouldAutoApproveOptions as G, type ToolHooks as H, type ToolHooksPlugin as I, agentsPlugin as J, buildModelSelection as K, type LLMCallContext as L, type McpApprovalSpec as M, compileAgentModule as N, compileContextWindow as O, type PermissionsPluginOptions as P, compileLoadedAgentModule as Q, compileProjectContext as R, type SkillsOptions as S, type ToolCallVeto as T, compileSkills as U, createAgentExecutionContext as V, WRITE_SCOPED_TOOLS as W, createApiErrorHandler as X, createPermissionsPlugin as Y, createThinkTagExtractor as Z, createToolHooksPlugin as _, type AgentModule as a, generateAgentManifest as a0, generateAgentRoutes as a1, isAgentContext as a2, loadMcpJson as a3, loadPersonalMcpServers as a4, mcpRegistry as a5, mcpToolApprovals as a6, projectContextMetadataOnlyKnobs as a7, reasoningEffortOf as a8, resolveMcpServers as a9, runWithApiErrorHandling as aa, shouldAutoApprove as ab, translateSdkEvent as ac, withClockCap as ad, withEphemeralAgent as ae, APPROVAL_MODES as b, type AfterToolCallContext as c, AgentBuilder as d, AgentDefinitionError as e, type AgentExecutionContext as f, type AgentManifest as g, type AgentManifestSource as h, type AgentManifestTool as i, type AgentRoute as j, type AgentRouteContext as k, type AgentRunInfo as l, type AgentsPluginOptions as m, type ApiErrorContext as n, type ApiErrorDecision as o, type ApiErrorPolicy as p, type ApprovalMode as q, type CompiledContextWindow as r, streamAgentUIMessages as s, ContextualTool as t, McpFileError as u, type McpRegistryConfig as v, type McpRequestContext as w, type McpSelection as x, type ProcessInputContext as y, type SdkMessage as z };
package/dist/bridge.d.ts CHANGED
@@ -1,14 +1,17 @@
1
- export { c as APPROVAL_MODES, d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinitionError, g as AgentExecutionContext, h as AgentManifest, A as AgentManifestEntry, i as AgentManifestSource, j as AgentManifestTool, b as AgentModule, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentsPluginOptions, o as ApiErrorContext, p as ApiErrorDecision, q as ApiErrorPolicy, r as ApprovalMode, a as ApprovalPosture, B as BeforeToolCallContext, u as CompiledContextWindow, v as ContextualTool, D as DefinitionOrThunk, w as DelegationTimeoutError, E as EphemeralAgent, L as LLMCallContext, M as McpApprovalSpec, x as McpFileError, y as McpRegistryConfig, z as McpRequestContext, F as McpSelection, P as PermissionsPluginOptions, G as ProcessInputContext, I as SdkAgentHandle, J as SdkMessage, K as SdkSendOptions, N as SdkTurnHandle, O as Segment, Q as ShouldAutoApproveOptions, T as ToolCallVeto, U as ToolHooks, V as ToolHooksPlugin, W as WRITE_SCOPED_TOOLS, X as agentsPlugin, Y as applyPosture, Z as buildModelSelection, _ as compileAgentModule, $ as compileContextWindow, a0 as compileLoadedAgentModule, a1 as compileProjectContext, a2 as compileSkills, a3 as createAgentExecutionContext, a4 as createApiErrorHandler, a5 as createPermissionsPlugin, a6 as createSdkAgentStream, a7 as createThinkTagExtractor, a8 as createToolHooksPlugin, a9 as extractThinkTagStream, aa as generateAgentManifest, ab as generateAgentRoutes, ac as isAgentContext, ad as loadMcpJson, ae as loadPersonalMcpServers, af as mcpRegistry, ag as mcpToolApprovals, ah as projectContextMetadataOnlyKnobs, ai as reasoningEffortOf, aj as resolveMcpServers, ak as runWithApiErrorHandling, al as shouldAutoApprove, s as streamAgentUIMessages, am as toAgentFactory, an as translateSdkEvent, ao as withClockCap, ap as withEphemeralAgent } from './bridge-entry-BxJWDpQP.js';
2
- export { b as AGENT_BRAND, A as AgentDefinition, c as CompatImportUnsupportedError, C as CompiledAgentOptions, a as CompiledTool, D as DefineAgentConfig, H as HookApprovalGate, j as HookApprovalRequest, k as HookGateUnsupportedError, I as InferAgentInput, l as InferAgentToolNames, T as ToolWalkResult, n as ToolboxWalkResult, o as compileAgentDefinition, p as compileTools, q as isAgentDefinition } from './agent-compiler-BMpuJFAI.js';
3
- export { A as AgentStopReason, d as AgentStreamEvent, e as AgentTurnMetadata, f as ApprovalRequiredEvent, g as ArtifactChunkEvent, h as ArtifactStartEvent, B as BackgroundDelegation, i as BudgetExceededError, C as CheckpointSavedEvent, k as DelegateFn, a as DelegateOptions, l as DelegationBudgetCostUnknownError, m as DelegationBudgetExceededError, n as DelegationError, o as DelegationPort, c as DelegationResult, D as DelegationTarget, p as DoneEvent, E as ErrorEvent, F as FileEditEvent, I as IterationEvent, P as PartialToolCallEvent, w as RunStartedEvent, x as ScoreVerdict, y as ScoredDelegation, z as Scorer, G as StateUpdateEvent, S as StreamEvent, T as TextDeltaEvent, H as ThinkingEvent, J as ToolCallEvent, K as ToolResultEvent, M as delegate, N as delegateBackground, O as delegateWithScoring, Q as isApprovalRequired, U as isDone, V as isError, W as isPartialToolCall, X as isTextDelta, Y as isToolCall, Z as isToolResult, a1 as presentUIMessageStream, a4 as streamAgentResponse } from './delegation-scoring-CURe4oSL.js';
1
+ export { b as APPROVAL_MODES, c as AfterToolCallContext, d as AgentBuilder, e as AgentDefinitionError, f as AgentExecutionContext, g as AgentManifest, A as AgentManifestEntry, h as AgentManifestSource, i as AgentManifestTool, a as AgentModule, j as AgentRoute, k as AgentRouteContext, l as AgentRunInfo, m as AgentsPluginOptions, n as ApiErrorContext, o as ApiErrorDecision, p as ApiErrorPolicy, q as ApprovalMode, B as BeforeToolCallContext, r as CompiledContextWindow, t as ContextualTool, D as DelegationTimeoutError, E as EphemeralAgent, L as LLMCallContext, M as McpApprovalSpec, u as McpFileError, v as McpRegistryConfig, w as McpRequestContext, x as McpSelection, P as PermissionsPluginOptions, y as ProcessInputContext, z as SdkMessage, F as Segment, G as ShouldAutoApproveOptions, T as ToolCallVeto, H as ToolHooks, I as ToolHooksPlugin, W as WRITE_SCOPED_TOOLS, J as agentsPlugin, K as buildModelSelection, N as compileAgentModule, O as compileContextWindow, Q as compileLoadedAgentModule, R as compileProjectContext, U as compileSkills, V as createAgentExecutionContext, X as createApiErrorHandler, Y as createPermissionsPlugin, Z as createThinkTagExtractor, _ as createToolHooksPlugin, $ as extractThinkTagStream, a0 as generateAgentManifest, a1 as generateAgentRoutes, a2 as isAgentContext, a3 as loadMcpJson, a4 as loadPersonalMcpServers, a5 as mcpRegistry, a6 as mcpToolApprovals, a7 as projectContextMetadataOnlyKnobs, a8 as reasoningEffortOf, a9 as resolveMcpServers, aa as runWithApiErrorHandling, ab as shouldAutoApprove, s as streamAgentUIMessages, ac as translateSdkEvent, ad as withClockCap, ae as withEphemeralAgent } from './bridge-entry-BNWDrPzg.js';
2
+ export { b as AGENT_BRAND, A as AgentDefinition, c as CompatImportUnsupportedError, a as CompiledAgentOptions, C as CompiledTool, D as DefineAgentConfig, H as HookApprovalGate, j as HookApprovalRequest, k as HookGateUnsupportedError, I as InferAgentInput, l as InferAgentToolNames, T as ToolWalkResult, n as ToolboxWalkResult, o as compileAgentDefinition, p as compileTools, q as isAgentDefinition } from './agent-compiler-JSYkHpa7.js';
3
+ export { a as AgentStopReason, b as AgentStreamEvent, c as AgentTurnMetadata, A as ApprovalRequiredEvent, d as ArtifactChunkEvent, e as ArtifactStartEvent, C as CheckpointSavedEvent, D as DoneEvent, E as ErrorEvent, F as FileEditEvent, I as IterationEvent, P as PartialToolCallEvent, R as RunStartedEvent, f as StateUpdateEvent, S as StreamEvent, T as TextDeltaEvent, g as ThinkingEvent, h as ToolCallEvent, i as ToolResultEvent, j as isApprovalRequired, k as isDone, l as isError, m as isPartialToolCall, n as isTextDelta, o as isToolCall, p as isToolResult, q as presentUIMessageStream, s as streamAgentResponse } from './agent-sse-handler-BRp9vHrb.js';
4
+ export { A as ApprovalPosture, D as DefinitionOrThunk, S as SdkAgentHandle, b as SdkSendOptions, c as SdkTurnHandle, d as applyPosture, e as createSdkAgentStream, t as toAgentFactory } from './sdk-adapter-DQnKx7bA.js';
5
+ export { B as BudgetExceededError, a as DelegateOptions, d as DelegationBudgetCostUnknownError, e as DelegationBudgetExceededError, f as DelegationError, D as DelegationResult, m as delegate } from './agent-orchestrator-BFWg2URC.js';
6
+ export { B as BackgroundDelegation, a as DelegateFn, b as DelegationPort, D as DelegationTarget, S as ScoreVerdict, c as ScoredDelegation, d as Scorer, e as delegateBackground, f as delegateWithScoring } from './delegation-scoring-Cn5eM4lQ.js';
4
7
  export { C as CompatSurface, a as GatedCompatSource, G as GatedSettingSource, P as ProjectSettingsGrant, R as ResolvedCompatSource, b as SettingSourceCapability, S as SettingSourcesSelection, U as UntrustedSettingSourceError, r as resolveCompatSources, c as resolveSettingSources } from './setting-sources-gate-BJJiKq33.js';
5
8
  import '@theokit/http';
6
- import './types-DdltPCj2.js';
9
+ import './types-D5cHmSLi.js';
7
10
  import '@theokit/sdk';
8
11
  import 'zod';
9
- import '@theokit/sdk/retry';
10
12
  import '@theokit/sdk/sandbox';
11
13
  import './hook-handlers-Cw2FsnE5.js';
12
14
  import '@theokit/presenter/wire';
13
15
  import '@theokit/sdk/errors';
14
16
  import '@theokit/sdk/subagents-loader';
17
+ import '@theokit/sdk/retry';
package/dist/bridge.js CHANGED
@@ -31,15 +31,25 @@ import {
31
31
  runWithApiErrorHandling,
32
32
  streamAgentResponse,
33
33
  streamAgentUIMessages
34
- } from "./chunk-FIGLHWR2.js";
34
+ } from "./chunk-4SXVNI5O.js";
35
+ import {
36
+ DelegationTimeoutError,
37
+ delegate,
38
+ delegateBackground,
39
+ delegateWithScoring,
40
+ withClockCap,
41
+ withEphemeralAgent
42
+ } from "./chunk-Z5SYU6Z6.js";
43
+ import "./chunk-MJ6FRILJ.js";
35
44
  import {
36
- APPROVAL_MODES,
37
45
  BudgetExceededError,
38
- CompatImportUnsupportedError,
39
46
  DelegationBudgetCostUnknownError,
40
47
  DelegationBudgetExceededError,
41
- DelegationError,
42
- DelegationTimeoutError,
48
+ DelegationError
49
+ } from "./chunk-A2UVVEB3.js";
50
+ import {
51
+ APPROVAL_MODES,
52
+ CompatImportUnsupportedError,
43
53
  HookGateUnsupportedError,
44
54
  WRITE_SCOPED_TOOLS,
45
55
  applyPosture,
@@ -48,19 +58,15 @@ import {
48
58
  createSdkAgentStream,
49
59
  createThinkTagExtractor,
50
60
  createToolHooksPlugin,
51
- delegate,
52
- delegateBackground,
53
- delegateWithScoring,
54
61
  extractThinkTagStream,
55
62
  projectContextMetadataOnlyKnobs,
56
63
  reasoningEffortOf,
57
64
  shouldAutoApprove,
58
65
  toAgentFactory,
59
- translateSdkEvent,
60
- withClockCap,
61
- withEphemeralAgent
62
- } from "./chunk-4PHZ25JN.js";
63
- import "./chunk-MJ6FRILJ.js";
66
+ translateSdkEvent
67
+ } from "./chunk-3TE4PJZL.js";
68
+ import "./chunk-M5J3Q6YC.js";
69
+ import "./chunk-Q65ZIFNK.js";
64
70
  import {
65
71
  AGENT_BRAND,
66
72
  UntrustedSettingSourceError,
@@ -69,8 +75,6 @@ import {
69
75
  resolveCompatSources,
70
76
  resolveSettingSources
71
77
  } from "./chunk-NIQJ4GZX.js";
72
- import "./chunk-M5J3Q6YC.js";
73
- import "./chunk-Q65ZIFNK.js";
74
78
  import "./chunk-2SP5BB6U.js";
75
79
  import "./chunk-OXNDJSAJ.js";
76
80
  import "./chunk-Z4QWC7IK.js";