@theokit/agents 0.6.0 → 0.8.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 +0,0 @@
1
- {"version":3,"sources":["../src/bridge/agent-execution-context.ts","../src/bridge/compile-context-window.ts","../src/bridge/compile-project-context.ts","../src/bridge/walk-agent-metadata.ts","../src/bridge/compile-skills.ts","../src/bridge/agent-compiler.ts","../src/bridge/agent-sse-handler.ts","../src/bridge/agent-stream-events.ts","../src/bridge/agent-route-generator.ts","../src/bridge/event-translator.ts","../src/bridge/sdk-adapter.ts","../src/loop/loop-strategy.ts","../src/loop/reflection-strategy.ts","../src/bridge/delegation-types.ts","../src/loop/run-reflective-loop.ts","../src/loop/agent-runner.ts","../src/bridge/agent-orchestrator.ts","../src/manifest/agent-manifest.ts","../src/theokit-plugin.ts"],"sourcesContent":["/**\n * AgentExecutionContext — extends http-decorators' ExecutionContext with agent-specific methods.\n *\n * Per ADR D2 (LSP): any guard that accepts ExecutionContext works unchanged with\n * AgentExecutionContext. Agent-specific guards can narrow via isAgentContext().\n */\nimport type { ExecutionContext } from '@theokit/http'\n\nimport type { AgentOptions, ToolOptions } from '../types.js'\n\nexport interface AgentRunInfo {\n id: string\n startedAt: Date\n}\n\nexport interface AgentExecutionContext extends ExecutionContext {\n /** The agent's configuration from @Agent() decorator. */\n getAgent(): AgentOptions\n /** The current run information. */\n getRun(): AgentRunInfo\n /** The tool being called, or null if in the main agent handler. */\n getToolCall(): ToolOptions | null\n /** Type guard — always true for AgentExecutionContext. */\n isAgentContext(): true\n}\n\n/** Create an AgentExecutionContext from a base ExecutionContext + agent state. */\nexport function createAgentExecutionContext(\n base: ExecutionContext,\n agent: AgentOptions,\n run: AgentRunInfo,\n toolCall?: ToolOptions,\n): AgentExecutionContext {\n return {\n getRequest: () => base.getRequest(),\n getUrl: () => base.getUrl(),\n getClass: () => base.getClass(),\n getMethodName: () => base.getMethodName(),\n getAgent: () => agent,\n getRun: () => run,\n getToolCall: () => toolCall ?? null,\n isAgentContext: () => true as const,\n }\n}\n\n/** Narrow an ExecutionContext to AgentExecutionContext if it is one. */\nexport function isAgentContext(ctx: ExecutionContext): ctx is AgentExecutionContext {\n return 'isAgentContext' in ctx && (ctx as AgentExecutionContext).isAgentContext()\n}\n","/**\n * M8-1 — compile `@ContextWindow` metadata into the SDK's `ContextSettings`.\n *\n * Per sdk-runtime.md, the SDK owns session/transcript storage + compaction.\n * The bridge therefore maps the one knob the SDK natively exposes as a budget —\n * `maxTokens` → `ContextSettings.maxTokens` — and reports the strategy knobs that\n * have NO native `AgentOptions` equivalent (`compactionStrategy`, `preserveLastN`,\n * `preserveToolResults`, `preserveSystemPrompt`). Those are surfaced as\n * `metadataOnlyKnobs` so the walk can emit an honest `metadata-only` warning\n * (ADR D2) instead of silently dropping them (G10 — honest enforcement).\n */\nimport type { ContextSettings } from '@theokit/sdk'\n\nimport type { ContextWindowOptions } from '../decorators/context-window.js'\n\n/** `@ContextWindow` knobs with no native SDK `AgentOptions` mapping. */\nconst STRATEGY_KNOBS = [\n 'compactionStrategy',\n 'preserveLastN',\n 'preserveToolResults',\n 'preserveSystemPrompt',\n] as const\n\nexport interface CompiledContextWindow {\n /** SDK-shaped context budget passed to `Agent.create({ context })`. */\n context: ContextSettings\n /** Declared knobs the SDK does not expose — reported, never silently dropped. */\n metadataOnlyKnobs: string[]\n}\n\nexport function compileContextWindow(options: ContextWindowOptions): CompiledContextWindow {\n const context: ContextSettings = {}\n if (typeof options.maxTokens === 'number') {\n context.maxTokens = options.maxTokens\n }\n\n const opts = options as Record<string, unknown>\n const metadataOnlyKnobs = STRATEGY_KNOBS.filter((knob) => opts[knob] !== undefined)\n\n return { context, metadataOnlyKnobs }\n}\n","/**\n * M8-2 — compile `@ProjectContext` metadata into an SDK `SystemPromptResolver`.\n *\n * There is no native `AgentOptions` field that carries a repo map, so the bridge\n * composes the documented `systemPrompt` seam (`string | SystemPromptResolver`):\n * the resolver prepends `buildEnvContext` + `buildRepoMap` (`@theokit/sdk-tools`)\n * and the nearest `THEO.md` (`@theokit/sdk/project#readProjectInstructions`) to\n * the agent's base prompt (ADR D3). The SDK primitives are dynamically imported\n * so `@theokit/sdk-tools` stays an OPTIONAL peer — only loaded when a `@ProjectContext`\n * agent actually sends.\n *\n * Knobs with no primitive mapping (`indexStrategy`, `relevanceStrategy`,\n * `maxFilesInContext`, `includeExtensions`, `rootMarkers`) are reported via\n * {@link projectContextMetadataOnlyKnobs} so the walk warns honestly (G10).\n * Only `ignorePatterns` is forwarded (to `buildRepoMap`).\n */\nimport type { SystemPromptResolver } from '@theokit/sdk'\n\nimport type { ProjectContextOptions } from '../decorators/project-context.js'\n\n/** `@ProjectContext` knobs with no primitive mapping (reported, not executed). */\nconst UNMAPPED_KNOBS = [\n 'indexStrategy',\n 'relevanceStrategy',\n 'maxFilesInContext',\n 'includeExtensions',\n 'rootMarkers',\n] as const\n\nexport function projectContextMetadataOnlyKnobs(options: ProjectContextOptions): string[] {\n const opts = options as Record<string, unknown>\n return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== undefined)\n}\n\n/**\n * Build a `SystemPromptResolver` that prepends env + repo map + project\n * instructions to `base`. When the SDK provides no `cwd`, the resolver returns\n * `base` unchanged (no filesystem guess — keeps `packages/agents/src` free of\n * direct Node `process` access per G8; the repo map needs a real cwd).\n */\nexport function compileProjectContext(\n options: ProjectContextOptions,\n base?: string,\n): SystemPromptResolver {\n return async (promptCtx) => {\n const cwd = promptCtx.cwd\n if (!cwd) {\n return base ?? ''\n }\n\n const { buildEnvContext, buildRepoMap } = await import('@theokit/sdk-tools')\n const { readProjectInstructions } = await import('@theokit/sdk/project')\n\n const env = buildEnvContext(cwd)\n const repoMap = buildRepoMap(cwd, { ignore: options.ignorePatterns })\n\n let instructions = ''\n try {\n instructions = (await readProjectInstructions(cwd)).content ?? ''\n } catch {\n // readProjectInstructions is best-effort: a missing/unreadable THEO.md must\n // never break a send. buildEnvContext/buildRepoMap are never-throw by contract.\n instructions = ''\n }\n\n return [env, repoMap, instructions, base].filter(Boolean).join('\\n\\n')\n }\n}\n","/**\n * Walk decorator metadata on agent + toolbox classes.\n * Mirrors http-decorators' walkControllerMetadata() pattern.\n *\n * EC-1: throws if @Agent class is missing @MainLoop.\n * EC-4: throws on duplicate routes across agents.\n */\nimport 'reflect-metadata'\n\nimport { Reflector } from '@theokit/http'\n\nimport { getContextWindowConfig } from '../decorators/context-window.js'\nimport type { ContextWindowOptions } from '../decorators/context-window.js'\nimport type { GatewayOptions } from '../decorators/gateway.js'\nimport { getGatewayConfig } from '../decorators/gateway.js'\nimport { getMcpConfig } from '../decorators/mcp.js'\nimport type { McpServersMap } from '../decorators/mcp.js'\nimport { getMemoryConfig } from '../decorators/memory.js'\nimport type { MemoryOptions } from '../decorators/memory.js'\nimport { Trace, Audit } from '../decorators/observability.js'\nimport { RequiresApproval, Budget } from '../decorators/policies.js'\nimport type { ProjectContextOptions } from '../decorators/project-context.js'\nimport { getProjectContextConfig } from '../decorators/project-context.js'\nimport { getSkillsConfig } from '../decorators/skills.js'\nimport type { SkillsOptions } from '../decorators/skills.js'\nimport { getSubAgents } from '../decorators/sub-agents.js'\nimport { getMeta } from '../metadata/index.js'\nimport {\n AGENT_CONFIG,\n AGENT_MAIN_LOOP,\n TOOLBOX_CONFIG,\n TOOL_CONFIG,\n TOOL_METHODS,\n} from '../metadata/keys.js'\nimport type {\n AgentOptions,\n MainLoopMeta,\n ToolboxOptions,\n ToolOptions,\n ApprovalOptions,\n BudgetOptions,\n} from '../types.js'\n\nimport { compileContextWindow } from './compile-context-window.js'\nimport { projectContextMetadataOnlyKnobs } from './compile-project-context.js'\n\n// http-decorators metadata keys for pipeline reuse\nconst USE_GUARDS = Symbol.for('theokit:http-decorators:use-guards')\nconst USE_INTERCEPTORS = Symbol.for('theokit:http-decorators:use-interceptors')\nconst USE_FILTERS = Symbol.for('theokit:http-decorators:use-filters')\n\n/**\n * Stable warning codes for agent pipeline metadata-only decorators.\n * Test by code, not by message string. Document in agent support matrix.\n */\nexport const AgentWarningCode = {\n INTERCEPTOR_METADATA_ONLY: 'THEO_AGENT_INTERCEPTOR_METADATA_ONLY',\n FILTER_METADATA_ONLY: 'THEO_AGENT_FILTER_METADATA_ONLY',\n BUDGET_TOP_LEVEL_METADATA_ONLY: 'THEO_AGENT_BUDGET_TOP_LEVEL_METADATA_ONLY',\n CONTEXT_STRATEGY_METADATA_ONLY: 'THEO_AGENT_CONTEXT_STRATEGY_METADATA_ONLY',\n PROJECT_CONTEXT_KNOB_METADATA_ONLY: 'THEO_AGENT_PROJECT_CONTEXT_KNOB_METADATA_ONLY',\n} as const\n\nconst reflectorInstance = new Reflector()\n\nexport interface AgentWalkResult {\n agentConfig: AgentOptions\n mainLoop: MainLoopMeta\n toolboxes: ToolboxWalkResult[]\n guards: Function[]\n interceptors: Function[]\n filters: Function[]\n route: string\n gateway?: GatewayOptions\n subAgentClasses: Function[]\n memory?: MemoryOptions\n skills?: SkillsOptions\n contextWindow?: ContextWindowOptions\n projectContext?: ProjectContextOptions\n mcpServers?: McpServersMap\n}\n\nexport interface ToolboxWalkResult {\n class: Function\n namespace: string\n tools: ToolWalkResult[]\n guards: Function[]\n}\n\nexport interface ToolWalkResult {\n propertyKey: string | symbol\n config: ToolOptions\n guards: Function[]\n approval?: ApprovalOptions\n capabilities?: string[]\n budget?: BudgetOptions\n trace: boolean\n audit: boolean\n}\n\nfunction walkToolbox(ToolboxClass: Function): ToolboxWalkResult {\n const config = getMeta<ToolboxOptions>(TOOLBOX_CONFIG, ToolboxClass) ?? {}\n const methods = getMeta<(string | symbol)[]>(TOOL_METHODS, ToolboxClass) ?? []\n const classGuards = getMeta<Function[]>(USE_GUARDS, ToolboxClass) ?? []\n\n const tools: ToolWalkResult[] = methods.map((propertyKey) => {\n const toolConfig = getMeta<ToolOptions>(TOOL_CONFIG, ToolboxClass, propertyKey)\n if (!toolConfig) {\n throw new Error(\n `[@theokit/agents] Toolbox ${ToolboxClass.name}: method '${String(propertyKey)}' is in TOOL_METHODS but has no @Tool() config.`,\n )\n }\n\n const methodGuards = getMeta<Function[]>(USE_GUARDS, ToolboxClass, propertyKey) ?? []\n\n // Read typed decorator metadata via Reflector (not generic readTypedMeta)\n const ref = reflectorInstance\n\n const approvalVal = ref.get(RequiresApproval, ToolboxClass, propertyKey)\n const traceVal = ref.get(Trace, ToolboxClass, propertyKey)\n const auditVal = ref.get(Audit, ToolboxClass, propertyKey)\n\n return {\n propertyKey,\n config: toolConfig,\n guards: [...classGuards, ...methodGuards],\n approval:\n approvalVal && typeof approvalVal === 'object' && 'reason' in approvalVal\n ? approvalVal\n : undefined,\n capabilities: undefined, // read via RequiresCapability when needed\n budget: undefined, // read via Budget when needed\n trace: traceVal ?? false,\n audit: auditVal ?? false,\n }\n })\n\n return {\n class: ToolboxClass,\n namespace: config.namespace ?? '',\n tools,\n guards: classGuards,\n }\n}\n\n/**\n * Emit one `metadata-only` warning per M8 decorator whose declared knobs have no\n * native SDK mapping. Extracted from {@link walkAgentMetadata} to keep its\n * cyclomatic complexity within budget (G6).\n */\nfunction warnUnmappedDecoratorKnobs(\n agentName: string,\n contextWindow: ContextWindowOptions | undefined,\n projectContext: ProjectContextOptions | undefined,\n): void {\n if (contextWindow) {\n const { metadataOnlyKnobs } = compileContextWindow(contextWindow)\n if (metadataOnlyKnobs.length > 0) {\n console.warn(\n `[${AgentWarningCode.CONTEXT_STRATEGY_METADATA_ONLY}] Agent ${agentName}: ` +\n `@ContextWindow knob(s) ${metadataOnlyKnobs.join(', ')} are metadata-only — ` +\n `the SDK manages transcript compaction internally. Only maxTokens is forwarded ` +\n `to Agent.create({ context }).`,\n )\n }\n }\n\n if (projectContext) {\n const unmapped = projectContextMetadataOnlyKnobs(projectContext)\n if (unmapped.length > 0) {\n console.warn(\n `[${AgentWarningCode.PROJECT_CONTEXT_KNOB_METADATA_ONLY}] Agent ${agentName}: ` +\n `@ProjectContext knob(s) ${unmapped.join(', ')} are metadata-only — ` +\n `the repo map is composed via buildRepoMap/buildEnvContext/readProjectInstructions; ` +\n `only ignorePatterns is forwarded.`,\n )\n }\n }\n}\n\n/** WeakMap cache — metadata is immutable; walk once per class. */\nconst agentWalkCache = new WeakMap<Function, AgentWalkResult>()\n\n/**\n * Walk all metadata on an agent class and its toolboxes.\n * Memoized per AgentClass via WeakMap.\n *\n * @throws Error if @Agent is missing @MainLoop (EC-1)\n */\nexport function walkAgentMetadata(\n AgentClass: Function,\n toolboxClasses: Function[] = [],\n): AgentWalkResult {\n // Cache key is AgentClass only (toolboxes are typically stable per agent)\n if (toolboxClasses.length === 0) {\n const cached = agentWalkCache.get(AgentClass)\n if (cached) return cached\n }\n const agentConfig = getMeta<AgentOptions>(AGENT_CONFIG, AgentClass)\n if (!agentConfig) {\n throw new Error(`[@theokit/agents] Class ${AgentClass.name} is missing @Agent() decorator.`)\n }\n\n const mainLoop = getMeta<MainLoopMeta>(AGENT_MAIN_LOOP, AgentClass)\n if (!mainLoop) {\n throw new Error(\n `[@theokit/agents] Agent ${AgentClass.name} is missing @MainLoop() decorator. ` +\n `Decorate exactly one method with @MainLoop().`,\n )\n }\n\n const guards = getMeta<Function[]>(USE_GUARDS, AgentClass) ?? []\n\n // Interceptors and filters are read but NOT enforced in agent pipeline.\n // Agent pipeline only shares guards with HTTP; interceptors/filters have\n // different lifecycle semantics (HTTP wraps a single handler; agents run\n // a multi-step loop with tool calls, streaming, checkpoints).\n // Warn explicitly so developers don't expect enforcement silently.\n const interceptors = getMeta<Function[]>(USE_INTERCEPTORS, AgentClass) ?? []\n if (interceptors.length > 0) {\n console.warn(\n `[${AgentWarningCode.INTERCEPTOR_METADATA_ONLY}] Agent ${AgentClass.name}: ` +\n `@UseInterceptors is metadata-only on agents and will not execute. ` +\n `Agent pipeline shares guards with HTTP but uses a distinct execution model. ` +\n `Interceptors are reserved for future agent-specific lifecycle hooks.`,\n )\n }\n\n const filters = getMeta<Function[]>(USE_FILTERS, AgentClass) ?? []\n if (filters.length > 0) {\n console.warn(\n `[${AgentWarningCode.FILTER_METADATA_ONLY}] Agent ${AgentClass.name}: ` +\n `@UseFilters is metadata-only on agents and will not catch agent runtime errors. ` +\n `Agent errors flow through SSE error events, not HTTP exception filters. ` +\n `Filters are reserved for future agent-specific error handling.`,\n )\n }\n\n // @Budget on agent class: metadata-only for top-level agents.\n // Budget enforcement is active only in delegate() (sub-agent calls) where\n // the orchestrator clamps cost mid-stream. Top-level agent budget depends\n // on the SDK's cost reporting in DoneEvent.\n const agentBudget = reflectorInstance.get(Budget, AgentClass)\n if (agentBudget) {\n console.warn(\n `[${AgentWarningCode.BUDGET_TOP_LEVEL_METADATA_ONLY}] Agent ${AgentClass.name}: ` +\n `@Budget on top-level agents is metadata-only in this version. ` +\n `Budget enforcement currently applies to delegate() calls only. ` +\n `Top-level run enforcement will be wired through SDK cost tracking in a future release.`,\n )\n }\n\n const toolboxes = toolboxClasses.map(walkToolbox)\n const gateway = getGatewayConfig(AgentClass)\n const subAgentClasses = getSubAgents(AgentClass)\n const memory = getMemoryConfig(AgentClass)\n const skills = getSkillsConfig(AgentClass)\n const mcpServers = getMcpConfig(AgentClass)\n\n // M8: @ContextWindow + @ProjectContext have native SDK mappings for only a\n // subset of their knobs; warn once for the rest (honest enforcement, G10).\n const contextWindow = getContextWindowConfig(AgentClass)\n const projectContext = getProjectContextConfig(AgentClass)\n warnUnmappedDecoratorKnobs(AgentClass.name, contextWindow, projectContext)\n\n const result: AgentWalkResult = {\n agentConfig,\n mainLoop,\n toolboxes,\n guards,\n interceptors,\n filters,\n route: agentConfig.route,\n gateway,\n subAgentClasses,\n memory,\n skills,\n contextWindow,\n projectContext,\n mcpServers,\n }\n\n if (toolboxClasses.length === 0) {\n agentWalkCache.set(AgentClass, result)\n }\n return result\n}\n\n/**\n * Validate that no two agents share the same route prefix.\n *\n * @throws Error on duplicate routes (EC-4)\n */\nexport function validateUniqueRoutes(results: AgentWalkResult[]): void {\n const seen = new Map<string, string>()\n for (const r of results) {\n const existing = seen.get(r.route)\n if (existing) {\n throw new Error(\n `[@theokit/agents] Duplicate agent route '${r.route}': ` +\n `both '${existing}' and '${r.agentConfig.name}' declare it.`,\n )\n }\n seen.set(r.route, r.agentConfig.name)\n }\n}\n","/**\n * M8-3 — compile `@Skills` metadata into the SDK's `SkillsSettings`.\n *\n * Per sdk-runtime.md: the bridge COMPILES decorator metadata into a format the\n * SDK accepts; the SDK is the runtime. `Agent.create({ skills })` natively\n * discovers `.theokit/skills/<name>/SKILL.md` files and injects the `<skills>`\n * block — so giving `@Skills` runtime is a pure shape translation, not a\n * reimplementation of discovery.\n *\n * Mapping (ADR D4):\n * - `{ include }` → `{ enabled: include, autoInject: true }`\n * - `{ autoDiscover: true }` → `{ autoInject: true }` (enabled omitted ⇒ the SDK\n * enables every discovered skill)\n */\nimport type { SkillsSettings } from '@theokit/sdk'\n\nimport type { SkillsOptions } from '../decorators/skills.js'\n\nexport function compileSkills(options: SkillsOptions): SkillsSettings {\n if (options.autoDiscover) {\n return { autoInject: true }\n }\n return { enabled: options.include, autoInject: true }\n}\n","/**\n * Agent compiler — transforms decorator metadata into SDK calls.\n *\n * Per ADR D1: @Agent is a macro over Agent.create().\n * Per ADR D3: @Tool compiles to defineTool().\n *\n * EC-3: throws if toolbox instance is missing from the instances map.\n */\nimport type { ContextSettings, SkillsSettings } from '@theokit/sdk'\n\nimport { getAgentConfig } from '../decorators/agent.js'\nimport type { McpServersMap } from '../decorators/mcp.js'\nimport type { MemoryOptions } from '../decorators/memory.js'\nimport type { ProjectContextOptions } from '../decorators/project-context.js'\n\nimport { compileContextWindow } from './compile-context-window.js'\nimport { compileSkills } from './compile-skills.js'\nimport type { ToolboxWalkResult, AgentWalkResult } from './walk-agent-metadata.js'\n\n/** Minimal interface matching defineTool() result shape. */\nexport interface CompiledTool {\n name: string\n description: string\n inputSchema: unknown\n handler: (input: unknown) => string | Promise<string>\n}\n\n/**\n * Compile @Tool metadata into tool definitions.\n *\n * @param toolboxes - Walked toolbox metadata\n * @param toolboxInstances - Map of Toolbox class → instantiated object (for `this` binding)\n */\nexport function compileTools(\n toolboxes: ToolboxWalkResult[],\n toolboxInstances: Map<Function, object>,\n): CompiledTool[] {\n const tools: CompiledTool[] = []\n\n for (const tb of toolboxes) {\n // EC-3: guard against missing toolbox instance\n const instance = toolboxInstances.get(tb.class)\n if (!instance) {\n throw new Error(\n `[@theokit/agents] Toolbox ${tb.class.name} not instantiated — add to providers or pass instances.`,\n )\n }\n\n for (const tool of tb.tools) {\n const handler = (instance as Record<string | symbol, Function>)[tool.propertyKey]\n if (typeof handler !== 'function') {\n throw new Error(\n `[@theokit/agents] Toolbox ${tb.class.name}: '${String(tool.propertyKey)}' is not a function.`,\n )\n }\n\n const name = tb.namespace ? `${tb.namespace}.${tool.config.name}` : tool.config.name\n\n tools.push({\n name,\n description: tool.config.description,\n inputSchema: tool.config.input,\n handler: (input: unknown) => handler.call(instance, input) as string | Promise<string>,\n })\n }\n }\n\n return tools\n}\n\n/** Compiled sub-agent definition matching SDK AgentDefinition shape. */\nexport interface CompiledSubAgent {\n model?: string\n systemPrompt?: string\n}\n\n/** Compiled agent options ready for SDK Agent.create(). */\nexport interface CompiledAgentOptions {\n model?: string\n systemPrompt?: string\n tools: CompiledTool[]\n agents: Record<string, CompiledSubAgent>\n memory?: MemoryOptions\n skills?: SkillsSettings\n context?: ContextSettings\n /** Raw @ProjectContext config; the adapter builds the (async) systemPrompt resolver from it. */\n projectContext?: ProjectContextOptions\n mcpServers?: McpServersMap\n maxIterations?: number\n timeoutMs?: number\n stream: boolean\n}\n\n/**\n * Compile @SubAgents references into SDK agents map.\n * Each sub-agent class must have @Agent() metadata.\n */\nexport function compileSubAgents(subAgentClasses: Function[]): Record<string, CompiledSubAgent> {\n const agents: Record<string, CompiledSubAgent> = {}\n for (const cls of subAgentClasses) {\n const config = getAgentConfig(cls)\n if (!config) continue // validated at decoration time\n agents[config.name] = {\n model: config.model,\n systemPrompt: config.systemPrompt,\n }\n }\n return agents\n}\n\n/**\n * Compile @Agent metadata into SDK-compatible options.\n *\n * EC-7: agents without toolboxes produce tools: [].\n */\nexport function compileAgent(\n walkResult: AgentWalkResult,\n toolboxInstances = new Map<Function, object>(),\n): CompiledAgentOptions {\n const tools = compileTools(walkResult.toolboxes, toolboxInstances)\n const agents = compileSubAgents(walkResult.subAgentClasses)\n\n return {\n model: walkResult.agentConfig.model,\n systemPrompt: walkResult.agentConfig.systemPrompt,\n tools,\n agents,\n memory: walkResult.memory,\n skills: walkResult.skills ? compileSkills(walkResult.skills) : undefined,\n context: walkResult.contextWindow\n ? compileContextWindow(walkResult.contextWindow).context\n : undefined,\n projectContext: walkResult.projectContext,\n mcpServers: walkResult.mcpServers,\n maxIterations: walkResult.mainLoop.maxIterations ?? walkResult.agentConfig.maxIterations,\n timeoutMs: walkResult.mainLoop.timeoutMs ?? walkResult.agentConfig.timeoutMs,\n stream: walkResult.agentConfig.stream ?? true,\n }\n}\n","/**\n * SSE streaming handler — Web Standard Response with ReadableStream.\n *\n * Per ADR D4: SSE is the v1 transport.\n * Per EC-2: uses ReadableStream with controller.enqueue() instead of res.write().\n * Works natively on Node, Bun, Deno, CF Workers.\n */\n\n/** Minimal event shape matching SDK's SDKMessage discriminated union. */\nexport interface StreamEvent {\n type: string\n [key: string]: unknown\n}\n\nconst encoder = new TextEncoder()\n\n/**\n * Create a Web Standard Response that streams SSE events.\n * Each event becomes: `event: {type}\\ndata: {json}\\n\\n`\n */\nexport function streamAgentResponse(\n eventStream: AsyncIterable<StreamEvent>,\n): Response {\n const stream = new ReadableStream({\n async start(controller) {\n let closed = false\n const safeEnqueue = (chunk: Uint8Array) => {\n if (closed) return\n try { controller.enqueue(chunk) } catch { closed = true }\n }\n try {\n for await (const event of eventStream) {\n if (closed) break // eslint-disable-line @typescript-eslint/no-unnecessary-condition -- mutated by safeEnqueue catch\n const data = JSON.stringify(event)\n const frame = `event: ${event.type}\\ndata: ${data}\\n\\n`\n safeEnqueue(encoder.encode(frame))\n }\n } catch (err) {\n if (!closed) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition -- mutated by safeEnqueue catch\n const errorEvent = {\n type: 'error',\n error: { message: err instanceof Error ? err.message : 'Internal agent error' },\n }\n const frame = `event: error\\ndata: ${JSON.stringify(errorEvent)}\\n\\n`\n safeEnqueue(encoder.encode(frame))\n }\n } finally {\n controller.close()\n }\n },\n })\n\n return new Response(stream, {\n status: 200,\n headers: {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache',\n 'connection': 'keep-alive',\n },\n })\n}\n","/**\n * Typed discriminated union for agent SSE stream events.\n *\n * Every event has a `type` field for discrimination.\n * Clients narrow via `if (event.type === 'text_delta') event.content`.\n */\n\n/** Partial text content from the LLM. */\nexport interface TextDeltaEvent {\n type: 'text_delta'\n content: string\n}\n\n/** Agent started a tool call. */\nexport interface ToolCallEvent {\n type: 'tool_call'\n callId: string\n toolName: string\n input: unknown\n}\n\n/** Tool execution completed. */\nexport interface ToolResultEvent {\n type: 'tool_result'\n callId: string\n toolName: string\n output: string\n durationMs: number\n isError: boolean\n}\n\n/** Extended thinking / reasoning (when model supports it). */\nexport interface ThinkingEvent {\n type: 'thinking'\n content: string\n}\n\n/** Agent loop iteration. */\nexport interface IterationEvent {\n type: 'iteration'\n step: number\n totalSteps: number | null\n}\n\n/** Human approval required before proceeding. */\nexport interface ApprovalRequiredEvent {\n type: 'approval_required'\n callId: string\n toolName: string\n question: string\n input?: unknown\n callbackUrl: string\n timeoutMs: number\n}\n\n/** Agent encountered an error. */\nexport interface ErrorEvent {\n type: 'error'\n code: string\n message: string\n retryable: boolean\n}\n\n/** Agent completed with a final result. */\nexport interface DoneEvent {\n type: 'done'\n result: string\n usage: {\n inputTokens: number\n outputTokens: number\n totalTokens: number\n }\n durationMs: number\n /** Total cost in USD for this agent run (EC-2: added for budget tracking). */\n cost?: number\n}\n\n/** Agent run started. */\nexport interface RunStartedEvent {\n type: 'run_started'\n runId: string\n agentName: string\n model?: string\n}\n\n/** Artifact generation started (code, document, diagram). */\nexport interface ArtifactStartEvent {\n type: 'artifact_start'\n artifactId: string\n mimeType: string\n filename?: string\n metadata?: Record<string, unknown>\n}\n\n/** Artifact content chunk (streamable artifacts). */\nexport interface ArtifactChunkEvent {\n type: 'artifact_chunk'\n artifactId: string\n chunk: string\n isLast: boolean\n}\n\n/** Real-time state update from @Observable channels. */\nexport interface StateUpdateEvent {\n type: 'state_update'\n channel: string\n data: unknown\n}\n\n/** Checkpoint saved (resumable agents). */\nexport interface CheckpointSavedEvent {\n type: 'checkpoint_saved'\n checkpointId: string\n step: number\n resumeToken: string\n}\n\n/** File edit produced by a code assistant tool. */\nexport interface FileEditEvent {\n type: 'file_edit'\n file: string\n format: 'search-replace' | 'unified-diff' | 'full-file' | 'line-range'\n search?: string\n replace?: string\n content?: string\n diff?: string\n startLine?: number\n endLine?: number\n}\n\n/** Discriminated union of all agent stream events. */\nexport type AgentStreamEvent =\n | RunStartedEvent\n | TextDeltaEvent\n | ToolCallEvent\n | ToolResultEvent\n | ThinkingEvent\n | IterationEvent\n | ApprovalRequiredEvent\n | ArtifactStartEvent\n | ArtifactChunkEvent\n | StateUpdateEvent\n | CheckpointSavedEvent\n | FileEditEvent\n | ErrorEvent\n | DoneEvent\n\n/** Type guard helpers. */\nexport function isTextDelta(e: AgentStreamEvent): e is TextDeltaEvent { return e.type === 'text_delta' }\nexport function isToolCall(e: AgentStreamEvent): e is ToolCallEvent { return e.type === 'tool_call' }\nexport function isToolResult(e: AgentStreamEvent): e is ToolResultEvent { return e.type === 'tool_result' }\nexport function isDone(e: AgentStreamEvent): e is DoneEvent { return e.type === 'done' }\nexport function isError(e: AgentStreamEvent): e is ErrorEvent { return e.type === 'error' }\nexport function isApprovalRequired(e: AgentStreamEvent): e is ApprovalRequiredEvent { return e.type === 'approval_required' }\n","/**\n * Auto-generate HTTP routes from @Agent metadata — Web Standard.\n *\n * Per ADR D5: @Agent({ route }) auto-generates two endpoints:\n * - POST {route}/chat — send message, receive SSE stream\n * - GET {route}/runs/:runId — get run status/result\n *\n * Routes are convention-based, generated at registration time.\n */\nimport type { CompiledAgentOptions } from './agent-compiler.js'\nimport { streamAgentResponse, type StreamEvent } from './agent-sse-handler.js'\nimport type { AgentWalkResult } from './walk-agent-metadata.js'\n\nexport interface AgentRoute {\n method: 'POST' | 'GET'\n path: string\n handler: (request: Request) => Promise<Response>\n}\n\nexport interface AgentRouteContext {\n walkResult: AgentWalkResult\n compiledOptions: CompiledAgentOptions\n createRun: (message: string, sessionId: string) => AsyncIterable<StreamEvent>\n getRun?: (runId: string) => Promise<{ id: string; status: string; result?: string } | null>\n}\n\n/** Generate HTTP routes for a single agent. Returns Web Standard handlers. */\nexport function generateAgentRoutes(ctx: AgentRouteContext): AgentRoute[] {\n const { walkResult, createRun, getRun } = ctx\n const basePath = walkResult.route.replace(/\\/$/, '')\n const routes: AgentRoute[] = []\n\n routes.push({\n method: 'POST',\n path: `${basePath}/chat`,\n handler: async (request) => {\n let body: Record<string, unknown> | null = null\n try {\n body = (await request.json()) as Record<string, unknown>\n } catch {\n /* empty */\n }\n\n const message = body?.message\n if (typeof message !== 'string' || message.length === 0) {\n return new Response(\n JSON.stringify({ error: { code: 'BAD_REQUEST', message: 'message field required' } }),\n { status: 400, headers: { 'content-type': 'application/json' } },\n )\n }\n\n const rawSessionId = body?.sessionId\n const sessionId = typeof rawSessionId === 'string' ? rawSessionId : `session-${Date.now()}`\n return streamAgentResponse(createRun(message, sessionId))\n },\n })\n\n if (getRun) {\n routes.push({\n method: 'GET',\n path: `${basePath}/runs/:runId`,\n handler: async (request) => {\n const url = new URL(request.url)\n const runId = url.pathname.split('/').pop() ?? ''\n const run = await getRun(runId)\n if (!run) {\n return new Response(\n JSON.stringify({ error: { code: 'NOT_FOUND', message: `Run ${runId} not found` } }),\n { status: 404, headers: { 'content-type': 'application/json' } },\n )\n }\n return new Response(JSON.stringify(run), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n },\n })\n }\n\n return routes\n}\n","/**\n * Translates @theokit/sdk SDKMessage events → TheoKit AgentStreamEvent.\n *\n * The SDK yields SDKMessage (system/assistant/tool_call/thinking/status).\n * TheoKit devtools + SSE handler expect AgentStreamEvent (run_started/text_delta/tool_call/done).\n * This module bridges the two — Adapter pattern (per sdk-integration-blueprint ADR-D2).\n */\nimport type { StreamEvent } from './agent-sse-handler.js'\n\n/** Minimal SDK message shape — duck-typed to avoid hard import of @theokit/sdk types. */\nexport interface SdkMessage {\n type: string\n [key: string]: unknown\n}\n\n/** Safely coerce unknown value to string. */\nfunction asString(value: unknown, fallback: string): string {\n if (typeof value === 'string') return value\n return fallback\n}\n\nfunction translateSystemEvent(msg: SdkMessage, runId: string): StreamEvent[] {\n return [\n {\n type: 'run_started',\n runId,\n agentName: asString(msg.agent_id, 'agent'),\n model: asString(msg.model, 'unknown'),\n },\n ]\n}\n\nfunction translateAssistantEvent(msg: SdkMessage): StreamEvent[] {\n const events: StreamEvent[] = []\n // Real SDKAssistantMessage (messages.ts:58): content lives at msg.message.content.\n const message = msg.message as { content?: unknown } | undefined\n const content = message?.content\n if (!Array.isArray(content)) return events\n\n for (const block of content) {\n const b = block as { type: string; text?: string; name?: string; input?: unknown; id?: string }\n if (b.type === 'text' && b.text) {\n events.push({ type: 'text_delta', content: b.text })\n }\n if (b.type === 'tool_use') {\n events.push({\n type: 'tool_call',\n callId: b.id ?? `tc-${Date.now()}`,\n toolName: b.name ?? 'unknown',\n input: b.input ?? {},\n })\n }\n }\n return events\n}\n\nfunction translateToolCallEvent(msg: SdkMessage): StreamEvent[] {\n // Real SDKToolUseMessage (messages.ts:89): call_id (not id), status running|completed|error,\n // tool output in `result` (no separate `error` field).\n const status = msg.status as string\n const callId = asString(msg.call_id, `tc-${Date.now()}`)\n const toolName = asString(msg.name, 'unknown')\n if (status === 'completed') {\n return [\n {\n type: 'tool_result',\n callId,\n toolName,\n output: asString(msg.result, ''),\n durationMs: 0,\n isError: false,\n },\n ]\n }\n if (status === 'error') {\n return [\n {\n type: 'tool_result',\n callId,\n toolName,\n output: asString(msg.result, 'Tool failed'),\n durationMs: 0,\n isError: true,\n },\n ]\n }\n return [] // 'running' status → no event (in progress)\n}\n\nfunction translateStatusEvent(msg: SdkMessage): StreamEvent[] {\n // Real SDKStatusMessage (messages.ts:106): status is UPPERCASE cloud-run lifecycle;\n // error text (when present) is in `msg.message`. FINISHED/CANCELLED are terminal-clean;\n // ERROR/EXPIRED are terminal-failure (must surface — fail-loud, Unbreakable Rule 8);\n // CREATING/RUNNING are in-progress.\n const s = msg.status as string\n if (s === 'FINISHED' || s === 'CANCELLED') {\n return [\n {\n type: 'done',\n result: '',\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n durationMs: 0,\n cost: 0,\n },\n ]\n }\n if (s === 'ERROR' || s === 'EXPIRED') {\n return [\n {\n type: 'error',\n code: 'AGENT_ERROR',\n message: asString(msg.message, 'Agent error'),\n retryable: false,\n },\n ]\n }\n return []\n}\n\n/**\n * Translate a single SDK message to zero or more TheoKit stream events.\n * Returns an array because one SDK message may map to multiple TheoKit events.\n */\nexport function translateSdkEvent(msg: SdkMessage, runId: string): StreamEvent[] {\n switch (msg.type) {\n case 'system':\n return translateSystemEvent(msg, runId)\n case 'assistant':\n return translateAssistantEvent(msg)\n case 'tool_call':\n return translateToolCallEvent(msg)\n case 'thinking':\n // Real SDKThinkingMessage (messages.ts:73): reasoning text is in msg.text.\n return [{ type: 'thinking', content: asString(msg.text, '') }]\n case 'status':\n return translateStatusEvent(msg)\n default:\n return [] // Unknown message types silently ignored\n }\n}\n","/**\n * SDK Adapter — bridges @theokit/agents decorators → @theokit/sdk runtime.\n *\n * Per rule sdk-runtime.md (INQUEBRÁVEL): @theokit/sdk is the ONLY agent runtime.\n * This adapter replaces llm-runner.ts (which called OpenRouter API directly).\n *\n * Flow: @Agent decorator → compileAgent() → createSdkAgentStream() → SDK Agent.create() → Run.stream()\n */\nimport type { ContextSettings, SkillsSettings, SystemPromptResolver } from '@theokit/sdk'\n\nimport type { CompiledAgentOptions, CompiledTool } from './agent-compiler.js'\nimport type { StreamEvent } from './agent-sse-handler.js'\nimport { compileProjectContext } from './compile-project-context.js'\nimport { translateSdkEvent, type SdkMessage } from './event-translator.js'\n\n/** Extra `Agent.create()` options compiled from the M8 declarative decorators. */\ninterface M8CreateOptions {\n skills?: SkillsSettings\n context?: ContextSettings\n systemPrompt?: string | SystemPromptResolver\n /** Settings source so the SDK can discover SKILL.md files (EC-1). */\n local?: { settingSources: string[] }\n}\n\n/**\n * Project the M8 fields from `CompiledAgentOptions` (the single compile site is\n * `agent-compiler.ts`, per sdk-runtime.md) into `Agent.create()` arguments. Only\n * the async `@ProjectContext` resolver is built here (it does I/O, so the compiler\n * keeps it raw). `applied` lists which decorators contributed, for the\n * observability log (wiring triad — runtime metric).\n */\nfunction assembleM8CreateOptions(compiled: CompiledAgentOptions): {\n options: M8CreateOptions\n applied: string[]\n} {\n const options: M8CreateOptions = {}\n const applied: string[] = []\n const base = compiled.systemPrompt\n\n if (compiled.skills) {\n options.skills = compiled.skills\n options.local = { settingSources: ['project'] }\n applied.push('skills')\n }\n if (compiled.context) {\n options.context = compiled.context\n applied.push('context')\n }\n if (compiled.projectContext) {\n options.systemPrompt = compileProjectContext(compiled.projectContext, base)\n applied.push('projectContext')\n } else if (base !== undefined) {\n options.systemPrompt = base\n }\n\n return { options, applied }\n}\n\n/**\n * Creates an agent stream factory using @theokit/sdk as the runtime.\n *\n * Returns a function that, given a message + sessionId, yields TheoKit\n * AgentStreamEvent via the SDK's Agent.create() + Run.stream() pipeline.\n */\nexport function createSdkAgentStream(\n compiled: CompiledAgentOptions,\n compiledTools: CompiledTool[],\n apiKey: string,\n envModel?: string,\n) {\n const model = envModel ?? compiled.model ?? 'openai/gpt-4o-mini'\n\n return (message: string, _sessionId: string): AsyncIterable<StreamEvent> => ({\n async *[Symbol.asyncIterator]() {\n const runId = `run-${Date.now()}`\n const t0 = Date.now()\n\n // Dynamic import — @theokit/sdk is optional peer dep\n let Agent: {\n create: (opts: Record<string, unknown>) => Promise<{\n send: (msg: string) => Promise<{ stream: () => AsyncGenerator<SdkMessage> }>\n dispose: () => Promise<void>\n }>\n }\n let defineTool: (spec: {\n name: string\n description: string\n inputSchema: unknown\n handler: (input: unknown) => string | Promise<string>\n }) => unknown\n\n try {\n const sdk = await import('@theokit/sdk')\n Agent = sdk.Agent as typeof Agent\n defineTool = sdk.defineTool as typeof defineTool\n } catch {\n yield {\n type: 'error',\n code: 'SDK_NOT_INSTALLED',\n message: 'Install @theokit/sdk: pnpm add @theokit/sdk',\n retryable: false,\n }\n return\n }\n\n // Convert compiled tools → SDK defineTool format\n const sdkTools = compiledTools.map((t) =>\n defineTool({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n handler: t.handler,\n }),\n )\n\n try {\n // Project the compiled M8 decorator fields into native Agent.create args.\n const { options: m8, applied } = assembleM8CreateOptions(compiled)\n if (applied.length > 0) {\n // Wiring triad — runtime metric: observable proof the decorators fired.\n console.debug('[THEO_AGENT_M8_RUNTIME_APPLIED]', {\n skills: applied.includes('skills'),\n context: applied.includes('context'),\n projectContext: applied.includes('projectContext'),\n })\n }\n\n // Create SDK agent (M8 fields spread; absent decorators add no keys)\n const agent = await Agent.create({\n apiKey,\n model: { id: model },\n tools: sdkTools,\n ...m8,\n })\n\n // Send message + stream response\n const run = await agent.send(message)\n\n let sawTerminal = false\n for await (const sdkEvent of run.stream()) {\n const translated = translateSdkEvent(sdkEvent, runId)\n for (const event of translated) {\n if (event.type === 'done' || event.type === 'error') sawTerminal = true\n yield event\n }\n }\n\n // Fallback terminal: only when the SDK stream did NOT already yield one\n // (a real run ends in a `status: FINISHED`/`ERROR` message → translated to\n // done/error). The loop's B1 guarantee relies on a terminal existing; this\n // keeps exactly-one-terminal without double-emitting to SSE consumers.\n if (!sawTerminal) {\n yield {\n type: 'done',\n result: '',\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n durationMs: Date.now() - t0,\n cost: 0,\n }\n }\n\n await agent.dispose()\n } catch (err) {\n yield {\n type: 'error',\n code: 'SDK_ERROR',\n message: err instanceof Error ? err.message : 'SDK agent error',\n retryable: false,\n }\n }\n },\n })\n}\n","/**\n * LoopStrategy — the per-round terminal-decision contract that gives runtime to\n * `@MainLoop({ strategy })`.\n *\n * V4-A proved `@MainLoop`'s `strategy` field was metadata-only (declared +\n * compiled, never executed). This module is the foundation Phase 2's\n * `runReflectiveLoop` branches on. Modeled on Mastra's `agentic-loop`/`stopWhen`\n * (inverted) + `maxSteps` ceiling — NOT Spring's per-call Advisor (plan ADR D1).\n * Config is Zod-validated so an invalid `maxIterations` fails fast at resolve\n * time, never as a silent infinite loop at runtime (plan ADR D3).\n *\n * referencia: knowledge-base/references/mastra agentic-loop/index.ts (stopWhen + maxSteps).\n */\nimport { z } from 'zod'\n\nimport type { MainLoopMeta } from '../types.js'\n\n/** Why a single round ended. Derived in the bridge from the SDK stream events. */\nexport type LoopFinishReason = 'tool-calls' | 'stop' | 'length' | 'error'\n\n/** Value object describing one round's result. */\nexport interface LoopOutcome {\n /** Why the round ended (the continuation signal). */\n readonly finishReason: LoopFinishReason\n /** 1-indexed round number that just completed. */\n readonly round: number\n /** Tool calls executed during the round. */\n readonly toolCalls: readonly { name: string; input: unknown; output: string }[]\n /** Accumulated assistant text for the round. */\n readonly responseText: string\n}\n\n/** The terminal-decision contract. `shouldContinue` is the inverted `stopWhen`. */\nexport interface LoopStrategy {\n /** The originating `@MainLoop` strategy name. */\n readonly name: MainLoopMeta['strategy']\n /** Hard ceiling on rounds — guarantees termination. */\n readonly maxIterations: number\n /** True ⇒ re-enter for another round; false ⇒ terminate. Never true forever. */\n shouldContinue(outcome: LoopOutcome): boolean\n}\n\n/** Default round ceiling when `@MainLoop` declares no `maxIterations` (EC-3: finite, never Infinity). */\nexport const DEFAULT_MAX_ITERATIONS = 8\n\n/** Serializable config for a LoopStrategy. SSoT per type-safety.md (ADR D3). */\nexport const loopStrategyConfigSchema = z.object({\n name: z.enum(['simple-chat', 'plan-act-reflect', 'react']),\n maxIterations: z.number().int().min(1),\n})\n\nexport type LoopStrategyConfig = z.infer<typeof loopStrategyConfigSchema>\n\n/**\n * Map a `@MainLoop` strategy + ceiling to a concrete {@link LoopStrategy}.\n *\n * - `simple-chat` ⇒ exactly one round (`shouldContinue` always false).\n * - `plan-act-reflect` / `react` ⇒ continue while the round ended on `tool-calls`\n * AND the ceiling has not been reached (`round < maxIterations`).\n *\n * Throws (Zod) when `maxIterations < 1` — fail fast, never a silent infinite loop.\n */\nexport function resolveLoopStrategy(\n strategy: MainLoopMeta['strategy'],\n maxIterations: number = DEFAULT_MAX_ITERATIONS,\n): LoopStrategy {\n const cfg = loopStrategyConfigSchema.parse({ name: strategy, maxIterations })\n\n if (cfg.name === 'simple-chat') {\n return { name: cfg.name, maxIterations: cfg.maxIterations, shouldContinue: () => false }\n }\n\n return {\n name: cfg.name,\n maxIterations: cfg.maxIterations,\n shouldContinue: (outcome: LoopOutcome): boolean =>\n outcome.finishReason === 'tool-calls' && outcome.round < cfg.maxIterations,\n }\n}\n","/**\n * ReflectionStrategy — composes INTO the loop between rounds (the loop calls\n * `reflect()` then `LoopStrategy.shouldContinue()`).\n *\n * `'plan-act-reflect'` resolves to the `'ladder'` default shipped here; a custom\n * strategy may be supplied (OCP — plan Drawback #2). `reflect()` is pure (no\n * I/O, no LLM) — it inspects the round's outcome and returns feedback to inject\n * into the next round's prompt plus a `continue` hint. The hard round ceiling\n * lives in `LoopStrategy.shouldContinue` (maxIterations), NOT here.\n *\n * referencia: knowledge-base/references/mastra agentic-loop/index.ts (onIterationComplete → { feedback, continue }).\n */\nimport { z } from 'zod'\n\nimport type { LoopOutcome } from './loop-strategy.js'\n\n/** Result of reflecting on a completed round. */\nexport interface ReflectionResult {\n /** Optional text prepended to the next round's prompt. */\n readonly feedback?: string\n /** Hint: should the loop reflect-and-continue? (the ceiling still bounds it) */\n readonly continue: boolean\n}\n\n/** Pluggable between-round reflection. Pure — never performs I/O. */\nexport interface ReflectionStrategy {\n /** Strategy identifier (e.g. `'ladder'`). */\n readonly name: string\n /** Inspect the round outcome; return feedback + continue hint. */\n reflect(outcome: LoopOutcome): ReflectionResult\n}\n\n/** Serializable config for a ReflectionStrategy. SSoT per type-safety.md (ADR D3). */\nexport const reflectionStrategyConfigSchema = z.object({\n name: z.string().min(1),\n})\n\nexport type ReflectionStrategyConfig = z.infer<typeof reflectionStrategyConfigSchema>\n\n/**\n * The default `'ladder'` reflection (what `'plan-act-reflect'` resolves to).\n *\n * Continues with bounded templated feedback while the round ended on\n * `tool-calls`; terminates on any terminal `finishReason` (`stop`/`error`/\n * `length`). The feedback is a short fixed template (bounded — EC-5; context\n * growth is the SDK's responsibility, not the loop's).\n */\nexport const ladderReflectionStrategy: ReflectionStrategy = {\n name: 'ladder',\n reflect(outcome: LoopOutcome): ReflectionResult {\n if (outcome.finishReason === 'tool-calls') {\n return {\n feedback: `Tool results received (round ${outcome.round}). Reflect on whether the goal is met; if not, refine the approach and continue.`,\n continue: true,\n }\n }\n return { continue: false }\n },\n}\n\n/**\n * No-op reflection for `'react'` (multi-round WITHOUT reflection feedback).\n *\n * Returns `{ continue: true }` (no feedback) so the round-continuation decision\n * is delegated entirely to `LoopStrategy.shouldContinue` (i.e. `react` loops\n * while `finishReason === 'tool-calls'` under the ceiling). NOTE: the plan's\n * pseudo-code (Files-to-edit) sketched `{ continue: false }`, which would make\n * `react` single-shot — that contradicts the plan's own Deep Dives (\"`react`\n * still multi-rounds while finishReason==='tool-calls'\"); `continue: true` is\n * the behavior the resolved react LoopStrategy requires.\n */\nexport const noopReflectionStrategy: ReflectionStrategy = {\n name: 'noop',\n reflect(): ReflectionResult {\n return { continue: true }\n },\n}\n","/**\n * Shared delegation value types + typed errors.\n *\n * Extracted from `agent-orchestrator.ts` so BOTH the orchestrator (`delegate`)\n * and the loop driver (`loop/run-reflective-loop.ts`) can import them WITHOUT a\n * cycle (orchestrator → loop → delegation-types; orchestrator → delegation-types;\n * delegation-types depends on nothing — Acyclic Dependencies Principle, G1).\n * `agent-orchestrator.ts` re-exports these for backward compatibility.\n */\n\nexport interface DelegationResult {\n response: string\n toolCalls: { name: string; input: unknown; output: string }[]\n cost: number\n tokens: number\n /** Rounds the reflective loop ran (set by `runReflectiveLoop`; absent for the single-shot path). */\n rounds?: number\n}\n\nexport class BudgetExceededError extends Error {\n constructor(\n public readonly agentName: string,\n public readonly actualCost: number,\n public readonly budgetLimit: number,\n ) {\n super(\n `Agent \"${agentName}\" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`,\n )\n this.name = 'BudgetExceededError'\n }\n}\n\nexport class DelegationError extends Error {\n constructor(\n public readonly agentName: string,\n public readonly cause: unknown,\n ) {\n super(\n `Delegation to agent \"${agentName}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n this.name = 'DelegationError'\n }\n}\n","/**\n * runReflectiveLoop — the multi-round reflective driver that gives `@MainLoop`\n * its runtime (closes the metadata-only gap, V4-A / plan ADR D2).\n *\n * Per round it consumes ONE SDK stream turn (the model call stays in the SDK —\n * the factory is `createSdkAgentStream(...)`, injected for testability), derives\n * a {@link LoopOutcome}, asks the {@link ReflectionStrategy} for feedback, then\n * the {@link LoopStrategy} whether to continue. Bounded by `maxIterations`\n * (forced terminal at the ceiling — never an infinite loop). The bridge owns the\n * loop; the SDK owns the model call (sdk-runtime.md / ADR 0031 — no second runtime).\n *\n * `runReflectiveLoop` is INTERNAL (not re-exported from the package barrel,\n * Drawback #4) — consumed by `delegate()` (T2.2) and `AgentRunner` (T3.1).\n *\n * referencia: knowledge-base/references/mastra agent.ts (re-enter the loop with feedback).\n */\nimport {\n BudgetExceededError,\n type DelegationResult,\n DelegationError,\n} from '../bridge/delegation-types.js'\n\nimport type { LoopFinishReason, LoopOutcome, LoopStrategy } from './loop-strategy.js'\nimport type { ReflectionStrategy } from './reflection-strategy.js'\n\n/** One SDK stream turn: `createSdkAgentStream(...)` returns this shape. */\nexport type RoundStreamFactory = (\n message: string,\n sessionId: string,\n) => AsyncIterable<{ type: string; [key: string]: unknown }>\n\n/** Strategies + options for {@link runReflectiveLoop}. */\nexport interface RunReflectiveLoopConfig {\n /** The terminal-decision strategy (resolved from `@MainLoop.strategy`). */\n readonly loop: LoopStrategy\n /** Between-round reflection (default `'ladder'` for `'plan-act-reflect'`). */\n readonly reflection: ReflectionStrategy\n /** Cumulative USD budget across ALL rounds (EC-4). Exceeding throws BudgetExceededError. */\n readonly budget?: number\n /** Cancellation — when aborted, the loop stops re-entering and advancing the in-flight stream. */\n readonly signal?: AbortSignal\n /** Name surfaced in typed errors. */\n readonly agentName?: string\n}\n\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback\n}\n\nfunction asNumber(value: unknown, fallback: number): number {\n return typeof value === 'number' ? value : fallback\n}\n\n/** One round's accumulated facts + the signals needed to derive `finishReason`. */\ninterface RoundResult {\n responseText: string\n toolCalls: { name: string; input: unknown; output: string }[]\n cost: number\n tokens: number\n finishReason: LoopFinishReason\n errorMessage: string\n}\n\n/**\n * Derive the round's terminal signal from the events seen this round.\n *\n * Precedence (B1 — the load-bearing fix):\n * 1. error event ⇒ 'error'\n * 2. explicit done.finishReason==='tool-calls' ⇒ 'tool-calls' (if a future SDK adapter sets it)\n * 3. ANY tool_result seen ⇒ 'tool-calls' — the turn USED TOOLS (\"still working\"), so the\n * outer reflective loop should reflect + re-prompt. The real `@theokit/sdk` adapter ALWAYS\n * appends a terminal `done` WITHOUT finishReason after a turn (sdk-adapter.ts / event-translator.ts);\n * letting that `done` short-circuit a tool-using turn to 'stop' is exactly what made the loop\n * dead in production (single-round). tool_result therefore OUTRANKS the bare done. Bounded by\n * `maxIterations` so it can never spin.\n * 4. otherwise (pure-answer `done`, text-only, or empty round) ⇒ 'stop' (terminal). EC-1: a\n * degenerate/empty round defaults to 'stop', NEVER 'tool-calls'.\n *\n * This is an honest heuristic: the SDK runs the inner tool loop to completion per turn, so the\n * outer loop treats a tool-using turn as \"continue/reflect\" and a pure-text answer as \"done\".\n */\nfunction deriveFinishReason(signals: {\n sawError: boolean\n sawDone: boolean\n doneFinishReason: string\n sawToolResult: boolean\n}): LoopFinishReason {\n if (signals.sawError) return 'error'\n if (signals.sawDone && signals.doneFinishReason === 'tool-calls') return 'tool-calls'\n if (signals.sawToolResult) return 'tool-calls'\n return 'stop'\n}\n\n/** Consume exactly one SDK stream turn and derive its {@link LoopFinishReason}. */\nasync function consumeOneRound(\n factory: RoundStreamFactory,\n prompt: string,\n sessionId: string,\n signal: AbortSignal | undefined,\n): Promise<RoundResult> {\n const r: RoundResult = {\n responseText: '',\n toolCalls: [],\n cost: 0,\n tokens: 0,\n finishReason: 'stop',\n errorMessage: '',\n }\n const signals = { sawError: false, sawDone: false, doneFinishReason: '', sawToolResult: false }\n\n for await (const event of factory(prompt, sessionId)) {\n if (signal?.aborted) break // cancellation: stop advancing the iterator\n if (event.type === 'text_delta' && typeof event.content === 'string') {\n r.responseText += event.content\n } else if (event.type === 'tool_result') {\n signals.sawToolResult = true\n r.toolCalls.push({\n name: asString(event.toolName, 'unknown'),\n input: event.input ?? {},\n output: asString(event.output, ''),\n })\n } else if (event.type === 'done') {\n signals.sawDone = true\n signals.doneFinishReason = asString(event.finishReason, '')\n r.cost = asNumber(event.cost, 0)\n r.tokens = (event.usage as { totalTokens?: number } | undefined)?.totalTokens ?? 0\n } else if (event.type === 'error') {\n signals.sawError = true\n r.errorMessage = asString((event as { message?: unknown }).message, 'Unknown agent error')\n }\n }\n\n r.finishReason = deriveFinishReason(signals)\n return r\n}\n\n/**\n * Drive the reflective loop to a terminal {@link DelegationResult}.\n *\n * Terminates when: the reflection/strategy says stop, the `maxIterations` ceiling\n * is reached (via `loop.shouldContinue`), the signal aborts, or a degenerate round\n * resolves to `stop`. Throws `DelegationError` on a mid-round error event\n * (fail-fast, typed) and `BudgetExceededError` when cumulative cost crosses `budget`.\n */\nexport async function runReflectiveLoop(\n factory: RoundStreamFactory,\n message: string,\n sessionId: string,\n config: RunReflectiveLoopConfig,\n): Promise<DelegationResult> {\n const {\n loop,\n reflection,\n budget = Number.POSITIVE_INFINITY,\n signal,\n agentName = loop.name,\n } = config\n const acc: DelegationResult = { response: '', toolCalls: [], cost: 0, tokens: 0, rounds: 0 }\n let round = 1\n let feedback: string | undefined\n\n while (!signal?.aborted) {\n // L2: only append the [reflection] block when there is actual feedback (react's\n // noop reflection returns no feedback — avoid polluting its prompt with an empty marker).\n const prompt = round === 1 || !feedback ? message : `${message}\\n\\n[reflection] ${feedback}`\n // M2: wrap the round so a RAW stream/iterator exception (not an `error` event — e.g. the\n // SDK dynamic import rejecting) surfaces as a typed DelegationError, matching the single-shot path.\n let r: RoundResult\n try {\n r = await consumeOneRound(factory, prompt, sessionId, signal)\n } catch (err) {\n if (err instanceof BudgetExceededError || err instanceof DelegationError) throw err\n throw new DelegationError(agentName, err)\n }\n\n acc.response += r.responseText\n acc.toolCalls.push(...r.toolCalls)\n acc.cost += r.cost\n acc.tokens += r.tokens\n\n if (r.finishReason === 'error') throw new DelegationError(agentName, r.errorMessage)\n if (Number.isFinite(budget) && acc.cost > budget) {\n throw new BudgetExceededError(agentName, acc.cost, budget)\n }\n\n const outcome: LoopOutcome = {\n finishReason: r.finishReason,\n round,\n toolCalls: r.toolCalls,\n responseText: r.responseText,\n }\n const reflectionResult = reflection.reflect(outcome)\n if (!(reflectionResult.continue && loop.shouldContinue(outcome))) {\n acc.rounds = round\n // Wiring triad — runtime metric (G10): observable proof the loop ran, with round count.\n // Fires for BOTH on-ramps (delegate + AgentRunner) since both share this driver.\n console.debug('[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]', { strategy: loop.name, rounds: round })\n return acc\n }\n\n feedback = reflectionResult.feedback\n round += 1\n }\n\n // Aborted before (re-)entering a round. L1: record the rounds that DID run\n // (round is 1-indexed and points at the next round, so `round - 1` ran).\n acc.rounds = round - 1\n return acc\n}\n","/**\n * AgentRunner — the imperative twin of `@MainLoop` (plan ADR D4, V4-B).\n *\n * `AgentRunner.builder(AgentClass).reflection().stream().build()` walks +\n * compiles the agent and resolves the SAME `{ compiled, loopStrategy }` that\n * `delegate()` resolves for the decorator path (two on-ramps, one runtime).\n * `build()` is the compile boundary (no I/O, no IoC — standalone, mirrors\n * Spring's `ChatClient.builder(...).build()`); `run()` does the I/O via\n * `runReflectiveLoop` (the SAME loop `delegate()` uses — DRY, ADR 0031).\n *\n * referencia: knowledge-base/references/spring-ai DefaultChatClientBuilder.java (build() returns standalone).\n */\nimport { type CompiledAgentOptions, compileAgent } from '../bridge/agent-compiler.js'\nimport type { DelegationResult } from '../bridge/delegation-types.js'\nimport { createSdkAgentStream } from '../bridge/sdk-adapter.js'\nimport { walkAgentMetadata } from '../bridge/walk-agent-metadata.js'\n\nimport { type LoopStrategy, resolveLoopStrategy } from './loop-strategy.js'\nimport {\n ladderReflectionStrategy,\n noopReflectionStrategy,\n type ReflectionStrategy,\n} from './reflection-strategy.js'\nimport { runReflectiveLoop } from './run-reflective-loop.js'\n\n/** Options for {@link AgentRunner.run}. */\nexport interface AgentRunnerRunOptions {\n /** LLM API key. */\n readonly apiKey: string\n /** Session id override (default: a fresh isolated id). */\n readonly sessionId?: string\n /** Cumulative USD budget across rounds. */\n readonly budget?: number\n /** Cancellation — aborts stop the reflective loop from re-entering. */\n readonly signal?: AbortSignal\n}\n\n/**\n * A built, runnable agent. Construct via {@link AgentRunner.builder} — the\n * constructor takes already-resolved state and is an internal detail.\n */\nexport class AgentRunner {\n constructor(\n private readonly compiled: CompiledAgentOptions,\n private readonly agentName: string,\n /** The resolved terminal-decision strategy (parity with `delegate()`). */\n readonly loopStrategy: LoopStrategy,\n /** The resolved between-round reflection (default or `.reflection(custom)` override). */\n readonly reflectionStrategy: ReflectionStrategy,\n /**\n * Recorded streaming preference. The reflective loop currently always\n * streams via the SDK `Run.stream()`; a non-streaming collect mode is future\n * work — the flag is captured + exposed here, not yet branched on (honest\n * per G10: documented, not a silent no-op).\n */\n readonly streamEnabled: boolean,\n ) {}\n\n /** Start a fluent builder for `AgentClass`. */\n static builder(AgentClass: Function): AgentRunnerBuilder {\n return new AgentRunnerBuilder(AgentClass)\n }\n\n /** Run the agent to a terminal result via the shared reflective loop. */\n run(message: string, opts: AgentRunnerRunOptions): Promise<DelegationResult> {\n const streamFactory = createSdkAgentStream(\n this.compiled,\n this.compiled.tools,\n opts.apiKey,\n this.compiled.model,\n )\n const sessionId = opts.sessionId ?? `runner-${crypto.randomUUID()}`\n return runReflectiveLoop(streamFactory, message, sessionId, {\n loop: this.loopStrategy,\n reflection: this.reflectionStrategy,\n budget: opts.budget,\n agentName: this.agentName,\n signal: opts.signal,\n })\n }\n}\n\n/** Fluent builder — accumulates config; `build()` is the compile boundary. */\nexport class AgentRunnerBuilder {\n private reflectionOverride?: ReflectionStrategy\n private streamEnabled = true\n\n constructor(private readonly AgentClass: Function) {}\n\n /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */\n reflection(strategy?: ReflectionStrategy): this {\n if (strategy) this.reflectionOverride = strategy\n return this\n }\n\n /** Record the streaming preference (see {@link AgentRunner.streamEnabled}). */\n stream(enabled = true): this {\n this.streamEnabled = enabled\n return this\n }\n\n /** Walk + compile + resolve strategies — the compile→execute boundary (no I/O). */\n build(): AgentRunner {\n const walk = walkAgentMetadata(this.AgentClass, [])\n const toolboxInstances = new Map(\n walk.toolboxes.map((tb) => [tb.class, new (tb.class as new () => object)()]),\n )\n const compiled = compileAgent(walk, toolboxInstances)\n const loopStrategy = resolveLoopStrategy(walk.mainLoop.strategy, walk.mainLoop.maxIterations)\n const reflectionStrategy =\n this.reflectionOverride ??\n (walk.mainLoop.strategy === 'plan-act-reflect'\n ? ladderReflectionStrategy\n : noopReflectionStrategy)\n return new AgentRunner(\n compiled,\n walk.agentConfig.name,\n loopStrategy,\n reflectionStrategy,\n this.streamEnabled,\n )\n }\n}\n","/**\n * Multi-agent orchestration runtime.\n *\n * Provides `delegate()` — a function that lets a parent agent invoke a\n * sub-agent and receive its result. Handles budget clamping (D4), tool sharing,\n * toolbox auto-instantiation (EC-1), and routes the resolved `@MainLoop` strategy\n * through `runReflectiveLoop` — the SAME driver `AgentRunner.run()` uses, so both\n * on-ramps are one runtime (ADR D4). `simple-chat` ⇒ `shouldContinue:()=>false`\n * ⇒ exactly one round; `react`/`plan-act-reflect` ⇒ multi-round reflective loop.\n */\nimport {\n ladderReflectionStrategy,\n noopReflectionStrategy,\n resolveLoopStrategy,\n} from '../loop/index.js'\nimport { runReflectiveLoop } from '../loop/run-reflective-loop.js'\n\nimport { compileAgent, type CompiledTool } from './agent-compiler.js'\nimport { type DelegationResult, DelegationError } from './delegation-types.js'\nimport { createSdkAgentStream } from './sdk-adapter.js'\nimport { walkAgentMetadata } from './walk-agent-metadata.js'\n\n// Re-export the delegation value types for backward compatibility — they moved\n// to delegation-types.js to break the orchestrator↔loop import cycle (G1).\nexport { BudgetExceededError, type DelegationResult, DelegationError } from './delegation-types.js'\n\nexport interface DelegateOptions {\n /** Max USD for this sub-agent call. */\n budget?: number\n /** Parent's remaining budget (for clamping). */\n parentBudgetRemaining?: number\n /** Parent's tools (for sharing — sub-agent inherits these). */\n parentTools?: CompiledTool[]\n /** LLM API key (inherited from parent). */\n apiKey?: string\n /** Session ID override (default: crypto.randomUUID for isolation). */\n sessionId?: string\n /** Cancellation — aborts stop the reflective loop from re-entering. */\n signal?: AbortSignal\n}\n\n/** Validate API key and throw DelegationError if missing. */\nfunction requireApiKey(opts: DelegateOptions, agentName: string): string {\n const apiKey = opts.apiKey ?? ''\n if (!apiKey) {\n throw new DelegationError(agentName, 'No API key provided. Pass apiKey in DelegateOptions.')\n }\n return apiKey\n}\n\n/** Merge parent tools with sub-agent tools (sub wins on collision). */\nfunction mergeTools(parentTools: CompiledTool[], subTools: CompiledTool[]): CompiledTool[] {\n const subToolNames = new Set(subTools.map((t) => t.name))\n const inherited = parentTools.filter((t) => !subToolNames.has(t.name))\n return [...inherited, ...subTools]\n}\n\n/**\n * Delegate a task to a sub-agent and collect its result.\n *\n * - Budget clamping: `min(parentBudgetRemaining, budget)` (D4)\n * - Tool sharing: parent tools merged with sub-agent tools (sub wins on collision)\n * - Toolbox auto-instantiation: sub-agent toolboxes instantiated without DI (EC-1)\n * - Session isolation: each delegation gets a unique session ID (EC-4)\n * - `@MainLoop` strategy runtime: routes through `runReflectiveLoop` (the same loop\n * `AgentRunner.run` uses — one runtime for both on-ramps, ADR D4). The runtime\n * metric (`THEO_AGENT_MAINLOOP_RUNTIME_APPLIED`) + typed-error + cumulative budget\n * all live in the shared driver, so they fire identically on both paths.\n */\nexport async function delegate(\n SubAgentClass: Function,\n message: string,\n opts: DelegateOptions = {},\n): Promise<DelegationResult> {\n const apiKey = requireApiKey(opts, SubAgentClass.name)\n\n // 1. Walk + compile sub-agent (EC-1: auto-instantiate toolboxes)\n const walk = walkAgentMetadata(SubAgentClass, [])\n const toolboxInstances = new Map(\n walk.toolboxes.map((tb) => [tb.class, new (tb.class as new () => object)()]),\n )\n const compiled = compileAgent(walk, toolboxInstances)\n\n // 2. Merge parent tools + clamp budget (D4)\n const allTools = mergeTools(opts.parentTools ?? [], compiled.tools)\n const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity)\n\n // 3. Build the stream factory (the model call stays in the SDK — ADR 0031) + session\n const streamFactory = createSdkAgentStream(compiled, allTools, apiKey, walk.agentConfig.model)\n const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`\n\n // 4. Resolve the @MainLoop strategy + reflection, then run the shared reflective loop.\n const loopStrategy = resolveLoopStrategy(walk.mainLoop.strategy, walk.mainLoop.maxIterations)\n const reflection =\n loopStrategy.name === 'plan-act-reflect' ? ladderReflectionStrategy : noopReflectionStrategy\n return runReflectiveLoop(streamFactory, message, sessionId, {\n loop: loopStrategy,\n reflection,\n budget,\n agentName: SubAgentClass.name,\n signal: opts.signal,\n })\n}\n","/**\n * Agent manifest generator — build-time JSON describing all agents, tools, guards, policies.\n *\n * Feeds: theokit agents list/inspect, TheoCloud deploy, UI agent consoles.\n */\nimport type { AgentWalkResult } from '../bridge/walk-agent-metadata.js'\n\nexport interface AgentManifest {\n version: '1.0'\n generatedAt: string\n agents: AgentManifestEntry[]\n}\n\nexport interface AgentManifestEntry {\n name: string\n route: string\n model?: string\n stream: boolean\n mainLoop: {\n method: string\n strategy: string\n }\n guards: string[]\n interceptors: string[]\n tools: AgentManifestTool[]\n gateway?: {\n platforms: string[]\n sessionStrategy: string\n }\n subAgents: string[]\n memory?: { provider: string; embeddings: boolean; fts: boolean; scope: string }\n skills?: string[]\n mcpServers?: string[]\n}\n\nexport interface AgentManifestTool {\n name: string\n description: string\n risk?: string\n approval: boolean\n capabilities?: string[]\n trace: boolean\n audit: boolean\n}\n\n/**\n * Generate a serializable agent manifest from walked metadata.\n * All Function references are converted to string names for JSON safety.\n */\nexport function generateAgentManifest(walkResults: AgentWalkResult[]): AgentManifest {\n return {\n version: '1.0',\n generatedAt: new Date().toISOString(),\n agents: walkResults.map((r) => ({\n name: r.agentConfig.name,\n route: r.route,\n model: r.agentConfig.model,\n stream: r.agentConfig.stream ?? true,\n mainLoop: {\n method: String(r.mainLoop.propertyKey),\n strategy: r.mainLoop.strategy,\n },\n guards: r.guards.map((g) => g.name),\n interceptors: r.interceptors.map((i) => i.name),\n tools: r.toolboxes.flatMap((tb) =>\n tb.tools.map((t) => ({\n name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,\n description: t.config.description,\n risk: t.config.risk,\n approval: t.approval !== undefined,\n capabilities: t.capabilities,\n trace: t.trace,\n audit: t.audit,\n })),\n ),\n gateway: r.gateway\n ? { platforms: r.gateway.platforms, sessionStrategy: r.gateway.sessionStrategy ?? 'per-user' }\n : undefined,\n subAgents: r.subAgentClasses.map((cls) => cls.name),\n memory: r.memory\n ? {\n provider: r.memory.provider ?? 'built-in',\n embeddings: r.memory.embeddings ?? false,\n fts: r.memory.fts ?? false,\n scope: r.memory.scope ?? 'per-user',\n }\n : undefined,\n skills: r.skills?.include,\n mcpServers: r.mcpServers ? Object.keys(r.mcpServers) : undefined,\n })),\n }\n}\n","/**\n * agentsPlugin() — TheoKit dev-server plugin for agent routes.\n *\n * Mirrors httpDecoratorsPlugin() pattern. Registers agent HTTP endpoints\n * (POST /chat, GET /runs/:id) via the TheoKit plugin hook system.\n *\n * Per ADR D6: structural { name, register } shape (no compile-time theokit dep).\n */\nimport 'reflect-metadata'\n\nimport { compileAgent, type CompiledAgentOptions } from './bridge/agent-compiler.js'\nimport { generateAgentRoutes, type AgentRoute } from './bridge/agent-route-generator.js'\nimport type { StreamEvent } from './bridge/agent-sse-handler.js'\nimport {\n walkAgentMetadata,\n validateUniqueRoutes,\n type AgentWalkResult,\n} from './bridge/walk-agent-metadata.js'\nimport { getMixins } from './decorators/mixin.js'\n\nexport interface AgentsPluginOptions {\n /** Agent classes decorated with @Agent(). */\n agents: Function[]\n /** Toolbox classes (or use @Mixin on agents). */\n toolboxes?: Function[]\n /** Factory that creates agent runs — bridges to SDK Agent.create() + agent.send(). */\n createRunFactory?: (\n compiled: CompiledAgentOptions,\n walkResult: AgentWalkResult,\n ) => (message: string, sessionId: string) => AsyncIterable<StreamEvent>\n}\n\ninterface PluginApp {\n addHook(name: string, fn: (ctx: { request: Request }) => Promise<Response | undefined>): void\n}\n\n/**\n * Create a TheoKit plugin that mounts agent routes.\n * Web Standard Request/Response — runtime-agnostic.\n */\nexport function agentsPlugin(opts: AgentsPluginOptions) {\n let routes: CompiledRoute[] | null = null\n\n return {\n name: '@theokit/agents',\n\n register(app: PluginApp) {\n app.addHook('onRequest', async (pluginCtx) => {\n routes ??= initRoutes(opts)\n\n const request = pluginCtx.request\n const url = new URL(request.url)\n const method = request.method.toUpperCase()\n\n const matched = matchRoute(routes, method, url.pathname)\n if (!matched) return // fall through\n\n return matched.handler(request)\n })\n },\n }\n}\n\n/** Initialize routes from agent metadata (once). */\nfunction initRoutes(opts: AgentsPluginOptions): CompiledRoute[] {\n const allRoutes: AgentRoute[] = []\n const walkResults: AgentWalkResult[] = []\n\n for (const AgentClass of opts.agents) {\n // Resolve toolboxes: explicit + @Mixin\n const mixins = getMixins(AgentClass)\n const toolboxes = [...(opts.toolboxes ?? []), ...mixins]\n\n const walkResult = walkAgentMetadata(AgentClass, toolboxes)\n walkResults.push(walkResult)\n\n const compiled = compileAgent(walkResult, new Map())\n const createRun = opts.createRunFactory\n ? opts.createRunFactory(compiled, walkResult)\n : defaultCreateRun(compiled)\n\n const agentRoutes = generateAgentRoutes({\n walkResult,\n compiledOptions: compiled,\n createRun,\n })\n\n allRoutes.push(...agentRoutes)\n }\n\n validateUniqueRoutes(walkResults)\n return compileRoutePatterns(allRoutes)\n}\n\n/** Default run factory — returns a mock stream when SDK not wired. */\nfunction defaultCreateRun(compiled: CompiledAgentOptions) {\n return async function* (_message: string, _sessionId: string): AsyncGenerator<StreamEvent> {\n await Promise.resolve() // yield to event loop for async contract\n yield {\n type: 'run_started',\n runId: `run-${Date.now()}`,\n agentName: compiled.model ?? 'unknown',\n }\n yield {\n type: 'error',\n code: 'SDK_NOT_WIRED',\n message:\n 'No createRunFactory provided — wire @theokit/sdk Agent.create() to enable real agent execution.',\n retryable: false,\n }\n }\n}\n\ninterface CompiledRoute extends AgentRoute {\n regex?: RegExp\n}\n\n/** Pre-compile route patterns for efficient matching. */\nfunction compileRoutePatterns(routes: AgentRoute[]): CompiledRoute[] {\n return routes.map((r) => {\n if (!r.path.includes(':')) return r\n const regexSource = r.path.replace(/:[^/]+/g, '[^/]+')\n return { ...r, regex: RegExp(`^${regexSource}$`) }\n })\n}\n\n/** Simple route matcher — checks method + path prefix. */\nfunction matchRoute(\n routes: CompiledRoute[],\n method: string,\n pathname: string,\n): CompiledRoute | undefined {\n return routes.find((r) => {\n if (r.method !== method) return false\n if (r.regex) return r.regex.test(pathname)\n return r.path === pathname\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,SAASA,4BACdC,MACAC,OACAC,KACAC,UAA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A;AAErB,UAAMM,cAAcC,oBAAoB;MACtCV;MACAW,iBAAiBR;MACjBG;IACF,CAAA;AAEAb,cAAUS,KAAI,GAAIO,WAAAA;EACpB;AAEAG,uBAAqBlB,WAAAA;AACrB,SAAOmB,qBAAqBpB,SAAAA;AAC9B;AA5BSV;AA+BT,SAASyB,iBAAiBL,UAA8B;AACtD,SAAO,iBAAiBW,UAAkBC,YAAkB;AAC1D,UAAMC,QAAQC,QAAO;AACrB,UAAM;MACJC,MAAM;MACNC,OAAO,OAAOC,KAAKC,IAAG,CAAA;MACtBC,WAAWnB,SAASoB,SAAS;IAC/B;AACA,UAAM;MACJL,MAAM;MACNM,MAAM;MACNC,SACE;MACFC,WAAW;IACb;EACF;AACF;AAhBSlB;AAuBT,SAASK,qBAAqBpC,QAAoB;AAChD,SAAOA,OAAOkD,IAAI,CAACC,MAAAA;AACjB,QAAI,CAACA,EAAEC,KAAKC,SAAS,GAAA,EAAM,QAAOF;AAClC,UAAMG,cAAcH,EAAEC,KAAKG,QAAQ,WAAW,OAAA;AAC9C,WAAO;MAAE,GAAGJ;MAAGK,OAAOC,OAAO,IAAIH,WAAAA,GAAc;IAAE;EACnD,CAAA;AACF;AANSlB;AAST,SAASvB,WACPb,QACAU,QACAI,UAAgB;AAEhB,SAAOd,OAAO0D,KAAK,CAACP,MAAAA;AAClB,QAAIA,EAAEzC,WAAWA,OAAQ,QAAO;AAChC,QAAIyC,EAAEK,MAAO,QAAOL,EAAEK,MAAMG,KAAK7C,QAAAA;AACjC,WAAOqC,EAAEC,SAAStC;EACpB,CAAA;AACF;AAVSD;","names":["createAgentExecutionContext","base","agent","run","toolCall","getRequest","getUrl","getClass","getMethodName","getAgent","getRun","getToolCall","isAgentContext","ctx","STRATEGY_KNOBS","compileContextWindow","options","context","maxTokens","opts","metadataOnlyKnobs","filter","knob","undefined","UNMAPPED_KNOBS","projectContextMetadataOnlyKnobs","options","opts","filter","knob","undefined","compileProjectContext","base","promptCtx","cwd","buildEnvContext","buildRepoMap","readProjectInstructions","env","repoMap","ignore","ignorePatterns","instructions","content","Boolean","join","Reflector","USE_GUARDS","Symbol","for","USE_INTERCEPTORS","USE_FILTERS","AgentWarningCode","INTERCEPTOR_METADATA_ONLY","FILTER_METADATA_ONLY","BUDGET_TOP_LEVEL_METADATA_ONLY","CONTEXT_STRATEGY_METADATA_ONLY","PROJECT_CONTEXT_KNOB_METADATA_ONLY","reflectorInstance","Reflector","walkToolbox","ToolboxClass","config","getMeta","TOOLBOX_CONFIG","methods","TOOL_METHODS","classGuards","tools","map","propertyKey","toolConfig","TOOL_CONFIG","Error","name","String","methodGuards","ref","approvalVal","get","RequiresApproval","traceVal","Trace","auditVal","Audit","guards","approval","undefined","capabilities","budget","trace","audit","class","namespace","warnUnmappedDecoratorKnobs","agentName","contextWindow","projectContext","metadataOnlyKnobs","compileContextWindow","length","console","warn","join","unmapped","projectContextMetadataOnlyKnobs","agentWalkCache","WeakMap","walkAgentMetadata","AgentClass","toolboxClasses","cached","agentConfig","AGENT_CONFIG","mainLoop","AGENT_MAIN_LOOP","interceptors","filters","agentBudget","Budget","toolboxes","gateway","getGatewayConfig","subAgentClasses","getSubAgents","memory","getMemoryConfig","skills","getSkillsConfig","mcpServers","getMcpConfig","getContextWindowConfig","getProjectContextConfig","result","route","set","validateUniqueRoutes","results","seen","Map","r","existing","compileSkills","options","autoDiscover","autoInject","enabled","include","compileTools","toolboxes","toolboxInstances","tools","tb","instance","get","class","Error","name","tool","handler","propertyKey","String","namespace","config","push","description","inputSchema","input","call","compileSubAgents","subAgentClasses","agents","cls","getAgentConfig","model","systemPrompt","compileAgent","walkResult","Map","agentConfig","memory","skills","compileSkills","undefined","context","contextWindow","compileContextWindow","projectContext","mcpServers","maxIterations","mainLoop","timeoutMs","stream","encoder","TextEncoder","streamAgentResponse","eventStream","stream","ReadableStream","start","controller","closed","safeEnqueue","chunk","enqueue","event","data","JSON","stringify","frame","type","encode","err","errorEvent","error","message","Error","close","Response","status","headers","isTextDelta","e","type","isToolCall","isToolResult","isDone","isError","isApprovalRequired","generateAgentRoutes","ctx","walkResult","createRun","getRun","basePath","route","replace","routes","push","method","path","handler","request","body","json","message","length","Response","JSON","stringify","error","code","status","headers","rawSessionId","sessionId","Date","now","streamAgentResponse","url","URL","runId","pathname","split","pop","run","asString","value","fallback","translateSystemEvent","msg","runId","type","agentName","agent_id","model","translateAssistantEvent","events","message","content","Array","isArray","block","b","text","push","callId","id","Date","now","toolName","name","input","translateToolCallEvent","status","call_id","output","result","durationMs","isError","translateStatusEvent","s","usage","inputTokens","outputTokens","totalTokens","cost","code","retryable","translateSdkEvent","assembleM8CreateOptions","compiled","options","applied","base","systemPrompt","skills","local","settingSources","push","context","projectContext","compileProjectContext","undefined","createSdkAgentStream","compiledTools","apiKey","envModel","model","message","_sessionId","Symbol","asyncIterator","runId","Date","now","t0","Agent","defineTool","sdk","type","code","retryable","sdkTools","map","t","name","description","inputSchema","handler","m8","length","console","debug","includes","agent","create","id","tools","run","send","sawTerminal","sdkEvent","stream","translated","translateSdkEvent","event","result","usage","inputTokens","outputTokens","totalTokens","durationMs","cost","dispose","err","Error","z","DEFAULT_MAX_ITERATIONS","loopStrategyConfigSchema","z","object","name","enum","maxIterations","number","int","min","resolveLoopStrategy","strategy","cfg","parse","shouldContinue","outcome","finishReason","round","z","reflectionStrategyConfigSchema","object","name","string","min","ladderReflectionStrategy","reflect","outcome","finishReason","feedback","round","continue","noopReflectionStrategy","BudgetExceededError","Error","agentName","actualCost","budgetLimit","toFixed","name","DelegationError","cause","message","String","asString","value","fallback","asNumber","deriveFinishReason","signals","sawError","sawDone","doneFinishReason","sawToolResult","consumeOneRound","factory","prompt","sessionId","signal","r","responseText","toolCalls","cost","tokens","finishReason","errorMessage","event","aborted","type","content","push","name","toolName","input","output","usage","totalTokens","message","runReflectiveLoop","config","loop","reflection","budget","Number","POSITIVE_INFINITY","agentName","acc","response","rounds","round","feedback","err","BudgetExceededError","DelegationError","isFinite","outcome","reflectionResult","reflect","continue","shouldContinue","console","debug","strategy","AgentRunner","compiled","agentName","loopStrategy","reflectionStrategy","streamEnabled","builder","AgentClass","AgentRunnerBuilder","run","message","opts","streamFactory","createSdkAgentStream","tools","apiKey","model","sessionId","crypto","randomUUID","runReflectiveLoop","loop","reflection","budget","signal","reflectionOverride","strategy","stream","enabled","build","walk","walkAgentMetadata","toolboxInstances","Map","toolboxes","map","tb","class","compileAgent","resolveLoopStrategy","mainLoop","maxIterations","ladderReflectionStrategy","noopReflectionStrategy","agentConfig","name","requireApiKey","opts","agentName","apiKey","DelegationError","mergeTools","parentTools","subTools","subToolNames","Set","map","t","name","inherited","filter","has","delegate","SubAgentClass","message","walk","walkAgentMetadata","toolboxInstances","Map","toolboxes","tb","class","compiled","compileAgent","allTools","tools","budget","Math","min","Infinity","parentBudgetRemaining","streamFactory","createSdkAgentStream","agentConfig","model","sessionId","crypto","randomUUID","loopStrategy","resolveLoopStrategy","mainLoop","strategy","maxIterations","reflection","ladderReflectionStrategy","noopReflectionStrategy","runReflectiveLoop","loop","signal","generateAgentManifest","walkResults","version","generatedAt","Date","toISOString","agents","map","r","name","agentConfig","route","model","stream","mainLoop","method","String","propertyKey","strategy","guards","g","interceptors","i","tools","toolboxes","flatMap","tb","t","namespace","config","description","risk","approval","undefined","capabilities","trace","audit","gateway","platforms","sessionStrategy","subAgents","subAgentClasses","cls","memory","provider","embeddings","fts","scope","skills","include","mcpServers","Object","keys","agentsPlugin","opts","routes","name","register","app","addHook","pluginCtx","initRoutes","request","url","URL","method","toUpperCase","matched","matchRoute","pathname","handler","allRoutes","walkResults","AgentClass","agents","mixins","getMixins","toolboxes","walkResult","walkAgentMetadata","push","compiled","compileAgent","Map","createRun","createRunFactory","defaultCreateRun","agentRoutes","generateAgentRoutes","compiledOptions","validateUniqueRoutes","compileRoutePatterns","_message","_sessionId","Promise","resolve","type","runId","Date","now","agentName","model","code","message","retryable","map","r","path","includes","regexSource","replace","regex","RegExp","find","test"]}
@@ -1 +0,0 @@
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/context-window.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 * @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 * @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,uBAAA;AAChC,IAAMC,kBAAkBF,uBAAOC,IAAI,0BAAA;AACnC,IAAME,iBAAiBH,uBAAOC,IAAI,wBAAA;AAClC,IAAMG,cAAcJ,uBAAOC,IAAI,qBAAA;AAC/B,IAAMI,eAAeL,uBAAOC,IAAI,6BAAA;;;AC2BvC,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AA,KAAW,CAAA;AACvD;AAFgBI;","names":["setMeta","getMeta","AGENT_CONFIG","Symbol","for","AGENT_MAIN_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","CONTEXT_WINDOW_CONFIG","Symbol","for","ContextWindow","options","target","setMeta","maxTokens","compactionStrategy","preserveSystemPrompt","preserveLastN","preserveToolResults","getContextWindowConfig","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"]}