@theokit/agents 0.1.0-alpha.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.
@@ -0,0 +1,461 @@
1
+ import {
2
+ AGENT_CONFIG,
3
+ AGENT_MAIN_LOOP,
4
+ Audit,
5
+ RequiresApproval,
6
+ TOOLBOX_CONFIG,
7
+ TOOL_CONFIG,
8
+ TOOL_METHODS,
9
+ Trace,
10
+ __name,
11
+ getAgentConfig,
12
+ getGatewayConfig,
13
+ getMcpConfig,
14
+ getMemoryConfig,
15
+ getMeta,
16
+ getMixins,
17
+ getSkillsConfig,
18
+ getSubAgents
19
+ } from "./chunk-3LCIXX3T.js";
20
+
21
+ // src/bridge/agent-execution-context.ts
22
+ function createAgentExecutionContext(base, agent, run, toolCall) {
23
+ return {
24
+ getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
25
+ getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
26
+ getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
27
+ getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
28
+ getAgent: /* @__PURE__ */ __name(() => agent, "getAgent"),
29
+ getRun: /* @__PURE__ */ __name(() => run, "getRun"),
30
+ getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
31
+ isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
32
+ };
33
+ }
34
+ __name(createAgentExecutionContext, "createAgentExecutionContext");
35
+ function isAgentContext(ctx) {
36
+ return "isAgentContext" in ctx && ctx.isAgentContext();
37
+ }
38
+ __name(isAgentContext, "isAgentContext");
39
+
40
+ // src/bridge/walk-agent-metadata.ts
41
+ import "reflect-metadata";
42
+ import { Reflector } from "@theokit/http-decorators";
43
+ var reflectorInstance = new Reflector();
44
+ var USE_GUARDS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-guards");
45
+ var USE_INTERCEPTORS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-interceptors");
46
+ var USE_FILTERS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-filters");
47
+ function walkToolbox(ToolboxClass) {
48
+ const config = getMeta(TOOLBOX_CONFIG, ToolboxClass) ?? {};
49
+ const methods = getMeta(TOOL_METHODS, ToolboxClass) ?? [];
50
+ const classGuards = getMeta(USE_GUARDS, ToolboxClass) ?? [];
51
+ const tools = methods.map((propertyKey) => {
52
+ const toolConfig = getMeta(TOOL_CONFIG, ToolboxClass, propertyKey);
53
+ if (!toolConfig) {
54
+ throw new Error(`[@theokit/agents] Toolbox ${ToolboxClass.name}: method '${String(propertyKey)}' is in TOOL_METHODS but has no @Tool() config.`);
55
+ }
56
+ const methodGuards = getMeta(USE_GUARDS, ToolboxClass, propertyKey) ?? [];
57
+ const ref = reflectorInstance;
58
+ const approvalVal = ref.get(RequiresApproval, ToolboxClass, propertyKey);
59
+ const traceVal = ref.get(Trace, ToolboxClass, propertyKey);
60
+ const auditVal = ref.get(Audit, ToolboxClass, propertyKey);
61
+ return {
62
+ propertyKey,
63
+ config: toolConfig,
64
+ guards: [
65
+ ...classGuards,
66
+ ...methodGuards
67
+ ],
68
+ approval: approvalVal && typeof approvalVal === "object" && "reason" in approvalVal ? approvalVal : void 0,
69
+ capabilities: void 0,
70
+ budget: void 0,
71
+ trace: traceVal ?? false,
72
+ audit: auditVal ?? false
73
+ };
74
+ });
75
+ return {
76
+ class: ToolboxClass,
77
+ namespace: config.namespace ?? "",
78
+ tools,
79
+ guards: classGuards
80
+ };
81
+ }
82
+ __name(walkToolbox, "walkToolbox");
83
+ var agentWalkCache = /* @__PURE__ */ new WeakMap();
84
+ function walkAgentMetadata(AgentClass, toolboxClasses = []) {
85
+ if (toolboxClasses.length === 0) {
86
+ const cached = agentWalkCache.get(AgentClass);
87
+ if (cached) return cached;
88
+ }
89
+ const agentConfig = getMeta(AGENT_CONFIG, AgentClass);
90
+ if (!agentConfig) {
91
+ throw new Error(`[@theokit/agents] Class ${AgentClass.name} is missing @Agent() decorator.`);
92
+ }
93
+ const mainLoop = getMeta(AGENT_MAIN_LOOP, AgentClass);
94
+ if (!mainLoop) {
95
+ throw new Error(`[@theokit/agents] Agent ${AgentClass.name} is missing @MainLoop() decorator. Decorate exactly one method with @MainLoop().`);
96
+ }
97
+ const guards = getMeta(USE_GUARDS, AgentClass) ?? [];
98
+ const interceptors = getMeta(USE_INTERCEPTORS, AgentClass) ?? [];
99
+ const filters = getMeta(USE_FILTERS, AgentClass) ?? [];
100
+ const toolboxes = toolboxClasses.map(walkToolbox);
101
+ const gateway = getGatewayConfig(AgentClass);
102
+ const subAgentClasses = getSubAgents(AgentClass);
103
+ const memory = getMemoryConfig(AgentClass);
104
+ const skills = getSkillsConfig(AgentClass);
105
+ const mcpServers = getMcpConfig(AgentClass);
106
+ const result = {
107
+ agentConfig,
108
+ mainLoop,
109
+ toolboxes,
110
+ guards,
111
+ interceptors,
112
+ filters,
113
+ route: agentConfig.route,
114
+ gateway,
115
+ subAgentClasses,
116
+ memory,
117
+ skills,
118
+ mcpServers
119
+ };
120
+ if (toolboxClasses.length === 0) {
121
+ agentWalkCache.set(AgentClass, result);
122
+ }
123
+ return result;
124
+ }
125
+ __name(walkAgentMetadata, "walkAgentMetadata");
126
+ function validateUniqueRoutes(results) {
127
+ const seen = /* @__PURE__ */ new Map();
128
+ for (const r of results) {
129
+ const existing = seen.get(r.route);
130
+ if (existing) {
131
+ throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
132
+ }
133
+ seen.set(r.route, r.agentConfig.name);
134
+ }
135
+ }
136
+ __name(validateUniqueRoutes, "validateUniqueRoutes");
137
+
138
+ // src/bridge/agent-compiler.ts
139
+ function compileTools(toolboxes, toolboxInstances) {
140
+ const tools = [];
141
+ for (const tb of toolboxes) {
142
+ const instance = toolboxInstances.get(tb.class);
143
+ if (!instance) {
144
+ throw new Error(`[@theokit/agents] Toolbox ${tb.class.name} not instantiated \u2014 add to providers or pass instances.`);
145
+ }
146
+ for (const tool of tb.tools) {
147
+ const handler = instance[tool.propertyKey];
148
+ if (typeof handler !== "function") {
149
+ throw new Error(`[@theokit/agents] Toolbox ${tb.class.name}: '${String(tool.propertyKey)}' is not a function.`);
150
+ }
151
+ const name = tb.namespace ? `${tb.namespace}.${tool.config.name}` : tool.config.name;
152
+ tools.push({
153
+ name,
154
+ description: tool.config.description,
155
+ inputSchema: tool.config.input,
156
+ handler: /* @__PURE__ */ __name((input) => handler.call(instance, input), "handler")
157
+ });
158
+ }
159
+ }
160
+ return tools;
161
+ }
162
+ __name(compileTools, "compileTools");
163
+ function compileSubAgents(subAgentClasses) {
164
+ const agents = {};
165
+ for (const cls of subAgentClasses) {
166
+ const config = getAgentConfig(cls);
167
+ if (!config) continue;
168
+ agents[config.name] = {
169
+ model: config.model,
170
+ systemPrompt: config.systemPrompt
171
+ };
172
+ }
173
+ return agents;
174
+ }
175
+ __name(compileSubAgents, "compileSubAgents");
176
+ function compileAgent(walkResult, toolboxInstances = /* @__PURE__ */ new Map()) {
177
+ const tools = compileTools(walkResult.toolboxes, toolboxInstances);
178
+ const agents = compileSubAgents(walkResult.subAgentClasses);
179
+ return {
180
+ model: walkResult.agentConfig.model,
181
+ systemPrompt: walkResult.agentConfig.systemPrompt,
182
+ tools,
183
+ agents,
184
+ memory: walkResult.memory,
185
+ skills: walkResult.skills,
186
+ mcpServers: walkResult.mcpServers,
187
+ maxIterations: walkResult.mainLoop.maxIterations ?? walkResult.agentConfig.maxIterations,
188
+ timeoutMs: walkResult.mainLoop.timeoutMs ?? walkResult.agentConfig.timeoutMs,
189
+ stream: walkResult.agentConfig.stream ?? true
190
+ };
191
+ }
192
+ __name(compileAgent, "compileAgent");
193
+
194
+ // src/bridge/agent-sse-handler.ts
195
+ var encoder = new TextEncoder();
196
+ function streamAgentResponse(eventStream) {
197
+ const stream = new ReadableStream({
198
+ async start(controller) {
199
+ try {
200
+ for await (const event of eventStream) {
201
+ const data = JSON.stringify(event);
202
+ const frame = `event: ${event.type}
203
+ data: ${data}
204
+
205
+ `;
206
+ controller.enqueue(encoder.encode(frame));
207
+ }
208
+ } catch (err) {
209
+ const errorEvent = {
210
+ type: "error",
211
+ error: {
212
+ message: err instanceof Error ? err.message : "Internal agent error"
213
+ }
214
+ };
215
+ const frame = `event: error
216
+ data: ${JSON.stringify(errorEvent)}
217
+
218
+ `;
219
+ controller.enqueue(encoder.encode(frame));
220
+ } finally {
221
+ controller.close();
222
+ }
223
+ }
224
+ });
225
+ return new Response(stream, {
226
+ status: 200,
227
+ headers: {
228
+ "content-type": "text/event-stream",
229
+ "cache-control": "no-cache",
230
+ "connection": "keep-alive"
231
+ }
232
+ });
233
+ }
234
+ __name(streamAgentResponse, "streamAgentResponse");
235
+
236
+ // src/bridge/agent-stream-events.ts
237
+ function isTextDelta(e) {
238
+ return e.type === "text_delta";
239
+ }
240
+ __name(isTextDelta, "isTextDelta");
241
+ function isToolCall(e) {
242
+ return e.type === "tool_call";
243
+ }
244
+ __name(isToolCall, "isToolCall");
245
+ function isToolResult(e) {
246
+ return e.type === "tool_result";
247
+ }
248
+ __name(isToolResult, "isToolResult");
249
+ function isDone(e) {
250
+ return e.type === "done";
251
+ }
252
+ __name(isDone, "isDone");
253
+ function isError(e) {
254
+ return e.type === "error";
255
+ }
256
+ __name(isError, "isError");
257
+ function isApprovalRequired(e) {
258
+ return e.type === "approval_required";
259
+ }
260
+ __name(isApprovalRequired, "isApprovalRequired");
261
+
262
+ // src/bridge/agent-route-generator.ts
263
+ function generateAgentRoutes(ctx) {
264
+ const { walkResult, createRun, getRun } = ctx;
265
+ const basePath = walkResult.route.replace(/\/$/, "");
266
+ const routes = [];
267
+ routes.push({
268
+ method: "POST",
269
+ path: `${basePath}/chat`,
270
+ handler: /* @__PURE__ */ __name(async (request) => {
271
+ let body = null;
272
+ try {
273
+ body = await request.json();
274
+ } catch {
275
+ }
276
+ const message = body?.message;
277
+ if (typeof message !== "string" || message.length === 0) {
278
+ return new Response(JSON.stringify({
279
+ error: {
280
+ code: "BAD_REQUEST",
281
+ message: "message field required"
282
+ }
283
+ }), {
284
+ status: 400,
285
+ headers: {
286
+ "content-type": "application/json"
287
+ }
288
+ });
289
+ }
290
+ const sessionId = body?.sessionId ?? `session-${Date.now()}`;
291
+ return streamAgentResponse(createRun(message, sessionId));
292
+ }, "handler")
293
+ });
294
+ if (getRun) {
295
+ routes.push({
296
+ method: "GET",
297
+ path: `${basePath}/runs/:runId`,
298
+ handler: /* @__PURE__ */ __name(async (request) => {
299
+ const url = new URL(request.url);
300
+ const runId = url.pathname.split("/").pop() ?? "";
301
+ const run = await getRun(runId);
302
+ if (!run) {
303
+ return new Response(JSON.stringify({
304
+ error: {
305
+ code: "NOT_FOUND",
306
+ message: `Run ${runId} not found`
307
+ }
308
+ }), {
309
+ status: 404,
310
+ headers: {
311
+ "content-type": "application/json"
312
+ }
313
+ });
314
+ }
315
+ return new Response(JSON.stringify(run), {
316
+ status: 200,
317
+ headers: {
318
+ "content-type": "application/json"
319
+ }
320
+ });
321
+ }, "handler")
322
+ });
323
+ }
324
+ return routes;
325
+ }
326
+ __name(generateAgentRoutes, "generateAgentRoutes");
327
+
328
+ // src/manifest/agent-manifest.ts
329
+ function generateAgentManifest(walkResults) {
330
+ return {
331
+ version: "1.0",
332
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
333
+ agents: walkResults.map((r) => ({
334
+ name: r.agentConfig.name,
335
+ route: r.route,
336
+ model: r.agentConfig.model,
337
+ stream: r.agentConfig.stream ?? true,
338
+ mainLoop: {
339
+ method: String(r.mainLoop.propertyKey),
340
+ strategy: r.mainLoop.strategy
341
+ },
342
+ guards: r.guards.map((g) => g.name),
343
+ interceptors: r.interceptors.map((i) => i.name),
344
+ tools: r.toolboxes.flatMap((tb) => tb.tools.map((t) => ({
345
+ name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,
346
+ description: t.config.description,
347
+ risk: t.config.risk,
348
+ approval: t.approval !== void 0,
349
+ capabilities: t.capabilities,
350
+ trace: t.trace,
351
+ audit: t.audit
352
+ }))),
353
+ gateway: r.gateway ? {
354
+ platforms: r.gateway.platforms,
355
+ sessionStrategy: r.gateway.sessionStrategy ?? "per-user"
356
+ } : void 0,
357
+ subAgents: r.subAgentClasses.map((cls) => cls.name),
358
+ memory: r.memory ? {
359
+ provider: r.memory.provider ?? "built-in",
360
+ embeddings: r.memory.embeddings ?? false,
361
+ fts: r.memory.fts ?? false,
362
+ scope: r.memory.scope ?? "per-user"
363
+ } : void 0,
364
+ skills: r.skills?.include,
365
+ mcpServers: r.mcpServers ? Object.keys(r.mcpServers) : void 0
366
+ }))
367
+ };
368
+ }
369
+ __name(generateAgentManifest, "generateAgentManifest");
370
+
371
+ // src/theokit-plugin.ts
372
+ import "reflect-metadata";
373
+ function agentsPlugin(opts) {
374
+ let routes = null;
375
+ return {
376
+ name: "@theokit/agents",
377
+ register(app) {
378
+ app.addHook("onRequest", async (pluginCtx) => {
379
+ if (!routes) routes = initRoutes(opts);
380
+ const request = pluginCtx.request;
381
+ const url = new URL(request.url);
382
+ const method = request.method.toUpperCase();
383
+ const matched = matchRoute(routes, method, url.pathname);
384
+ if (!matched) return;
385
+ return matched.handler(request);
386
+ });
387
+ }
388
+ };
389
+ }
390
+ __name(agentsPlugin, "agentsPlugin");
391
+ function initRoutes(opts) {
392
+ const allRoutes = [];
393
+ const walkResults = [];
394
+ for (const AgentClass of opts.agents) {
395
+ const mixins = getMixins(AgentClass);
396
+ const toolboxes = [
397
+ ...opts.toolboxes ?? [],
398
+ ...mixins
399
+ ];
400
+ const walkResult = walkAgentMetadata(AgentClass, toolboxes);
401
+ walkResults.push(walkResult);
402
+ const compiled = compileAgent(walkResult, /* @__PURE__ */ new Map());
403
+ const createRun = opts.createRunFactory ? opts.createRunFactory(compiled, walkResult) : defaultCreateRun(compiled);
404
+ const agentRoutes = generateAgentRoutes({
405
+ walkResult,
406
+ compiledOptions: compiled,
407
+ createRun
408
+ });
409
+ allRoutes.push(...agentRoutes);
410
+ }
411
+ validateUniqueRoutes(walkResults);
412
+ return allRoutes;
413
+ }
414
+ __name(initRoutes, "initRoutes");
415
+ function defaultCreateRun(compiled) {
416
+ return async function* (_message, _sessionId) {
417
+ yield {
418
+ type: "run_started",
419
+ runId: `run-${Date.now()}`,
420
+ agentName: compiled.model ?? "unknown"
421
+ };
422
+ yield {
423
+ type: "error",
424
+ code: "SDK_NOT_WIRED",
425
+ message: "No createRunFactory provided \u2014 wire @theokit/sdk Agent.create() to enable real agent execution.",
426
+ retryable: false
427
+ };
428
+ };
429
+ }
430
+ __name(defaultCreateRun, "defaultCreateRun");
431
+ function matchRoute(routes, method, pathname) {
432
+ return routes.find((r) => {
433
+ if (r.method !== method) return false;
434
+ if (r.path.includes(":")) {
435
+ const pattern = r.path.replace(/:[^/]+/g, "[^/]+");
436
+ return new RegExp(`^${pattern}$`).test(pathname);
437
+ }
438
+ return r.path === pathname;
439
+ });
440
+ }
441
+ __name(matchRoute, "matchRoute");
442
+
443
+ export {
444
+ createAgentExecutionContext,
445
+ isAgentContext,
446
+ walkAgentMetadata,
447
+ validateUniqueRoutes,
448
+ compileTools,
449
+ compileAgent,
450
+ streamAgentResponse,
451
+ isTextDelta,
452
+ isToolCall,
453
+ isToolResult,
454
+ isDone,
455
+ isError,
456
+ isApprovalRequired,
457
+ generateAgentRoutes,
458
+ generateAgentManifest,
459
+ agentsPlugin
460
+ };
461
+ //# sourceMappingURL=chunk-YK76AQNU.js.map
@@ -0,0 +1 @@
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/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 try {\n for await (const event of eventStream) {\n const data = JSON.stringify(event)\n const frame = `event: ${event.type}\\ndata: ${data}\\n\\n`\n controller.enqueue(encoder.encode(frame))\n }\n } catch (err) {\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 controller.enqueue(encoder.encode(frame))\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 * 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,6BAAM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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","event","data","JSON","stringify","frame","type","enqueue","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","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"]}