@theokit/agents 0.4.0 → 0.5.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,7 +1,6 @@
1
1
  import {
2
2
  Artifact,
3
3
  Checkpoint,
4
- ContextWindow,
5
4
  Conversation,
6
5
  EditFormat,
7
6
  Hook,
@@ -9,14 +8,12 @@ import {
9
8
  MainLoop,
10
9
  Model,
11
10
  Observable,
12
- ProjectContext,
13
11
  Sandbox,
14
12
  Tool,
15
13
  Toolbox,
16
14
  applyDecorators,
17
15
  getArtifactConfig,
18
16
  getCheckpointConfig,
19
- getContextWindowConfig,
20
17
  getConversationConfig,
21
18
  getHooks,
22
19
  getHooksByPoint,
@@ -24,37 +21,40 @@ import {
24
21
  getMainLoop,
25
22
  getObservableByChannel,
26
23
  getObservables,
27
- getProjectContextConfig,
28
24
  getSandboxConfig,
29
25
  getToolConfig,
30
26
  getToolMethods,
31
27
  getToolboxConfig,
32
28
  isCommandAllowed,
33
29
  isPathAllowed
34
- } from "./chunk-VKHDADMG.js";
30
+ } from "./chunk-XWVZS2PQ.js";
35
31
  import {
36
32
  Agent,
37
33
  Audit,
38
34
  Budget,
35
+ ContextWindow,
39
36
  Gateway,
40
37
  MCP,
41
38
  Memory,
42
39
  Mixin,
43
40
  Policy,
41
+ ProjectContext,
44
42
  RequiresApproval,
45
43
  RequiresCapability,
46
44
  Skills,
47
45
  SubAgents,
48
46
  Trace,
49
47
  getAgentConfig,
48
+ getContextWindowConfig,
50
49
  getGatewayConfig,
51
50
  getMcpConfig,
52
51
  getMemoryConfig,
53
52
  getMixins,
53
+ getProjectContextConfig,
54
54
  getSkillsConfig,
55
55
  getSubAgents,
56
56
  resolveSessionId
57
- } from "./chunk-O4UG4RXE.js";
57
+ } from "./chunk-MVEY7HEY.js";
58
58
  import "./chunk-7QVYU63E.js";
59
59
  export {
60
60
  Agent,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- export { Agent, Artifact, ArtifactOptions, ArtifactResult, Audit, Budget, Checkpoint, CheckpointOptions, CheckpointState, CheckpointStorage, CheckpointStrategy, CommandPermissions, CompactionStrategy, ContextCompactionStrategy, ContextWindow, ContextWindowOptions, Conversation, ConversationOptions, ConversationStorage, EditFormat, EditFormatType, FilesystemPermissions, Hook, HookEntry, HookPoint, HumanInTheLoop, HumanInTheLoopOptions, IndexStrategy, MainLoop, Mixin, Model, Observable, ObservableEntry, Policy, ProjectContext, ProjectContextOptions, RelevanceStrategy, RequiresApproval, RequiresCapability, Sandbox, SandboxOptions, SubAgents, TimeoutAction, Tool, Toolbox, Trace, applyDecorators, getAgentConfig, getArtifactConfig, getCheckpointConfig, getContextWindowConfig, getConversationConfig, getHooks, getHooksByPoint, getHumanInTheLoopConfig, getMainLoop, getMixins, getObservableByChannel, getObservables, getProjectContextConfig, getSandboxConfig, getSubAgents, getToolConfig, getToolMethods, getToolboxConfig, isCommandAllowed, isPathAllowed } from './decorators.js';
2
- export { A as AgentOptions, a as ApprovalOptions, B as BudgetOptions, G as Gateway, b as GatewayOptions, M as MCP, c as MainLoopMeta, d as MainLoopOptions, e as McpServerConfig, f as McpServersMap, g as Memory, h as MemoryOptions, i as MemoryProvider, j as MemoryScope, P as PlatformName, k as PolicyHandler, S as SessionStrategy, l as Skills, m as SkillsOptions, T as ToolOptions, n as ToolboxOptions, o as getGatewayConfig, p as getMcpConfig, q as getMemoryConfig, r as getSkillsConfig, s as resolveSessionId } from './mcp-yyfC5u7t.js';
3
- export { AgentExecutionContext, AgentManifest, AgentManifestEntry, AgentManifestTool, AgentRoute, AgentRouteContext, AgentRunInfo, AgentStreamEvent, AgentWalkResult, AgentWarningCode, AgentsPluginOptions, ApprovalRequiredEvent, ArtifactChunkEvent, ArtifactStartEvent, BudgetExceededError, CheckpointSavedEvent, CompiledAgentOptions, CompiledTool, DelegateOptions, DelegationError, DelegationResult, DoneEvent, ErrorEvent, FileEditEvent, IterationEvent, RunStartedEvent, SdkMessage, StateUpdateEvent, StreamEvent, TextDeltaEvent, ThinkingEvent, ToolCallEvent, ToolResultEvent, ToolWalkResult, ToolboxWalkResult, agentsPlugin, compileAgent, compileTools, createAgentExecutionContext, createSdkAgentStream, delegate, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, streamAgentResponse, translateSdkEvent, validateUniqueRoutes, walkAgentMetadata } from './bridge.js';
1
+ export { Agent, Artifact, ArtifactOptions, ArtifactResult, Audit, Budget, Checkpoint, CheckpointOptions, CheckpointState, CheckpointStorage, CheckpointStrategy, CommandPermissions, CompactionStrategy, Conversation, ConversationOptions, ConversationStorage, EditFormat, EditFormatType, FilesystemPermissions, Hook, HookEntry, HookPoint, HumanInTheLoop, HumanInTheLoopOptions, MainLoop, Mixin, Model, Observable, ObservableEntry, Policy, RequiresApproval, RequiresCapability, Sandbox, SandboxOptions, SubAgents, TimeoutAction, Tool, Toolbox, Trace, applyDecorators, getAgentConfig, getArtifactConfig, getCheckpointConfig, getConversationConfig, getHooks, getHooksByPoint, getHumanInTheLoopConfig, getMainLoop, getMixins, getObservableByChannel, getObservables, getSandboxConfig, getSubAgents, getToolConfig, getToolMethods, getToolboxConfig, isCommandAllowed, isPathAllowed } from './decorators.js';
2
+ export { A as AgentOptions, a as ApprovalOptions, B as BudgetOptions, C as ContextCompactionStrategy, b as ContextWindow, c as ContextWindowOptions, G as Gateway, d as GatewayOptions, I as IndexStrategy, M as MCP, e as MainLoopMeta, f as MainLoopOptions, g as McpServerConfig, h as McpServersMap, i as Memory, j as MemoryOptions, k as MemoryProvider, l as MemoryScope, P as PlatformName, m as PolicyHandler, n as ProjectContext, o as ProjectContextOptions, R as RelevanceStrategy, S as SessionStrategy, p as Skills, q as SkillsOptions, T as ToolOptions, r as ToolboxOptions, s as getContextWindowConfig, t as getGatewayConfig, u as getMcpConfig, v as getMemoryConfig, w as getProjectContextConfig, x as getSkillsConfig, y as resolveSessionId } from './skills-DnfvEUSg.js';
3
+ export { AgentExecutionContext, AgentManifest, AgentManifestEntry, AgentManifestTool, AgentRoute, AgentRouteContext, AgentRunInfo, AgentStreamEvent, AgentWalkResult, AgentWarningCode, AgentsPluginOptions, ApprovalRequiredEvent, ArtifactChunkEvent, ArtifactStartEvent, BudgetExceededError, CheckpointSavedEvent, CompiledAgentOptions, CompiledContextWindow, CompiledTool, DelegateOptions, DelegationError, DelegationResult, DoneEvent, ErrorEvent, FileEditEvent, IterationEvent, RunStartedEvent, SdkMessage, StateUpdateEvent, StreamEvent, TextDeltaEvent, ThinkingEvent, ToolCallEvent, ToolResultEvent, ToolWalkResult, ToolboxWalkResult, agentsPlugin, compileAgent, compileContextWindow, compileProjectContext, compileSkills, compileTools, createAgentExecutionContext, createSdkAgentStream, delegate, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, projectContextMetadataOnlyKnobs, streamAgentResponse, translateSdkEvent, validateUniqueRoutes, walkAgentMetadata } from './bridge.js';
4
4
  import 'zod';
5
5
  import '@theokit/http';
6
+ import '@theokit/sdk';
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  Artifact,
3
3
  Checkpoint,
4
- ContextWindow,
5
4
  Conversation,
6
5
  EditFormat,
7
6
  Hook,
@@ -9,14 +8,12 @@ import {
9
8
  MainLoop,
10
9
  Model,
11
10
  Observable,
12
- ProjectContext,
13
11
  Sandbox,
14
12
  Tool,
15
13
  Toolbox,
16
14
  applyDecorators,
17
15
  getArtifactConfig,
18
16
  getCheckpointConfig,
19
- getContextWindowConfig,
20
17
  getConversationConfig,
21
18
  getHooks,
22
19
  getHooksByPoint,
@@ -24,20 +21,22 @@ import {
24
21
  getMainLoop,
25
22
  getObservableByChannel,
26
23
  getObservables,
27
- getProjectContextConfig,
28
24
  getSandboxConfig,
29
25
  getToolConfig,
30
26
  getToolMethods,
31
27
  getToolboxConfig,
32
28
  isCommandAllowed,
33
29
  isPathAllowed
34
- } from "./chunk-VKHDADMG.js";
30
+ } from "./chunk-XWVZS2PQ.js";
35
31
  import {
36
32
  AgentWarningCode,
37
33
  BudgetExceededError,
38
34
  DelegationError,
39
35
  agentsPlugin,
40
36
  compileAgent,
37
+ compileContextWindow,
38
+ compileProjectContext,
39
+ compileSkills,
41
40
  compileTools,
42
41
  createAgentExecutionContext,
43
42
  createSdkAgentStream,
@@ -51,34 +50,39 @@ import {
51
50
  isTextDelta,
52
51
  isToolCall,
53
52
  isToolResult,
53
+ projectContextMetadataOnlyKnobs,
54
54
  streamAgentResponse,
55
55
  translateSdkEvent,
56
56
  validateUniqueRoutes,
57
57
  walkAgentMetadata
58
- } from "./chunk-NC5EE7HN.js";
58
+ } from "./chunk-2MI27XCA.js";
59
59
  import {
60
60
  Agent,
61
61
  Audit,
62
62
  Budget,
63
+ ContextWindow,
63
64
  Gateway,
64
65
  MCP,
65
66
  Memory,
66
67
  Mixin,
67
68
  Policy,
69
+ ProjectContext,
68
70
  RequiresApproval,
69
71
  RequiresCapability,
70
72
  Skills,
71
73
  SubAgents,
72
74
  Trace,
73
75
  getAgentConfig,
76
+ getContextWindowConfig,
74
77
  getGatewayConfig,
75
78
  getMcpConfig,
76
79
  getMemoryConfig,
77
80
  getMixins,
81
+ getProjectContextConfig,
78
82
  getSkillsConfig,
79
83
  getSubAgents,
80
84
  resolveSessionId
81
- } from "./chunk-O4UG4RXE.js";
85
+ } from "./chunk-MVEY7HEY.js";
82
86
  import "./chunk-7QVYU63E.js";
83
87
  export {
84
88
  Agent,
@@ -114,6 +118,9 @@ export {
114
118
  agentsPlugin,
115
119
  applyDecorators,
116
120
  compileAgent,
121
+ compileContextWindow,
122
+ compileProjectContext,
123
+ compileSkills,
117
124
  compileTools,
118
125
  createAgentExecutionContext,
119
126
  createSdkAgentStream,
@@ -151,6 +158,7 @@ export {
151
158
  isTextDelta,
152
159
  isToolCall,
153
160
  isToolResult,
161
+ projectContextMetadataOnlyKnobs,
154
162
  resolveSessionId,
155
163
  streamAgentResponse,
156
164
  translateSdkEvent,
@@ -66,6 +66,22 @@ type PolicyHandler = (user: {
66
66
  roles: string[];
67
67
  }) => boolean;
68
68
 
69
+ type ContextCompactionStrategy = 'truncate-oldest' | 'summarize-oldest' | 'sliding-window' | 'priority-based';
70
+ interface ContextWindowOptions {
71
+ /** Maximum tokens before compaction triggers. */
72
+ maxTokens?: number;
73
+ /** How to compact when maxTokens is exceeded. */
74
+ compactionStrategy?: ContextCompactionStrategy;
75
+ /** Always preserve the system prompt during compaction (default: true). */
76
+ preserveSystemPrompt?: boolean;
77
+ /** Number of recent messages to always keep intact (default: 10). */
78
+ preserveLastN?: number;
79
+ /** Keep all tool results even during compaction (default: true). */
80
+ preserveToolResults?: boolean;
81
+ }
82
+ declare function ContextWindow(options?: ContextWindowOptions): ClassDecorator;
83
+ declare function getContextWindowConfig(target: Function): ContextWindowOptions | undefined;
84
+
69
85
  type PlatformName = 'telegram' | 'discord' | 'slack' | 'whatsapp' | 'teams' | 'email' | 'sms' | 'mattermost' | 'line' | 'matrix';
70
86
  type SessionStrategy = 'per-user' | 'per-channel' | 'per-thread';
71
87
  interface GatewayOptions {
@@ -92,6 +108,20 @@ declare function resolveSessionId(strategy: SessionStrategy, platform: string, s
92
108
  topicId?: string;
93
109
  }): string;
94
110
 
111
+ interface McpServerConfig {
112
+ /** Command to start the MCP server. */
113
+ command: string;
114
+ /** Arguments passed to the command. */
115
+ args?: string[];
116
+ /** Environment variables for the server process. */
117
+ env?: Record<string, string>;
118
+ /** Working directory for the server process. */
119
+ cwd?: string;
120
+ }
121
+ type McpServersMap = Record<string, McpServerConfig>;
122
+ declare function MCP(servers: McpServersMap): ClassDecorator;
123
+ declare function getMcpConfig(target: Function): McpServersMap | undefined;
124
+
95
125
  type MemoryProvider = 'built-in' | 'honcho' | 'supermemory' | 'mem0';
96
126
  type MemoryScope = 'per-user' | 'per-agent' | 'per-tenant' | 'global';
97
127
  interface MemoryOptions {
@@ -109,6 +139,25 @@ interface MemoryOptions {
109
139
  declare function Memory(options?: MemoryOptions): ClassDecorator;
110
140
  declare function getMemoryConfig(target: Function): MemoryOptions | undefined;
111
141
 
142
+ type IndexStrategy = 'tree-sitter' | 'regex' | 'none';
143
+ type RelevanceStrategy = 'git-history' | 'import-graph' | 'semantic' | 'manual';
144
+ interface ProjectContextOptions {
145
+ /** Files that mark the project root (searched upward from cwd). */
146
+ rootMarkers?: string[];
147
+ /** How to index the codebase for structural understanding. */
148
+ indexStrategy?: IndexStrategy;
149
+ /** Maximum files to include in context per request. */
150
+ maxFilesInContext?: number;
151
+ /** How to rank file relevance when selecting context. */
152
+ relevanceStrategy?: RelevanceStrategy;
153
+ /** Glob patterns to exclude from indexing and context. */
154
+ ignorePatterns?: string[];
155
+ /** File extensions to include in indexing (default: all text files). */
156
+ includeExtensions?: string[];
157
+ }
158
+ declare function ProjectContext(options?: ProjectContextOptions): ClassDecorator;
159
+ declare function getProjectContextConfig(target: Function): ProjectContextOptions | undefined;
160
+
112
161
  interface SkillsOptions {
113
162
  /** Skill names to include (resolved from .theokit/skills/<name>/SKILL.md). */
114
163
  include: string[];
@@ -118,18 +167,4 @@ interface SkillsOptions {
118
167
  declare function Skills(namesOrOptions: string[] | SkillsOptions): ClassDecorator;
119
168
  declare function getSkillsConfig(target: Function): SkillsOptions | undefined;
120
169
 
121
- interface McpServerConfig {
122
- /** Command to start the MCP server. */
123
- command: string;
124
- /** Arguments passed to the command. */
125
- args?: string[];
126
- /** Environment variables for the server process. */
127
- env?: Record<string, string>;
128
- /** Working directory for the server process. */
129
- cwd?: string;
130
- }
131
- type McpServersMap = Record<string, McpServerConfig>;
132
- declare function MCP(servers: McpServersMap): ClassDecorator;
133
- declare function getMcpConfig(target: Function): McpServersMap | undefined;
134
-
135
- export { type AgentOptions as A, type BudgetOptions as B, Gateway as G, MCP as M, type PlatformName as P, type SessionStrategy as S, type ToolOptions as T, type ApprovalOptions as a, type GatewayOptions as b, type MainLoopMeta as c, type MainLoopOptions as d, type McpServerConfig as e, type McpServersMap as f, Memory as g, type MemoryOptions as h, type MemoryProvider as i, type MemoryScope as j, type PolicyHandler as k, Skills as l, type SkillsOptions as m, type ToolboxOptions as n, getGatewayConfig as o, getMcpConfig as p, getMemoryConfig as q, getSkillsConfig as r, resolveSessionId as s };
170
+ export { type AgentOptions as A, type BudgetOptions as B, type ContextCompactionStrategy as C, Gateway as G, type IndexStrategy as I, MCP as M, type PlatformName as P, type RelevanceStrategy as R, type SessionStrategy as S, type ToolOptions as T, type ApprovalOptions as a, ContextWindow as b, type ContextWindowOptions as c, type GatewayOptions as d, type MainLoopMeta as e, type MainLoopOptions as f, type McpServerConfig as g, type McpServersMap as h, Memory as i, type MemoryOptions as j, type MemoryProvider as k, type MemoryScope as l, type PolicyHandler as m, ProjectContext as n, type ProjectContextOptions as o, Skills as p, type SkillsOptions as q, type ToolboxOptions as r, getContextWindowConfig as s, getGatewayConfig as t, getMcpConfig as u, getMemoryConfig as v, getProjectContextConfig as w, getSkillsConfig as x, resolveSessionId as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/agents",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Unified decorator runtime — AI agents as first-class citizens of the TheoKit pipeline. @Agent() compiles to SDK Agent.create(), @Tool() compiles to defineTool().",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -36,16 +36,27 @@
36
36
  },
37
37
  "peerDependencies": {
38
38
  "@theokit/http": ">=0.1.0-alpha.0",
39
- "@theokit/sdk": ">=1.5.0",
39
+ "@theokit/sdk": ">=2.5.0",
40
+ "@theokit/sdk-tools": ">=0.2.0",
40
41
  "reflect-metadata": ">=0.2.0",
41
42
  "zod": "^4.0.0"
42
43
  },
44
+ "peerDependenciesMeta": {
45
+ "@theokit/sdk-tools": {
46
+ "optional": true
47
+ }
48
+ },
43
49
  "devDependencies": {
44
50
  "@theokit/http": "workspace:*",
45
- "reflect-metadata": "^0.2.0",
46
- "zod": "^4.0.0",
47
- "tsup": "^8.0.0",
48
- "typescript": "^5.5.0",
49
- "vitest": "^3.0.0"
51
+ "@theokit/sdk": "^2.5.0",
52
+ "@theokit/sdk-tools": "^0.2.0",
53
+ "reflect-metadata": "^0.2.2",
54
+ "tsup": "^8.5.1",
55
+ "typescript": "^5.9.3",
56
+ "vitest": "^3.2.6",
57
+ "zod": "^4.4.3"
58
+ },
59
+ "engines": {
60
+ "node": ">=22.12.0"
50
61
  }
51
62
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/bridge/agent-execution-context.ts","../src/bridge/walk-agent-metadata.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/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 * 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 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 { 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\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} 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 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/** 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 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 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 * 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 { getAgentConfig } from '../decorators/agent.js'\nimport type { McpServersMap } from '../decorators/mcp.js'\nimport type { MemoryOptions } from '../decorators/memory.js'\nimport type { SkillsOptions } from '../decorators/skills.js'\n\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\n ? `${tb.namespace}.${tool.config.name}`\n : 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?: SkillsOptions\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,\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 const content = msg.content as unknown[] | undefined\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 const status = msg.status as string\n if (status === 'completed') {\n return [\n {\n type: 'tool_result',\n callId: asString(msg.id, `tc-${Date.now()}`),\n toolName: asString(msg.name, 'unknown'),\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: asString(msg.id, `tc-${Date.now()}`),\n toolName: asString(msg.name, 'unknown'),\n output: asString(msg.error, '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 const s = msg.status as string\n if (s === 'done' || s === 'completed') {\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') {\n return [\n {\n type: 'error',\n code: 'AGENT_ERROR',\n message: asString(msg.error, '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 return [{ type: 'thinking', content: asString(msg.content, '') }]\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 { CompiledTool } from './agent-compiler.js'\nimport type { StreamEvent } from './agent-sse-handler.js'\nimport { translateSdkEvent, type SdkMessage } from './event-translator.js'\nimport type { AgentWalkResult } from './walk-agent-metadata.js'\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 agentWalk: AgentWalkResult,\n compiledTools: CompiledTool[],\n apiKey: string,\n envModel?: string,\n) {\n const model = envModel ?? agentWalk.agentConfig.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: (\n opts: Record<string, unknown>,\n ) => 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 // Create SDK agent\n const agent = await Agent.create({\n apiKey,\n model: { id: model },\n tools: sdkTools,\n systemPrompt: agentWalk.agentConfig.systemPrompt,\n })\n\n // Send message + stream response\n const run = await agent.send(message)\n\n for await (const sdkEvent of run.stream()) {\n const translated = translateSdkEvent(sdkEvent, runId)\n for (const event of translated) {\n yield event\n }\n }\n\n // Emit done if SDK didn't emit status:done\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 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 * 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),\n * tool sharing, and toolbox auto-instantiation (EC-1).\n */\nimport type { CompiledTool } from './agent-compiler.js'\nimport { compileAgent } from './agent-compiler.js'\nimport { createSdkAgentStream } from './sdk-adapter.js'\nimport { walkAgentMetadata } from './walk-agent-metadata.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}\n\nexport interface DelegationResult {\n response: string\n toolCalls: { name: string; input: unknown; output: string }[]\n cost: number\n tokens: 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/** Safely coerce unknown to string. */\nfunction asString(value: unknown, fallback: string): string {\n if (typeof value === 'string') return value\n return fallback\n}\n\n/** Safely coerce unknown to number. */\nfunction asNumber(value: unknown, fallback: number): number {\n if (typeof value === 'number') return value\n return fallback\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/** Mutable accumulator for stream event processing. */\ninterface StreamAccumulator {\n response: string\n toolCalls: { name: string; input: unknown; output: string }[]\n cost: number\n tokens: number\n}\n\n/** Process a single stream event into the accumulator. Throws on budget exceeded or error. */\nfunction processStreamEvent(\n event: { type: string; [key: string]: unknown },\n acc: StreamAccumulator,\n budget: number,\n agentName: string,\n): void {\n if (event.type === 'text_delta' && typeof event.content === 'string') {\n acc.response += event.content\n return\n }\n if (event.type === 'tool_result') {\n acc.toolCalls.push({\n name: asString(event.toolName, 'unknown'),\n input: event.input ?? {},\n output: asString(event.output, ''),\n })\n return\n }\n if (event.type === 'done') {\n acc.cost = asNumber(event.cost, 0)\n const usage = event.usage as { totalTokens?: number } | undefined\n acc.tokens = usage?.totalTokens ?? 0\n if (Number.isFinite(budget) && acc.cost > budget) {\n throw new BudgetExceededError(agentName, acc.cost, budget)\n }\n return\n }\n if (event.type === 'error') {\n throw new DelegationError(\n agentName,\n asString((event as { message?: unknown }).message, 'Unknown agent error'),\n )\n }\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 */\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\n const allTools = mergeTools(opts.parentTools ?? [], compiled.tools)\n\n // 3. Budget clamping (D4)\n const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity)\n\n // 4. Create stream + collect (EC-4: randomUUID for session isolation)\n const streamFactory = createSdkAgentStream(walk, allTools, apiKey, walk.agentConfig.model)\n const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`\n\n const acc: StreamAccumulator = { response: '', toolCalls: [], cost: 0, tokens: 0 }\n\n try {\n for await (const event of streamFactory(message, sessionId)) {\n processStreamEvent(event, acc, budget, SubAgentClass.name)\n }\n } catch (err) {\n if (err instanceof BudgetExceededError || err instanceof DelegationError) throw err\n throw new DelegationError(SubAgentClass.name, err)\n }\n\n // 5. Budget enforcement (post-run check)\n if (Number.isFinite(budget) && acc.cost > budget) {\n throw new BudgetExceededError(SubAgentClass.name, acc.cost, budget)\n }\n\n return acc\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,UAAsB;AAEtB,SAAO;IACLC,YAAY,6BAAMJ,KAAKI,WAAU,GAArB;IACZC,QAAQ,6BAAML,KAAKK,OAAM,GAAjB;IACRC,UAAU,6BAAMN,KAAKM,SAAQ,GAAnB;IACVC,eAAe,6BAAMP,KAAKO,cAAa,GAAxB;IACfC,UAAU,6BAAMP,OAAN;IACVQ,QAAQ,6BAAMP,KAA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K7C,QAAAA;AACjC,WAAOqC,EAAEC,SAAStC;EACpB,CAAA;AACF;AAVSD;","names":["createAgentExecutionContext","base","agent","run","toolCall","getRequest","getUrl","getClass","getMethodName","getAgent","getRun","getToolCall","isAgentContext","ctx","Reflector","USE_GUARDS","Symbol","for","USE_INTERCEPTORS","USE_FILTERS","AgentWarningCode","INTERCEPTOR_METADATA_ONLY","FILTER_METADATA_ONLY","BUDGET_TOP_LEVEL_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","agentWalkCache","WeakMap","walkAgentMetadata","AgentClass","toolboxClasses","length","cached","agentConfig","AGENT_CONFIG","mainLoop","AGENT_MAIN_LOOP","interceptors","console","warn","filters","agentBudget","Budget","toolboxes","gateway","getGatewayConfig","subAgentClasses","getSubAgents","memory","getMemoryConfig","skills","getSkillsConfig","mcpServers","getMcpConfig","result","route","set","validateUniqueRoutes","results","seen","Map","r","existing","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","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","content","Array","isArray","block","b","text","push","callId","id","Date","now","toolName","name","input","translateToolCallEvent","status","output","result","durationMs","isError","error","translateStatusEvent","s","usage","inputTokens","outputTokens","totalTokens","cost","code","message","retryable","translateSdkEvent","createSdkAgentStream","agentWalk","compiledTools","apiKey","envModel","model","agentConfig","message","_sessionId","Symbol","asyncIterator","runId","Date","now","t0","Agent","defineTool","sdk","type","code","retryable","sdkTools","map","t","name","description","inputSchema","handler","agent","create","id","tools","systemPrompt","run","send","sdkEvent","stream","translated","translateSdkEvent","event","result","usage","inputTokens","outputTokens","totalTokens","durationMs","cost","dispose","err","Error","BudgetExceededError","Error","agentName","actualCost","budgetLimit","toFixed","name","DelegationError","cause","message","String","asString","value","fallback","asNumber","requireApiKey","opts","apiKey","mergeTools","parentTools","subTools","subToolNames","Set","map","t","inherited","filter","has","processStreamEvent","event","acc","budget","type","content","response","toolCalls","push","toolName","input","output","cost","usage","tokens","totalTokens","Number","isFinite","delegate","SubAgentClass","walk","walkAgentMetadata","toolboxInstances","Map","toolboxes","tb","class","compiled","compileAgent","allTools","tools","Math","min","Infinity","parentBudgetRemaining","streamFactory","createSdkAgentStream","agentConfig","model","sessionId","crypto","randomUUID","err","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/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 * @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,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,CAACC,WAAAA;AACN,UAAMC,UAAyBC,MAAMC,QAAQJ,cAAAA,IACzC;MAAEK,SAASL;MAAgBM,cAAc;IAAM,IAC/CN;AACJO,YAAQX,eAAeK,QAAQC,OAAAA;EACjC;AACF;AAPgBH;AAST,SAASS,gBAAgBP,QAAgB;AAC9C,SAAOQ,QAAuBb,eAAeK,MAAAA;AAC/C;AAFgBO;;;ACfhB,IAAME,aAAaC,uBAAOC,IAAI,oBAAA;AAevB,SAASC,IAAIC,SAAsB;AACxC,SAAO,CAACC,WAAAA;AACNC,YAAQN,YAAYK,QAAQD,OAAAA;EAC9B;AACF;AAJgBD;AAMT,SAASI,aAAaF,QAAgB;AAC3C,SAAOG,QAAuBR,YAAYK,MAAAA;AAC5C;AAFgBE;;;ACRhB,IAAME,gBAAgBC,uBAAOC,IAAI,uBAAA;AAE1B,SAASC,SAASC,cAAwB;AAC/C,SAAO,CAACC,WAAAA;AACN,UAAMC,WAAWC,QAAoBP,eAAeK,MAAAA,KAAW,CAAA;AAC/DG,YAAQR,eAAeK,QAAQ;SAAIC;SAAaF;KAAa;EAC/D;AACF;AALgBD;AAOT,SAASM,UAAUJ,QAAgB;AACxC,SAAOE,QAAoBP,eAAeK,MAAAA,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","MIXIN_CLASSES","Symbol","for","Mixin","mixinClasses","target","existing","getMeta","setMeta","getMixins"]}