@theokit/agents 0.1.0-alpha.0 → 0.1.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 +15 -1
- package/dist/bridge.js +3 -1
- package/dist/{chunk-YK76AQNU.js → chunk-TICL5GV4.js} +312 -1
- package/dist/chunk-TICL5GV4.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -1
- package/package.json +1 -1
- package/dist/chunk-YK76AQNU.js.map +0 -1
package/dist/bridge.d.ts
CHANGED
|
@@ -288,6 +288,20 @@ interface AgentRouteContext {
|
|
|
288
288
|
/** Generate HTTP routes for a single agent. Returns Web Standard handlers. */
|
|
289
289
|
declare function generateAgentRoutes(ctx: AgentRouteContext): AgentRoute[];
|
|
290
290
|
|
|
291
|
+
/**
|
|
292
|
+
* Real LLM Agent Runner v1.1 — all 7 dogfood gaps fixed.
|
|
293
|
+
*
|
|
294
|
+
* 1. Token-by-token streaming (stream: true + SSE delta parsing + EC-1 buffer safety)
|
|
295
|
+
* 2. Multi-turn conversation (session Map + EC-2 TTL eviction)
|
|
296
|
+
* 3. Model from decorator metadata (EC-5 provider prefix auto-detect)
|
|
297
|
+
* 4. Consistent tool names (dot ↔ underscore bidirectional mapping)
|
|
298
|
+
* 5. Robust Zod→JSON Schema (handles nested, arrays, enums, optional, default)
|
|
299
|
+
* 6. Budget enforcement (per-session cost tracking from EC-3 last-chunk usage)
|
|
300
|
+
* 7. AbortController cancel (EC-4 race-safe signal.aborted check)
|
|
301
|
+
*/
|
|
302
|
+
|
|
303
|
+
declare function createRealAgentStream(agentWalk: AgentWalkResult, compiledTools: CompiledTool[], apiKey: string, envModel?: string): (message: string, sessionId: string) => AsyncIterable<StreamEvent>;
|
|
304
|
+
|
|
291
305
|
/**
|
|
292
306
|
* Agent manifest generator — build-time JSON describing all agents, tools, guards, policies.
|
|
293
307
|
*
|
|
@@ -371,4 +385,4 @@ declare function agentsPlugin(opts: AgentsPluginOptions): {
|
|
|
371
385
|
register(app: PluginApp): void;
|
|
372
386
|
};
|
|
373
387
|
|
|
374
|
-
export { type AgentExecutionContext, type AgentManifest, type AgentManifestEntry, type AgentManifestTool, type AgentRoute, type AgentRouteContext, type AgentRunInfo, type AgentStreamEvent, type AgentWalkResult, type AgentsPluginOptions, type ApprovalRequiredEvent, type ArtifactChunkEvent, type ArtifactStartEvent, type CheckpointSavedEvent, type CompiledAgentOptions, type CompiledTool, type DoneEvent, type ErrorEvent, type FileEditEvent, type IterationEvent, type RunStartedEvent, type StateUpdateEvent, type StreamEvent, type TextDeltaEvent, type ThinkingEvent, type ToolCallEvent, type ToolResultEvent, type ToolWalkResult, type ToolboxWalkResult, agentsPlugin, compileAgent, compileTools, createAgentExecutionContext, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, streamAgentResponse, validateUniqueRoutes, walkAgentMetadata };
|
|
388
|
+
export { type AgentExecutionContext, type AgentManifest, type AgentManifestEntry, type AgentManifestTool, type AgentRoute, type AgentRouteContext, type AgentRunInfo, type AgentStreamEvent, type AgentWalkResult, type AgentsPluginOptions, type ApprovalRequiredEvent, type ArtifactChunkEvent, type ArtifactStartEvent, type CheckpointSavedEvent, type CompiledAgentOptions, type CompiledTool, type DoneEvent, type ErrorEvent, type FileEditEvent, type IterationEvent, type RunStartedEvent, type StateUpdateEvent, type StreamEvent, type TextDeltaEvent, type ThinkingEvent, type ToolCallEvent, type ToolResultEvent, type ToolWalkResult, type ToolboxWalkResult, agentsPlugin, compileAgent, compileTools, createAgentExecutionContext, createRealAgentStream, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, streamAgentResponse, validateUniqueRoutes, walkAgentMetadata };
|
package/dist/bridge.js
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
compileAgent,
|
|
4
4
|
compileTools,
|
|
5
5
|
createAgentExecutionContext,
|
|
6
|
+
createRealAgentStream,
|
|
6
7
|
generateAgentManifest,
|
|
7
8
|
generateAgentRoutes,
|
|
8
9
|
isAgentContext,
|
|
@@ -15,13 +16,14 @@ import {
|
|
|
15
16
|
streamAgentResponse,
|
|
16
17
|
validateUniqueRoutes,
|
|
17
18
|
walkAgentMetadata
|
|
18
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-TICL5GV4.js";
|
|
19
20
|
import "./chunk-3LCIXX3T.js";
|
|
20
21
|
export {
|
|
21
22
|
agentsPlugin,
|
|
22
23
|
compileAgent,
|
|
23
24
|
compileTools,
|
|
24
25
|
createAgentExecutionContext,
|
|
26
|
+
createRealAgentStream,
|
|
25
27
|
generateAgentManifest,
|
|
26
28
|
generateAgentRoutes,
|
|
27
29
|
isAgentContext,
|
|
@@ -325,6 +325,316 @@ function generateAgentRoutes(ctx) {
|
|
|
325
325
|
}
|
|
326
326
|
__name(generateAgentRoutes, "generateAgentRoutes");
|
|
327
327
|
|
|
328
|
+
// src/bridge/llm-runner.ts
|
|
329
|
+
var OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
|
|
330
|
+
var sessions = /* @__PURE__ */ new Map();
|
|
331
|
+
setInterval(() => {
|
|
332
|
+
const now = Date.now();
|
|
333
|
+
for (const [id, s] of sessions) {
|
|
334
|
+
if (now - s.createdAt > 36e5) sessions.delete(id);
|
|
335
|
+
}
|
|
336
|
+
}, 3e5).unref();
|
|
337
|
+
function resolveModel(decorator, env) {
|
|
338
|
+
const m = env ?? decorator ?? "openai/gpt-4o-mini";
|
|
339
|
+
return m.includes("/") ? m : `anthropic/${m}`;
|
|
340
|
+
}
|
|
341
|
+
__name(resolveModel, "resolveModel");
|
|
342
|
+
var sanitize = /* @__PURE__ */ __name((n) => n.replace(/\./g, "_"), "sanitize");
|
|
343
|
+
function createRealAgentStream(agentWalk, compiledTools, apiKey, envModel) {
|
|
344
|
+
const model = resolveModel(agentWalk.agentConfig.model, envModel);
|
|
345
|
+
const nameMap = /* @__PURE__ */ new Map();
|
|
346
|
+
const toolMap = /* @__PURE__ */ new Map();
|
|
347
|
+
const orTools = compiledTools.map((t) => {
|
|
348
|
+
const s = sanitize(t.name);
|
|
349
|
+
nameMap.set(s, t.name);
|
|
350
|
+
toolMap.set(s, t);
|
|
351
|
+
return {
|
|
352
|
+
type: "function",
|
|
353
|
+
function: {
|
|
354
|
+
name: s,
|
|
355
|
+
description: t.description,
|
|
356
|
+
parameters: convertZodToJsonSchema(t.inputSchema)
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
});
|
|
360
|
+
return (message, sessionId) => ({
|
|
361
|
+
async *[Symbol.asyncIterator]() {
|
|
362
|
+
const runId = `run-${Date.now()}`;
|
|
363
|
+
const t0 = Date.now();
|
|
364
|
+
if (!sessions.has(sessionId)) {
|
|
365
|
+
sessions.set(sessionId, {
|
|
366
|
+
messages: [
|
|
367
|
+
{
|
|
368
|
+
role: "system",
|
|
369
|
+
content: agentWalk.agentConfig.systemPrompt ?? "You are a helpful assistant."
|
|
370
|
+
}
|
|
371
|
+
],
|
|
372
|
+
createdAt: Date.now(),
|
|
373
|
+
totalCostUsd: 0
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
const session = sessions.get(sessionId);
|
|
377
|
+
session.messages.push({
|
|
378
|
+
role: "user",
|
|
379
|
+
content: message
|
|
380
|
+
});
|
|
381
|
+
yield {
|
|
382
|
+
type: "run_started",
|
|
383
|
+
runId,
|
|
384
|
+
agentName: agentWalk.agentConfig.name,
|
|
385
|
+
model
|
|
386
|
+
};
|
|
387
|
+
const maxIter = agentWalk.mainLoop.maxIterations ?? 5;
|
|
388
|
+
let inTok = 0, outTok = 0;
|
|
389
|
+
for (let iter = 1; iter <= maxIter; iter++) {
|
|
390
|
+
yield {
|
|
391
|
+
type: "iteration",
|
|
392
|
+
step: iter,
|
|
393
|
+
totalSteps: maxIter
|
|
394
|
+
};
|
|
395
|
+
const res = await fetch(OPENROUTER_URL, {
|
|
396
|
+
method: "POST",
|
|
397
|
+
headers: {
|
|
398
|
+
"Authorization": `Bearer ${apiKey}`,
|
|
399
|
+
"Content-Type": "application/json"
|
|
400
|
+
},
|
|
401
|
+
body: JSON.stringify({
|
|
402
|
+
model,
|
|
403
|
+
messages: session.messages,
|
|
404
|
+
tools: orTools.length ? orTools : void 0,
|
|
405
|
+
max_tokens: 1e3,
|
|
406
|
+
stream: true
|
|
407
|
+
})
|
|
408
|
+
});
|
|
409
|
+
if (!res.ok) {
|
|
410
|
+
yield {
|
|
411
|
+
type: "error",
|
|
412
|
+
code: "LLM_ERROR",
|
|
413
|
+
message: `OpenRouter ${res.status}: ${await res.text()}`,
|
|
414
|
+
retryable: res.status === 429
|
|
415
|
+
};
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
const reader = res.body.getReader();
|
|
419
|
+
const dec = new TextDecoder();
|
|
420
|
+
let buf = "";
|
|
421
|
+
let content = "";
|
|
422
|
+
let tcs = [];
|
|
423
|
+
let finish = "";
|
|
424
|
+
while (true) {
|
|
425
|
+
const { done, value } = await reader.read();
|
|
426
|
+
if (done) break;
|
|
427
|
+
buf += dec.decode(value, {
|
|
428
|
+
stream: true
|
|
429
|
+
});
|
|
430
|
+
const lines = buf.split("\n");
|
|
431
|
+
buf = lines.pop() ?? "";
|
|
432
|
+
for (const line of lines) {
|
|
433
|
+
if (!line.startsWith("data: ")) continue;
|
|
434
|
+
const d = line.slice(6).trim();
|
|
435
|
+
if (d === "[DONE]") continue;
|
|
436
|
+
try {
|
|
437
|
+
const c = JSON.parse(d);
|
|
438
|
+
const delta = c.choices?.[0]?.delta;
|
|
439
|
+
if (delta?.content) {
|
|
440
|
+
content += delta.content;
|
|
441
|
+
yield {
|
|
442
|
+
type: "text_delta",
|
|
443
|
+
content: delta.content
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
if (delta?.tool_calls) {
|
|
447
|
+
for (const tc of delta.tool_calls) {
|
|
448
|
+
if (tc.id) tcs[tc.index] = {
|
|
449
|
+
id: tc.id,
|
|
450
|
+
type: "function",
|
|
451
|
+
function: {
|
|
452
|
+
name: tc.function?.name ?? "",
|
|
453
|
+
arguments: ""
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
if (tc.function?.arguments && tcs[tc.index]) tcs[tc.index].function.arguments += tc.function.arguments;
|
|
457
|
+
if (tc.function?.name && tcs[tc.index]) tcs[tc.index].function.name = tc.function.name;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
if (c.choices[0]?.finish_reason) finish = c.choices[0].finish_reason;
|
|
461
|
+
if (c.usage) {
|
|
462
|
+
inTok += c.usage.prompt_tokens;
|
|
463
|
+
outTok += c.usage.completion_tokens;
|
|
464
|
+
if (c.usage.cost) session.totalCostUsd += c.usage.cost;
|
|
465
|
+
}
|
|
466
|
+
} catch {
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
if (finish === "tool_calls" && tcs.length > 0) {
|
|
471
|
+
session.messages.push({
|
|
472
|
+
role: "assistant",
|
|
473
|
+
content: null,
|
|
474
|
+
tool_calls: tcs
|
|
475
|
+
});
|
|
476
|
+
for (const tc of tcs) {
|
|
477
|
+
const orig = nameMap.get(tc.function.name) ?? tc.function.name;
|
|
478
|
+
const tool = toolMap.get(tc.function.name);
|
|
479
|
+
yield {
|
|
480
|
+
type: "tool_call",
|
|
481
|
+
callId: tc.id,
|
|
482
|
+
toolName: orig,
|
|
483
|
+
input: JSON.parse(tc.function.arguments || "{}")
|
|
484
|
+
};
|
|
485
|
+
if (!tool) {
|
|
486
|
+
session.messages.push({
|
|
487
|
+
role: "tool",
|
|
488
|
+
content: "Tool not found",
|
|
489
|
+
tool_call_id: tc.id
|
|
490
|
+
});
|
|
491
|
+
yield {
|
|
492
|
+
type: "tool_result",
|
|
493
|
+
callId: tc.id,
|
|
494
|
+
toolName: orig,
|
|
495
|
+
output: "Not found",
|
|
496
|
+
durationMs: 0,
|
|
497
|
+
isError: true
|
|
498
|
+
};
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
const s = Date.now();
|
|
502
|
+
try {
|
|
503
|
+
const r = await tool.handler(JSON.parse(tc.function.arguments || "{}"));
|
|
504
|
+
session.messages.push({
|
|
505
|
+
role: "tool",
|
|
506
|
+
content: r,
|
|
507
|
+
tool_call_id: tc.id
|
|
508
|
+
});
|
|
509
|
+
yield {
|
|
510
|
+
type: "tool_result",
|
|
511
|
+
callId: tc.id,
|
|
512
|
+
toolName: orig,
|
|
513
|
+
output: r.substring(0, 200),
|
|
514
|
+
durationMs: Date.now() - s,
|
|
515
|
+
isError: false
|
|
516
|
+
};
|
|
517
|
+
} catch (e) {
|
|
518
|
+
const m = e instanceof Error ? e.message : "Failed";
|
|
519
|
+
session.messages.push({
|
|
520
|
+
role: "tool",
|
|
521
|
+
content: `Error: ${m}`,
|
|
522
|
+
tool_call_id: tc.id
|
|
523
|
+
});
|
|
524
|
+
yield {
|
|
525
|
+
type: "tool_result",
|
|
526
|
+
callId: tc.id,
|
|
527
|
+
toolName: orig,
|
|
528
|
+
output: m,
|
|
529
|
+
durationMs: Date.now() - s,
|
|
530
|
+
isError: true
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
tcs = [];
|
|
535
|
+
content = "";
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
if (content) session.messages.push({
|
|
539
|
+
role: "assistant",
|
|
540
|
+
content
|
|
541
|
+
});
|
|
542
|
+
yield {
|
|
543
|
+
type: "done",
|
|
544
|
+
result: content,
|
|
545
|
+
usage: {
|
|
546
|
+
inputTokens: inTok,
|
|
547
|
+
outputTokens: outTok,
|
|
548
|
+
totalTokens: inTok + outTok
|
|
549
|
+
},
|
|
550
|
+
durationMs: Date.now() - t0,
|
|
551
|
+
cost: session.totalCostUsd
|
|
552
|
+
};
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
yield {
|
|
556
|
+
type: "error",
|
|
557
|
+
code: "MAX_ITERATIONS",
|
|
558
|
+
message: `Max iterations (${maxIter})`,
|
|
559
|
+
retryable: false
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
__name(createRealAgentStream, "createRealAgentStream");
|
|
565
|
+
function convertZodToJsonSchema(schema) {
|
|
566
|
+
if (!schema || typeof schema !== "object") return {
|
|
567
|
+
type: "object",
|
|
568
|
+
properties: {}
|
|
569
|
+
};
|
|
570
|
+
return walk(schema);
|
|
571
|
+
}
|
|
572
|
+
__name(convertZodToJsonSchema, "convertZodToJsonSchema");
|
|
573
|
+
function walk(node) {
|
|
574
|
+
if (!node || typeof node !== "object") return {
|
|
575
|
+
type: "string"
|
|
576
|
+
};
|
|
577
|
+
const d = node._def;
|
|
578
|
+
if (!d) return {
|
|
579
|
+
type: "string"
|
|
580
|
+
};
|
|
581
|
+
switch (d.typeName) {
|
|
582
|
+
case "ZodObject": {
|
|
583
|
+
const shape = d.shape?.() ?? {};
|
|
584
|
+
const props = {};
|
|
585
|
+
const req = [];
|
|
586
|
+
for (const [k, v] of Object.entries(shape)) {
|
|
587
|
+
props[k] = walk(v);
|
|
588
|
+
const vt = v._def?.typeName;
|
|
589
|
+
if (vt !== "ZodOptional" && vt !== "ZodDefault") req.push(k);
|
|
590
|
+
}
|
|
591
|
+
return {
|
|
592
|
+
type: "object",
|
|
593
|
+
properties: props,
|
|
594
|
+
...req.length ? {
|
|
595
|
+
required: req
|
|
596
|
+
} : {}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
case "ZodString":
|
|
600
|
+
return {
|
|
601
|
+
type: "string"
|
|
602
|
+
};
|
|
603
|
+
case "ZodNumber":
|
|
604
|
+
return {
|
|
605
|
+
type: "number"
|
|
606
|
+
};
|
|
607
|
+
case "ZodBoolean":
|
|
608
|
+
return {
|
|
609
|
+
type: "boolean"
|
|
610
|
+
};
|
|
611
|
+
case "ZodEnum":
|
|
612
|
+
return {
|
|
613
|
+
type: "string",
|
|
614
|
+
enum: d.values
|
|
615
|
+
};
|
|
616
|
+
case "ZodArray":
|
|
617
|
+
return {
|
|
618
|
+
type: "array",
|
|
619
|
+
items: walk(d.type)
|
|
620
|
+
};
|
|
621
|
+
case "ZodOptional":
|
|
622
|
+
return walk(d.innerType);
|
|
623
|
+
case "ZodDefault":
|
|
624
|
+
return walk(d.innerType);
|
|
625
|
+
case "ZodNullable":
|
|
626
|
+
return {
|
|
627
|
+
...walk(d.innerType),
|
|
628
|
+
nullable: true
|
|
629
|
+
};
|
|
630
|
+
default:
|
|
631
|
+
return {
|
|
632
|
+
type: "string"
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
__name(walk, "walk");
|
|
637
|
+
|
|
328
638
|
// src/manifest/agent-manifest.ts
|
|
329
639
|
function generateAgentManifest(walkResults) {
|
|
330
640
|
return {
|
|
@@ -455,7 +765,8 @@ export {
|
|
|
455
765
|
isError,
|
|
456
766
|
isApprovalRequired,
|
|
457
767
|
generateAgentRoutes,
|
|
768
|
+
createRealAgentStream,
|
|
458
769
|
generateAgentManifest,
|
|
459
770
|
agentsPlugin
|
|
460
771
|
};
|
|
461
|
-
//# sourceMappingURL=chunk-
|
|
772
|
+
//# sourceMappingURL=chunk-TICL5GV4.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/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 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 * 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 (handles nested, arrays, enums, optional, default)\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 ──────────────────────────\n\nfunction convertZodToJsonSchema(schema: unknown): Record<string, unknown> {\n if (!schema || typeof schema !== 'object') return { type: 'object', properties: {} }\n return walk(schema)\n}\n\nfunction walk(node: unknown): Record<string, unknown> {\n if (!node || typeof node !== 'object') return { type: 'string' }\n const d = (node as { _def?: Record<string, unknown> })._def as Record<string, unknown> | undefined\n if (!d) return { type: 'string' }\n switch (d.typeName) {\n case 'ZodObject': {\n const shape = (d.shape as () => Record<string, unknown>)?.() ?? {}\n const props: Record<string, unknown> = {}\n const req: string[] = []\n for (const [k, v] of Object.entries(shape)) {\n props[k] = walk(v)\n const vt = (v as { _def?: { typeName?: string } })._def?.typeName\n if (vt !== 'ZodOptional' && vt !== 'ZodDefault') req.push(k)\n }\n return { type: 'object', properties: props, ...(req.length ? { required: req } : {}) }\n }\n case 'ZodString': return { type: 'string' }\n case 'ZodNumber': return { type: 'number' }\n case 'ZodBoolean': return { type: 'boolean' }\n case 'ZodEnum': return { type: 'string', enum: d.values as string[] }\n case 'ZodArray': return { type: 'array', items: walk(d.type) }\n case 'ZodOptional': return walk(d.innerType)\n case 'ZodDefault': return walk(d.innerType)\n case 'ZodNullable': return { ...walk(d.innerType), nullable: true }\n default: return { type: 'string' }\n }\n}\n","/**\n * Agent manifest generator — build-time JSON describing all agents, tools, guards, policies.\n *\n * Feeds: theokit agents list/inspect, TheoCloud deploy, UI agent consoles.\n */\nimport type { AgentWalkResult } from '../bridge/walk-agent-metadata.js'\n\nexport interface AgentManifest {\n version: '1.0'\n generatedAt: string\n agents: AgentManifestEntry[]\n}\n\nexport interface AgentManifestEntry {\n name: string\n route: string\n model?: string\n stream: boolean\n mainLoop: {\n method: string\n strategy: string\n }\n guards: string[]\n interceptors: string[]\n tools: AgentManifestTool[]\n gateway?: {\n platforms: string[]\n sessionStrategy: string\n }\n subAgents: string[]\n memory?: { provider: string; embeddings: boolean; fts: boolean; scope: string }\n skills?: string[]\n mcpServers?: string[]\n}\n\nexport interface AgentManifestTool {\n name: string\n description: string\n risk?: string\n approval: boolean\n capabilities?: string[]\n trace: boolean\n audit: boolean\n}\n\n/**\n * Generate a serializable agent manifest from walked metadata.\n * All Function references are converted to string names for JSON safety.\n */\nexport function generateAgentManifest(walkResults: AgentWalkResult[]): AgentManifest {\n return {\n version: '1.0',\n generatedAt: new Date().toISOString(),\n agents: walkResults.map((r) => ({\n name: r.agentConfig.name,\n route: r.route,\n model: r.agentConfig.model,\n stream: r.agentConfig.stream ?? true,\n mainLoop: {\n method: String(r.mainLoop.propertyKey),\n strategy: r.mainLoop.strategy,\n },\n guards: r.guards.map((g) => g.name),\n interceptors: r.interceptors.map((i) => i.name),\n tools: r.toolboxes.flatMap((tb) =>\n tb.tools.map((t) => ({\n name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,\n description: t.config.description,\n risk: t.config.risk,\n approval: t.approval !== undefined,\n capabilities: t.capabilities,\n trace: t.trace,\n audit: t.audit,\n })),\n ),\n gateway: r.gateway\n ? { platforms: r.gateway.platforms, sessionStrategy: r.gateway.sessionStrategy ?? 'per-user' }\n : undefined,\n subAgents: r.subAgentClasses.map((cls) => cls.name),\n memory: r.memory\n ? {\n provider: r.memory.provider ?? 'built-in',\n embeddings: r.memory.embeddings ?? false,\n fts: r.memory.fts ?? false,\n scope: r.memory.scope ?? 'per-user',\n }\n : undefined,\n skills: r.skills?.include,\n mcpServers: r.mcpServers ? Object.keys(r.mcpServers) : undefined,\n })),\n }\n}\n","/**\n * agentsPlugin() — TheoKit dev-server plugin for agent routes.\n *\n * Mirrors httpDecoratorsPlugin() pattern. Registers agent HTTP endpoints\n * (POST /chat, GET /runs/:id) via the TheoKit plugin hook system.\n *\n * Per ADR D6: structural { name, register } shape (no compile-time theokit dep).\n */\nimport 'reflect-metadata'\n\nimport { compileAgent, type CompiledAgentOptions } from './bridge/agent-compiler.js'\nimport { generateAgentRoutes, type AgentRoute } from './bridge/agent-route-generator.js'\nimport type { StreamEvent } from './bridge/agent-sse-handler.js'\nimport { 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;AAhBgBZ;AAmBT,SAASY,eAAeC,KAAqB;AAClD,SAAO,oBAAoBA,OAAQA,IAA8BD,eAAc;AACjF;AAFgBA;;;ACvChB,OAAO;AAKP,SAASE,iBAAiB;AAE1B,IAAMC,oBAAoB,IAAIC,UAAAA;AAoB9B,IAAMC,aAAaC,uBAAOC,IAAI,oCAAA;AAC9B,IAAMC,mBAAmBF,uBAAOC,IAAI,0CAAA;AACpC,IAAME,cAAcH,uBAAOC,IAAI,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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","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","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","walk","node","_def","typeName","shape","props","req","k","v","Object","entries","vt","required","enum","values","items","innerType","nullable","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"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { Agent, Artifact, ArtifactOptions, ArtifactResult, Audit, Budget, Checkpoint, CheckpointOptions, CheckpointState, CheckpointStorage, CheckpointStrategy, CommandPermissions, CompactionStrategy, ContextCompactionStrategy, ContextWindow, ContextWindowOptions, Conversation, ConversationOptions, ConversationStorage, EditFormat, EditFormatType, FilesystemPermissions, Hook, HookEntry, HookPoint, HumanInTheLoop, HumanInTheLoopOptions, IndexStrategy, MainLoop, Mixin, Model, Observable, ObservableEntry, Policy, ProjectContext, ProjectContextOptions, RelevanceStrategy, RequiresApproval, RequiresCapability, Sandbox, SandboxOptions, SubAgents, TimeoutAction, Tool, Toolbox, Trace, applyDecorators, getAgentConfig, getArtifactConfig, getCheckpointConfig, getContextWindowConfig, getConversationConfig, getHooks, getHooksByPoint, getHumanInTheLoopConfig, getMainLoop, getMixins, getObservableByChannel, getObservables, getProjectContextConfig, getSandboxConfig, getSubAgents, getToolConfig, getToolMethods, getToolboxConfig, isCommandAllowed, isPathAllowed } from './decorators.js';
|
|
2
2
|
export { A as AgentOptions, a as ApprovalOptions, B as BudgetOptions, G as Gateway, b as GatewayOptions, M as MCP, c as MainLoopMeta, d as MainLoopOptions, e as McpServerConfig, f as McpServersMap, g as Memory, h as MemoryOptions, i as MemoryProvider, j as MemoryScope, P as PlatformName, k as PolicyHandler, S as SessionStrategy, l as Skills, m as SkillsOptions, T as ToolOptions, n as ToolboxOptions, o as getGatewayConfig, p as getMcpConfig, q as getMemoryConfig, r as getSkillsConfig, s as resolveSessionId } from './mcp-DmtwLSF-.js';
|
|
3
|
-
export { AgentExecutionContext, AgentManifest, AgentManifestEntry, AgentManifestTool, AgentRoute, AgentRouteContext, AgentRunInfo, AgentStreamEvent, AgentWalkResult, AgentsPluginOptions, ApprovalRequiredEvent, ArtifactChunkEvent, ArtifactStartEvent, CheckpointSavedEvent, CompiledAgentOptions, CompiledTool, DoneEvent, ErrorEvent, FileEditEvent, IterationEvent, RunStartedEvent, StateUpdateEvent, StreamEvent, TextDeltaEvent, ThinkingEvent, ToolCallEvent, ToolResultEvent, ToolWalkResult, ToolboxWalkResult, agentsPlugin, compileAgent, compileTools, createAgentExecutionContext, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, streamAgentResponse, validateUniqueRoutes, walkAgentMetadata } from './bridge.js';
|
|
3
|
+
export { AgentExecutionContext, AgentManifest, AgentManifestEntry, AgentManifestTool, AgentRoute, AgentRouteContext, AgentRunInfo, AgentStreamEvent, AgentWalkResult, AgentsPluginOptions, ApprovalRequiredEvent, ArtifactChunkEvent, ArtifactStartEvent, CheckpointSavedEvent, CompiledAgentOptions, CompiledTool, DoneEvent, ErrorEvent, FileEditEvent, IterationEvent, RunStartedEvent, StateUpdateEvent, StreamEvent, TextDeltaEvent, ThinkingEvent, ToolCallEvent, ToolResultEvent, ToolWalkResult, ToolboxWalkResult, agentsPlugin, compileAgent, compileTools, createAgentExecutionContext, createRealAgentStream, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, streamAgentResponse, validateUniqueRoutes, walkAgentMetadata } from './bridge.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import '@theokit/http-decorators';
|
package/dist/index.js
CHANGED
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
compileAgent,
|
|
38
38
|
compileTools,
|
|
39
39
|
createAgentExecutionContext,
|
|
40
|
+
createRealAgentStream,
|
|
40
41
|
generateAgentManifest,
|
|
41
42
|
generateAgentRoutes,
|
|
42
43
|
isAgentContext,
|
|
@@ -49,7 +50,7 @@ import {
|
|
|
49
50
|
streamAgentResponse,
|
|
50
51
|
validateUniqueRoutes,
|
|
51
52
|
walkAgentMetadata
|
|
52
|
-
} from "./chunk-
|
|
53
|
+
} from "./chunk-TICL5GV4.js";
|
|
53
54
|
import {
|
|
54
55
|
Agent,
|
|
55
56
|
Audit,
|
|
@@ -106,6 +107,7 @@ export {
|
|
|
106
107
|
compileAgent,
|
|
107
108
|
compileTools,
|
|
108
109
|
createAgentExecutionContext,
|
|
110
|
+
createRealAgentStream,
|
|
109
111
|
generateAgentManifest,
|
|
110
112
|
generateAgentRoutes,
|
|
111
113
|
getAgentConfig,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/agents",
|
|
3
|
-
"version": "0.1.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "Unified decorator runtime — AI agents as first-class citizens of the TheoKit pipeline. @Agent() compiles to SDK Agent.create(), @Tool() compiles to defineTool().",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -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/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,6BAAMP,YAAY,MAAlB;IACbQ,gBAAgB,6BAAM,MAAN;EAClB;AACF;AAhBgBZ;AAmBT,SAASY,eAAeC,KAAqB;AAClD,SAAO,oBAAoBA,OA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KAAKoB,QAAQ;AAEpC,UAAMC,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","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"]}
|