@theokit/agents 9.2.1 → 9.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1110 @@
1
+ import {
2
+ createHitlPlugin,
3
+ createSdkAgentStream
4
+ } from "./chunk-W6TABP2S.js";
5
+ import {
6
+ compileAgentDefinition,
7
+ defineAgent,
8
+ isAgentDefinition
9
+ } from "./chunk-4VHCH6IZ.js";
10
+ import {
11
+ __name
12
+ } from "./chunk-Z4QWC7IK.js";
13
+
14
+ // src/errors.ts
15
+ import { ConfigurationError } from "@theokit/sdk/errors";
16
+
17
+ // src/bridge/compile-context-window.ts
18
+ var STRATEGY_KNOBS = [
19
+ "compactionStrategy",
20
+ "preserveLastN",
21
+ "preserveToolResults",
22
+ "preserveSystemPrompt"
23
+ ];
24
+ function compileContextWindow(options) {
25
+ const context = {};
26
+ if (typeof options.maxTokens === "number") {
27
+ context.maxTokens = options.maxTokens;
28
+ }
29
+ const opts = options;
30
+ const metadataOnlyKnobs = STRATEGY_KNOBS.filter((knob) => opts[knob] !== void 0);
31
+ return {
32
+ context,
33
+ metadataOnlyKnobs
34
+ };
35
+ }
36
+ __name(compileContextWindow, "compileContextWindow");
37
+
38
+ // src/bridge/compile-skills.ts
39
+ function compileSkills(options) {
40
+ if (options.autoDiscover) {
41
+ return {
42
+ autoInject: true
43
+ };
44
+ }
45
+ return {
46
+ enabled: options.include,
47
+ autoInject: true
48
+ };
49
+ }
50
+ __name(compileSkills, "compileSkills");
51
+
52
+ // src/bridge/agent-compiler.ts
53
+ var SDK_TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
54
+ var SDK_TOOL_NAME_MAX_LENGTH = 64;
55
+ var SDK_TOOL_NAME_CHARSET = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
56
+ var SDK_RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set([
57
+ "shell",
58
+ "memory_search",
59
+ "memory_get"
60
+ ]);
61
+ var SDK_RESERVED_TOOL_PREFIX = "mcp_";
62
+ function toolRuntimeName(namespace, toolName) {
63
+ if (toolName.trim().length === 0) {
64
+ const where = namespace ? ` in namespace "${namespace}"` : "";
65
+ throw new ConfigurationError(`tool: empty name${where} \u2014 declare a non-empty name for the tool`);
66
+ }
67
+ const name = namespace ? `${namespace}_${toolName}` : toolName;
68
+ if (!SDK_TOOL_NAME.test(name)) {
69
+ if (SDK_TOOL_NAME_CHARSET.test(name)) {
70
+ throw new ConfigurationError(`tool: name "${name}" has length ${name.length} \u2014 the composition namespace + "_" + tool exceeds the maximum of ${SDK_TOOL_NAME_MAX_LENGTH} the SDK accepts`);
71
+ }
72
+ throw new ConfigurationError(`tool: invalid name "${name}" \u2014 it must match ${String(SDK_TOOL_NAME)} (the SDK rejects the rest; check the namespace and the tool name)`);
73
+ }
74
+ if (SDK_RESERVED_TOOL_NAMES.has(name) || name.startsWith(SDK_RESERVED_TOOL_PREFIX)) {
75
+ throw new ConfigurationError(`tool: reserved name "${name}" \u2014 the SDK reserves ${[
76
+ ...SDK_RESERVED_TOOL_NAMES
77
+ ].join(", ")} and the prefix "${SDK_RESERVED_TOOL_PREFIX}"`);
78
+ }
79
+ return name;
80
+ }
81
+ __name(toolRuntimeName, "toolRuntimeName");
82
+ function compileHitlGates(toolboxes) {
83
+ const gates = /* @__PURE__ */ new Map();
84
+ for (const tb of toolboxes) {
85
+ for (const tool of tb.tools) {
86
+ if (tool.hitl) {
87
+ gates.set(toolRuntimeName(tb.namespace, tool.config.name), tool.hitl);
88
+ }
89
+ }
90
+ }
91
+ return gates;
92
+ }
93
+ __name(compileHitlGates, "compileHitlGates");
94
+ function compileTools(toolboxes, toolboxInstances) {
95
+ const tools = [];
96
+ for (const tb of toolboxes) {
97
+ const instance = toolboxInstances.get(tb.class);
98
+ if (!instance) {
99
+ throw new ConfigurationError(`toolbox: ${tb.class.name} was not instantiated \u2014 pass the instance in \`toolboxInstances\``);
100
+ }
101
+ for (const tool of tb.tools) {
102
+ const handler = instance[tool.propertyKey];
103
+ if (typeof handler !== "function") {
104
+ throw new ConfigurationError(`toolbox: ${tb.class.name}.${String(tool.propertyKey)} is not a method (tool "${tool.config.name}")`);
105
+ }
106
+ const name = toolRuntimeName(tb.namespace, tool.config.name);
107
+ tools.push({
108
+ name,
109
+ description: tool.config.description,
110
+ inputSchema: tool.config.input,
111
+ handler: /* @__PURE__ */ __name((input) => handler.call(instance, input), "handler")
112
+ });
113
+ }
114
+ }
115
+ return tools;
116
+ }
117
+ __name(compileTools, "compileTools");
118
+
119
+ // src/bridge/agent-execution-context.ts
120
+ function createAgentExecutionContext(base, agent, run, toolCall) {
121
+ return {
122
+ getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
123
+ getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
124
+ getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
125
+ getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
126
+ getAgent: /* @__PURE__ */ __name(() => agent, "getAgent"),
127
+ getRun: /* @__PURE__ */ __name(() => run, "getRun"),
128
+ getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
129
+ isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
130
+ };
131
+ }
132
+ __name(createAgentExecutionContext, "createAgentExecutionContext");
133
+ function isAgentContext(ctx) {
134
+ return "isAgentContext" in ctx && ctx.isAgentContext();
135
+ }
136
+ __name(isAgentContext, "isAgentContext");
137
+
138
+ // src/bridge/agent-sse-handler.ts
139
+ var encoder = new TextEncoder();
140
+ function streamAgentResponse(eventStream) {
141
+ const stream = new ReadableStream({
142
+ async start(controller) {
143
+ let closed = false;
144
+ const safeEnqueue = /* @__PURE__ */ __name((chunk) => {
145
+ if (closed) return;
146
+ try {
147
+ controller.enqueue(chunk);
148
+ } catch {
149
+ closed = true;
150
+ }
151
+ }, "safeEnqueue");
152
+ try {
153
+ for await (const event of eventStream) {
154
+ if (closed) break;
155
+ const data = JSON.stringify(event);
156
+ const frame = `event: ${event.type}
157
+ data: ${data}
158
+
159
+ `;
160
+ safeEnqueue(encoder.encode(frame));
161
+ }
162
+ } catch (err) {
163
+ if (!closed) {
164
+ const errorEvent = {
165
+ type: "error",
166
+ error: {
167
+ message: err instanceof Error ? err.message : "Internal agent error"
168
+ }
169
+ };
170
+ const frame = `event: error
171
+ data: ${JSON.stringify(errorEvent)}
172
+
173
+ `;
174
+ safeEnqueue(encoder.encode(frame));
175
+ }
176
+ } finally {
177
+ controller.close();
178
+ }
179
+ }
180
+ });
181
+ return new Response(stream, {
182
+ status: 200,
183
+ headers: {
184
+ "content-type": "text/event-stream",
185
+ "cache-control": "no-cache",
186
+ connection: "keep-alive"
187
+ }
188
+ });
189
+ }
190
+ __name(streamAgentResponse, "streamAgentResponse");
191
+
192
+ // src/bridge/agent-stream-events.ts
193
+ function isTextDelta(e) {
194
+ return e.type === "text_delta";
195
+ }
196
+ __name(isTextDelta, "isTextDelta");
197
+ function isToolCall(e) {
198
+ return e.type === "tool_call";
199
+ }
200
+ __name(isToolCall, "isToolCall");
201
+ function isPartialToolCall(e) {
202
+ return e.type === "partial_tool_call";
203
+ }
204
+ __name(isPartialToolCall, "isPartialToolCall");
205
+ function isToolResult(e) {
206
+ return e.type === "tool_result";
207
+ }
208
+ __name(isToolResult, "isToolResult");
209
+ function isDone(e) {
210
+ return e.type === "done";
211
+ }
212
+ __name(isDone, "isDone");
213
+ function isError(e) {
214
+ return e.type === "error";
215
+ }
216
+ __name(isError, "isError");
217
+ function isApprovalRequired(e) {
218
+ return e.type === "approval_required";
219
+ }
220
+ __name(isApprovalRequired, "isApprovalRequired");
221
+
222
+ // src/bridge/agent-route-generator.ts
223
+ function generateAgentRoutes(ctx) {
224
+ const { walkResult, createRun, getRun } = ctx;
225
+ const basePath = walkResult.route.replace(/\/$/, "");
226
+ const routes = [];
227
+ routes.push({
228
+ method: "POST",
229
+ path: `${basePath}/chat`,
230
+ handler: /* @__PURE__ */ __name(async (request) => {
231
+ let body = null;
232
+ try {
233
+ body = await request.json();
234
+ } catch {
235
+ }
236
+ const message = body?.message;
237
+ if (typeof message !== "string" || message.length === 0) {
238
+ return new Response(JSON.stringify({
239
+ error: {
240
+ code: "BAD_REQUEST",
241
+ message: "message field required"
242
+ }
243
+ }), {
244
+ status: 400,
245
+ headers: {
246
+ "content-type": "application/json"
247
+ }
248
+ });
249
+ }
250
+ const rawSessionId = body?.sessionId;
251
+ const sessionId = typeof rawSessionId === "string" ? rawSessionId : `session-${Date.now()}`;
252
+ return streamAgentResponse(createRun(message, sessionId));
253
+ }, "handler")
254
+ });
255
+ if (getRun) {
256
+ routes.push({
257
+ method: "GET",
258
+ path: `${basePath}/runs/:runId`,
259
+ handler: /* @__PURE__ */ __name(async (request) => {
260
+ const url = new URL(request.url);
261
+ const runId = url.pathname.split("/").pop() ?? "";
262
+ const run = await getRun(runId);
263
+ if (!run) {
264
+ return new Response(JSON.stringify({
265
+ error: {
266
+ code: "NOT_FOUND",
267
+ message: `Run ${runId} not found`
268
+ }
269
+ }), {
270
+ status: 404,
271
+ headers: {
272
+ "content-type": "application/json"
273
+ }
274
+ });
275
+ }
276
+ return new Response(JSON.stringify(run), {
277
+ status: 200,
278
+ headers: {
279
+ "content-type": "application/json"
280
+ }
281
+ });
282
+ }, "handler")
283
+ });
284
+ }
285
+ return routes;
286
+ }
287
+ __name(generateAgentRoutes, "generateAgentRoutes");
288
+
289
+ // src/bridge/present-ui-message-stream.ts
290
+ import { UIMessageStreamPresenter } from "@theokit/presenter";
291
+ function toAgentOutputEvent(e) {
292
+ switch (e.type) {
293
+ case "text_delta":
294
+ return {
295
+ type: "text",
296
+ text: e.content
297
+ };
298
+ case "thinking":
299
+ return {
300
+ type: "reasoning",
301
+ text: e.content
302
+ };
303
+ case "tool_call":
304
+ return {
305
+ type: "tool-call",
306
+ callId: e.callId,
307
+ name: e.toolName,
308
+ input: e.input
309
+ };
310
+ case "tool_result":
311
+ return {
312
+ type: "tool-result",
313
+ callId: e.callId,
314
+ name: e.toolName,
315
+ result: e.output,
316
+ isError: e.isError
317
+ };
318
+ default:
319
+ return null;
320
+ }
321
+ }
322
+ __name(toAgentOutputEvent, "toAgentOutputEvent");
323
+ function doneToMetadata(event) {
324
+ return event.cost === void 0 ? {
325
+ usage: event.usage,
326
+ durationMs: event.durationMs
327
+ } : {
328
+ usage: event.usage,
329
+ durationMs: event.durationMs,
330
+ cost: event.cost
331
+ };
332
+ }
333
+ __name(doneToMetadata, "doneToMetadata");
334
+ var ERROR_CODE_DATA_PART = "data-error-code";
335
+ var INPUT_REQUESTED_DATA_PART = "data-input-requested";
336
+ var TASK_PROGRESS_DATA_PART = "data-task-progress";
337
+ var SHELL_OUTPUT_DATA_PART = "data-shell-output";
338
+ function dataPart(type, data) {
339
+ return {
340
+ type,
341
+ data,
342
+ transient: true
343
+ };
344
+ }
345
+ __name(dataPart, "dataPart");
346
+ function* errorChunks(errorText, code) {
347
+ if (code !== void 0) yield dataPart(ERROR_CODE_DATA_PART, {
348
+ code
349
+ });
350
+ yield {
351
+ type: "error",
352
+ errorText
353
+ };
354
+ }
355
+ __name(errorChunks, "errorChunks");
356
+ function diagnosticDataPart(event) {
357
+ switch (event.type) {
358
+ case "checkpoint_saved":
359
+ return dataPart("data-checkpoint", {
360
+ checkpointId: event.checkpointId,
361
+ resumeToken: event.resumeToken,
362
+ step: event.step
363
+ });
364
+ // theokit#141 — without these cases the three restored events would be dropped by the loop's
365
+ // catch-all, which is the reported defect one layer down: translating an event and never
366
+ // presenting it leaves the consumer just as blind, minus even the warning.
367
+ case "input_requested":
368
+ return dataPart(INPUT_REQUESTED_DATA_PART, {
369
+ requestId: event.requestId
370
+ });
371
+ case "task_progress":
372
+ return dataPart(TASK_PROGRESS_DATA_PART, {
373
+ ...event.status !== void 0 ? {
374
+ status: event.status
375
+ } : {},
376
+ ...event.text !== void 0 ? {
377
+ text: event.text
378
+ } : {}
379
+ });
380
+ case "shell_output":
381
+ return dataPart(SHELL_OUTPUT_DATA_PART, {
382
+ event: event.event
383
+ });
384
+ default:
385
+ return null;
386
+ }
387
+ }
388
+ __name(diagnosticDataPart, "diagnosticDataPart");
389
+ async function* presentUIMessageStream(events, opts) {
390
+ const presenter = new UIMessageStreamPresenter({
391
+ textId: opts.textId
392
+ });
393
+ yield {
394
+ type: "start"
395
+ };
396
+ let turnMetadata;
397
+ try {
398
+ for await (const event of events) {
399
+ const output = toAgentOutputEvent(event);
400
+ if (output !== null) {
401
+ yield* presenter.present(output);
402
+ continue;
403
+ }
404
+ if (event.type === "approval_required") {
405
+ yield* presenter.closeBlock();
406
+ if (!presenter.hasSeen(event.callId)) {
407
+ presenter.markSeen(event.callId);
408
+ yield {
409
+ type: "tool-input-available",
410
+ toolCallId: event.callId,
411
+ toolName: event.toolName,
412
+ input: event.input ?? {},
413
+ dynamic: true
414
+ };
415
+ }
416
+ yield {
417
+ type: "tool-approval-request",
418
+ approvalId: event.callId,
419
+ toolCallId: event.callId
420
+ };
421
+ continue;
422
+ }
423
+ const diagnostic = diagnosticDataPart(event);
424
+ if (diagnostic !== null) {
425
+ yield* presenter.closeBlock();
426
+ yield diagnostic;
427
+ continue;
428
+ }
429
+ if (event.type === "error") {
430
+ yield* errorChunks(event.message, event.code);
431
+ break;
432
+ }
433
+ if (event.type === "done") {
434
+ turnMetadata = doneToMetadata(event);
435
+ break;
436
+ }
437
+ }
438
+ } catch (err) {
439
+ const code = err.code;
440
+ yield* errorChunks(String(err), typeof code === "string" ? code : void 0);
441
+ }
442
+ yield* presenter.finish(turnMetadata);
443
+ }
444
+ __name(presentUIMessageStream, "presentUIMessageStream");
445
+
446
+ // src/bridge/agent-builder.ts
447
+ var ContextualTool = {
448
+ /**
449
+ * Tag a {@link CustomTool} with a literal name (so `.tool()` can accumulate the tool-name union)
450
+ * and, optionally, a required run-context type. The `requiredContext` argument is a type-only
451
+ * witness — pass `undefined as C` or a sample value; it is never read at runtime.
452
+ */
453
+ of(tool, _requiredContext) {
454
+ return tool;
455
+ }
456
+ };
457
+ function makeBuilder(config) {
458
+ const runtime = {
459
+ input: /* @__PURE__ */ __name((schema) => makeBuilder({
460
+ ...config,
461
+ input: schema
462
+ }), "input"),
463
+ model: /* @__PURE__ */ __name((id) => makeBuilder({
464
+ ...config,
465
+ model: id
466
+ }), "model"),
467
+ system: /* @__PURE__ */ __name((prompt) => makeBuilder({
468
+ ...config,
469
+ system: prompt
470
+ }), "system"),
471
+ reasoningEffort: /* @__PURE__ */ __name((effort) => makeBuilder({
472
+ ...config,
473
+ reasoningEffort: effort
474
+ }), "reasoningEffort"),
475
+ context: /* @__PURE__ */ __name((value) => makeBuilder({
476
+ ...config,
477
+ context: value
478
+ }), "context"),
479
+ tool: /* @__PURE__ */ __name((tool) => makeBuilder({
480
+ ...config,
481
+ tools: [
482
+ ...config.tools ?? [],
483
+ tool
484
+ ]
485
+ }), "tool"),
486
+ tools: /* @__PURE__ */ __name((list) => makeBuilder({
487
+ ...config,
488
+ tools: [
489
+ ...config.tools ?? [],
490
+ ...list
491
+ ]
492
+ }), "tools"),
493
+ // `when` is deliberately not a conditional-typed return: the branch runs or it does not, and
494
+ // either way the caller gets a builder carrying the same accumulated state. Returning `builder`
495
+ // unchanged on `false` is what makes it a true no-op rather than a reset.
496
+ when: /* @__PURE__ */ __name((condition, apply) => {
497
+ const builder = makeBuilder(config);
498
+ return condition ? apply(builder) : builder;
499
+ }, "when"),
500
+ guardrail: /* @__PURE__ */ __name((g) => makeBuilder({
501
+ ...config,
502
+ guardrails: [
503
+ ...config.guardrails ?? [],
504
+ g
505
+ ]
506
+ }), "guardrail"),
507
+ guardrails: /* @__PURE__ */ __name((gs) => makeBuilder({
508
+ ...config,
509
+ guardrails: gs
510
+ }), "guardrails"),
511
+ approval: /* @__PURE__ */ __name((toolName, options) => makeBuilder({
512
+ ...config,
513
+ approvals: {
514
+ ...config.approvals ?? {},
515
+ [toolName]: options
516
+ }
517
+ }), "approval"),
518
+ approvals: /* @__PURE__ */ __name((map) => makeBuilder({
519
+ ...config,
520
+ approvals: map
521
+ }), "approvals"),
522
+ skills: /* @__PURE__ */ __name((selection) => makeBuilder({
523
+ ...config,
524
+ skills: selection
525
+ }), "skills"),
526
+ settingSources: /* @__PURE__ */ __name((selection) => makeBuilder({
527
+ ...config,
528
+ settingSources: selection
529
+ }), "settingSources"),
530
+ memory: /* @__PURE__ */ __name((settings) => makeBuilder({
531
+ ...config,
532
+ memory: settings
533
+ }), "memory"),
534
+ hooks: /* @__PURE__ */ __name((map) => makeBuilder({
535
+ ...config,
536
+ hooks: map
537
+ }), "hooks"),
538
+ plugins: /* @__PURE__ */ __name((list) => makeBuilder({
539
+ ...config,
540
+ plugins: list
541
+ }), "plugins"),
542
+ mcp: /* @__PURE__ */ __name((servers) => makeBuilder({
543
+ ...config,
544
+ mcpServers: servers
545
+ }), "mcp"),
546
+ use: /* @__PURE__ */ __name((preset) => preset(runtime), "use"),
547
+ build: /* @__PURE__ */ __name(() => defineAgent(config), "build")
548
+ };
549
+ return runtime;
550
+ }
551
+ __name(makeBuilder, "makeBuilder");
552
+ var AgentBuilder = {
553
+ /**
554
+ * Start a fluent agent definition. Chain `.model()` (required) + `.context()` / `.system()` /
555
+ * `.input()` / `.tool()` / `.use()`, then `.build()` to get the branded {@link AgentDefinition}.
556
+ */
557
+ create() {
558
+ return makeBuilder({});
559
+ }
560
+ };
561
+
562
+ // src/bridge/agent-endpoint.ts
563
+ import { TheokitAgentError } from "@theokit/sdk/errors";
564
+ var AgentDefinitionError = class extends TheokitAgentError {
565
+ static {
566
+ __name(this, "AgentDefinitionError");
567
+ }
568
+ name = "AgentDefinitionError";
569
+ constructor(source) {
570
+ super(`[@theokit/agents] ${source}: an agents/ file must default-export a defineAgent(...) value or an @Agent-decorated class.`, {
571
+ code: "AGENT_DEFINITION_INVALID",
572
+ // a malformed module does not become well-formed by being loaded twice.
573
+ isRetryable: false
574
+ });
575
+ }
576
+ };
577
+ function extractDefaultExport(mod) {
578
+ if (typeof mod === "object" && mod !== null && "default" in mod) {
579
+ return mod.default;
580
+ }
581
+ return mod;
582
+ }
583
+ __name(extractDefaultExport, "extractDefaultExport");
584
+ function isCompiledAgentOptions(value) {
585
+ if (typeof value !== "object" || value === null) return false;
586
+ const v = value;
587
+ return Array.isArray(v.tools) && typeof v.agents === "object" && v.agents !== null;
588
+ }
589
+ __name(isCompiledAgentOptions, "isCompiledAgentOptions");
590
+ function compileAgentModule(mod, source = "agent module") {
591
+ const def = extractDefaultExport(mod);
592
+ if (isAgentDefinition(def)) {
593
+ return compileAgentDefinition(def);
594
+ }
595
+ if (isCompiledAgentOptions(def)) return def;
596
+ throw new AgentDefinitionError(source);
597
+ }
598
+ __name(compileAgentModule, "compileAgentModule");
599
+ async function* asAgentStream(events) {
600
+ for await (const e of events) yield e;
601
+ }
602
+ __name(asAgentStream, "asAgentStream");
603
+ var EventQueue = class EventQueue2 {
604
+ static {
605
+ __name(this, "EventQueue");
606
+ }
607
+ #items = [];
608
+ #resolvers = [];
609
+ #closed = false;
610
+ push(item) {
611
+ if (this.#closed) return;
612
+ const r = this.#resolvers.shift();
613
+ if (r) r({
614
+ value: item,
615
+ done: false
616
+ });
617
+ else this.#items.push(item);
618
+ }
619
+ close() {
620
+ this.#closed = true;
621
+ for (const r of this.#resolvers.splice(0)) r({
622
+ value: void 0,
623
+ done: true
624
+ });
625
+ }
626
+ async *drain() {
627
+ for (; ; ) {
628
+ if (this.#items.length > 0) {
629
+ yield this.#items.shift();
630
+ continue;
631
+ }
632
+ if (this.#closed) return;
633
+ const next = await new Promise((resolve) => this.#resolvers.push(resolve));
634
+ if (next.done) return;
635
+ yield next.value;
636
+ }
637
+ }
638
+ };
639
+ async function* appendCheckpointSaved(source, sessionId) {
640
+ let emitted = false;
641
+ const checkpoint = /* @__PURE__ */ __name(() => ({
642
+ type: "checkpoint_saved",
643
+ checkpointId: crypto.randomUUID(),
644
+ step: 0,
645
+ resumeToken: sessionId
646
+ }), "checkpoint");
647
+ for await (const ev of source) {
648
+ if (ev.type === "done" && !emitted) {
649
+ emitted = true;
650
+ yield checkpoint();
651
+ }
652
+ yield ev;
653
+ }
654
+ if (!emitted) yield checkpoint();
655
+ }
656
+ __name(appendCheckpointSaved, "appendCheckpointSaved");
657
+ function streamAgentUIMessages(compiled, apiKey, input) {
658
+ const textId = crypto.randomUUID();
659
+ const overrides = {};
660
+ if (input.cwd !== void 0) overrides.cwd = input.cwd;
661
+ if (input.baseDir !== void 0) overrides.baseDir = input.baseDir;
662
+ if (input.images !== void 0) overrides.images = input.images;
663
+ if (input.onRunEvent !== void 0) overrides.onRunEvent = input.onRunEvent;
664
+ let source;
665
+ if (!input.hitl || input.hitl.gated.size === 0) {
666
+ const events2 = createSdkAgentStream(compiled, compiled.tools, apiKey, overrides)(input.message, input.sessionId);
667
+ source = asAgentStream(events2);
668
+ } else {
669
+ const queue = new EventQueue();
670
+ input.signal?.addEventListener("abort", () => {
671
+ queue.close();
672
+ }, {
673
+ once: true
674
+ });
675
+ const plugin = createHitlPlugin({
676
+ gated: input.hitl.gated,
677
+ emit: /* @__PURE__ */ __name((e) => {
678
+ queue.push(e);
679
+ }, "emit"),
680
+ awaitApproval: input.hitl.awaitApproval
681
+ });
682
+ const sdkStream = createSdkAgentStream(compiled, compiled.tools, apiKey, {
683
+ ...overrides,
684
+ // The HITL plugin is a structural @theokit/sdk Plugin (createHitlPlugin returns the
685
+ // { name, register } shape); the RuntimeOverrides.plugins union is widened at the SDK edge.
686
+ plugins: [
687
+ plugin
688
+ ]
689
+ })(input.message, input.sessionId);
690
+ void (async () => {
691
+ try {
692
+ for await (const e of sdkStream) queue.push(e);
693
+ } catch (err) {
694
+ queue.push({
695
+ type: "error",
696
+ code: "SDK_STREAM_ERROR",
697
+ message: err instanceof Error ? err.message : String(err),
698
+ retryable: false
699
+ });
700
+ } finally {
701
+ queue.close();
702
+ }
703
+ })();
704
+ source = queue.drain();
705
+ }
706
+ const durableCheckpoint = compiled.checkpoint?.storage === "filesystem";
707
+ const events = durableCheckpoint ? appendCheckpointSaved(source, input.sessionId) : source;
708
+ return presentUIMessageStream(events, {
709
+ textId
710
+ });
711
+ }
712
+ __name(streamAgentUIMessages, "streamAgentUIMessages");
713
+
714
+ // src/bridge/api-error-handler.ts
715
+ var DEFAULT_MAX_ATTEMPTS = 3;
716
+ async function runWithApiErrorHandling(thunk, policy) {
717
+ const maxAttempts = policy.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
718
+ let attempt = 0;
719
+ for (; ; ) {
720
+ attempt += 1;
721
+ try {
722
+ return await thunk();
723
+ } catch (error) {
724
+ const decision = await policy.processApiError({
725
+ error,
726
+ attempt
727
+ });
728
+ if (decision.retry && attempt < maxAttempts) continue;
729
+ if (!decision.retry && "fallback" in decision && decision.fallback !== void 0) {
730
+ return decision.fallback;
731
+ }
732
+ throw error;
733
+ }
734
+ }
735
+ }
736
+ __name(runWithApiErrorHandling, "runWithApiErrorHandling");
737
+ function createApiErrorHandler(policy) {
738
+ return (thunk) => runWithApiErrorHandling(thunk, policy);
739
+ }
740
+ __name(createApiErrorHandler, "createApiErrorHandler");
741
+
742
+ // src/bridge/mcp-resolver.ts
743
+ async function resolveMcpServers(selection, ctx) {
744
+ if (selection === void 0) return void 0;
745
+ if (typeof selection !== "function") return selection;
746
+ const resolved = await selection(ctx);
747
+ if (typeof resolved !== "object" || resolved === null) {
748
+ throw new Error("[@theokit/agents] MCP resolver must return an McpServersMap object");
749
+ }
750
+ return resolved;
751
+ }
752
+ __name(resolveMcpServers, "resolveMcpServers");
753
+ function mcpRegistry(config) {
754
+ const registry = config.registry;
755
+ if (registry === "composio") {
756
+ const apps = config.apps ?? [];
757
+ return {
758
+ composio: {
759
+ command: "npx",
760
+ args: [
761
+ "-y",
762
+ "@composio/mcp",
763
+ ...apps.length > 0 ? [
764
+ "--apps",
765
+ apps.join(",")
766
+ ] : []
767
+ ],
768
+ env: {
769
+ COMPOSIO_API_KEY: config.apiKey
770
+ }
771
+ }
772
+ };
773
+ }
774
+ if (registry === "mcp.run") {
775
+ return {
776
+ "mcp.run": {
777
+ command: "npx",
778
+ args: [
779
+ "-y",
780
+ "@mcp.run/cli",
781
+ "serve",
782
+ ...config.profile ? [
783
+ "--profile",
784
+ config.profile
785
+ ] : []
786
+ ],
787
+ env: {
788
+ MCP_RUN_API_KEY: config.apiKey
789
+ }
790
+ }
791
+ };
792
+ }
793
+ throw new Error(`mcpRegistry: unknown registry ${JSON.stringify(registry)} (supported: 'composio', 'mcp.run').`);
794
+ }
795
+ __name(mcpRegistry, "mcpRegistry");
796
+ function mcpToolApprovals(specs) {
797
+ const out = {};
798
+ for (const [tool, spec] of Object.entries(specs)) {
799
+ out[tool] = typeof spec === "string" ? {
800
+ question: spec
801
+ } : spec;
802
+ }
803
+ return out;
804
+ }
805
+ __name(mcpToolApprovals, "mcpToolApprovals");
806
+
807
+ // src/bridge/mcp-file.ts
808
+ import { existsSync, readFileSync } from "fs";
809
+ import { join } from "path";
810
+ import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
811
+ function warningChannel(opts) {
812
+ return opts.onWarn ?? ((warning) => {
813
+ process.stderr.write(`[@theokit/agents] ${warning}
814
+ `);
815
+ });
816
+ }
817
+ __name(warningChannel, "warningChannel");
818
+ var McpFileError = class extends TheokitAgentError2 {
819
+ static {
820
+ __name(this, "McpFileError");
821
+ }
822
+ name = "McpFileError";
823
+ constructor(message) {
824
+ super(`[@theokit/agents] ${message}`);
825
+ }
826
+ };
827
+ var MCP_FILENAME = ".mcp.json";
828
+ function loadMcpJson(cwd, opts = {}) {
829
+ const path = join(cwd, MCP_FILENAME);
830
+ if (!existsSync(path)) return {};
831
+ let text;
832
+ try {
833
+ text = readFileSync(path, "utf8");
834
+ } catch (err) {
835
+ throw new McpFileError(`failed to read ${path}: ${describeIt(err)}`);
836
+ }
837
+ let parsed;
838
+ try {
839
+ parsed = JSON.parse(text);
840
+ } catch (err) {
841
+ throw new McpFileError(`${path} is not valid JSON: ${describeIt(err)}`);
842
+ }
843
+ return parseMcpJson(parsed, path, warningChannel(opts));
844
+ }
845
+ __name(loadMcpJson, "loadMcpJson");
846
+ function parseMcpJson(raw, source, onWarn) {
847
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
848
+ throw new McpFileError(`${source}: root must be a JSON object with an "mcpServers" key.`);
849
+ }
850
+ const serversRaw = raw.mcpServers;
851
+ if (serversRaw === void 0) return {};
852
+ if (typeof serversRaw !== "object" || serversRaw === null || Array.isArray(serversRaw)) {
853
+ throw new McpFileError(`${source}: "mcpServers" must be an object keyed by server name.`);
854
+ }
855
+ const out = {};
856
+ for (const [name, entryRaw] of Object.entries(serversRaw)) {
857
+ const reason = validateEntry(name, entryRaw);
858
+ if (reason !== void 0) {
859
+ onWarn(`${source}: server "${name}" ignored \u2014 ${reason}`);
860
+ continue;
861
+ }
862
+ out[name] = buildEntry(entryRaw);
863
+ }
864
+ return out;
865
+ }
866
+ __name(parseMcpJson, "parseMcpJson");
867
+ function validateEntry(name, entryRaw) {
868
+ if (typeof entryRaw !== "object" || entryRaw === null || Array.isArray(entryRaw)) {
869
+ return "the entry must be an object.";
870
+ }
871
+ const entry = entryRaw;
872
+ const hasUrl = entry.url !== void 0;
873
+ const hasCommand = entry.command !== void 0;
874
+ if (hasUrl && hasCommand) return 'declares both "command" and "url" \u2014 pick one transport.';
875
+ if (!hasUrl && !hasCommand) return 'requires "command" (stdio) or "url" (http/sse).';
876
+ return hasUrl ? validateRemote(entry) : validateStdio(entry);
877
+ }
878
+ __name(validateEntry, "validateEntry");
879
+ function validateStdio(entry) {
880
+ if (typeof entry.command !== "string" || entry.command.length === 0) {
881
+ return 'field "command" must be a non-empty string.';
882
+ }
883
+ if (entry.args !== void 0 && !isStringArray(entry.args)) return 'field "args" must be an array of strings.';
884
+ if (entry.env !== void 0 && !isStringRecord(entry.env)) return 'field "env" must be a map of strings.';
885
+ if (entry.cwd !== void 0 && typeof entry.cwd !== "string") return 'field "cwd" must be a string.';
886
+ return void 0;
887
+ }
888
+ __name(validateStdio, "validateStdio");
889
+ function validateRemote(entry) {
890
+ if (typeof entry.url !== "string" || entry.url.length === 0) {
891
+ return 'field "url" must be a non-empty string.';
892
+ }
893
+ try {
894
+ new URL(entry.url);
895
+ } catch {
896
+ return 'field "url" is not a valid URL.';
897
+ }
898
+ if (entry.type !== void 0 && entry.type !== "http" && entry.type !== "sse") {
899
+ return 'field "type" must be "http" or "sse".';
900
+ }
901
+ if (entry.headers !== void 0 && !isStringRecord(entry.headers)) {
902
+ return 'field "headers" must be a map of strings.';
903
+ }
904
+ if (entry.requestTimeoutMs !== void 0 && typeof entry.requestTimeoutMs !== "number") {
905
+ return 'field "requestTimeoutMs" must be a number.';
906
+ }
907
+ return void 0;
908
+ }
909
+ __name(validateRemote, "validateRemote");
910
+ function buildEntry(entry) {
911
+ if (entry.url !== void 0) {
912
+ const remote = {
913
+ url: entry.url
914
+ };
915
+ if (entry.type !== void 0) remote.type = entry.type;
916
+ if (entry.headers !== void 0) remote.headers = entry.headers;
917
+ if (entry.auth !== void 0) remote.auth = entry.auth;
918
+ if (entry.requestTimeoutMs !== void 0) remote.requestTimeoutMs = entry.requestTimeoutMs;
919
+ return remote;
920
+ }
921
+ const stdio = {
922
+ command: entry.command
923
+ };
924
+ if (entry.args !== void 0) stdio.args = entry.args;
925
+ if (entry.env !== void 0) stdio.env = entry.env;
926
+ if (entry.cwd !== void 0) stdio.cwd = entry.cwd;
927
+ return stdio;
928
+ }
929
+ __name(buildEntry, "buildEntry");
930
+ function describeIt(err) {
931
+ return err instanceof Error ? err.message : String(err);
932
+ }
933
+ __name(describeIt, "describeIt");
934
+ function isStringArray(v) {
935
+ return Array.isArray(v) && v.every((x) => typeof x === "string");
936
+ }
937
+ __name(isStringArray, "isStringArray");
938
+ function isStringRecord(v) {
939
+ return typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
940
+ }
941
+ __name(isStringRecord, "isStringRecord");
942
+
943
+ // src/manifest/agent-manifest.ts
944
+ function generateAgentManifest(sources) {
945
+ return {
946
+ version: "1.0",
947
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
948
+ agents: sources.map((r) => ({
949
+ name: r.agentConfig.name,
950
+ route: r.route,
951
+ model: r.agentConfig.model,
952
+ stream: r.agentConfig.stream ?? true,
953
+ mainLoop: {
954
+ method: String(r.mainLoop.propertyKey),
955
+ strategy: r.mainLoop.strategy
956
+ },
957
+ guards: r.guards.map((g) => g.name),
958
+ interceptors: r.interceptors.map((i) => i.name),
959
+ tools: r.toolboxes.flatMap((tb) => tb.tools.map((t) => ({
960
+ name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,
961
+ description: t.config.description,
962
+ risk: t.config.risk,
963
+ approval: t.approval !== void 0,
964
+ capabilities: t.capabilities,
965
+ trace: t.trace,
966
+ audit: t.audit
967
+ }))),
968
+ gateway: r.gateway ? {
969
+ platforms: r.gateway.platforms,
970
+ sessionStrategy: r.gateway.sessionStrategy ?? "per-user"
971
+ } : void 0,
972
+ subAgents: r.subAgentClasses.map((cls) => cls.name),
973
+ memory: r.memory ? {
974
+ provider: r.memory.provider ?? "built-in",
975
+ embeddings: r.memory.embeddings ?? false,
976
+ fts: r.memory.fts ?? false,
977
+ scope: r.memory.scope ?? "per-user"
978
+ } : void 0,
979
+ skills: r.skills?.include,
980
+ mcpServers: r.mcpServers ? Object.keys(r.mcpServers) : void 0
981
+ }))
982
+ };
983
+ }
984
+ __name(generateAgentManifest, "generateAgentManifest");
985
+
986
+ // src/theokit-plugin.ts
987
+ function validateUniqueRoutes(results) {
988
+ const seen = /* @__PURE__ */ new Map();
989
+ for (const r of results) {
990
+ const existing = seen.get(r.route);
991
+ if (existing !== void 0) {
992
+ throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
993
+ }
994
+ seen.set(r.route, r.agentConfig.name);
995
+ }
996
+ }
997
+ __name(validateUniqueRoutes, "validateUniqueRoutes");
998
+ function agentsPlugin(opts) {
999
+ let routes = null;
1000
+ return {
1001
+ name: "@theokit/agents",
1002
+ register(app) {
1003
+ app.addHook("onRequest", async (pluginCtx) => {
1004
+ routes ??= initRoutes(opts);
1005
+ const request = pluginCtx.request;
1006
+ const url = new URL(request.url);
1007
+ const method = request.method.toUpperCase();
1008
+ const matched = matchRoute(routes, method, url.pathname);
1009
+ if (!matched) return;
1010
+ return matched.handler(request);
1011
+ });
1012
+ }
1013
+ };
1014
+ }
1015
+ __name(agentsPlugin, "agentsPlugin");
1016
+ function initRoutes(opts) {
1017
+ const allRoutes = [];
1018
+ const routeIdentities = [];
1019
+ for (const entry of opts.agents) {
1020
+ routeIdentities.push({
1021
+ route: entry.route,
1022
+ agentConfig: {
1023
+ name: entry.name
1024
+ }
1025
+ });
1026
+ const createRun = opts.createRunFactory ? opts.createRunFactory(entry.compiled) : defaultCreateRun(entry.compiled);
1027
+ allRoutes.push(...generateAgentRoutes({
1028
+ walkResult: {
1029
+ route: entry.route
1030
+ },
1031
+ compiledOptions: entry.compiled,
1032
+ createRun
1033
+ }));
1034
+ }
1035
+ validateUniqueRoutes(routeIdentities);
1036
+ return compileRoutePatterns(allRoutes);
1037
+ }
1038
+ __name(initRoutes, "initRoutes");
1039
+ function defaultCreateRun(compiled) {
1040
+ return async function* (_message, _sessionId) {
1041
+ await Promise.resolve();
1042
+ yield {
1043
+ type: "run_started",
1044
+ runId: `run-${Date.now()}`,
1045
+ agentName: compiled.model ?? "unknown"
1046
+ };
1047
+ yield {
1048
+ type: "error",
1049
+ code: "SDK_NOT_WIRED",
1050
+ message: "No createRunFactory provided \u2014 wire @theokit/sdk Agent.create() to enable real agent execution.",
1051
+ retryable: false
1052
+ };
1053
+ };
1054
+ }
1055
+ __name(defaultCreateRun, "defaultCreateRun");
1056
+ function compileRoutePatterns(routes) {
1057
+ return routes.map((r) => {
1058
+ if (!r.path.includes(":")) return r;
1059
+ const regexSource = r.path.replace(/:[^/]+/g, "[^/]+");
1060
+ return {
1061
+ ...r,
1062
+ regex: RegExp(`^${regexSource}$`)
1063
+ };
1064
+ });
1065
+ }
1066
+ __name(compileRoutePatterns, "compileRoutePatterns");
1067
+ function matchRoute(routes, method, pathname) {
1068
+ return routes.find((r) => {
1069
+ if (r.method !== method) return false;
1070
+ if (r.regex) return r.regex.test(pathname);
1071
+ return r.path === pathname;
1072
+ });
1073
+ }
1074
+ __name(matchRoute, "matchRoute");
1075
+
1076
+ export {
1077
+ ConfigurationError,
1078
+ compileContextWindow,
1079
+ compileSkills,
1080
+ toolRuntimeName,
1081
+ compileHitlGates,
1082
+ compileTools,
1083
+ createAgentExecutionContext,
1084
+ isAgentContext,
1085
+ streamAgentResponse,
1086
+ isTextDelta,
1087
+ isToolCall,
1088
+ isPartialToolCall,
1089
+ isToolResult,
1090
+ isDone,
1091
+ isError,
1092
+ isApprovalRequired,
1093
+ generateAgentRoutes,
1094
+ presentUIMessageStream,
1095
+ ContextualTool,
1096
+ AgentBuilder,
1097
+ AgentDefinitionError,
1098
+ compileAgentModule,
1099
+ streamAgentUIMessages,
1100
+ runWithApiErrorHandling,
1101
+ createApiErrorHandler,
1102
+ resolveMcpServers,
1103
+ mcpRegistry,
1104
+ mcpToolApprovals,
1105
+ McpFileError,
1106
+ loadMcpJson,
1107
+ generateAgentManifest,
1108
+ agentsPlugin
1109
+ };
1110
+ //# sourceMappingURL=chunk-CAXGTLRU.js.map