@theokit/agents 0.2.0 → 0.4.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.
- package/dist/bridge.d.ts +97 -13
- package/dist/bridge.js +15 -4
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/{chunk-YSQAZWGW.js → chunk-NC5EE7HN.js} +325 -237
- package/dist/chunk-NC5EE7HN.js.map +1 -0
- package/dist/{chunk-3LCIXX3T.js → chunk-O4UG4RXE.js} +19 -7
- package/dist/chunk-O4UG4RXE.js.map +1 -0
- package/dist/{chunk-XUACDN32.js → chunk-VKHDADMG.js} +35 -13
- package/dist/chunk-VKHDADMG.js.map +1 -0
- package/dist/decorators.d.ts +8 -4
- package/dist/decorators.js +3 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +16 -5
- package/dist/{mcp-DmtwLSF-.d.ts → mcp-yyfC5u7t.d.ts} +2 -2
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +73 -0
- package/dist/testing.js.map +1 -0
- package/package.json +9 -3
- package/dist/chunk-3LCIXX3T.js.map +0 -1
- package/dist/chunk-XUACDN32.js.map +0 -1
- package/dist/chunk-YSQAZWGW.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -31,13 +31,17 @@ import {
|
|
|
31
31
|
getToolboxConfig,
|
|
32
32
|
isCommandAllowed,
|
|
33
33
|
isPathAllowed
|
|
34
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-VKHDADMG.js";
|
|
35
35
|
import {
|
|
36
|
+
AgentWarningCode,
|
|
37
|
+
BudgetExceededError,
|
|
38
|
+
DelegationError,
|
|
36
39
|
agentsPlugin,
|
|
37
40
|
compileAgent,
|
|
38
41
|
compileTools,
|
|
39
42
|
createAgentExecutionContext,
|
|
40
|
-
|
|
43
|
+
createSdkAgentStream,
|
|
44
|
+
delegate,
|
|
41
45
|
generateAgentManifest,
|
|
42
46
|
generateAgentRoutes,
|
|
43
47
|
isAgentContext,
|
|
@@ -48,9 +52,10 @@ import {
|
|
|
48
52
|
isToolCall,
|
|
49
53
|
isToolResult,
|
|
50
54
|
streamAgentResponse,
|
|
55
|
+
translateSdkEvent,
|
|
51
56
|
validateUniqueRoutes,
|
|
52
57
|
walkAgentMetadata
|
|
53
|
-
} from "./chunk-
|
|
58
|
+
} from "./chunk-NC5EE7HN.js";
|
|
54
59
|
import {
|
|
55
60
|
Agent,
|
|
56
61
|
Audit,
|
|
@@ -73,15 +78,19 @@ import {
|
|
|
73
78
|
getSkillsConfig,
|
|
74
79
|
getSubAgents,
|
|
75
80
|
resolveSessionId
|
|
76
|
-
} from "./chunk-
|
|
81
|
+
} from "./chunk-O4UG4RXE.js";
|
|
82
|
+
import "./chunk-7QVYU63E.js";
|
|
77
83
|
export {
|
|
78
84
|
Agent,
|
|
85
|
+
AgentWarningCode,
|
|
79
86
|
Artifact,
|
|
80
87
|
Audit,
|
|
81
88
|
Budget,
|
|
89
|
+
BudgetExceededError,
|
|
82
90
|
Checkpoint,
|
|
83
91
|
ContextWindow,
|
|
84
92
|
Conversation,
|
|
93
|
+
DelegationError,
|
|
85
94
|
EditFormat,
|
|
86
95
|
Gateway,
|
|
87
96
|
Hook,
|
|
@@ -107,7 +116,8 @@ export {
|
|
|
107
116
|
compileAgent,
|
|
108
117
|
compileTools,
|
|
109
118
|
createAgentExecutionContext,
|
|
110
|
-
|
|
119
|
+
createSdkAgentStream,
|
|
120
|
+
delegate,
|
|
111
121
|
generateAgentManifest,
|
|
112
122
|
generateAgentRoutes,
|
|
113
123
|
getAgentConfig,
|
|
@@ -143,6 +153,7 @@ export {
|
|
|
143
153
|
isToolResult,
|
|
144
154
|
resolveSessionId,
|
|
145
155
|
streamAgentResponse,
|
|
156
|
+
translateSdkEvent,
|
|
146
157
|
validateUniqueRoutes,
|
|
147
158
|
walkAgentMetadata
|
|
148
159
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { z } from 'zod';
|
|
2
2
|
|
|
3
3
|
/** Configuration stored by @Agent() decorator. */
|
|
4
4
|
interface AgentOptions {
|
|
@@ -45,7 +45,7 @@ interface ToolOptions {
|
|
|
45
45
|
/** LLM-facing description. */
|
|
46
46
|
description: string;
|
|
47
47
|
/** Zod input schema — compiled to JSON Schema via defineTool(). */
|
|
48
|
-
input:
|
|
48
|
+
input: z.ZodType;
|
|
49
49
|
/** Risk level (informational — feeds manifest + UI). */
|
|
50
50
|
risk?: 'low' | 'medium' | 'high';
|
|
51
51
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createMockAgentStream — test agents without an LLM API key.
|
|
3
|
+
*
|
|
4
|
+
* Returns an AsyncIterable that yields typed SSE events in sequence,
|
|
5
|
+
* simulating an agent conversation. Use in vitest/jest to test agent
|
|
6
|
+
* wiring, tool call handling, and UI rendering without real LLM costs.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { createMockAgentStream } from '@theokit/agents/testing'
|
|
11
|
+
*
|
|
12
|
+
* const stream = createMockAgentStream({
|
|
13
|
+
* responses: [
|
|
14
|
+
* { type: 'text', content: 'Here are your tasks:' },
|
|
15
|
+
* { type: 'tool_call', name: 'tasks.list', input: {}, output: '[{"id":1}]' },
|
|
16
|
+
* { type: 'text', content: 'You have 1 task.' },
|
|
17
|
+
* ],
|
|
18
|
+
* })
|
|
19
|
+
*
|
|
20
|
+
* const events = []
|
|
21
|
+
* for await (const event of stream('hello', 'session-1')) {
|
|
22
|
+
* events.push(event)
|
|
23
|
+
* }
|
|
24
|
+
* // events: [run_started, text_delta, tool_call, tool_result, text_delta, done]
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
interface MockResponse {
|
|
28
|
+
type: 'text' | 'tool_call' | 'error';
|
|
29
|
+
content?: string;
|
|
30
|
+
name?: string;
|
|
31
|
+
input?: unknown;
|
|
32
|
+
output?: string;
|
|
33
|
+
message?: string;
|
|
34
|
+
}
|
|
35
|
+
interface MockAgentStreamOptions {
|
|
36
|
+
agentName?: string;
|
|
37
|
+
responses: MockResponse[];
|
|
38
|
+
/** Simulated cost in USD (default: 0). */
|
|
39
|
+
cost?: number;
|
|
40
|
+
}
|
|
41
|
+
interface MockStreamEvent {
|
|
42
|
+
type: string;
|
|
43
|
+
[key: string]: unknown;
|
|
44
|
+
}
|
|
45
|
+
declare function createMockAgentStream(opts: MockAgentStreamOptions): (_message: string, _sessionId: string) => AsyncIterable<MockStreamEvent>;
|
|
46
|
+
|
|
47
|
+
export { type MockAgentStreamOptions, type MockResponse, type MockStreamEvent, createMockAgentStream };
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/testing/mock-stream.ts
|
|
6
|
+
function createMockAgentStream(opts) {
|
|
7
|
+
return (_message, _sessionId) => ({
|
|
8
|
+
async *[Symbol.asyncIterator]() {
|
|
9
|
+
await Promise.resolve();
|
|
10
|
+
const runId = `mock-${Date.now()}`;
|
|
11
|
+
yield {
|
|
12
|
+
type: "run_started",
|
|
13
|
+
runId,
|
|
14
|
+
agentName: opts.agentName ?? "mock-agent",
|
|
15
|
+
model: "mock"
|
|
16
|
+
};
|
|
17
|
+
let totalTokens = 0;
|
|
18
|
+
for (const r of opts.responses) {
|
|
19
|
+
if (r.type === "text" && r.content) {
|
|
20
|
+
const words = r.content.split(" ");
|
|
21
|
+
for (const word of words) {
|
|
22
|
+
yield {
|
|
23
|
+
type: "text_delta",
|
|
24
|
+
content: word + " "
|
|
25
|
+
};
|
|
26
|
+
totalTokens += 2;
|
|
27
|
+
}
|
|
28
|
+
} else if (r.type === "tool_call") {
|
|
29
|
+
const callId = `tc-${Date.now()}-${crypto.randomUUID().slice(0, 4)}`;
|
|
30
|
+
yield {
|
|
31
|
+
type: "tool_call",
|
|
32
|
+
callId,
|
|
33
|
+
toolName: r.name ?? "unknown",
|
|
34
|
+
input: r.input ?? {}
|
|
35
|
+
};
|
|
36
|
+
yield {
|
|
37
|
+
type: "tool_result",
|
|
38
|
+
callId,
|
|
39
|
+
toolName: r.name ?? "unknown",
|
|
40
|
+
output: r.output ?? "",
|
|
41
|
+
durationMs: 0,
|
|
42
|
+
isError: false
|
|
43
|
+
};
|
|
44
|
+
totalTokens += 10;
|
|
45
|
+
} else if (r.type === "error") {
|
|
46
|
+
yield {
|
|
47
|
+
type: "error",
|
|
48
|
+
code: "MOCK_ERROR",
|
|
49
|
+
message: r.message ?? "Mock error",
|
|
50
|
+
retryable: false
|
|
51
|
+
};
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
yield {
|
|
56
|
+
type: "done",
|
|
57
|
+
result: opts.responses.filter((r) => r.type === "text").map((r) => r.content).join(" "),
|
|
58
|
+
usage: {
|
|
59
|
+
inputTokens: totalTokens,
|
|
60
|
+
outputTokens: totalTokens,
|
|
61
|
+
totalTokens: totalTokens * 2
|
|
62
|
+
},
|
|
63
|
+
durationMs: 0,
|
|
64
|
+
cost: opts.cost ?? 0
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
__name(createMockAgentStream, "createMockAgentStream");
|
|
70
|
+
export {
|
|
71
|
+
createMockAgentStream
|
|
72
|
+
};
|
|
73
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing/mock-stream.ts"],"sourcesContent":["/**\n * createMockAgentStream — test agents without an LLM API key.\n *\n * Returns an AsyncIterable that yields typed SSE events in sequence,\n * simulating an agent conversation. Use in vitest/jest to test agent\n * wiring, tool call handling, and UI rendering without real LLM costs.\n *\n * @example\n * ```ts\n * import { createMockAgentStream } from '@theokit/agents/testing'\n *\n * const stream = createMockAgentStream({\n * responses: [\n * { type: 'text', content: 'Here are your tasks:' },\n * { type: 'tool_call', name: 'tasks.list', input: {}, output: '[{\"id\":1}]' },\n * { type: 'text', content: 'You have 1 task.' },\n * ],\n * })\n *\n * const events = []\n * for await (const event of stream('hello', 'session-1')) {\n * events.push(event)\n * }\n * // events: [run_started, text_delta, tool_call, tool_result, text_delta, done]\n * ```\n */\n\nexport interface MockResponse {\n type: 'text' | 'tool_call' | 'error'\n content?: string\n name?: string\n input?: unknown\n output?: string\n message?: string\n}\n\nexport interface MockAgentStreamOptions {\n agentName?: string\n responses: MockResponse[]\n /** Simulated cost in USD (default: 0). */\n cost?: number\n}\n\nexport interface MockStreamEvent {\n type: string\n [key: string]: unknown\n}\n\nexport function createMockAgentStream(opts: MockAgentStreamOptions) {\n return (_message: string, _sessionId: string): AsyncIterable<MockStreamEvent> => ({\n async *[Symbol.asyncIterator]() {\n await Promise.resolve() // yield to event loop for async contract\n const runId = `mock-${Date.now()}`\n yield { type: 'run_started', runId, agentName: opts.agentName ?? 'mock-agent', model: 'mock' }\n\n let totalTokens = 0\n for (const r of opts.responses) {\n if (r.type === 'text' && r.content) {\n const words = r.content.split(' ')\n for (const word of words) {\n yield { type: 'text_delta', content: word + ' ' }\n totalTokens += 2\n }\n } else if (r.type === 'tool_call') {\n const callId = `tc-${Date.now()}-${crypto.randomUUID().slice(0, 4)}`\n yield { type: 'tool_call', callId, toolName: r.name ?? 'unknown', input: r.input ?? {} }\n yield {\n type: 'tool_result',\n callId,\n toolName: r.name ?? 'unknown',\n output: r.output ?? '',\n durationMs: 0,\n isError: false,\n }\n totalTokens += 10\n } else if (r.type === 'error') {\n yield {\n type: 'error',\n code: 'MOCK_ERROR',\n message: r.message ?? 'Mock error',\n retryable: false,\n }\n return\n }\n }\n\n yield {\n type: 'done',\n result: opts.responses\n .filter((r) => r.type === 'text')\n .map((r) => r.content)\n .join(' '),\n usage: {\n inputTokens: totalTokens,\n outputTokens: totalTokens,\n totalTokens: totalTokens * 2,\n },\n durationMs: 0,\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aAAazB;UACb0B,cAAc1B;UACdA,aAAaA,cAAc;QAC7B;QACAe,YAAY;QACZY,MAAMxC,KAAKwC,QAAQ;MACrB;IACF;EACF;AACF;AAtDgBzC;","names":["createMockAgentStream","opts","_message","_sessionId","Symbol","asyncIterator","Promise","resolve","runId","Date","now","type","agentName","model","totalTokens","r","responses","content","words","split","word","callId","crypto","randomUUID","slice","toolName","name","input","output","durationMs","isError","code","message","retryable","result","filter","map","join","usage","inputTokens","outputTokens","cost"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/agents",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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
|
+
"sideEffects": false,
|
|
6
7
|
"main": "./dist/index.js",
|
|
7
8
|
"types": "./dist/index.d.ts",
|
|
8
9
|
"exports": {
|
|
@@ -17,6 +18,10 @@
|
|
|
17
18
|
"./bridge": {
|
|
18
19
|
"import": "./dist/bridge.js",
|
|
19
20
|
"types": "./dist/bridge.d.ts"
|
|
21
|
+
},
|
|
22
|
+
"./testing": {
|
|
23
|
+
"import": "./dist/testing.js",
|
|
24
|
+
"types": "./dist/testing.d.ts"
|
|
20
25
|
}
|
|
21
26
|
},
|
|
22
27
|
"files": [
|
|
@@ -30,12 +35,13 @@
|
|
|
30
35
|
"test:watch": "vitest"
|
|
31
36
|
},
|
|
32
37
|
"peerDependencies": {
|
|
33
|
-
"@theokit/http
|
|
38
|
+
"@theokit/http": ">=0.1.0-alpha.0",
|
|
39
|
+
"@theokit/sdk": ">=1.5.0",
|
|
34
40
|
"reflect-metadata": ">=0.2.0",
|
|
35
41
|
"zod": "^4.0.0"
|
|
36
42
|
},
|
|
37
43
|
"devDependencies": {
|
|
38
|
-
"@theokit/http
|
|
44
|
+
"@theokit/http": "workspace:*",
|
|
39
45
|
"reflect-metadata": "^0.2.0",
|
|
40
46
|
"zod": "^4.0.0",
|
|
41
47
|
"tsup": "^8.0.0",
|
|
@@ -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-decorators'\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 * Stores AgentOptions metadata. The compiler reads this to call\n * Agent.create() from @theokit/sdk at registration time.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support-agent', route: '/api/agents/support', model: 'claude-sonnet-4-5-20250929' })\n * @UseGuards(AuthGuard)\n * class SupportAgent {\n * @MainLoop()\n * async run(ctx: AgentContext) { ... }\n * }\n * ```\n */\nimport { setMeta, getMeta, AGENT_CONFIG } from '../metadata/index.js'\nimport type { AgentOptions } from '../types.js'\n\nexport function Agent(options: AgentOptions): ClassDecorator {\n return (target: Function) => {\n setMeta(AGENT_CONFIG, target, { stream: true, ...options })\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-decorators'\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-decorators'\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, 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;;;ACahC,SAASK,MAAMC,SAAqB;AACzC,SAAO,CAACC,WAAAA;AACNC,YAAQC,cAAcF,QAAQ;MAAEG,QAAQ;MAAM,GAAGJ;IAAQ,CAAA;EAC3D;AACF;AAJgBD;AAMT,SAASM,eAAeJ,QAAgB;AAC7C,SAAOK,QAAsBH,cAAcF,MAAAA;AAC7C;AAFgBI;;;ACnBhB,SAASE,uBAAuB;AAKzB,IAAMC,mBAAmBD,gBAAAA;AAGzB,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HODS","Agent","options","target","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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/decorators/main-loop.ts","../src/decorators/tool.ts","../src/decorators/hook.ts","../src/decorators/conversation.ts","../src/decorators/human-in-the-loop.ts","../src/decorators/context-window.ts","../src/decorators/model.ts","../src/decorators/artifact.ts","../src/decorators/checkpoint.ts","../src/decorators/observable.ts","../src/decorators/sandbox.ts","../src/decorators/edit-format.ts","../src/decorators/project-context.ts","../src/decorators/apply-decorators.ts"],"sourcesContent":["/**\n * @MainLoop() — marks the execution entry point of an agent.\n *\n * Only one @MainLoop per agent class. Second application overwrites (last-wins, with warning).\n */\nimport { setMeta, getMeta, AGENT_MAIN_LOOP } from '../metadata/index.js'\nimport type { MainLoopOptions, MainLoopMeta } from '../types.js'\n\nexport function MainLoop(options: MainLoopOptions = {}): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<MainLoopMeta>(AGENT_MAIN_LOOP, actualTarget)\n if (existing) {\n console.warn(\n `[@theokit/agents] ${actualTarget.name}: @MainLoop() already declared on '${String(existing.propertyKey)}'. Overwriting with '${String(propertyKey)}'.`,\n )\n }\n const meta: MainLoopMeta = {\n propertyKey,\n strategy: options.strategy ?? 'simple-chat',\n maxIterations: options.maxIterations,\n timeoutMs: options.timeoutMs,\n }\n setMeta(AGENT_MAIN_LOOP, actualTarget, meta)\n }\n}\n\nexport function getMainLoop(target: Function): MainLoopMeta | undefined {\n return getMeta<MainLoopMeta>(AGENT_MAIN_LOOP, target)\n}\n","/**\n * @Toolbox() + @Tool() — group and define agent tools.\n *\n * @Toolbox({ namespace }) is a class decorator that groups related tools.\n * @Tool({ name, description, input, risk }) is a method decorator compiled to defineTool().\n *\n * @UseGuards on @Toolbox applies to ALL tools (per ADR D7).\n */\nimport { setMeta, getMeta, TOOLBOX_CONFIG, TOOL_CONFIG, TOOL_METHODS } from '../metadata/index.js'\nimport type { ToolboxOptions, ToolOptions } from '../types.js'\n\nexport function Toolbox(options: ToolboxOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(TOOLBOX_CONFIG, target, options)\n }\n}\n\nexport function Tool(options: ToolOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(TOOL_CONFIG, actualTarget, options, propertyKey)\n // Accumulate tool methods list\n const existing = getMeta<(string | symbol)[]>(TOOL_METHODS, actualTarget) ?? []\n setMeta(TOOL_METHODS, actualTarget, [...existing, propertyKey])\n }\n}\n\nexport function getToolboxConfig(target: Function): ToolboxOptions | undefined {\n return getMeta<ToolboxOptions>(TOOLBOX_CONFIG, target)\n}\n\nexport function getToolMethods(target: Function): (string | symbol)[] {\n return getMeta<(string | symbol)[]>(TOOL_METHODS, target) ?? []\n}\n\nexport function getToolConfig(target: Function, propertyKey: string | symbol): ToolOptions | undefined {\n return getMeta<ToolOptions>(TOOL_CONFIG, target, propertyKey)\n}\n","/**\n * @Hook() — lifecycle hooks WITHIN the agent loop.\n *\n * Unlike HTTP interceptors (which wrap the entire handler), hooks fire at\n * specific points during the agent's reasoning → tool → response cycle.\n *\n * Hook points:\n * - 'before:llm-call' — before each LLM API call\n * - 'after:llm-call' — after each LLM response\n * - 'before:tool-call' — before each tool execution\n * - 'after:tool-call' — after each tool result\n * - 'on:iteration' — at each loop iteration\n * - 'on:complete' — when the agent produces a final answer\n * - 'on:error' — when the agent encounters an error\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n *\n * @Hook('before:llm-call')\n * async injectContext(ctx: HookContext) {\n * ctx.appendSystemPrompt(`Time: ${new Date().toISOString()}`)\n * }\n *\n * @Hook('after:tool-call')\n * async trackCost(ctx: HookContext) {\n * await billing.track(ctx.toolCall!.name, ctx.toolCall!.durationMs)\n * }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst HOOKS_CONFIG = Symbol.for('theokit:agents:hooks')\n\nexport type HookPoint =\n | 'before:llm-call'\n | 'after:llm-call'\n | 'before:tool-call'\n | 'after:tool-call'\n | 'on:iteration'\n | 'on:complete'\n | 'on:error'\n\nexport interface HookEntry {\n point: HookPoint\n propertyKey: string | symbol\n}\n\nexport function Hook(point: HookPoint): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<HookEntry[]>(HOOKS_CONFIG, actualTarget) ?? []\n setMeta(HOOKS_CONFIG, actualTarget, [...existing, { point, propertyKey }])\n }\n}\n\nexport function getHooks(target: Function): HookEntry[] {\n return getMeta<HookEntry[]>(HOOKS_CONFIG, target) ?? []\n}\n\nexport function getHooksByPoint(target: Function, point: HookPoint): HookEntry[] {\n return getHooks(target).filter((h) => h.point === point)\n}\n","/**\n * @Conversation() — declares conversation persistence strategy for an agent.\n *\n * Controls how the agent remembers message history across sessions.\n * Compiles to SDK's ConversationStorageAdapter configuration.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * @Conversation({\n * storage: 'drizzle',\n * maxHistory: 100,\n * compaction: 'summarize',\n * ttl: 24 * 60 * 60 * 1000,\n * })\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CONVERSATION_CONFIG = Symbol.for('theokit:agents:conversation')\n\nexport type ConversationStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis'\nexport type CompactionStrategy = 'truncate' | 'summarize' | 'sliding-window'\n\nexport interface ConversationOptions {\n /** Storage backend for conversation history. */\n storage?: ConversationStorage\n /** Maximum messages before compaction triggers (0 = no limit). */\n maxHistory?: number\n /** How to compact when maxHistory is exceeded. */\n compaction?: CompactionStrategy\n /** Time-to-live in milliseconds before conversation expires (0 = never). */\n ttl?: number\n /** Number of recent messages to always preserve during compaction. */\n preserveLastN?: number\n}\n\nexport function Conversation(options: ConversationOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CONVERSATION_CONFIG, target, {\n storage: 'memory',\n maxHistory: 0,\n compaction: 'truncate',\n ttl: 0,\n preserveLastN: 5,\n ...options,\n })\n }\n}\n\nexport function getConversationConfig(target: Function): ConversationOptions | undefined {\n return getMeta<ConversationOptions>(CONVERSATION_CONFIG, target)\n}\n","/**\n * @HumanInTheLoop() — pause agent execution to request human approval.\n *\n * When applied to a @Tool method, the agent pauses before executing the tool\n * and emits an 'approval_required' SSE event. The client must POST to the\n * callback URL to approve or deny. If denied or timed out, the tool is skipped.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'ops' })\n * class OpsTools {\n * @Tool({ name: 'deploy', description: 'Deploy to prod', input: z.object({...}) })\n * @HumanInTheLoop({\n * question: 'Confirm deployment to production?',\n * timeout: 300_000,\n * onTimeout: 'abort',\n * })\n * async deploy(input: {...}) { ... }\n * }\n * ```\n *\n * SSE event emitted:\n * ```json\n * { \"type\": \"approval_required\", \"toolName\": \"ops.deploy\", \"question\": \"...\", \"callbackUrl\": \"/agents/x/approve/call-123\" }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst HITL_CONFIG = Symbol.for('theokit:agents:human-in-the-loop')\n\nexport type TimeoutAction = 'abort' | 'proceed' | 'retry'\n\nexport interface HumanInTheLoopOptions {\n /** Question shown to the human approver. */\n question: string\n /** Timeout in milliseconds before onTimeout fires (default: 300_000 = 5 min). */\n timeout?: number\n /** Action when timeout expires (default: 'abort'). */\n onTimeout?: TimeoutAction\n /** Show the tool input to the approver (default: true). */\n showInput?: boolean\n}\n\nexport function HumanInTheLoop(options: HumanInTheLoopOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(HITL_CONFIG, actualTarget, {\n timeout: 300_000,\n onTimeout: 'abort',\n showInput: true,\n ...options,\n }, propertyKey)\n }\n}\n\nexport function getHumanInTheLoopConfig(\n target: Function,\n propertyKey: string | symbol,\n): HumanInTheLoopOptions | undefined {\n return getMeta<HumanInTheLoopOptions>(HITL_CONFIG, target, propertyKey)\n}\n","/**\n * @ContextWindow() — declares context window management strategy.\n *\n * Controls how the agent handles context when conversation history grows\n * beyond the LLM's context window. Mirrors Claude Code's PreCompact behavior.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * @ContextWindow({\n * maxTokens: 100_000,\n * compactionStrategy: 'summarize-oldest',\n * preserveSystemPrompt: true,\n * preserveLastN: 10,\n * })\n * class ResearchAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CONTEXT_WINDOW_CONFIG = Symbol.for('theokit:agents:context-window')\n\nexport type ContextCompactionStrategy =\n | 'truncate-oldest' // Drop oldest messages beyond limit\n | 'summarize-oldest' // LLM-summarize oldest messages into a single message\n | 'sliding-window' // Keep last N messages only\n | 'priority-based' // Keep tool results + recent; summarize reasoning\n\nexport interface ContextWindowOptions {\n /** Maximum tokens before compaction triggers. */\n maxTokens?: number\n /** How to compact when maxTokens is exceeded. */\n compactionStrategy?: ContextCompactionStrategy\n /** Always preserve the system prompt during compaction (default: true). */\n preserveSystemPrompt?: boolean\n /** Number of recent messages to always keep intact (default: 10). */\n preserveLastN?: number\n /** Keep all tool results even during compaction (default: true). */\n preserveToolResults?: boolean\n}\n\nexport function ContextWindow(options: ContextWindowOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CONTEXT_WINDOW_CONFIG, target, {\n maxTokens: 100_000,\n compactionStrategy: 'summarize-oldest',\n preserveSystemPrompt: true,\n preserveLastN: 10,\n preserveToolResults: true,\n ...options,\n })\n }\n}\n\nexport function getContextWindowConfig(target: Function): ContextWindowOptions | undefined {\n return getMeta<ContextWindowOptions>(CONTEXT_WINDOW_CONFIG, target)\n}\n","/**\n * @Model() — override the LLM model at agent or tool level.\n *\n * Hierarchical resolution via Reflector.getAllAndOverride:\n * tool @Model > agent @Model > @Agent({ model }) > config default\n *\n * This is a MODEL selector, not a PROVIDER selector. Provider routing\n * (which API key, which endpoint, fallback chains) lives in theo.config.ts\n * as runtime configuration — not in decorators.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * @Model('claude-sonnet-4-5-20250929') // default for all tools\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n * }\n *\n * @Toolbox({ namespace: 'code' })\n * class CodeTools {\n * @Tool({ name: 'generate', description: 'Generate code', input: z.object({...}) })\n * @Model('claude-opus-4-6') // this tool needs the most capable model\n * async generate() { ... }\n *\n * @Tool({ name: 'lint', description: 'Lint code', input: z.object({...}) })\n * // no @Model — inherits from agent level\n * async lint() { ... }\n * }\n * ```\n */\nimport { createDecorator } from '@theokit/http-decorators'\n\n/** Override the LLM model for an agent class or a specific tool method. */\nexport const Model = createDecorator<string>()\n","/**\n * @Artifact() — marks a tool as producing structured output artifacts.\n *\n * Artifacts are SEPARATE from text responses. When a tool produces an artifact\n * (code file, document, diagram, JSON data), the SSE stream emits artifact_start\n * + artifact_chunk events alongside text_delta events.\n *\n * Inspired by assistant-ui's A2AArtifact pattern where artifacts have their own\n * lifecycle (start → chunks → complete) independent of message content.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'code' })\n * class CodeTools {\n * @Tool({ name: 'generate', description: 'Generate code', input: z.object({...}) })\n * @Artifact({ mimeType: 'text/typescript', streamable: true })\n * async generate(input: { spec: string }): Promise<ArtifactResult> {\n * return {\n * content: generatedCode,\n * filename: 'component.tsx',\n * metadata: { language: 'typescript', loc: 42 },\n * }\n * }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst ARTIFACT_CONFIG = Symbol.for('theokit:agents:artifact')\n\nexport interface ArtifactOptions {\n /** MIME type of the artifact output. */\n mimeType: string\n /** Whether the artifact can be streamed in chunks (default: true). */\n streamable?: boolean\n /** Maximum size in bytes (0 = no limit). */\n maxSize?: number\n}\n\n/** Return type for tools decorated with @Artifact. */\nexport interface ArtifactResult {\n /** The artifact content (string for text, Buffer for binary). */\n content: string\n /** Optional filename hint for the client. */\n filename?: string\n /** Optional metadata attached to the artifact. */\n metadata?: Record<string, unknown>\n}\n\nexport function Artifact(options: ArtifactOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(ARTIFACT_CONFIG, actualTarget, { streamable: true, maxSize: 0, ...options }, propertyKey)\n }\n}\n\nexport function getArtifactConfig(\n target: Function,\n propertyKey: string | symbol,\n): ArtifactOptions | undefined {\n return getMeta<ArtifactOptions>(ARTIFACT_CONFIG, target, propertyKey)\n}\n","/**\n * @Checkpoint() — enables resumable agent execution from the last successful step.\n *\n * Long-running agents (research, code review, multi-step workflows) can fail\n * partway through. Without checkpointing, users restart from step 1 — wasting\n * tokens, time, and cost.\n *\n * Inspired by tRPC's tracked() + lastEventId pattern and Dapr's actor state\n * checkpointing. The agent persists a recovery point after each successful\n * tool call or iteration, and can resume from that point on retry.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * @Checkpoint({\n * storage: 'drizzle',\n * strategy: 'after-tool-call',\n * maxCheckpoints: 20,\n * ttl: 3_600_000, // 1h\n * })\n * class ResearchAgent {\n * @MainLoop({ strategy: 'plan-act-reflect', maxIterations: 15 })\n * async run() {}\n * }\n *\n * // Resume from checkpoint:\n * // POST /agents/research/chat { resumeToken: 'chk_abc123' }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CHECKPOINT_CONFIG = Symbol.for('theokit:agents:checkpoint')\n\nexport type CheckpointStrategy =\n | 'after-tool-call' // checkpoint after every successful tool execution\n | 'after-iteration' // checkpoint after every loop iteration\n | 'manual' // only checkpoint when explicitly called via ctx.checkpoint()\n\nexport type CheckpointStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis'\n\nexport interface CheckpointOptions {\n /** Where to persist checkpoints. */\n storage?: CheckpointStorage\n /** When to auto-checkpoint (default: 'after-tool-call'). */\n strategy?: CheckpointStrategy\n /** Maximum checkpoints to retain per run (rolling window). */\n maxCheckpoints?: number\n /** Time-to-live in ms before checkpoints expire (default: 3_600_000 = 1h). */\n ttl?: number\n}\n\n/** Serializable checkpoint state. */\nexport interface CheckpointState {\n id: string\n runId: string\n agentName: string\n step: number\n messages: unknown[]\n toolResults: unknown[]\n createdAt: number\n resumeToken: string\n}\n\nexport function Checkpoint(options: CheckpointOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CHECKPOINT_CONFIG, target, {\n storage: 'memory',\n strategy: 'after-tool-call',\n maxCheckpoints: 10,\n ttl: 3_600_000,\n ...options,\n })\n }\n}\n\nexport function getCheckpointConfig(target: Function): CheckpointOptions | undefined {\n return getMeta<CheckpointOptions>(CHECKPOINT_CONFIG, target)\n}\n","/**\n * @Observable() — exposes agent internal state as a real-time stream.\n *\n * Clients subscribe to named observables to monitor agent execution in real-time:\n * token usage, cost, iteration progress, pending approvals, retrieved facts.\n *\n * Inspired by Liveblocks' Presence pattern and tRPC subscriptions. The agent\n * pushes state updates via SSE alongside response events — clients are never\n * \"blind\" during long-running agent operations.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * class ResearchAgent {\n * @MainLoop()\n * async run() {}\n *\n * @Observable('metrics')\n * getMetrics(ctx: AgentContext): AgentMetrics {\n * return {\n * tokensUsed: ctx.tokenCount,\n * costUsd: ctx.costUsd,\n * iteration: ctx.iteration,\n * pendingApprovals: ctx.pendingApprovals.length,\n * }\n * }\n * }\n *\n * // SSE emits: { type: 'state_update', channel: 'metrics', data: {...} }\n * // Client: eventSource.addEventListener('state_update', handler)\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst OBSERVABLE_CONFIG = Symbol.for('theokit:agents:observable')\n\nexport interface ObservableEntry {\n channel: string\n propertyKey: string | symbol\n}\n\nexport function Observable(channel: string): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<ObservableEntry[]>(OBSERVABLE_CONFIG, actualTarget) ?? []\n setMeta(OBSERVABLE_CONFIG, actualTarget, [...existing, { channel, propertyKey }])\n }\n}\n\nexport function getObservables(target: Function): ObservableEntry[] {\n return getMeta<ObservableEntry[]>(OBSERVABLE_CONFIG, target) ?? []\n}\n\nexport function getObservableByChannel(target: Function, channel: string): ObservableEntry | undefined {\n return getObservables(target).find((o) => o.channel === channel)\n}\n","/**\n * @Sandbox() — declares file/command permission scope for code assistant agents.\n *\n * Controls what the agent can read, write, and execute. The runtime enforces\n * these permissions BEFORE tool execution — a tool that tries to write to a\n * denied path gets a typed error, not a crash.\n *\n * Inspired by Claude Code's permission system (allow/deny per tool + path).\n *\n * @example\n * ```ts\n * @Agent({ name: 'coder', route: '/agents/coder' })\n * @Sandbox({\n * filesystem: {\n * read: ['src/**', 'tests/**', 'package.json'],\n * write: ['src/**', 'tests/**'],\n * deny: ['node_modules/**', '.env', '*.key'],\n * },\n * commands: {\n * allow: ['npm test', 'tsc --noEmit', 'git diff'],\n * deny: ['rm -rf', 'git push --force', 'npm publish'],\n * },\n * network: false,\n * })\n * class CoderAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst SANDBOX_CONFIG = Symbol.for('theokit:agents:sandbox')\n\nexport interface FilesystemPermissions {\n /** Glob patterns for allowed read paths. */\n read?: string[]\n /** Glob patterns for allowed write paths. */\n write?: string[]\n /** Glob patterns for DENIED paths (overrides read/write). */\n deny?: string[]\n}\n\nexport interface CommandPermissions {\n /** Command prefixes allowed to execute. */\n allow?: string[]\n /** Command prefixes denied (overrides allow). */\n deny?: string[]\n}\n\nexport interface SandboxOptions {\n /** Filesystem read/write permissions. */\n filesystem?: FilesystemPermissions\n /** Shell command execution permissions. */\n commands?: CommandPermissions\n /** Allow outbound network from tools (default: true). */\n network?: boolean\n /** Maximum execution time per command in ms (default: 120_000). */\n commandTimeout?: number\n /** Working directory root (default: process.cwd()). */\n cwd?: string\n}\n\nexport function Sandbox(options: SandboxOptions): ClassDecorator {\n return (target: Function) => {\n setMeta(SANDBOX_CONFIG, target, {\n network: true,\n commandTimeout: 120_000,\n ...options,\n })\n }\n}\n\nexport function getSandboxConfig(target: Function): SandboxOptions | undefined {\n return getMeta<SandboxOptions>(SANDBOX_CONFIG, target)\n}\n\n/**\n * Check if a file path is allowed for the given operation.\n * Deny patterns always win over allow patterns.\n */\nexport function isPathAllowed(\n sandbox: SandboxOptions,\n filePath: string,\n operation: 'read' | 'write',\n): boolean {\n const fs = sandbox.filesystem\n if (!fs) return true // no filesystem restrictions\n\n // Deny always wins\n if (fs.deny?.some((pattern) => matchGlob(pattern, filePath))) return false\n\n const allowList = operation === 'read' ? fs.read : fs.write\n if (!allowList) return true // no explicit allow = allow all (minus deny)\n\n return allowList.some((pattern) => matchGlob(pattern, filePath))\n}\n\n/**\n * Check if a command is allowed to execute.\n * Deny patterns always win over allow patterns.\n */\nexport function isCommandAllowed(sandbox: SandboxOptions, command: string): boolean {\n const cmds = sandbox.commands\n if (!cmds) return true\n\n // Deny always wins\n if (cmds.deny?.some((prefix) => command.startsWith(prefix))) return false\n\n if (!cmds.allow) return true // no explicit allow = allow all (minus deny)\n\n return cmds.allow.some((prefix) => command.startsWith(prefix))\n}\n\n/** Simple glob matcher (supports * and ** patterns). */\nfunction matchGlob(pattern: string, path: string): boolean {\n const regex = pattern\n .replace(/\\./g, '\\\\.')\n .replace(/\\*\\*/g, '{{GLOBSTAR}}')\n .replace(/\\*/g, '[^/]*')\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, '.*')\n return new RegExp(`^${regex}$`).test(path)\n}\n","/**\n * @EditFormat() — declares how a tool outputs file edits.\n *\n * Code assistants show DIFFS, not entire files. This decorator tells the\n * runtime which format the tool produces so the SSE stream emits the\n * correct `file_edit` event type.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'editor' })\n * class EditorTools {\n * @Tool({ name: 'edit', description: 'Edit file', input: editSchema })\n * @EditFormat('search-replace')\n * async edit(input: { file: string; search: string; replace: string }) {\n * return { file: input.file, search: input.search, replace: input.replace }\n * }\n *\n * @Tool({ name: 'write', description: 'Write file', input: writeSchema })\n * @EditFormat('full-file')\n * async write(input: { file: string; content: string }) {\n * return { file: input.file, content: input.content }\n * }\n * }\n * ```\n */\nimport { createDecorator } from '@theokit/http-decorators'\n\nexport type EditFormatType =\n | 'search-replace' // { file, search, replace } — Claude Code Edit pattern\n | 'unified-diff' // Standard unified diff format\n | 'full-file' // Complete file content (Write pattern)\n | 'line-range' // { file, startLine, endLine, content }\n\n/** Declare the edit format a tool produces. */\nexport const EditFormat = createDecorator<EditFormatType>()\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 * applyDecorators() — compose multiple decorators into a single reusable decorator.\n *\n * NestJS-compatible utility. Enables creating \"preset\" decorators that bundle\n * common configurations (auth + throttle + trace + memory + ...) into one decorator.\n *\n * @example\n * ```ts\n * // Create a reusable preset\n * const ProductionAgent = (name: string, route: string) => applyDecorators(\n * Agent({ name, route, model: 'claude-sonnet-4-5-20250929' }),\n * UseGuards(AuthGuard, TenantGuard),\n * Throttle({ limit: 30, ttl: 60_000 }),\n * Budget({ maxCostUsd: 5.00 }),\n * Trace(true),\n * )\n *\n * // Apply preset to any agent\n * @ProductionAgent('support', '/api/agents/support')\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n * }\n * ```\n */\n\ntype AnyDecorator = ClassDecorator | MethodDecorator | PropertyDecorator\n\n/**\n * Compose multiple decorators into a single decorator.\n * Works for both class-level and method-level decorators.\n */\nexport function applyDecorators(\n ...decorators: AnyDecorator[]\n): ClassDecorator & MethodDecorator {\n return (\n target: object | Function,\n propertyKey?: string | symbol,\n descriptor?: PropertyDescriptor,\n ) => {\n for (const decorator of decorators) {\n if (propertyKey !== undefined && descriptor !== undefined) {\n // Method-level\n ;(decorator as MethodDecorator)(target, propertyKey, descriptor)\n } else {\n // Class-level\n ;(decorator as ClassDecorator)(target as Function)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAQO,SAASA,SAASC,UAA2B,CAAC,GAAC;AACpD,SAAO,CAACC,QAAgBC,gBAAAA;AACtB,UAAMC,eAAeF,OAAO;AAC5B,UAAMG,WAAWC,QAAsBC,iBAAiBH,YAAAA;AACxD,QAAIC,UAAU;AACZG,cAAQC,KACN,qBAAqBL,aAAaM,IAAI,sCAAsCC,OAAON,SAASF,WAAW,CAAA,wBAAyBQ,OAAOR,WAAAA,CAAAA,IAAgB;IAE3J;AACA,UAAMS,OAAqB;MACzBT;MACAU,UAAUZ,QAAQY,YAAY;MAC9BC,eAAeb,QAAQa;MACvBC,WAAWd,QAAQc;IACrB;AACAC,YAAQT,iBAAiBH,cAAcQ,IAAAA;EACzC;AACF;AAjBgBZ;AAmBT,SAASiB,YAAYf,QAAgB;AAC1C,SAAOI,QAAsBC,iBAAiBL,MAAAA;AAChD;AAFgBe;;;AChBT,SAASC,QAAQC,UAA0B,CAAC,GAAC;AAClD,SAAO,CAACC,WAAAA;AACNC,YAAQC,gBAAgBF,QAAQD,OAAAA;EAClC;AACF;AAJgBD;AAMT,SAASK,KAAKJ,SAAoB;AACvC,SAAO,CAACC,QAAgBI,gBA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ACXC,YAA0B;AAE7B,SAAO,CACLC,QACAC,aACAC,eAAAA;AAEA,eAAWC,aAAaJ,YAAY;AAClC,UAAIE,gBAAgBG,UAAaF,eAAeE,QAAW;;AAEvDD,kBAA8BH,QAAQC,aAAaC,UAAAA;MACvD,OAAO;;AAEHC,kBAA6BH,MAAAA;MACjC;IACF;EACF;AACF;AAlBgBF;","names":["MainLoop","options","target","propertyKey","actualTarget","existing","getMeta","AGENT_MAIN_LOOP","console","warn","name","String","meta","strategy","maxIterations","timeoutMs","setMeta","getMainLoop","Toolbox","options","target","setMeta","TOOLBOX_CONFIG","Tool","propertyKey","actualTarget","TOOL_CONFIG","existing","getMeta","TOOL_METHODS","getToolboxConfig","getToolMethods","getToolConfig","HOOKS_CONFIG","Symbol","for","Hook","point","target","propertyKey","actualTarget","existing","getMeta","setMeta","getHooks","getHooksByPoint","filter","h","CONVERSATION_CONFIG","Symbol","for","Conversation","options","target","setMeta","storage","maxHistory","compaction","ttl","preserveLastN","getConversationConfig","getMeta","HITL_CONFIG","Symbol","for","HumanInTheLoop","options","target","propertyKey","actualTarget","setMeta","timeout","onTimeout","showInput","getHumanInTheLoopConfig","getMeta","CONTEXT_WINDOW_CONFIG","Symbol","for","ContextWindow","options","target","setMeta","maxTokens","compactionStrategy","preserveSystemPrompt","preserveLastN","preserveToolResults","getContextWindowConfig","getMeta","createDecorator","Model","ARTIFACT_CONFIG","Symbol","for","Artifact","options","target","propertyKey","actualTarget","setMeta","streamable","maxSize","getArtifactConfig","getMeta","CHECKPOINT_CONFIG","Symbol","for","Checkpoint","options","target","setMeta","storage","strategy","maxCheckpoints","ttl","getCheckpointConfig","getMeta","OBSERVABLE_CONFIG","Symbol","for","Observable","channel","target","propertyKey","actualTarget","existing","getMeta","setMeta","getObservables","getObservableByChannel","find","o","SANDBOX_CONFIG","Symbol","for","Sandbox","options","target","setMeta","network","commandTimeout","getSandboxConfig","getMeta","isPathAllowed","sandbox","filePath","operation","fs","filesystem","deny","some","pattern","matchGlob","allowList","read","write","isCommandAllowed","command","cmds","commands","prefix","startsWith","allow","path","regex","replace","RegExp","test","createDecorator","EditFormat","PROJECT_CONTEXT_CONFIG","Symbol","for","ProjectContext","options","target","setMeta","rootMarkers","indexStrategy","maxFilesInContext","relevanceStrategy","ignorePatterns","getProjectContextConfig","getMeta","applyDecorators","decorators","target","propertyKey","descriptor","decorator","undefined"]}
|
|
@@ -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/llm-runner.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-decorators'\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'\nimport type { GatewayOptions } from '../decorators/gateway.js'\nimport { getGatewayConfig } from '../decorators/gateway.js'\nimport { RequiresApproval } from '../decorators/policies.js'\nimport { Trace, Audit } from '../decorators/observability.js'\nimport { Reflector } from '@theokit/http-decorators'\n\nconst reflectorInstance = new Reflector()\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 { 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 { AGENT_CONFIG, AGENT_MAIN_LOOP, TOOLBOX_CONFIG, TOOL_CONFIG, TOOL_METHODS } 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\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\n/** Read a createDecorator-style metadata value by searching for its Symbol key. */\nfunction readTypedMeta<T>(target: Function, propertyKey?: string | symbol): T | undefined {\n // createDecorator uses Symbol.for(`theokit:custom:${counter}`)\n // We read via Reflect.getMetadataKeys and filter\n const keys = propertyKey !== undefined\n ? Reflect.getMetadataKeys(target, propertyKey)\n : Reflect.getMetadataKeys(target)\n\n for (const key of keys) {\n if (typeof key === 'symbol') {\n const desc = Symbol.keyFor(key)\n if (desc?.startsWith('theokit:custom:')) {\n const value = propertyKey !== undefined\n ? Reflect.getMetadata(key, target, propertyKey)\n : Reflect.getMetadata(key, target)\n if (value !== undefined) return value as T\n }\n }\n }\n return undefined\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: approvalVal && typeof approvalVal === 'object' && 'reason' in approvalVal ? approvalVal : 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(\n `[@theokit/agents] Class ${AgentClass.name} is missing @Agent() decorator.`,\n )\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 const interceptors = getMeta<Function[]>(USE_INTERCEPTORS, AgentClass) ?? []\n const filters = getMeta<Function[]>(USE_FILTERS, AgentClass) ?? []\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}\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 { body = await request.json() as Record<string, unknown> } catch { /* empty */ }\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 sessionId = (body?.sessionId as string) ?? `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), { status: 200, headers: { 'content-type': 'application/json' } })\n },\n })\n }\n\n return routes\n}\n","/**\n * Real LLM Agent Runner v1.1 — all 7 dogfood gaps fixed.\n *\n * 1. Token-by-token streaming (stream: true + SSE delta parsing + EC-1 buffer safety)\n * 2. Multi-turn conversation (session Map + EC-2 TTL eviction)\n * 3. Model from decorator metadata (EC-5 provider prefix auto-detect)\n * 4. Consistent tool names (dot ↔ underscore bidirectional mapping)\n * 5. Robust Zod→JSON Schema via Zod v4 native z.toJSONSchema()\n * 6. Budget enforcement (per-session cost tracking from EC-3 last-chunk usage)\n * 7. AbortController cancel (EC-4 race-safe signal.aborted check)\n */\nimport type { StreamEvent } from './agent-sse-handler.js'\nimport type { CompiledTool } from './agent-compiler.js'\nimport type { AgentWalkResult } from './walk-agent-metadata.js'\n\nconst OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'\n\ninterface Message {\n role: 'system' | 'user' | 'assistant' | 'tool'\n content: string | null\n tool_calls?: ToolCall[]\n tool_call_id?: string\n}\n\ninterface ToolCall {\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\n// ─── Gap 2: Session store with TTL eviction (EC-2) ──────────\n\ninterface Session { messages: Message[]; createdAt: number; totalCostUsd: number }\nconst sessions = new Map<string, Session>()\nsetInterval(() => {\n const now = Date.now()\n for (const [id, s] of sessions) { if (now - s.createdAt > 3600_000) sessions.delete(id) }\n}, 300_000).unref()\n\n// ─── Gap 3: Model resolution (EC-5: auto-prefix) ───────────\n\nfunction resolveModel(decorator?: string, env?: string): string {\n const m = env ?? decorator ?? 'openai/gpt-4o-mini'\n return m.includes('/') ? m : `anthropic/${m}`\n}\n\n// ─── Gap 4: Tool name mapping ───────────────────────────────\n\nconst sanitize = (n: string) => n.replace(/\\./g, '_')\n\nexport function createRealAgentStream(\n agentWalk: AgentWalkResult,\n compiledTools: CompiledTool[],\n apiKey: string,\n envModel?: string,\n) {\n const model = resolveModel(agentWalk.agentConfig.model, envModel)\n\n const nameMap = new Map<string, string>()\n const toolMap = new Map<string, CompiledTool>()\n const orTools = compiledTools.map((t) => {\n const s = sanitize(t.name)\n nameMap.set(s, t.name)\n toolMap.set(s, t)\n return { type: 'function' as const, function: { name: s, description: t.description, parameters: convertZodToJsonSchema(t.inputSchema) } }\n })\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 if (!sessions.has(sessionId)) {\n sessions.set(sessionId, {\n messages: [{ role: 'system', content: agentWalk.agentConfig.systemPrompt ?? 'You are a helpful assistant.' }],\n createdAt: Date.now(), totalCostUsd: 0,\n })\n }\n const session = sessions.get(sessionId)!\n session.messages.push({ role: 'user', content: message })\n\n yield { type: 'run_started', runId, agentName: agentWalk.agentConfig.name, model }\n\n const maxIter = agentWalk.mainLoop.maxIterations ?? 5\n let inTok = 0, outTok = 0\n\n for (let iter = 1; iter <= maxIter; iter++) {\n yield { type: 'iteration', step: iter, totalSteps: maxIter }\n\n // ─── Gap 1: Streaming fetch ─────────────────────\n const res = await fetch(OPENROUTER_URL, {\n method: 'POST',\n headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({ model, messages: session.messages, tools: orTools.length ? orTools : undefined, max_tokens: 1000, stream: true }),\n })\n\n if (!res.ok) {\n yield { type: 'error', code: 'LLM_ERROR', message: `OpenRouter ${res.status}: ${await res.text()}`, retryable: res.status === 429 }\n return\n }\n\n // Parse SSE stream (EC-1: line buffering for partial JSON)\n const reader = res.body!.getReader()\n const dec = new TextDecoder()\n let buf = ''\n let content = ''\n let tcs: ToolCall[] = []\n let finish = ''\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buf += dec.decode(value, { stream: true })\n const lines = buf.split('\\n')\n buf = lines.pop() ?? ''\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue\n const d = line.slice(6).trim()\n if (d === '[DONE]') continue\n try {\n const c = JSON.parse(d) as { choices: [{ delta: { content?: string; tool_calls?: { index: number; id?: string; function?: { name?: string; arguments?: string } }[] }; finish_reason?: string }]; usage?: { prompt_tokens: number; completion_tokens: number; cost?: number } }\n const delta = c.choices?.[0]?.delta\n if (delta?.content) { content += delta.content; yield { type: 'text_delta', content: delta.content } }\n if (delta?.tool_calls) {\n for (const tc of delta.tool_calls) {\n if (tc.id) tcs[tc.index] = { id: tc.id, type: 'function', function: { name: tc.function?.name ?? '', arguments: '' } }\n if (tc.function?.arguments && tcs[tc.index]) tcs[tc.index].function.arguments += tc.function.arguments\n if (tc.function?.name && tcs[tc.index]) tcs[tc.index].function.name = tc.function.name\n }\n }\n if (c.choices[0]?.finish_reason) finish = c.choices[0].finish_reason\n if (c.usage) { inTok += c.usage.prompt_tokens; outTok += c.usage.completion_tokens; if (c.usage.cost) session.totalCostUsd += c.usage.cost }\n } catch { /* EC-1: skip malformed */ }\n }\n }\n\n // Tool calls?\n if (finish === 'tool_calls' && tcs.length > 0) {\n session.messages.push({ role: 'assistant', content: null, tool_calls: tcs })\n for (const tc of tcs) {\n const orig = nameMap.get(tc.function.name) ?? tc.function.name\n const tool = toolMap.get(tc.function.name)\n yield { type: 'tool_call', callId: tc.id, toolName: orig, input: JSON.parse(tc.function.arguments || '{}') }\n if (!tool) {\n session.messages.push({ role: 'tool', content: 'Tool not found', tool_call_id: tc.id })\n yield { type: 'tool_result', callId: tc.id, toolName: orig, output: 'Not found', durationMs: 0, isError: true }\n continue\n }\n const s = Date.now()\n try {\n const r = await tool.handler(JSON.parse(tc.function.arguments || '{}'))\n session.messages.push({ role: 'tool', content: r, tool_call_id: tc.id })\n yield { type: 'tool_result', callId: tc.id, toolName: orig, output: r.substring(0, 200), durationMs: Date.now() - s, isError: false }\n } catch (e) {\n const m = e instanceof Error ? e.message : 'Failed'\n session.messages.push({ role: 'tool', content: `Error: ${m}`, tool_call_id: tc.id })\n yield { type: 'tool_result', callId: tc.id, toolName: orig, output: m, durationMs: Date.now() - s, isError: true }\n }\n }\n tcs = []; content = ''\n continue\n }\n\n if (content) session.messages.push({ role: 'assistant', content })\n yield { type: 'done', result: content, usage: { inputTokens: inTok, outputTokens: outTok, totalTokens: inTok + outTok }, durationMs: Date.now() - t0, cost: session.totalCostUsd }\n return\n }\n yield { type: 'error', code: 'MAX_ITERATIONS', message: `Max iterations (${maxIter})`, retryable: false }\n },\n })\n}\n\n// ─── Gap 5: Robust Zod→JSON Schema (Zod v4 native) ─────────\n\nimport { z } from 'zod'\n\nfunction convertZodToJsonSchema(schema: unknown): Record<string, unknown> {\n if (!schema || typeof schema !== 'object') return { type: 'object', properties: {} }\n const { $schema: _, ...rest } = z.toJSONSchema(schema as z.ZodType) as Record<string, unknown>\n return rest\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 { walkAgentMetadata, validateUniqueRoutes, type AgentWalkResult } 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?: (compiled: CompiledAgentOptions, walkResult: AgentWalkResult) =>\n (message: string, sessionId: string) => AsyncIterable<StreamEvent>\n}\n\ninterface PluginApp {\n addHook(name: string, fn: (ctx: { request: Request }) => Promise<Response | void>): 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: AgentRoute[] | null = null\n\n return {\n name: '@theokit/agents',\n\n register(app: PluginApp) {\n app.addHook('onRequest', async (pluginCtx) => {\n if (!routes) 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): AgentRoute[] {\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 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 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: 'No createRunFactory provided — wire @theokit/sdk Agent.create() to enable real agent execution.',\n retryable: false,\n }\n }\n}\n\n/** Simple route matcher — checks method + path prefix. */\nfunction matchRoute(routes: AgentRoute[], method: string, pathname: string): AgentRoute | undefined {\n return routes.find((r) => {\n if (r.method !== method) return false\n // Handle :param patterns\n if (r.path.includes(':')) {\n const pattern = r.path.replace(/:[^/]+/g, '[^/]+')\n return new RegExp(`^${pattern}$`).test(pathname)\n }\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,KAAN;IACRQ,aAAa,6BAAMP,YAAY,MAAlB;IACbQ,gBAAgB,6BAAM,MAAN;EAClB;AACF;AAhBgB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AMC,SAASC,UAAUH,UAAAA;AACzB,UAAMI,YAAY;SAAKvB,KAAKuB,aAAa,CAAA;SAAQF;;AAEjD,UAAMG,aAAaC,kBAAkBN,YAAYI,SAAAA;AACjDL,gBAAYQ,KAAKF,UAAAA;AAEjB,UAAMG,WAAWC,aAAaJ,YAAY,oBAAIK,IAAAA,CAAAA;AAC9C,UAAMC,YAAY9B,KAAK+B,mBACnB/B,KAAK+B,iBAAiBJ,UAAUH,UAAAA,IAChCQ,iBAAiBL,QAAAA;AAErB,UAAMM,cAAcC,oBAAoB;MACtCV;MACAW,iBAAiBR;MACjBG;IACF,CAAA;AAEAb,cAAUS,KAAI,GAAIO,WAAAA;EACpB;AAEAG,uBAAqBlB,WAAAA;AACrB,SAAOD;AACT;AA5BSV;AA+BT,SAASyB,iBAAiBL,UAA8B;AACtD,SAAO,iBAAiBU,UAAkBC,YAAkB;AAC1D,UAAM;MACJC,MAAM;MACNC,OAAO,OAAOC,KAAKC,IAAG,CAAA;MACtBC,WAAWhB,SAASiB,SAAS;IAC/B;AACA,UAAM;MACJL,MAAM;MACNM,MAAM;MACNC,SAAS;MACTC,WAAW;IACb;EACF;AACF;AAdSf;AAiBT,SAASlB,WAAWb,QAAsBU,QAAgBI,UAAgB;AACxE,SAAOd,OAAO+C,KAAK,CAACC,MAAAA;AAClB,QAAIA,EAAEtC,WAAWA,OAAQ,QAAO;AAEhC,QAAIsC,EAAEC,KAAKC,SAAS,GAAA,GAAM;AACxB,YAAMC,UAAUH,EAAEC,KAAKG,QAAQ,WAAW,OAAA;AAC1C,aAAO,IAAIC,OAAO,IAAIF,OAAAA,GAAU,EAAEG,KAAKxC,QAAAA;IACzC;AACA,WAAOkC,EAAEC,SAASnC;EACpB,CAAA;AACF;AAVSD;","names":["createAgentExecutionContext","base","agent","run","toolCall","getRequest","getUrl","getClass","getMethodName","getAgent","getRun","getToolCall","isAgentContext","ctx","Reflector","reflectorInstance","Reflector","USE_GUARDS","Symbol","for","USE_INTERCEPTORS","USE_FILTERS","walkToolbox","ToolboxClass","config","getMeta","TOOLBOX_CONFIG","methods","TOOL_METHODS","classGuards","USE_GUARDS","tools","map","propertyKey","toolConfig","TOOL_CONFIG","Error","name","String","methodGuards","ref","reflectorInstance","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","USE_INTERCEPTORS","filters","USE_FILTERS","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","sessionId","Date","now","streamAgentResponse","url","URL","runId","pathname","split","pop","run","z","OPENROUTER_URL","sessions","Map","setInterval","now","Date","id","s","createdAt","delete","unref","resolveModel","decorator","env","m","includes","sanitize","n","replace","createRealAgentStream","agentWalk","compiledTools","apiKey","envModel","model","agentConfig","nameMap","toolMap","orTools","map","t","name","set","type","function","description","parameters","convertZodToJsonSchema","inputSchema","message","sessionId","Symbol","asyncIterator","runId","t0","has","messages","role","content","systemPrompt","totalCostUsd","session","get","push","agentName","maxIter","mainLoop","maxIterations","inTok","outTok","iter","step","totalSteps","res","fetch","method","headers","body","JSON","stringify","tools","length","undefined","max_tokens","stream","ok","code","status","text","retryable","reader","getReader","dec","TextDecoder","buf","tcs","finish","done","value","read","decode","lines","split","pop","line","startsWith","d","slice","trim","c","parse","delta","choices","tool_calls","tc","index","arguments","finish_reason","usage","prompt_tokens","completion_tokens","cost","orig","tool","callId","toolName","input","tool_call_id","output","durationMs","isError","r","handler","substring","e","Error","result","inputTokens","outputTokens","totalTokens","schema","properties","$schema","_","rest","z","toJSONSchema","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","_message","_sessionId","type","runId","Date","now","agentName","model","code","message","retryable","find","r","path","includes","pattern","replace","RegExp","test"]}
|