@theokit/agents 0.31.0 → 0.32.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.
@@ -1,5 +1,5 @@
1
1
  import { ExecutionContext } from '@theokit/http';
2
- import { A as AgentOptions, D as ToolOptions, m as MainLoopMeta, a as ApprovalOptions, B as BudgetOptions, l as HumanInTheLoopOptions, k as GatewayOptions, r as MemoryOptions, z as SkillsOptions, j as ContextWindowOptions, w as ProjectContextOptions, p as McpServersMap, g as CompactionDecoratorConfig, b as CheckpointOptions, R as ReasoningEffort } from './skills-Dx_KJ6Eg.js';
2
+ import { A as AgentOptions, D as ToolOptions, m as MainLoopMeta, a as ApprovalOptions, B as BudgetOptions, l as HumanInTheLoopOptions, k as GatewayOptions, r as MemoryOptions, z as SkillsOptions, j as ContextWindowOptions, w as ProjectContextOptions, p as McpServersMap, g as CompactionDecoratorConfig, b as CheckpointOptions, R as ReasoningEffort } from './skills-DvI_LYWZ.js';
3
3
  import { SystemPromptResolver, SkillsSettings, ContextSettings, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition as AgentDefinition$1, BudgetTracker, ConversationStorageAdapter, CustomTool, ModelSelection } from '@theokit/sdk';
4
4
  import { UIMessageChunk } from 'ai';
5
5
  import { z } from 'zod';
@@ -420,6 +420,8 @@ interface ApprovalRequiredEvent {
420
420
  input?: unknown;
421
421
  callbackUrl: string;
422
422
  timeoutMs: number;
423
+ /** M20 — JSON-schema descriptor of the custom payload the approver may attach (optional). */
424
+ payloadSchema?: Record<string, unknown>;
423
425
  }
424
426
  /** Agent encountered an error. */
425
427
  interface ErrorEvent {
@@ -914,14 +916,27 @@ declare function agent(): AgentBuilder;
914
916
  * surfaces as a tool result the model self-corrects on).
915
917
  */
916
918
 
919
+ /**
920
+ * M20 — a settled HITL decision. Structural mirror of the harness's `ApprovalDecision` (the agents
921
+ * package must not import from `theokit` — dependency direction). `awaitApproval` may resolve a bare
922
+ * boolean (legacy) OR this object; the plugin normalizes both.
923
+ */
924
+ interface HitlDecision {
925
+ approved: boolean;
926
+ reason?: string;
927
+ payload?: unknown;
928
+ }
917
929
  /** Injected wiring — the harness (mount-agent) supplies these; the plugin stays pure. */
918
930
  interface HitlWiring {
919
931
  /** Tool name → its `@HumanInTheLoop` config. A tool absent here is NOT gated. */
920
932
  gated: Map<string, HumanInTheLoopOptions>;
921
933
  /** Push the approval-required event into the agent stream (the translator emits the chunk). */
922
934
  emit: (event: ApprovalRequiredEvent) => void;
923
- /** Await the human decision for `approvalId`; resolves true=approve, false=deny (or timeout). */
924
- awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions, toolName: string) => Promise<boolean>;
935
+ /**
936
+ * Await the human decision for `approvalId`; resolves approve/deny (or timeout). M20 — may resolve
937
+ * a bare boolean (legacy) OR a {@link HitlDecision} carrying an approver `reason` + `payload`.
938
+ */
939
+ awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions, toolName: string) => Promise<boolean | HitlDecision>;
925
940
  }
926
941
 
927
942
  /**
@@ -1281,11 +1296,17 @@ declare function delegate(SubAgentClass: Function, message: string, opts?: Deleg
1281
1296
  /**
1282
1297
  * M10 (theokit-ai-first) — createToolHooksPlugin: `beforeToolCall` / `afterToolCall` observability.
1283
1298
  *
1284
- * ADR-0040 § D2: a HOME/BOUNDARY plugin over the SDK's OWN `pre_tool_call` / `post_tool_call`
1285
- * hooks (mirrors {@link createHitlPlugin}). It calls no LLM, dispatches no tool, runs no second
1286
- * loop — the SDK owns the run. `beforeToolCall` may VETO a call; `afterToolCall` observes the
1287
- * result. The processor pipeline's remaining lifecycle hooks (LLM request/response) live in the
1288
- * SDK; this ships the two tool-boundary hooks the framework can wire today.
1299
+ * ADR-0040 § D2: a HOME/BOUNDARY plugin over the SDK's OWN `pre_tool_call` / `post_tool_call` /
1300
+ * `pre_llm_call` / `post_llm_call` / `pre_user_send` hooks (mirrors {@link createHitlPlugin}). It
1301
+ * calls no LLM, dispatches no tool, runs no second loop — the SDK owns the run. `beforeToolCall`
1302
+ * may VETO a call; `afterToolCall` observes the result.
1303
+ *
1304
+ * M19 — `processInput` completes the input side of the processor pipeline, wired to the SDK
1305
+ * `pre_user_send` hook. NOTE (honest ceiling): the SDK does NOT let a plugin mutate the raw
1306
+ * prompt/stream; `pre_user_send` lets a handler INJECT derived context (`recalledContext`) BEFORE
1307
+ * the model. So `processInput` receives the prompt and returns an optional string, which the SDK
1308
+ * injects as a `<memory-context>` block ahead of the prompt. The api-error side of M19 lives in
1309
+ * `./api-error-handler` (a sibling factory — the SDK owns retry and exposes no error hook).
1289
1310
  */
1290
1311
  /** A tool call about to run (mirrored from the SDK `pre_tool_call` context — type-only). */
1291
1312
  interface BeforeToolCallContext {
@@ -1314,6 +1335,19 @@ interface ToolHooks {
1314
1335
  beforeLLMCall?: (ctx: LLMCallContext) => void | Promise<void>;
1315
1336
  /** M10 — observe every LLM turn AFTER it completes (SDK `post_llm_call`). Observability only. */
1316
1337
  afterLLMCall?: (ctx: LLMCallContext) => void | Promise<void>;
1338
+ /**
1339
+ * M19 — pre-process the user input BEFORE the model runs (SDK `pre_user_send`). Receives the
1340
+ * prompt; return a string to INJECT as derived context ahead of it (the SDK wraps it in a
1341
+ * `<memory-context>` block), or `undefined` to inject nothing. The SDK does not expose raw-prompt
1342
+ * mutation to plugins, so this is additive, not a rewrite of the caller's stream.
1343
+ */
1344
+ processInput?: (ctx: ProcessInputContext) => string | undefined | Promise<string | undefined>;
1345
+ }
1346
+ /** Context of the input seam (mirrors the SDK `PreUserSendContext`). */
1347
+ interface ProcessInputContext {
1348
+ prompt: string;
1349
+ agentId: string;
1350
+ runId: string;
1317
1351
  }
1318
1352
  /** Context of an LLM turn (mirrors the SDK `LlmCallContext` for `pre_llm_call`/`post_llm_call`). */
1319
1353
  interface LLMCallContext {
@@ -1333,12 +1367,22 @@ interface ToolHookRawContext {
1333
1367
  args?: Record<string, unknown>;
1334
1368
  result?: unknown;
1335
1369
  iteration?: number;
1370
+ /** M19 — the user prompt, present on the `pre_user_send` seam. */
1371
+ prompt?: string;
1336
1372
  }
1337
1373
  interface ToolHooksPluginContext {
1338
1374
  on(hook: string, handler: (ctx: ToolHookRawContext) => unknown): void;
1339
1375
  }
1340
1376
  interface ToolHooksPlugin {
1341
1377
  name: string;
1378
+ /** SDK `BasePlugin.version` — required by the `@theokit/sdk` Plugin contract. */
1379
+ version: string;
1380
+ /**
1381
+ * SDK Plugin discriminator. MUST be `'general'` — the SDK's `isCodePlugin()` gate filters out any
1382
+ * plugin object lacking `kind: 'general'` (a `register()`-only object is silently dropped and its
1383
+ * hooks NEVER fire). Regression guard for the M10/M19 latent E2E bug.
1384
+ */
1385
+ kind: 'general';
1342
1386
  register(ctx: ToolHooksPluginContext): void;
1343
1387
  }
1344
1388
  /**
@@ -1347,6 +1391,168 @@ interface ToolHooksPlugin {
1347
1391
  */
1348
1392
  declare function createToolHooksPlugin(hooks: ToolHooks): ToolHooksPlugin;
1349
1393
 
1394
+ /**
1395
+ * M19 (theokit-ai-first) — `processApiError`: app-level fallback around an agent run.
1396
+ *
1397
+ * ADR-0040 § D2 + sdk-runtime.md: the `@theokit/sdk` runtime OWNS the LLM call AND its own
1398
+ * retry/backoff, and exposes NO api-error hook to plugins. This module is therefore NOT a plugin —
1399
+ * it is a thin app-boundary wrapper (the M19 DoD explicitly allows "a sibling factory"). It
1400
+ * RE-INVOKES the caller's run thunk on error; it never calls an LLM, never dispatches a tool, never
1401
+ * reimplements retry inside the loop (G2). The SDK's internal retry runs first; this handles what
1402
+ * survives it — a second, app-owned fallback layer (the M19 top-risk note: "app-level fallback, not
1403
+ * a second retry loop" inside the SDK).
1404
+ */
1405
+ /** What the app decides after seeing an API error. */
1406
+ interface ApiErrorDecision<R = unknown> {
1407
+ /** Re-invoke the run thunk once more. Ignored past `maxAttempts`. */
1408
+ retry?: boolean;
1409
+ /**
1410
+ * A value to return INSTEAD of rethrowing, when `retry` is false/absent. Lets the app degrade
1411
+ * gracefully (e.g. a canned response) rather than surface the raw provider error.
1412
+ */
1413
+ fallback?: R;
1414
+ }
1415
+ /** Context handed to the app's error handler for each failed attempt (1-based). */
1416
+ interface ApiErrorContext {
1417
+ error: unknown;
1418
+ /** 1-based attempt number that just failed. */
1419
+ attempt: number;
1420
+ }
1421
+ interface ApiErrorPolicy<R = unknown> {
1422
+ /** Called once per failed attempt. Return `{ retry: true }` to try again, or a `{ fallback }`. */
1423
+ processApiError: (ctx: ApiErrorContext) => ApiErrorDecision<R> | Promise<ApiErrorDecision<R>>;
1424
+ /**
1425
+ * Hard cap on total attempts (defaults to 3). A backstop so a handler that always returns
1426
+ * `{ retry: true }` cannot loop forever (mirrors the SDK's own bounded retry philosophy).
1427
+ */
1428
+ maxAttempts?: number;
1429
+ }
1430
+ /**
1431
+ * Run `thunk`, applying the app's `processApiError` policy on failure. Returns the run's value on
1432
+ * success, the policy's `fallback` when it declines to retry with one, or rethrows the last error.
1433
+ *
1434
+ * `thunk` is typically `() => agent.send(msg).then((r) => r.wait())` — a whole SDK run. On retry the
1435
+ * thunk is re-invoked from scratch (a fresh run), never resumed mid-loop.
1436
+ */
1437
+ declare function runWithApiErrorHandling<R>(thunk: () => Promise<R>, policy: ApiErrorPolicy<R>): Promise<R>;
1438
+ /**
1439
+ * Build a reusable guard bound to one policy. `const guard = createApiErrorHandler({ ... })` then
1440
+ * `guard(() => agent.send(m).then((r) => r.wait()))` — the same policy applied to many runs.
1441
+ */
1442
+ declare function createApiErrorHandler<R = unknown>(policy: ApiErrorPolicy<R>): (thunk: () => Promise<R>) => Promise<R>;
1443
+
1444
+ /**
1445
+ * M25 (theokit-ai-first) — background delegation + task-completion scoring.
1446
+ *
1447
+ * Two THIN wrappers over the M12 `delegate` (ADR 0038/0040): no new orchestration engine, no second
1448
+ * loop, no new store. `delegateBackground` kicks off a sub-agent without blocking the supervisor and
1449
+ * hands back a handle to await later. `delegateWithScoring` runs `delegate`, scores the result with
1450
+ * an injected scorer, and re-delegates with the scorer's feedback until it passes or `maxRounds` is
1451
+ * hit. The `delegate` implementation is injectable (`delegateFn`) so this is testable without a
1452
+ * SubAgent class or an LLM — and so it NEVER re-implements the delegation runtime.
1453
+ */
1454
+
1455
+ /** The delegation primitive both wrappers drive. Defaults to the M12 {@link delegate}. */
1456
+ type DelegateFn = (subAgent: Function, message: string, opts?: DelegateOptions) => Promise<DelegationResult>;
1457
+ /** A running background delegation the supervisor can await/poll later. */
1458
+ interface BackgroundDelegation {
1459
+ /** Await the sub-agent's result (or rejection). Idempotent — returns the same settled promise. */
1460
+ wait(): Promise<DelegationResult>;
1461
+ /** Whether the underlying delegation has resolved or rejected. */
1462
+ settled(): boolean;
1463
+ }
1464
+ /**
1465
+ * Start a sub-agent WITHOUT blocking the supervisor. Returns immediately with a handle; the
1466
+ * supervisor keeps working and calls `wait()` when it needs the result. A thin async wrapper over
1467
+ * `delegate` — not a scheduler (Top-risk 1). Rejections are still observable via `wait()`.
1468
+ */
1469
+ declare function delegateBackground(subAgent: Function, message: string, opts?: DelegateOptions & {
1470
+ delegateFn?: DelegateFn;
1471
+ }): BackgroundDelegation;
1472
+ /** A scorer's verdict on a sub-agent result. `feedback` is fed back into the next round on failure. */
1473
+ interface ScoreVerdict {
1474
+ pass: boolean;
1475
+ /** Optional numeric score (0..1) for logging/telemetry. */
1476
+ score?: number;
1477
+ /** Guidance appended to the next delegation when `pass` is false. */
1478
+ feedback?: string;
1479
+ }
1480
+ /** Scores a sub-agent result. Opt-in (Top-risk 2) — the caller supplies it, and pays its cost. */
1481
+ type Scorer = (result: DelegationResult) => ScoreVerdict | Promise<ScoreVerdict>;
1482
+ /** The outcome of a scored delegation: the final result plus the per-round verdict trail. */
1483
+ interface ScoredDelegation {
1484
+ result: DelegationResult;
1485
+ /** Rounds actually run (1..maxRounds). */
1486
+ rounds: number;
1487
+ /** Whether the final round passed the scorer. */
1488
+ passed: boolean;
1489
+ /** The verdict from each round, in order. */
1490
+ verdicts: ScoreVerdict[];
1491
+ }
1492
+ /**
1493
+ * Run `delegate`, score the result, and re-delegate with the scorer's feedback until it passes or
1494
+ * `maxRounds` is reached. Each round is ONE `delegate` call — no second loop, no new store. Returns
1495
+ * the final result (passing, or the last attempt) with the per-round verdict trail.
1496
+ */
1497
+ declare function delegateWithScoring(subAgent: Function, message: string, opts: DelegateOptions & {
1498
+ scorer: Scorer;
1499
+ maxRounds?: number;
1500
+ delegateFn?: DelegateFn;
1501
+ feedbackTemplate?: (message: string, feedback: string) => string;
1502
+ }): Promise<ScoredDelegation>;
1503
+
1504
+ /**
1505
+ * M24 (ADR-0041) — MCP follow-ups, framework-side layer over the `@MCP` config (ADR-0040 § D2).
1506
+ *
1507
+ * Three home/boundary helpers that compose with the existing `@MCP` / `defineAgent` surfaces — the
1508
+ * SDK still owns MCP server EXECUTION (`Agent.create({ mcpServers })`); these only shape the config:
1509
+ * - `resolveMcpServers` — per-request resolver so multi-tenant apps hand different MCP creds to
1510
+ * different callers (mirrors the M13 skills resolver);
1511
+ * - `mcpRegistry` — build a server config for a known MCP registry (Composio / mcp.run);
1512
+ * - `mcpToolApprovals` — mark MCP tools for approval, producing the M14 `approvals` entries so a
1513
+ * gated MCP tool routes through the (E2E-proven) HITL flow.
1514
+ */
1515
+
1516
+ /** The request context handed to an MCP resolver (the M7 run-context — opaque per-request data). */
1517
+ type McpRequestContext = Record<string, unknown>;
1518
+ /**
1519
+ * How the MCP server set is chosen:
1520
+ * - a map — static `@MCP`-style config.
1521
+ * - a function — resolved per request from the {@link McpRequestContext} (sync or async).
1522
+ */
1523
+ type McpSelection = McpServersMap | ((ctx: McpRequestContext) => McpServersMap | Promise<McpServersMap>);
1524
+ /**
1525
+ * Resolve the MCP servers for a request. Returns `undefined` when no selection is given. Fails fast
1526
+ * if a resolver returns a non-object (error-handling.md). Multi-tenant apps pass a function that
1527
+ * reads per-user credentials from `ctx`.
1528
+ */
1529
+ declare function resolveMcpServers(selection: McpSelection | undefined, ctx: McpRequestContext): Promise<McpServersMap | undefined>;
1530
+ /** Config for {@link mcpRegistry}. `registry` selects a known provider. */
1531
+ interface McpRegistryConfig {
1532
+ registry: 'composio' | 'mcp.run';
1533
+ /** The registry API key (kept in the server's env, never logged). */
1534
+ apiKey: string;
1535
+ /** Composio: the app toolkits to expose (e.g. `['github', 'slack']`). */
1536
+ apps?: string[];
1537
+ /** mcp.run: the profile to connect. */
1538
+ profile?: string;
1539
+ }
1540
+ /**
1541
+ * Build an {@link McpServersMap} for a known MCP registry. Emits an `npx`-launched server config with
1542
+ * the API key in `env`. Documented registries: **Composio** (`@composio/mcp`) and **mcp.run**
1543
+ * (`@mcp.run/cli`). Other registries are wired manually via a raw `@MCP` entry.
1544
+ */
1545
+ declare function mcpRegistry(config: McpRegistryConfig): McpServersMap;
1546
+ /** An MCP tool's approval spec: full {@link HumanInTheLoopOptions} or a bare question string. */
1547
+ type McpApprovalSpec = HumanInTheLoopOptions | string;
1548
+ /**
1549
+ * Mark MCP tools for human approval (`requireToolApproval`). Returns the `Record<toolName,
1550
+ * HumanInTheLoopOptions>` shape the M14 `defineAgent({ approvals })` map consumes — so a gated MCP
1551
+ * tool routes through the same (E2E-proven) HITL flow as a native gated tool. A bare string is
1552
+ * shorthand for `{ question }`.
1553
+ */
1554
+ declare function mcpToolApprovals(specs: Record<string, McpApprovalSpec>): Record<string, HumanInTheLoopOptions>;
1555
+
1350
1556
  /**
1351
1557
  * Agent manifest generator — build-time JSON describing all agents, tools, guards, policies.
1352
1558
  *
@@ -1430,4 +1636,4 @@ declare function agentsPlugin(opts: AgentsPluginOptions): {
1430
1636
  register(app: PluginApp): void;
1431
1637
  };
1432
1638
 
1433
- export { type ReflectionResult as $, type AgentManifestEntry as A, type BeforeToolCallContext as B, type CompiledAgentOptions as C, type DelegationResult as D, type DefineAgentConfig as E, type DelegateOptions as F, type Guardrail as G, DelegationError as H, type DoneEvent as I, type ErrorEvent as J, type FileEditEvent as K, type LoopStrategy as L, type GuardrailAction as M, type GuardrailPhase as N, type GuardrailResult as O, GuardrailViolationError as P, type InferAgentInput as Q, type ReflectionStrategy as R, type StreamEvent as S, type InferAgentToolNames as T, type IterationEvent as U, type LLMCallContext as V, type LoopFinishReason as W, type LoopOutcome as X, type LoopStrategyConfig as Y, type PartialToolCallEvent as Z, type ReflectionContext as _, type CompiledTool as a, type ReflectionStrategyConfig as a0, type RunStartedEvent as a1, type SdkMessage as a2, type Segment as a3, type SkillsRequestContext as a4, type SkillsSelection as a5, type StateUpdateEvent as a6, type TextDeltaEvent as a7, type ThinkingEvent as a8, type ToolCallEvent as a9, isAgentContext as aA, isAgentDefinition as aB, isApprovalRequired as aC, isDone as aD, isError as aE, isPartialToolCall as aF, isTextDelta as aG, isToolCall as aH, isToolResult as aI, ladderReflectionStrategy as aJ, loopStrategyConfigSchema as aK, noopReflectionStrategy as aL, projectContextMetadataOnlyKnobs as aM, reflectionStrategyConfigSchema as aN, resolveEnabledSkills as aO, resolveLoopStrategy as aP, streamAgentResponse as aQ, streamAgentUIMessages as aR, translateSdkEvent as aS, translateToUIMessageStream as aT, validateUniqueRoutes as aU, walkAgentMetadata as aV, type ToolCallVeto as aa, type ToolHooks as ab, type ToolHooksPlugin as ac, type ToolResultEvent as ad, type ToolWalkResult as ae, type ToolboxWalkResult as af, agent as ag, agentsPlugin as ah, buildModelSelection as ai, compileAgent as aj, compileAgentDefinition as ak, compileAgentModule as al, compileContextWindow as am, compileProjectContext as an, compileSkills as ao, compileTools as ap, contextualTool as aq, createAgentExecutionContext as ar, createSdkAgentStream as as, createThinkTagExtractor as at, createToolHooksPlugin as au, defineAgent as av, delegate as aw, extractThinkTagStream as ax, generateAgentManifest as ay, generateAgentRoutes as az, type RoundStreamFactory as b, AGENT_BRAND as c, type AfterToolCallContext as d, type AgentBuilder as e, type AgentDefinition as f, AgentDefinitionError as g, type AgentExecutionContext as h, type AgentManifest as i, type AgentManifestTool as j, type AgentRoute as k, type AgentRouteContext as l, type AgentRunInfo as m, type AgentStreamEvent as n, type AgentWalkResult as o, AgentWarningCode as p, type AgentsPluginOptions as q, type ApprovalRequiredEvent as r, type ArtifactChunkEvent as s, type ArtifactStartEvent as t, BudgetExceededError as u, type CheckpointSavedEvent as v, type CompiledContextWindow as w, type ContextualTool as x, CostBudgetExceededError as y, DEFAULT_MAX_ITERATIONS as z };
1639
+ export { type LoopFinishReason as $, type AgentManifestEntry as A, type BackgroundDelegation as B, type CompiledAgentOptions as C, type DelegationResult as D, type CompiledContextWindow as E, type ContextualTool as F, type Guardrail as G, CostBudgetExceededError as H, DEFAULT_MAX_ITERATIONS as I, type DefineAgentConfig as J, type DelegateFn as K, type LoopStrategy as L, type DelegateOptions as M, DelegationError as N, type DoneEvent as O, type ErrorEvent as P, type FileEditEvent as Q, type ReflectionStrategy as R, type StreamEvent as S, type GuardrailAction as T, type GuardrailPhase as U, type GuardrailResult as V, GuardrailViolationError as W, type InferAgentInput as X, type InferAgentToolNames as Y, type IterationEvent as Z, type LLMCallContext as _, type CompiledTool as a, mcpRegistry as a$, type LoopOutcome as a0, type LoopStrategyConfig as a1, type McpApprovalSpec as a2, type McpRegistryConfig as a3, type McpRequestContext as a4, type McpSelection as a5, type PartialToolCallEvent as a6, type ProcessInputContext as a7, type ReflectionContext as a8, type ReflectionResult as a9, compileProjectContext as aA, compileSkills as aB, compileTools as aC, contextualTool as aD, createAgentExecutionContext as aE, createApiErrorHandler as aF, createSdkAgentStream as aG, createThinkTagExtractor as aH, createToolHooksPlugin as aI, defineAgent as aJ, delegate as aK, delegateBackground as aL, delegateWithScoring as aM, extractThinkTagStream as aN, generateAgentManifest as aO, generateAgentRoutes as aP, isAgentContext as aQ, isAgentDefinition as aR, isApprovalRequired as aS, isDone as aT, isError as aU, isPartialToolCall as aV, isTextDelta as aW, isToolCall as aX, isToolResult as aY, ladderReflectionStrategy as aZ, loopStrategyConfigSchema as a_, type ReflectionStrategyConfig as aa, type RunStartedEvent as ab, type ScoreVerdict as ac, type ScoredDelegation as ad, type Scorer as ae, type SdkMessage as af, type Segment as ag, type SkillsRequestContext as ah, type SkillsSelection as ai, type StateUpdateEvent as aj, type TextDeltaEvent as ak, type ThinkingEvent as al, type ToolCallEvent as am, type ToolCallVeto as an, type ToolHooks as ao, type ToolHooksPlugin as ap, type ToolResultEvent as aq, type ToolWalkResult as ar, type ToolboxWalkResult as as, agent as at, agentsPlugin as au, buildModelSelection as av, compileAgent as aw, compileAgentDefinition as ax, compileAgentModule as ay, compileContextWindow as az, type RoundStreamFactory as b, mcpToolApprovals as b0, noopReflectionStrategy as b1, projectContextMetadataOnlyKnobs as b2, reflectionStrategyConfigSchema as b3, resolveEnabledSkills as b4, resolveLoopStrategy as b5, resolveMcpServers as b6, runWithApiErrorHandling as b7, streamAgentResponse as b8, streamAgentUIMessages as b9, translateSdkEvent as ba, translateToUIMessageStream as bb, validateUniqueRoutes as bc, walkAgentMetadata as bd, AGENT_BRAND as c, type AfterToolCallContext as d, type AgentBuilder as e, type AgentDefinition as f, AgentDefinitionError as g, type AgentExecutionContext as h, type AgentManifest as i, type AgentManifestTool as j, type AgentRoute as k, type AgentRouteContext as l, type AgentRunInfo as m, type AgentStreamEvent as n, type AgentWalkResult as o, AgentWarningCode as p, type AgentsPluginOptions as q, type ApiErrorContext as r, type ApiErrorDecision as s, type ApiErrorPolicy as t, type ApprovalRequiredEvent as u, type ArtifactChunkEvent as v, type ArtifactStartEvent as w, type BeforeToolCallContext as x, BudgetExceededError as y, type CheckpointSavedEvent as z };
package/dist/bridge.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { c as AGENT_BRAND, d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinition, g as AgentDefinitionError, h as AgentExecutionContext, i as AgentManifest, A as AgentManifestEntry, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentWalkResult, p as AgentWarningCode, q as AgentsPluginOptions, r as ApprovalRequiredEvent, s as ArtifactChunkEvent, t as ArtifactStartEvent, B as BeforeToolCallContext, u as BudgetExceededError, v as CheckpointSavedEvent, C as CompiledAgentOptions, w as CompiledContextWindow, a as CompiledTool, x as ContextualTool, E as DefineAgentConfig, F as DelegateOptions, H as DelegationError, D as DelegationResult, I as DoneEvent, J as ErrorEvent, K as FileEditEvent, Q as InferAgentInput, T as InferAgentToolNames, U as IterationEvent, V as LLMCallContext, Z as PartialToolCallEvent, a1 as RunStartedEvent, a2 as SdkMessage, a3 as Segment, a6 as StateUpdateEvent, S as StreamEvent, a7 as TextDeltaEvent, a8 as ThinkingEvent, a9 as ToolCallEvent, aa as ToolCallVeto, ab as ToolHooks, ac as ToolHooksPlugin, ad as ToolResultEvent, ae as ToolWalkResult, af as ToolboxWalkResult, ag as agent, ah as agentsPlugin, ai as buildModelSelection, aj as compileAgent, ak as compileAgentDefinition, al as compileAgentModule, am as compileContextWindow, an as compileProjectContext, ao as compileSkills, ap as compileTools, aq as contextualTool, ar as createAgentExecutionContext, as as createSdkAgentStream, at as createThinkTagExtractor, au as createToolHooksPlugin, av as defineAgent, aw as delegate, ax as extractThinkTagStream, ay as generateAgentManifest, az as generateAgentRoutes, aA as isAgentContext, aB as isAgentDefinition, aC as isApprovalRequired, aD as isDone, aE as isError, aF as isPartialToolCall, aG as isTextDelta, aH as isToolCall, aI as isToolResult, aM as projectContextMetadataOnlyKnobs, aQ as streamAgentResponse, aR as streamAgentUIMessages, aS as translateSdkEvent, aT as translateToUIMessageStream, aU as validateUniqueRoutes, aV as walkAgentMetadata } from './bridge-entry-DtDotZGW.js';
1
+ export { c as AGENT_BRAND, d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinition, g as AgentDefinitionError, h as AgentExecutionContext, i as AgentManifest, A as AgentManifestEntry, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentWalkResult, p as AgentWarningCode, q as AgentsPluginOptions, r as ApiErrorContext, s as ApiErrorDecision, t as ApiErrorPolicy, u as ApprovalRequiredEvent, v as ArtifactChunkEvent, w as ArtifactStartEvent, B as BackgroundDelegation, x as BeforeToolCallContext, y as BudgetExceededError, z as CheckpointSavedEvent, C as CompiledAgentOptions, E as CompiledContextWindow, a as CompiledTool, F as ContextualTool, J as DefineAgentConfig, K as DelegateFn, M as DelegateOptions, N as DelegationError, D as DelegationResult, O as DoneEvent, P as ErrorEvent, Q as FileEditEvent, X as InferAgentInput, Y as InferAgentToolNames, Z as IterationEvent, _ as LLMCallContext, a2 as McpApprovalSpec, a3 as McpRegistryConfig, a4 as McpRequestContext, a5 as McpSelection, a6 as PartialToolCallEvent, a7 as ProcessInputContext, ab as RunStartedEvent, ac as ScoreVerdict, ad as ScoredDelegation, ae as Scorer, af as SdkMessage, ag as Segment, aj as StateUpdateEvent, S as StreamEvent, ak as TextDeltaEvent, al as ThinkingEvent, am as ToolCallEvent, an as ToolCallVeto, ao as ToolHooks, ap as ToolHooksPlugin, aq as ToolResultEvent, ar as ToolWalkResult, as as ToolboxWalkResult, at as agent, au as agentsPlugin, av as buildModelSelection, aw as compileAgent, ax as compileAgentDefinition, ay as compileAgentModule, az as compileContextWindow, aA as compileProjectContext, aB as compileSkills, aC as compileTools, aD as contextualTool, aE as createAgentExecutionContext, aF as createApiErrorHandler, aG as createSdkAgentStream, aH as createThinkTagExtractor, aI as createToolHooksPlugin, aJ as defineAgent, aK as delegate, aL as delegateBackground, aM as delegateWithScoring, aN as extractThinkTagStream, aO as generateAgentManifest, aP as generateAgentRoutes, aQ as isAgentContext, aR as isAgentDefinition, aS as isApprovalRequired, aT as isDone, aU as isError, aV as isPartialToolCall, aW as isTextDelta, aX as isToolCall, aY as isToolResult, a$ as mcpRegistry, b0 as mcpToolApprovals, b2 as projectContextMetadataOnlyKnobs, b6 as resolveMcpServers, b7 as runWithApiErrorHandling, b8 as streamAgentResponse, b9 as streamAgentUIMessages, ba as translateSdkEvent, bb as translateToUIMessageStream, bc as validateUniqueRoutes, bd as walkAgentMetadata } from './bridge-entry-1r1DL-mS.js';
2
2
  import '@theokit/http';
3
- import './skills-Dx_KJ6Eg.js';
3
+ import './skills-DvI_LYWZ.js';
4
4
  import '@theokit/sdk';
5
5
  import 'zod';
6
6
  import 'ai';
package/dist/bridge.js CHANGED
@@ -16,11 +16,14 @@ import {
16
16
  compileTools,
17
17
  contextualTool,
18
18
  createAgentExecutionContext,
19
+ createApiErrorHandler,
19
20
  createSdkAgentStream,
20
21
  createThinkTagExtractor,
21
22
  createToolHooksPlugin,
22
23
  defineAgent,
23
24
  delegate,
25
+ delegateBackground,
26
+ delegateWithScoring,
24
27
  extractThinkTagStream,
25
28
  generateAgentManifest,
26
29
  generateAgentRoutes,
@@ -33,15 +36,19 @@ import {
33
36
  isTextDelta,
34
37
  isToolCall,
35
38
  isToolResult,
39
+ mcpRegistry,
40
+ mcpToolApprovals,
36
41
  projectContextMetadataOnlyKnobs,
42
+ resolveMcpServers,
43
+ runWithApiErrorHandling,
37
44
  streamAgentResponse,
38
45
  streamAgentUIMessages,
39
46
  translateSdkEvent,
40
47
  translateToUIMessageStream,
41
48
  validateUniqueRoutes,
42
49
  walkAgentMetadata
43
- } from "./chunk-BWYBOMKR.js";
44
- import "./chunk-FI6ZG2YP.js";
50
+ } from "./chunk-5VIRIPVV.js";
51
+ import "./chunk-3AX6M5TF.js";
45
52
  import "./chunk-7QVYU63E.js";
46
53
  export {
47
54
  AGENT_BRAND,
@@ -61,11 +68,14 @@ export {
61
68
  compileTools,
62
69
  contextualTool,
63
70
  createAgentExecutionContext,
71
+ createApiErrorHandler,
64
72
  createSdkAgentStream,
65
73
  createThinkTagExtractor,
66
74
  createToolHooksPlugin,
67
75
  defineAgent,
68
76
  delegate,
77
+ delegateBackground,
78
+ delegateWithScoring,
69
79
  extractThinkTagStream,
70
80
  generateAgentManifest,
71
81
  generateAgentRoutes,
@@ -78,7 +88,11 @@ export {
78
88
  isTextDelta,
79
89
  isToolCall,
80
90
  isToolResult,
91
+ mcpRegistry,
92
+ mcpToolApprovals,
81
93
  projectContextMetadataOnlyKnobs,
94
+ resolveMcpServers,
95
+ runWithApiErrorHandling,
82
96
  streamAgentResponse,
83
97
  streamAgentUIMessages,
84
98
  translateSdkEvent,
@@ -311,4 +311,4 @@ export {
311
311
  Mixin,
312
312
  getMixins
313
313
  };
314
- //# sourceMappingURL=chunk-FI6ZG2YP.js.map
314
+ //# sourceMappingURL=chunk-3AX6M5TF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/metadata/index.ts","../src/metadata/keys.ts","../src/decorators/agent.ts","../src/decorators/policies.ts","../src/decorators/observability.ts","../src/decorators/gateway.ts","../src/decorators/sub-agents.ts","../src/decorators/memory.ts","../src/decorators/skills.ts","../src/decorators/mcp.ts","../src/decorators/human-in-the-loop.ts","../src/decorators/context-window.ts","../src/decorators/compaction.ts","../src/decorators/checkpoint.ts","../src/decorators/project-context.ts","../src/decorators/mixin.ts"],"sourcesContent":["// Re-export setMeta/getMeta from http-decorators (DRY — single metadata engine)\n// Relative path for workspace-local usage; vitest resolves via alias\nexport { setMeta, getMeta } from '@theokit/http'\n\nexport * from './keys.js'\n","/** Symbol.for metadata keys for agent decorators — cross-module safe with SWC loader. */\n\nexport const AGENT_CONFIG = Symbol.for('theokit:agents:config')\nexport const AGENT_MAIN_LOOP = Symbol.for('theokit:agents:main-loop')\nexport const TOOLBOX_CONFIG = Symbol.for('theokit:agents:toolbox')\nexport const TOOL_CONFIG = Symbol.for('theokit:agents:tool')\nexport const TOOL_METHODS = Symbol.for('theokit:agents:tool-methods')\n","/**\n * @Agent() — marks a class as an AI agent controller.\n *\n * Convention over configuration:\n * @Agent() → name + route inferred from class name\n * @Agent({ model: '...' }) → name + route inferred, model explicit\n * @Agent({ name, route, model }) → fully explicit\n *\n * @example\n * ```ts\n * // Convention: SupportAgent → name: 'support', route: '/api/agents/support'\n * @Agent()\n * class SupportAgent { ... }\n *\n * // Partial: infer name + route, set model\n * @Agent({ model: 'claude-sonnet-4-5-20250929' })\n * class SupportAgent { ... }\n *\n * // Explicit: full control\n * @Agent({ name: 'support-agent', route: '/api/agents/support', model: '...' })\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta, AGENT_CONFIG } from '../metadata/index.js'\nimport type { AgentOptions } from '../types.js'\n\n/**\n * Infer agent name and route from class name (Rails-style convention).\n *\n * SupportAgent → name: 'support', route: '/api/agents/support'\n * ResearchAgent → name: 'research', route: '/api/agents/research'\n * CodeReviewAgent → name: 'code-review', route: '/api/agents/code-review'\n */\nfunction inferAgentMeta(className: string): { name: string; route: string } {\n const stripped = className.replace(/Agent$/, '')\n const kebab = stripped\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')\n .toLowerCase()\n return { name: kebab, route: `/api/agents/${kebab}` }\n}\n\nexport function Agent(options?: Partial<AgentOptions>): ClassDecorator {\n return (target: Function) => {\n const inferred = inferAgentMeta(target.name)\n setMeta(AGENT_CONFIG, target, {\n stream: true,\n name: inferred.name,\n route: inferred.route,\n ...options, // explicit values override inferred\n })\n }\n}\n\nexport function getAgentConfig(target: Function): AgentOptions | undefined {\n return getMeta<AgentOptions>(AGENT_CONFIG, target)\n}\n","/**\n * Agent-native policy decorators — built on http-decorators' createDecorator<T>().\n *\n * These decorators work with Reflector.getAllAndOverride() for hierarchical\n * resolution: tool → toolbox → agent (method-level overrides class-level).\n */\nimport { createDecorator } from '@theokit/http'\n\nimport type { ApprovalOptions, BudgetOptions, PolicyHandler } from '../types.js'\n\n/** Mark a tool as requiring human approval before execution. */\nexport const RequiresApproval = createDecorator<ApprovalOptions>()\n\n/** Require specific capabilities (permissions) to execute a tool. */\nexport const RequiresCapability = createDecorator<string[]>()\n\n/** Set a cost budget for an agent or tool scope. */\nexport const Budget = createDecorator<BudgetOptions>()\n\n/** Attach policy handler functions (CASL-style authorization). */\nexport const Policy = createDecorator<PolicyHandler[]>()\n","/**\n * Observability decorators for agent tracing and auditing.\n */\nimport { createDecorator } from '@theokit/http'\n\n/** Enable distributed tracing for a tool/toolbox/agent. */\nexport const Trace = createDecorator<boolean>()\n\n/** Enable audit logging for a tool/toolbox/agent. */\nexport const Audit = createDecorator<boolean>()\n","/**\n * @Gateway() — declares which platform adapters an agent supports.\n *\n * Stores gateway configuration metadata on the agent class.\n * The GatewayRunner reads this to auto-wire adapters without manual plumbing.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/api/agents/support' })\n * @Gateway({\n * platforms: ['telegram', 'discord', 'slack'],\n * sessionStrategy: 'per-user',\n * })\n * @UseGuards(AuthGuard)\n * class SupportAgent {\n * @MainLoop()\n * async run(ctx: AgentContext) { ... }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst GATEWAY_CONFIG = Symbol.for('theokit:agents:gateway')\n\nexport type PlatformName =\n | 'telegram'\n | 'discord'\n | 'slack'\n | 'whatsapp'\n | 'teams'\n | 'email'\n | 'sms'\n | 'mattermost'\n | 'line'\n | 'matrix'\n\nexport type SessionStrategy =\n | 'per-user' // telegram-dm-{userId}\n | 'per-channel' // telegram-grp-{channelId}\n | 'per-thread' // telegram-tpc-{channelId}-{topicId}\n\nexport interface GatewayOptions {\n /** Platform adapters this agent supports. */\n platforms: PlatformName[]\n /** How to resolve agentId from inbound events (default: 'per-user'). */\n sessionStrategy?: SessionStrategy\n /** Auto-start typing indicator while agent processes (default: true). */\n typing?: boolean\n}\n\nexport function Gateway(options: GatewayOptions): ClassDecorator {\n return (target: Function) => {\n setMeta(GATEWAY_CONFIG, target, { typing: true, sessionStrategy: 'per-user', ...options })\n }\n}\n\nexport function getGatewayConfig(target: Function): GatewayOptions | undefined {\n return getMeta<GatewayOptions>(GATEWAY_CONFIG, target)\n}\n\n/**\n * Resolve a stable agentId from a platform event based on the session strategy.\n *\n * Mirrors @theokit/gateway SessionRouter.defaultStrategy() but is configurable\n * via the @Gateway decorator.\n */\nexport function resolveSessionId(\n strategy: SessionStrategy,\n platform: string,\n sender: { id: string },\n channel: { id: string; type: 'dm' | 'group' | 'thread'; topicId?: string },\n): string {\n switch (strategy) {\n case 'per-user':\n return `${platform}-dm-${sender.id}`\n case 'per-channel':\n return `${platform}-grp-${channel.id}`\n case 'per-thread':\n return `${platform}-tpc-${channel.id}-${channel.topicId ?? 'main'}`\n }\n}\n","/**\n * @SubAgents() — declares child agents that a parent agent can handoff to.\n *\n * Compiles to the SDK's `AgentOptions.agents` map. The parent agent\n * can delegate work to sub-agents via the built-in Agent tool.\n *\n * @example\n * ```ts\n * @Agent({ name: 'orchestrator', route: '/api/agents/orchestrator' })\n * @SubAgents([ResearchAgent, CoderAgent, ReviewerAgent])\n * class OrchestratorAgent {\n * @MainLoop({ strategy: 'plan-act-reflect' })\n * async run(ctx: AgentContext) { ... }\n * }\n * ```\n *\n * Each referenced class MUST be decorated with @Agent().\n * The compiler reads their metadata to build the SDK agents map.\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nimport { getAgentConfig } from './agent.js'\n\nconst SUB_AGENTS = Symbol.for('theokit:agents:sub-agents')\n\nexport function SubAgents(agentClasses: Function[]): ClassDecorator {\n return (target: Function) => {\n // Validate at decoration time: all classes must have @Agent\n for (const cls of agentClasses) {\n const config = getAgentConfig(cls)\n if (!config) {\n throw new Error(\n `[@theokit/agents] @SubAgents on ${target.name}: class ${cls.name} is missing @Agent() decorator.`,\n )\n }\n }\n setMeta(SUB_AGENTS, target, agentClasses)\n }\n}\n\nexport function getSubAgents(target: Function): Function[] {\n return getMeta<Function[]>(SUB_AGENTS, target) ?? []\n}\n","/**\n * @Memory() — declares persistent memory configuration for an agent.\n *\n * Compiles to SDK's MemorySettings in Agent.create({ memory }).\n * Memory is per-agent, scoped by session strategy.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/api/agents/support' })\n * @Memory({ provider: 'built-in', embeddings: true, fts: true, scope: 'per-user' })\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst MEMORY_CONFIG = Symbol.for('theokit:agents:memory')\n\nexport type MemoryProvider = 'built-in' | 'honcho' | 'supermemory' | 'mem0'\nexport type MemoryScope = 'per-user' | 'per-agent' | 'per-tenant' | 'global'\n\nexport interface MemoryOptions {\n /** Memory provider backend. */\n provider?: MemoryProvider\n /** Enable semantic search via embeddings. */\n embeddings?: boolean\n /** Enable full-text search (FTS5). */\n fts?: boolean\n /** Memory isolation scope (default: 'per-user'). */\n scope?: MemoryScope\n /** Maximum facts to retain per scope (0 = unlimited). */\n maxFacts?: number\n}\n\nexport function Memory(options: MemoryOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(MEMORY_CONFIG, target, {\n provider: 'built-in',\n embeddings: false,\n fts: false,\n scope: 'per-user',\n ...options,\n })\n }\n}\n\nexport function getMemoryConfig(target: Function): MemoryOptions | undefined {\n return getMeta<MemoryOptions>(MEMORY_CONFIG, target)\n}\n","/**\n * @Skills() — declares markdown skill files injected into the agent's system prompt.\n *\n * Compiles to SDK's SkillsSettings in Agent.create({ skills }).\n * Skills are .theokit/skills/<name>/SKILL.md files discovered at agent creation.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/api/agents/support' })\n * @Skills(['customer-service', 'refund-policy', 'escalation-protocol'])\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst SKILLS_CONFIG = Symbol.for('theokit:agents:skills')\n\nexport interface SkillsOptions {\n /** Skill names to include (resolved from .theokit/skills/<name>/SKILL.md). */\n include: string[]\n /** Auto-discover all skills in .theokit/skills/ (default: false). */\n autoDiscover?: boolean\n}\n\nexport function Skills(namesOrOptions: string[] | SkillsOptions): ClassDecorator {\n return (target: Function) => {\n const options: SkillsOptions = Array.isArray(namesOrOptions)\n ? { include: namesOrOptions, autoDiscover: false }\n : namesOrOptions\n setMeta(SKILLS_CONFIG, target, options)\n }\n}\n\nexport function getSkillsConfig(target: Function): SkillsOptions | undefined {\n return getMeta<SkillsOptions>(SKILLS_CONFIG, target)\n}\n","/**\n * @MCP() — declares Model Context Protocol servers available to an agent.\n *\n * Compiles to SDK's mcpServers in Agent.create({ mcpServers }).\n * Each key is a server name; the value is the server configuration.\n *\n * @example\n * ```ts\n * @Agent({ name: 'dev', route: '/api/agents/dev' })\n * @MCP({\n * github: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] },\n * filesystem: { command: 'npx', args: ['-y', '@mcp/server-filesystem', '/workspace'] },\n * })\n * class DevAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst MCP_CONFIG = Symbol.for('theokit:agents:mcp')\n\nexport interface McpServerConfig {\n /** Command to start the MCP server. */\n command: string\n /** Arguments passed to the command. */\n args?: string[]\n /** Environment variables for the server process. */\n env?: Record<string, string>\n /** Working directory for the server process. */\n cwd?: string\n}\n\nexport type McpServersMap = Record<string, McpServerConfig>\n\nexport function MCP(servers: McpServersMap): ClassDecorator {\n return (target: Function) => {\n setMeta(MCP_CONFIG, target, servers)\n }\n}\n\nexport function getMcpConfig(target: Function): McpServersMap | undefined {\n return getMeta<McpServersMap>(MCP_CONFIG, target)\n}\n","/**\n * @HumanInTheLoop() — pause agent execution to request human approval.\n *\n * When applied to a @Tool method, the agent pauses before executing the tool\n * and emits an 'approval_required' SSE event. The client must POST to the\n * callback URL to approve or deny. If denied or timed out, the tool is skipped.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'ops' })\n * class OpsTools {\n * @Tool({ name: 'deploy', description: 'Deploy to prod', input: z.object({...}) })\n * @HumanInTheLoop({\n * question: 'Confirm deployment to production?',\n * timeout: 300_000,\n * onTimeout: 'abort',\n * })\n * async deploy(input: {...}) { ... }\n * }\n * ```\n *\n * SSE event emitted:\n * ```json\n * { \"type\": \"approval_required\", \"toolName\": \"ops.deploy\", \"question\": \"...\", \"callbackUrl\": \"/agents/x/approve/call-123\" }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst HITL_CONFIG = Symbol.for('theokit:agents:human-in-the-loop')\n\nexport type TimeoutAction = 'abort' | 'proceed' | 'retry'\n\nexport interface HumanInTheLoopOptions {\n /** Question shown to the human approver. */\n question: string\n /** Timeout in milliseconds before onTimeout fires (default: 300_000 = 5 min). */\n timeout?: number\n /** Action when timeout expires (default: 'abort'). */\n onTimeout?: TimeoutAction\n /** Show the tool input to the approver (default: true). */\n showInput?: boolean\n /**\n * M20 — an optional JSON-schema descriptor of the custom payload the approver may attach (edited\n * args, a review note). Carried into the `approval_required` event + `GET /approvals` so the UI\n * knows what to collect. A plain JSON object, not a live Zod schema (keeps the wire serializable).\n */\n payloadSchema?: Record<string, unknown>\n}\n\nexport function HumanInTheLoop(options: HumanInTheLoopOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(\n HITL_CONFIG,\n actualTarget,\n {\n timeout: 300_000,\n onTimeout: 'abort',\n showInput: true,\n ...options,\n },\n propertyKey,\n )\n }\n}\n\nexport function getHumanInTheLoopConfig(\n target: Function,\n propertyKey: string | symbol,\n): HumanInTheLoopOptions | undefined {\n return getMeta<HumanInTheLoopOptions>(HITL_CONFIG, target, propertyKey)\n}\n","/**\n * @ContextWindow() — declares context window management strategy.\n *\n * Controls how the agent handles context when conversation history grows\n * beyond the LLM's context window. Mirrors Claude Code's PreCompact behavior.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * @ContextWindow({\n * maxTokens: 100_000,\n * compactionStrategy: 'summarize-oldest',\n * preserveSystemPrompt: true,\n * preserveLastN: 10,\n * })\n * class ResearchAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CONTEXT_WINDOW_CONFIG = Symbol.for('theokit:agents:context-window')\n\nexport type ContextCompactionStrategy =\n | 'truncate-oldest' // Drop oldest messages beyond limit\n | 'summarize-oldest' // LLM-summarize oldest messages into a single message\n | 'sliding-window' // Keep last N messages only\n | 'priority-based' // Keep tool results + recent; summarize reasoning\n\nexport interface ContextWindowOptions {\n /** Maximum tokens before compaction triggers. */\n maxTokens?: number\n /** How to compact when maxTokens is exceeded. */\n compactionStrategy?: ContextCompactionStrategy\n /** Always preserve the system prompt during compaction (default: true). */\n preserveSystemPrompt?: boolean\n /** Number of recent messages to always keep intact (default: 10). */\n preserveLastN?: number\n /** Keep all tool results even during compaction (default: true). */\n preserveToolResults?: boolean\n}\n\nexport function ContextWindow(options: ContextWindowOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CONTEXT_WINDOW_CONFIG, target, {\n maxTokens: 100_000,\n compactionStrategy: 'summarize-oldest',\n preserveSystemPrompt: true,\n preserveLastN: 10,\n preserveToolResults: true,\n ...options,\n })\n }\n}\n\nexport function getContextWindowConfig(target: Function): ContextWindowOptions | undefined {\n return getMeta<ContextWindowOptions>(CONTEXT_WINDOW_CONFIG, target)\n}\n","/**\n * `@Compaction(name, opts)` — declares the agent's transcript-compaction strategy\n * (V4-F). Metadata-only: it records the choice; `AgentRunner.build()` resolves it\n * to a concrete {@link TranscriptCompactionStrategy} via `resolveCompactionStrategy`\n * (EC-5 — an invalid name/budget fails fast at build, not at decoration).\n *\n * Mirrors the `@ContextWindow` metadata pattern (`setMeta`/`getMeta` + a unique\n * Symbol). NOT auto-applied by the loop (ADR D1) — the resolved strategy is exposed\n * as `runner.compaction` for the app to call.\n *\n * @example\n * ```ts\n * @Agent({ model })\n * @Compaction('token-budget', { keepTokens: 8000 })\n * class CodeAgent {}\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst COMPACTION_CONFIG = Symbol.for('theokit:agents:compaction')\n\n/** Stored `@Compaction` declaration (resolved + validated at `AgentRunner.build()`). */\nexport interface CompactionDecoratorConfig {\n /** Strategy name (e.g. `'token-budget'`). Validated at resolve time. */\n name: string\n /** Token budget for `'token-budget'`. Required at resolve time (EC-2). */\n keepTokens?: number\n}\n\nexport function Compaction(name: string, options: { keepTokens?: number } = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(COMPACTION_CONFIG, target, { name, keepTokens: options.keepTokens })\n }\n}\n\nexport function getCompactionConfig(target: Function): CompactionDecoratorConfig | undefined {\n return getMeta<CompactionDecoratorConfig>(COMPACTION_CONFIG, target)\n}\n","/**\n * @Checkpoint() — enables resumable agent execution from the last successful step.\n *\n * Long-running agents (research, code review, multi-step workflows) can fail\n * partway through. Without checkpointing, users restart from step 1 — wasting\n * tokens, time, and cost.\n *\n * Inspired by tRPC's tracked() + lastEventId pattern and Dapr's actor state\n * checkpointing. The agent persists a recovery point after each successful\n * tool call or iteration, and can resume from that point on retry.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * @Checkpoint({\n * storage: 'filesystem', // only 'filesystem' resumes across requests in the M2 harness (M4)\n * strategy: 'after-tool-call',\n * maxCheckpoints: 20,\n * ttl: 3_600_000, // 1h\n * })\n * class ResearchAgent {\n * @MainLoop({ strategy: 'plan-act-reflect', maxIterations: 15 })\n * async run() {}\n * }\n *\n * // Resume: a follow-up POST /api/agents/research with the SAME sessionId replays the persisted\n * // history. NOTE (M4): only `storage: 'filesystem'` resumes across requests today — `memory`\n * // (the default below) is per-run; `drizzle`/`redis` are not shipped by the SDK. A non-filesystem\n * // @Checkpoint emits a THEO_AGENT_CHECKPOINT_STORAGE_METADATA_ONLY warning (honest enforcement).\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CHECKPOINT_CONFIG = Symbol.for('theokit:agents:checkpoint')\n\nexport type CheckpointStrategy =\n | 'after-tool-call' // checkpoint after every successful tool execution\n | 'after-iteration' // checkpoint after every loop iteration\n | 'manual' // only checkpoint when explicitly called via ctx.checkpoint()\n\nexport type CheckpointStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis'\n\nexport interface CheckpointOptions {\n /** Where to persist checkpoints. */\n storage?: CheckpointStorage\n /** When to auto-checkpoint (default: 'after-tool-call'). */\n strategy?: CheckpointStrategy\n /** Maximum checkpoints to retain per run (rolling window). */\n maxCheckpoints?: number\n /** Time-to-live in ms before checkpoints expire (default: 3_600_000 = 1h). */\n ttl?: number\n}\n\n/** Serializable checkpoint state. */\nexport interface CheckpointState {\n id: string\n runId: string\n agentName: string\n step: number\n messages: unknown[]\n toolResults: unknown[]\n createdAt: number\n resumeToken: string\n}\n\nexport function Checkpoint(options: CheckpointOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CHECKPOINT_CONFIG, target, {\n storage: 'memory',\n strategy: 'after-tool-call',\n maxCheckpoints: 10,\n ttl: 3_600_000,\n ...options,\n })\n }\n}\n\nexport function getCheckpointConfig(target: Function): CheckpointOptions | undefined {\n return getMeta<CheckpointOptions>(CHECKPOINT_CONFIG, target)\n}\n","/**\n * @ProjectContext() — declares how the agent understands the codebase.\n *\n * A code assistant needs to know: what's the project root, which files\n * are relevant, how to parse code structure, what to ignore. This\n * metadata feeds the context window management and file discovery.\n *\n * @example\n * ```ts\n * @Agent({ name: 'coder', route: '/agents/coder' })\n * @ProjectContext({\n * rootMarkers: ['package.json', 'tsconfig.json'],\n * indexStrategy: 'tree-sitter',\n * maxFilesInContext: 20,\n * relevanceStrategy: 'git-history',\n * ignorePatterns: ['node_modules', 'dist', '.git'],\n * })\n * class CoderAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst PROJECT_CONTEXT_CONFIG = Symbol.for('theokit:agents:project-context')\n\nexport type IndexStrategy =\n | 'tree-sitter' // Parse AST for structural understanding\n | 'regex' // Simple regex-based symbol extraction\n | 'none' // No indexing — rely on grep/glob only\n\nexport type RelevanceStrategy =\n | 'git-history' // Prioritize recently-edited files\n | 'import-graph' // Follow import chains from entry points\n | 'semantic' // Embedding-based similarity search\n | 'manual' // Only files explicitly provided\n\nexport interface ProjectContextOptions {\n /** Files that mark the project root (searched upward from cwd). */\n rootMarkers?: string[]\n /** How to index the codebase for structural understanding. */\n indexStrategy?: IndexStrategy\n /** Maximum files to include in context per request. */\n maxFilesInContext?: number\n /** How to rank file relevance when selecting context. */\n relevanceStrategy?: RelevanceStrategy\n /** Glob patterns to exclude from indexing and context. */\n ignorePatterns?: string[]\n /** File extensions to include in indexing (default: all text files). */\n includeExtensions?: string[]\n}\n\nexport function ProjectContext(options: ProjectContextOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(PROJECT_CONTEXT_CONFIG, target, {\n rootMarkers: ['package.json', 'tsconfig.json', 'go.mod', 'Cargo.toml', 'pyproject.toml'],\n indexStrategy: 'regex',\n maxFilesInContext: 20,\n relevanceStrategy: 'git-history',\n ignorePatterns: ['node_modules', 'dist', 'build', '.git', 'coverage', '__pycache__'],\n ...options,\n })\n }\n}\n\nexport function getProjectContextConfig(target: Function): ProjectContextOptions | undefined {\n return getMeta<ProjectContextOptions>(PROJECT_CONTEXT_CONFIG, target)\n}\n","/**\n * @Mixin() — compose reusable capability classes into an agent.\n *\n * Mixins are classes with @Tool methods that can be shared across agents.\n * @Mixin copies tool metadata from mixin classes to the decorated agent,\n * making those tools available without inheritance.\n *\n * @example\n * ```ts\n * // Define reusable capabilities\n * class WithSearchCapability {\n * @Tool({ name: 'web_search', description: 'Search', input: z.object({...}) })\n * async webSearch(input) { ... }\n * }\n *\n * class WithFileSystem {\n * @Tool({ name: 'read_file', description: 'Read', input: z.object({...}) })\n * async readFile(input) { ... }\n * }\n *\n * // Compose into agent\n * @Agent({ name: 'research', route: '/research' })\n * @Mixin(WithSearchCapability, WithFileSystem)\n * class ResearchAgent {\n * @MainLoop()\n * async run() {}\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst MIXIN_CLASSES = Symbol.for('theokit:agents:mixins')\n\nexport function Mixin(...mixinClasses: Function[]): ClassDecorator {\n return (target: Function) => {\n const existing = getMeta<Function[]>(MIXIN_CLASSES, target) ?? []\n setMeta(MIXIN_CLASSES, target, [...existing, ...mixinClasses])\n }\n}\n\nexport function getMixins(target: Function): Function[] {\n return getMeta<Function[]>(MIXIN_CLASSES, target) ?? []\n}\n"],"mappings":";;;;;AAEA,SAASA,SAASC,eAAe;;;ACA1B,IAAMC,eAAeC,uBAAOC,IAAI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_LOOP","TOOLBOX_CONFIG","TOOL_CONFIG","TOOL_METHODS","inferAgentMeta","className","stripped","replace","kebab","toLowerCase","name","route","Agent","options","target","inferred","setMeta","AGENT_CONFIG","stream","getAgentConfig","getMeta","createDecorator","RequiresApproval","RequiresCapability","Budget","Policy","createDecorator","Trace","Audit","GATEWAY_CONFIG","Symbol","for","Gateway","options","target","setMeta","typing","sessionStrategy","getGatewayConfig","getMeta","resolveSessionId","strategy","platform","sender","channel","id","topicId","SUB_AGENTS","Symbol","for","SubAgents","agentClasses","target","cls","config","getAgentConfig","Error","name","setMeta","getSubAgents","getMeta","MEMORY_CONFIG","Symbol","for","Memory","options","target","setMeta","provider","embeddings","fts","scope","getMemoryConfig","getMeta","SKILLS_CONFIG","Symbol","for","Skills","namesOrOptions","target","options","Array","isArray","include","autoDiscover","setMeta","getSkillsConfig","getMeta","MCP_CONFIG","Symbol","for","MCP","servers","target","setMeta","getMcpConfig","getMeta","HITL_CONFIG","Symbol","for","HumanInTheLoop","options","target","propertyKey","actualTarget","setMeta","timeout","onTimeout","showInput","getHumanInTheLoopConfig","getMeta","CONTEXT_WINDOW_CONFIG","Symbol","for","ContextWindow","options","target","setMeta","maxTokens","compactionStrategy","preserveSystemPrompt","preserveLastN","preserveToolResults","getContextWindowConfig","getMeta","COMPACTION_CONFIG","Symbol","for","Compaction","name","options","target","setMeta","keepTokens","getCompactionConfig","getMeta","CHECKPOINT_CONFIG","Symbol","for","Checkpoint","options","target","setMeta","storage","strategy","maxCheckpoints","ttl","getCheckpointConfig","getMeta","PROJECT_CONTEXT_CONFIG","Symbol","for","ProjectContext","options","target","setMeta","rootMarkers","indexStrategy","maxFilesInContext","relevanceStrategy","ignorePatterns","getProjectContextConfig","getMeta","MIXIN_CLASSES","Symbol","for","Mixin","mixinClasses","target","existing","getMeta","setMeta","getMixins"]}