@theokit/agents 7.4.2 → 7.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/auth.js +72 -74
- package/dist/auth.js.map +1 -1
- package/dist/bridge.js +2 -1
- package/dist/{chunk-FJA4QQLZ.js → chunk-2BAFKRXT.js} +221 -165
- package/dist/chunk-2BAFKRXT.js.map +1 -0
- package/dist/{chunk-PHUNONZT.js → chunk-WKBZZQBO.js} +975 -445
- package/dist/chunk-WKBZZQBO.js.map +1 -0
- package/dist/chunk-Z4QWC7IK.js +7 -0
- package/dist/chunk-Z4QWC7IK.js.map +1 -0
- package/dist/client-react.js +9 -3
- package/dist/client-react.js.map +1 -1
- package/dist/client.js +2 -1
- package/dist/index.d.ts +15 -0
- package/dist/index.js +365 -129
- package/dist/index.js.map +1 -1
- package/dist/interactive.js +3 -6
- package/dist/interactive.js.map +1 -1
- package/dist/persistence.js +2 -0
- package/dist/persistence.js.map +1 -1
- package/dist/pty.js +3 -7
- package/dist/pty.js.map +1 -1
- package/dist/sandbox.js +3 -26
- package/dist/sandbox.js.map +1 -1
- package/dist/testing.js +21 -3
- package/dist/testing.js.map +1 -1
- package/dist/tools.js +3 -55
- package/dist/tools.js.map +1 -1
- package/package.json +12 -12
- package/dist/chunk-FJA4QQLZ.js.map +0 -1
- package/dist/chunk-PHUNONZT.js.map +0 -1
|
@@ -1,21 +1,30 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-Z4QWC7IK.js";
|
|
4
|
+
|
|
1
5
|
// src/errors.ts
|
|
2
6
|
import { ConfigurationError } from "@theokit/sdk/errors";
|
|
3
7
|
|
|
4
8
|
// src/bridge/define-agent.ts
|
|
5
9
|
var AGENT_BRAND = /* @__PURE__ */ Symbol.for("theokit.agent.definition");
|
|
6
10
|
function defineAgent(config) {
|
|
7
|
-
return {
|
|
11
|
+
return {
|
|
12
|
+
...config,
|
|
13
|
+
[AGENT_BRAND]: true
|
|
14
|
+
};
|
|
8
15
|
}
|
|
16
|
+
__name(defineAgent, "defineAgent");
|
|
9
17
|
function isAgentDefinition(value) {
|
|
10
18
|
return typeof value === "object" && value !== null && value[AGENT_BRAND] === true;
|
|
11
19
|
}
|
|
20
|
+
__name(isAgentDefinition, "isAgentDefinition");
|
|
12
21
|
function toCompiledTool(tool) {
|
|
13
22
|
const handler = tool.handler;
|
|
14
23
|
const compiled = {
|
|
15
24
|
name: tool.name,
|
|
16
25
|
description: tool.description,
|
|
17
26
|
inputSchema: tool.inputSchema,
|
|
18
|
-
handler: (input, ctx) => handler(input, ctx)
|
|
27
|
+
handler: /* @__PURE__ */ __name((input, ctx) => handler(input, ctx), "handler")
|
|
19
28
|
};
|
|
20
29
|
for (const sym of Object.getOwnPropertySymbols(tool)) {
|
|
21
30
|
;
|
|
@@ -23,6 +32,7 @@ function toCompiledTool(tool) {
|
|
|
23
32
|
}
|
|
24
33
|
return compiled;
|
|
25
34
|
}
|
|
35
|
+
__name(toCompiledTool, "toCompiledTool");
|
|
26
36
|
function compileAgentDefinition(def) {
|
|
27
37
|
return {
|
|
28
38
|
model: def.model,
|
|
@@ -33,33 +43,48 @@ function compileAgentDefinition(def) {
|
|
|
33
43
|
stream: true,
|
|
34
44
|
// M7 — run-context flows to CompiledAgentOptions.runContext (distinct from the
|
|
35
45
|
// context-window `context` field the decorator path uses); absent ⇒ no key.
|
|
36
|
-
...def.context !== void 0 ? {
|
|
46
|
+
...def.context !== void 0 ? {
|
|
47
|
+
runContext: def.context
|
|
48
|
+
} : {},
|
|
37
49
|
// M9 — guardrails flow through unchanged; the runner applies them at the input boundary.
|
|
38
|
-
...def.guardrails !== void 0 ? {
|
|
50
|
+
...def.guardrails !== void 0 ? {
|
|
51
|
+
guardrails: def.guardrails
|
|
52
|
+
} : {},
|
|
39
53
|
// M14 — HITL approvals compile into the same `hitl` map the decorator path produces.
|
|
40
|
-
...def.approvals !== void 0 ? {
|
|
54
|
+
...def.approvals !== void 0 ? {
|
|
55
|
+
hitl: compileApprovals(def)
|
|
56
|
+
} : {},
|
|
41
57
|
// M13 — skills: a static list → SDK skills.enabled; a resolver → carried for the request path.
|
|
42
58
|
...compileSkillsSelection(def.skills),
|
|
43
59
|
// theokit-file-based-config — the declared `.theokit/` sources flow to the run path, which
|
|
44
60
|
// projects them into `Agent.create({ local.settingSources })`; absent ⇒ inline config only.
|
|
45
|
-
...def.settingSources !== void 0 ? {
|
|
61
|
+
...def.settingSources !== void 0 ? {
|
|
62
|
+
settingSources: def.settingSources
|
|
63
|
+
} : {},
|
|
46
64
|
// M49 — memory flows to the projection layer; `assembleM8CreateOptions` forwards it to Agent.create.
|
|
47
|
-
...def.memory !== void 0 ? {
|
|
65
|
+
...def.memory !== void 0 ? {
|
|
66
|
+
memory: def.memory
|
|
67
|
+
} : {},
|
|
48
68
|
// Hooks are converted here — the layer EVERY path converges on — rather than on the builder, so
|
|
49
69
|
// `defineAgent({ hooks })` cannot type-check and silently no-op. A lifecycle hook that is
|
|
50
70
|
// declared but never registered is a security gate that does not gate.
|
|
51
71
|
...compileHooksAndPlugins(def),
|
|
52
72
|
// MCP — builder/`defineAgent` servers converge on the same `mcpServers` field the `@MCP`
|
|
53
73
|
// decorator path populates; the SDK adapter forwards it to `Agent.create({ mcpServers })`.
|
|
54
|
-
...def.mcpServers !== void 0 ? {
|
|
74
|
+
...def.mcpServers !== void 0 ? {
|
|
75
|
+
mcpServers: def.mcpServers
|
|
76
|
+
} : {}
|
|
55
77
|
};
|
|
56
78
|
}
|
|
79
|
+
__name(compileAgentDefinition, "compileAgentDefinition");
|
|
57
80
|
function compileHooksAndPlugins(def) {
|
|
58
81
|
const map = def.hooks;
|
|
59
82
|
const entries = Object.entries(map ?? {}).filter(([, h]) => typeof h === "function");
|
|
60
83
|
const explicit = def.plugins ?? [];
|
|
61
84
|
if (entries.length === 0) {
|
|
62
|
-
return def.plugins !== void 0 ? {
|
|
85
|
+
return def.plugins !== void 0 ? {
|
|
86
|
+
plugins: def.plugins
|
|
87
|
+
} : {};
|
|
63
88
|
}
|
|
64
89
|
const plugin = {
|
|
65
90
|
name: "theokit-builder-hooks",
|
|
@@ -71,11 +96,19 @@ function compileHooksAndPlugins(def) {
|
|
|
71
96
|
}
|
|
72
97
|
}
|
|
73
98
|
};
|
|
74
|
-
return {
|
|
99
|
+
return {
|
|
100
|
+
plugins: [
|
|
101
|
+
...explicit,
|
|
102
|
+
plugin
|
|
103
|
+
]
|
|
104
|
+
};
|
|
75
105
|
}
|
|
106
|
+
__name(compileHooksAndPlugins, "compileHooksAndPlugins");
|
|
76
107
|
function compileSkillsSelection(skills) {
|
|
77
108
|
if (skills === void 0) return {};
|
|
78
|
-
if (typeof skills === "function") return {
|
|
109
|
+
if (typeof skills === "function") return {
|
|
110
|
+
skillsResolver: skills
|
|
111
|
+
};
|
|
79
112
|
const enabled = [];
|
|
80
113
|
const inline = [];
|
|
81
114
|
for (const entry of skills) {
|
|
@@ -83,22 +116,30 @@ function compileSkillsSelection(skills) {
|
|
|
83
116
|
else inline.push(entry);
|
|
84
117
|
}
|
|
85
118
|
return {
|
|
86
|
-
skills: {
|
|
119
|
+
skills: {
|
|
120
|
+
enabled,
|
|
121
|
+
autoInject: true,
|
|
122
|
+
...inline.length > 0 ? {
|
|
123
|
+
inline
|
|
124
|
+
} : {}
|
|
125
|
+
}
|
|
87
126
|
};
|
|
88
127
|
}
|
|
128
|
+
__name(compileSkillsSelection, "compileSkillsSelection");
|
|
89
129
|
function compileApprovals(def) {
|
|
90
130
|
const toolNames = new Set((def.tools ?? []).map((t) => t.name));
|
|
91
131
|
const gates = /* @__PURE__ */ new Map();
|
|
92
132
|
for (const [toolName, options] of Object.entries(def.approvals ?? {})) {
|
|
93
133
|
if (!toolNames.has(toolName)) {
|
|
94
|
-
throw new Error(
|
|
95
|
-
|
|
96
|
-
);
|
|
134
|
+
throw new Error(`[@theokit/agents] defineAgent approval references unknown tool "${toolName}". Declared tools: ${[
|
|
135
|
+
...toolNames
|
|
136
|
+
].join(", ") || "(none)"}.`);
|
|
97
137
|
}
|
|
98
138
|
gates.set(toolName, options);
|
|
99
139
|
}
|
|
100
140
|
return gates;
|
|
101
141
|
}
|
|
142
|
+
__name(compileApprovals, "compileApprovals");
|
|
102
143
|
|
|
103
144
|
// src/bridge/compile-context-window.ts
|
|
104
145
|
var STRATEGY_KNOBS = [
|
|
@@ -114,16 +155,26 @@ function compileContextWindow(options) {
|
|
|
114
155
|
}
|
|
115
156
|
const opts = options;
|
|
116
157
|
const metadataOnlyKnobs = STRATEGY_KNOBS.filter((knob) => opts[knob] !== void 0);
|
|
117
|
-
return {
|
|
158
|
+
return {
|
|
159
|
+
context,
|
|
160
|
+
metadataOnlyKnobs
|
|
161
|
+
};
|
|
118
162
|
}
|
|
163
|
+
__name(compileContextWindow, "compileContextWindow");
|
|
119
164
|
|
|
120
165
|
// src/bridge/compile-skills.ts
|
|
121
166
|
function compileSkills(options) {
|
|
122
167
|
if (options.autoDiscover) {
|
|
123
|
-
return {
|
|
168
|
+
return {
|
|
169
|
+
autoInject: true
|
|
170
|
+
};
|
|
124
171
|
}
|
|
125
|
-
return {
|
|
172
|
+
return {
|
|
173
|
+
enabled: options.include,
|
|
174
|
+
autoInject: true
|
|
175
|
+
};
|
|
126
176
|
}
|
|
177
|
+
__name(compileSkills, "compileSkills");
|
|
127
178
|
|
|
128
179
|
// src/bridge/agent-compiler.ts
|
|
129
180
|
var SDK_TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
|
|
@@ -143,21 +194,18 @@ function toolRuntimeName(namespace, toolName) {
|
|
|
143
194
|
const name = namespace ? `${namespace}_${toolName}` : toolName;
|
|
144
195
|
if (!SDK_TOOL_NAME.test(name)) {
|
|
145
196
|
if (SDK_TOOL_NAME_CHARSET.test(name)) {
|
|
146
|
-
throw new ConfigurationError(
|
|
147
|
-
`tool: name "${name}" has length ${name.length} \u2014 the composition namespace + "_" + tool exceeds the maximum of ${SDK_TOOL_NAME_MAX_LENGTH} the SDK accepts`
|
|
148
|
-
);
|
|
197
|
+
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`);
|
|
149
198
|
}
|
|
150
|
-
throw new ConfigurationError(
|
|
151
|
-
`tool: invalid name "${name}" \u2014 it must match ${String(SDK_TOOL_NAME)} (the SDK rejects the rest; check the namespace and the tool name)`
|
|
152
|
-
);
|
|
199
|
+
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)`);
|
|
153
200
|
}
|
|
154
201
|
if (SDK_RESERVED_TOOL_NAMES.has(name) || name.startsWith(SDK_RESERVED_TOOL_PREFIX)) {
|
|
155
|
-
throw new ConfigurationError(
|
|
156
|
-
|
|
157
|
-
);
|
|
202
|
+
throw new ConfigurationError(`tool: reserved name "${name}" \u2014 the SDK reserves ${[
|
|
203
|
+
...SDK_RESERVED_TOOL_NAMES
|
|
204
|
+
].join(", ")} and the prefix "${SDK_RESERVED_TOOL_PREFIX}"`);
|
|
158
205
|
}
|
|
159
206
|
return name;
|
|
160
207
|
}
|
|
208
|
+
__name(toolRuntimeName, "toolRuntimeName");
|
|
161
209
|
function compileHitlGates(toolboxes) {
|
|
162
210
|
const gates = /* @__PURE__ */ new Map();
|
|
163
211
|
for (const tb of toolboxes) {
|
|
@@ -169,50 +217,50 @@ function compileHitlGates(toolboxes) {
|
|
|
169
217
|
}
|
|
170
218
|
return gates;
|
|
171
219
|
}
|
|
220
|
+
__name(compileHitlGates, "compileHitlGates");
|
|
172
221
|
function compileTools(toolboxes, toolboxInstances) {
|
|
173
222
|
const tools = [];
|
|
174
223
|
for (const tb of toolboxes) {
|
|
175
224
|
const instance = toolboxInstances.get(tb.class);
|
|
176
225
|
if (!instance) {
|
|
177
|
-
throw new ConfigurationError(
|
|
178
|
-
`toolbox: ${tb.class.name} was not instantiated \u2014 pass the instance in \`toolboxInstances\``
|
|
179
|
-
);
|
|
226
|
+
throw new ConfigurationError(`toolbox: ${tb.class.name} was not instantiated \u2014 pass the instance in \`toolboxInstances\``);
|
|
180
227
|
}
|
|
181
228
|
for (const tool of tb.tools) {
|
|
182
229
|
const handler = instance[tool.propertyKey];
|
|
183
230
|
if (typeof handler !== "function") {
|
|
184
|
-
throw new ConfigurationError(
|
|
185
|
-
`toolbox: ${tb.class.name}.${String(tool.propertyKey)} is not a method (tool "${tool.config.name}")`
|
|
186
|
-
);
|
|
231
|
+
throw new ConfigurationError(`toolbox: ${tb.class.name}.${String(tool.propertyKey)} is not a method (tool "${tool.config.name}")`);
|
|
187
232
|
}
|
|
188
233
|
const name = toolRuntimeName(tb.namespace, tool.config.name);
|
|
189
234
|
tools.push({
|
|
190
235
|
name,
|
|
191
236
|
description: tool.config.description,
|
|
192
237
|
inputSchema: tool.config.input,
|
|
193
|
-
handler: (input) => handler.call(instance, input)
|
|
238
|
+
handler: /* @__PURE__ */ __name((input) => handler.call(instance, input), "handler")
|
|
194
239
|
});
|
|
195
240
|
}
|
|
196
241
|
}
|
|
197
242
|
return tools;
|
|
198
243
|
}
|
|
244
|
+
__name(compileTools, "compileTools");
|
|
199
245
|
|
|
200
246
|
// src/bridge/agent-execution-context.ts
|
|
201
247
|
function createAgentExecutionContext(base, agent, run, toolCall) {
|
|
202
248
|
return {
|
|
203
|
-
getRequest: () => base.getRequest(),
|
|
204
|
-
getUrl: () => base.getUrl(),
|
|
205
|
-
getClass: () => base.getClass(),
|
|
206
|
-
getMethodName: () => base.getMethodName(),
|
|
207
|
-
getAgent: () => agent,
|
|
208
|
-
getRun: () => run,
|
|
209
|
-
getToolCall: () => toolCall ?? null,
|
|
210
|
-
isAgentContext: () => true
|
|
249
|
+
getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
|
|
250
|
+
getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
|
|
251
|
+
getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
|
|
252
|
+
getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
|
|
253
|
+
getAgent: /* @__PURE__ */ __name(() => agent, "getAgent"),
|
|
254
|
+
getRun: /* @__PURE__ */ __name(() => run, "getRun"),
|
|
255
|
+
getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
|
|
256
|
+
isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
|
|
211
257
|
};
|
|
212
258
|
}
|
|
259
|
+
__name(createAgentExecutionContext, "createAgentExecutionContext");
|
|
213
260
|
function isAgentContext(ctx) {
|
|
214
261
|
return "isAgentContext" in ctx && ctx.isAgentContext();
|
|
215
262
|
}
|
|
263
|
+
__name(isAgentContext, "isAgentContext");
|
|
216
264
|
|
|
217
265
|
// src/bridge/compile-project-context.ts
|
|
218
266
|
var UNMAPPED_KNOBS = [
|
|
@@ -226,6 +274,7 @@ function projectContextMetadataOnlyKnobs(options) {
|
|
|
226
274
|
const opts = options;
|
|
227
275
|
return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== void 0);
|
|
228
276
|
}
|
|
277
|
+
__name(projectContextMetadataOnlyKnobs, "projectContextMetadataOnlyKnobs");
|
|
229
278
|
function compileProjectContext(options, base) {
|
|
230
279
|
return async (promptCtx) => {
|
|
231
280
|
const resolvedBase = typeof base === "function" ? await base(promptCtx) : base;
|
|
@@ -236,16 +285,24 @@ function compileProjectContext(options, base) {
|
|
|
236
285
|
const { buildEnvContext, buildRepoMap } = await import("@theokit/sdk-tools");
|
|
237
286
|
const { readProjectInstructions } = await import("@theokit/sdk/project");
|
|
238
287
|
const env = buildEnvContext(cwd);
|
|
239
|
-
const repoMap = buildRepoMap(cwd, {
|
|
288
|
+
const repoMap = buildRepoMap(cwd, {
|
|
289
|
+
ignore: options.ignorePatterns
|
|
290
|
+
});
|
|
240
291
|
let instructions = "";
|
|
241
292
|
try {
|
|
242
293
|
instructions = (await readProjectInstructions(cwd)).content ?? "";
|
|
243
294
|
} catch {
|
|
244
295
|
instructions = "";
|
|
245
296
|
}
|
|
246
|
-
return [
|
|
297
|
+
return [
|
|
298
|
+
env,
|
|
299
|
+
repoMap,
|
|
300
|
+
instructions,
|
|
301
|
+
resolvedBase
|
|
302
|
+
].filter(Boolean).join("\n\n");
|
|
247
303
|
};
|
|
248
304
|
}
|
|
305
|
+
__name(compileProjectContext, "compileProjectContext");
|
|
249
306
|
|
|
250
307
|
// src/bridge/agent-sse-handler.ts
|
|
251
308
|
var encoder = new TextEncoder();
|
|
@@ -253,14 +310,14 @@ function streamAgentResponse(eventStream) {
|
|
|
253
310
|
const stream = new ReadableStream({
|
|
254
311
|
async start(controller) {
|
|
255
312
|
let closed = false;
|
|
256
|
-
const safeEnqueue = (chunk) => {
|
|
313
|
+
const safeEnqueue = /* @__PURE__ */ __name((chunk) => {
|
|
257
314
|
if (closed) return;
|
|
258
315
|
try {
|
|
259
316
|
controller.enqueue(chunk);
|
|
260
317
|
} catch {
|
|
261
318
|
closed = true;
|
|
262
319
|
}
|
|
263
|
-
};
|
|
320
|
+
}, "safeEnqueue");
|
|
264
321
|
try {
|
|
265
322
|
for await (const event of eventStream) {
|
|
266
323
|
if (closed) break;
|
|
@@ -275,7 +332,9 @@ data: ${data}
|
|
|
275
332
|
if (!closed) {
|
|
276
333
|
const errorEvent = {
|
|
277
334
|
type: "error",
|
|
278
|
-
error: {
|
|
335
|
+
error: {
|
|
336
|
+
message: err instanceof Error ? err.message : "Internal agent error"
|
|
337
|
+
}
|
|
279
338
|
};
|
|
280
339
|
const frame = `event: error
|
|
281
340
|
data: ${JSON.stringify(errorEvent)}
|
|
@@ -297,29 +356,37 @@ data: ${JSON.stringify(errorEvent)}
|
|
|
297
356
|
}
|
|
298
357
|
});
|
|
299
358
|
}
|
|
359
|
+
__name(streamAgentResponse, "streamAgentResponse");
|
|
300
360
|
|
|
301
361
|
// src/bridge/agent-stream-events.ts
|
|
302
362
|
function isTextDelta(e) {
|
|
303
363
|
return e.type === "text_delta";
|
|
304
364
|
}
|
|
365
|
+
__name(isTextDelta, "isTextDelta");
|
|
305
366
|
function isToolCall(e) {
|
|
306
367
|
return e.type === "tool_call";
|
|
307
368
|
}
|
|
369
|
+
__name(isToolCall, "isToolCall");
|
|
308
370
|
function isPartialToolCall(e) {
|
|
309
371
|
return e.type === "partial_tool_call";
|
|
310
372
|
}
|
|
373
|
+
__name(isPartialToolCall, "isPartialToolCall");
|
|
311
374
|
function isToolResult(e) {
|
|
312
375
|
return e.type === "tool_result";
|
|
313
376
|
}
|
|
377
|
+
__name(isToolResult, "isToolResult");
|
|
314
378
|
function isDone(e) {
|
|
315
379
|
return e.type === "done";
|
|
316
380
|
}
|
|
381
|
+
__name(isDone, "isDone");
|
|
317
382
|
function isError(e) {
|
|
318
383
|
return e.type === "error";
|
|
319
384
|
}
|
|
385
|
+
__name(isError, "isError");
|
|
320
386
|
function isApprovalRequired(e) {
|
|
321
387
|
return e.type === "approval_required";
|
|
322
388
|
}
|
|
389
|
+
__name(isApprovalRequired, "isApprovalRequired");
|
|
323
390
|
|
|
324
391
|
// src/bridge/agent-route-generator.ts
|
|
325
392
|
function generateAgentRoutes(ctx) {
|
|
@@ -329,7 +396,7 @@ function generateAgentRoutes(ctx) {
|
|
|
329
396
|
routes.push({
|
|
330
397
|
method: "POST",
|
|
331
398
|
path: `${basePath}/chat`,
|
|
332
|
-
handler: async (request) => {
|
|
399
|
+
handler: /* @__PURE__ */ __name(async (request) => {
|
|
333
400
|
let body = null;
|
|
334
401
|
try {
|
|
335
402
|
body = await request.json();
|
|
@@ -337,75 +404,92 @@ function generateAgentRoutes(ctx) {
|
|
|
337
404
|
}
|
|
338
405
|
const message = body?.message;
|
|
339
406
|
if (typeof message !== "string" || message.length === 0) {
|
|
340
|
-
return new Response(
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
407
|
+
return new Response(JSON.stringify({
|
|
408
|
+
error: {
|
|
409
|
+
code: "BAD_REQUEST",
|
|
410
|
+
message: "message field required"
|
|
411
|
+
}
|
|
412
|
+
}), {
|
|
413
|
+
status: 400,
|
|
414
|
+
headers: {
|
|
415
|
+
"content-type": "application/json"
|
|
416
|
+
}
|
|
417
|
+
});
|
|
344
418
|
}
|
|
345
419
|
const rawSessionId = body?.sessionId;
|
|
346
420
|
const sessionId = typeof rawSessionId === "string" ? rawSessionId : `session-${Date.now()}`;
|
|
347
421
|
return streamAgentResponse(createRun(message, sessionId));
|
|
348
|
-
}
|
|
422
|
+
}, "handler")
|
|
349
423
|
});
|
|
350
424
|
if (getRun) {
|
|
351
425
|
routes.push({
|
|
352
426
|
method: "GET",
|
|
353
427
|
path: `${basePath}/runs/:runId`,
|
|
354
|
-
handler: async (request) => {
|
|
428
|
+
handler: /* @__PURE__ */ __name(async (request) => {
|
|
355
429
|
const url = new URL(request.url);
|
|
356
430
|
const runId = url.pathname.split("/").pop() ?? "";
|
|
357
431
|
const run = await getRun(runId);
|
|
358
432
|
if (!run) {
|
|
359
|
-
return new Response(
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
433
|
+
return new Response(JSON.stringify({
|
|
434
|
+
error: {
|
|
435
|
+
code: "NOT_FOUND",
|
|
436
|
+
message: `Run ${runId} not found`
|
|
437
|
+
}
|
|
438
|
+
}), {
|
|
439
|
+
status: 404,
|
|
440
|
+
headers: {
|
|
441
|
+
"content-type": "application/json"
|
|
442
|
+
}
|
|
443
|
+
});
|
|
363
444
|
}
|
|
364
445
|
return new Response(JSON.stringify(run), {
|
|
365
446
|
status: 200,
|
|
366
|
-
headers: {
|
|
447
|
+
headers: {
|
|
448
|
+
"content-type": "application/json"
|
|
449
|
+
}
|
|
367
450
|
});
|
|
368
|
-
}
|
|
451
|
+
}, "handler")
|
|
369
452
|
});
|
|
370
453
|
}
|
|
371
454
|
return routes;
|
|
372
455
|
}
|
|
456
|
+
__name(generateAgentRoutes, "generateAgentRoutes");
|
|
373
457
|
|
|
374
458
|
// src/guardrails/types.ts
|
|
375
459
|
var GuardrailViolationError = class extends Error {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
this.guardName = guardName;
|
|
379
|
-
this.phase = phase;
|
|
380
|
-
this.reason = reason;
|
|
381
|
-
this.name = "GuardrailViolationError";
|
|
460
|
+
static {
|
|
461
|
+
__name(this, "GuardrailViolationError");
|
|
382
462
|
}
|
|
383
463
|
guardName;
|
|
384
464
|
phase;
|
|
385
465
|
reason;
|
|
466
|
+
constructor(guardName, phase, reason) {
|
|
467
|
+
super(`Guardrail "${guardName}" blocked ${phase}: ${reason}`), this.guardName = guardName, this.phase = phase, this.reason = reason;
|
|
468
|
+
this.name = "GuardrailViolationError";
|
|
469
|
+
}
|
|
386
470
|
};
|
|
387
471
|
var CostBudgetExceededError = class extends Error {
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
this.usedTokens = usedTokens;
|
|
391
|
-
this.maxTokens = maxTokens;
|
|
392
|
-
this.name = "CostBudgetExceededError";
|
|
472
|
+
static {
|
|
473
|
+
__name(this, "CostBudgetExceededError");
|
|
393
474
|
}
|
|
394
475
|
usedTokens;
|
|
395
476
|
maxTokens;
|
|
477
|
+
constructor(usedTokens, maxTokens) {
|
|
478
|
+
super(`Cost budget exceeded: ${usedTokens} > ${maxTokens} tokens`), this.usedTokens = usedTokens, this.maxTokens = maxTokens;
|
|
479
|
+
this.name = "CostBudgetExceededError";
|
|
480
|
+
}
|
|
396
481
|
};
|
|
397
482
|
|
|
398
483
|
// src/guardrails/detectors.ts
|
|
399
484
|
function estimateTokens(text) {
|
|
400
485
|
return Math.ceil(text.length / 4);
|
|
401
486
|
}
|
|
487
|
+
__name(estimateTokens, "estimateTokens");
|
|
402
488
|
var INJECTION_PHRASES = [
|
|
403
489
|
"previous instructions",
|
|
404
|
-
// "ignore/disregard [all|the] previous instructions"
|
|
405
490
|
"disregard the above",
|
|
406
491
|
"you are now dan",
|
|
407
492
|
"system prompt",
|
|
408
|
-
// "reveal your/the system prompt"
|
|
409
493
|
"no restrictions",
|
|
410
494
|
"without restrictions",
|
|
411
495
|
"no rules",
|
|
@@ -414,21 +498,31 @@ var INJECTION_PHRASES = [
|
|
|
414
498
|
function normalizeForMatch(text) {
|
|
415
499
|
return text.toLowerCase().replace(/\s+/g, " ");
|
|
416
500
|
}
|
|
501
|
+
__name(normalizeForMatch, "normalizeForMatch");
|
|
417
502
|
function promptInjectionDetector(options = {}) {
|
|
418
|
-
const phrases = [
|
|
503
|
+
const phrases = [
|
|
504
|
+
...INJECTION_PHRASES,
|
|
505
|
+
...(options.extra ?? []).map((p) => p.toLowerCase())
|
|
506
|
+
];
|
|
419
507
|
return {
|
|
420
508
|
name: "prompt-injection",
|
|
421
509
|
checkInput(text) {
|
|
422
510
|
const normalized = normalizeForMatch(text);
|
|
423
511
|
for (const phrase of phrases) {
|
|
424
512
|
if (normalized.includes(phrase)) {
|
|
425
|
-
return {
|
|
513
|
+
return {
|
|
514
|
+
action: "block",
|
|
515
|
+
reason: `prompt injection phrase matched: "${phrase}"`
|
|
516
|
+
};
|
|
426
517
|
}
|
|
427
518
|
}
|
|
428
|
-
return {
|
|
519
|
+
return {
|
|
520
|
+
action: "allow"
|
|
521
|
+
};
|
|
429
522
|
}
|
|
430
523
|
};
|
|
431
524
|
}
|
|
525
|
+
__name(promptInjectionDetector, "promptInjectionDetector");
|
|
432
526
|
var CPF = /\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g;
|
|
433
527
|
var EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
|
|
434
528
|
var PHONE = /\+?\d[\d\s()-]{7,13}\d/g;
|
|
@@ -441,22 +535,36 @@ function piiDetector(options = {}) {
|
|
|
441
535
|
redacted = redacted.replace(EMAIL, placeholder);
|
|
442
536
|
redacted = redacted.replace(CPF, placeholder);
|
|
443
537
|
redacted = redacted.replace(PHONE, placeholder);
|
|
444
|
-
if (redacted === text) return {
|
|
445
|
-
|
|
538
|
+
if (redacted === text) return {
|
|
539
|
+
action: "allow"
|
|
540
|
+
};
|
|
541
|
+
return {
|
|
542
|
+
action: "redact",
|
|
543
|
+
text: redacted,
|
|
544
|
+
reason: "PII detected and redacted"
|
|
545
|
+
};
|
|
446
546
|
}
|
|
447
547
|
};
|
|
448
548
|
}
|
|
549
|
+
__name(piiDetector, "piiDetector");
|
|
449
550
|
var OBFUSCATION_CHARS = /[\u200B-\u200D\uFEFF\u202A-\u202E\u2066-\u2069]/g;
|
|
450
551
|
function unicodeNormalizer() {
|
|
451
552
|
return {
|
|
452
553
|
name: "unicode-normalizer",
|
|
453
554
|
checkInput(text) {
|
|
454
555
|
const cleaned = text.normalize("NFKC").replace(OBFUSCATION_CHARS, "");
|
|
455
|
-
if (cleaned === text) return {
|
|
456
|
-
|
|
556
|
+
if (cleaned === text) return {
|
|
557
|
+
action: "allow"
|
|
558
|
+
};
|
|
559
|
+
return {
|
|
560
|
+
action: "redact",
|
|
561
|
+
text: cleaned,
|
|
562
|
+
reason: "obfuscation characters normalized"
|
|
563
|
+
};
|
|
457
564
|
}
|
|
458
565
|
};
|
|
459
566
|
}
|
|
567
|
+
__name(unicodeNormalizer, "unicodeNormalizer");
|
|
460
568
|
function costGuard(options) {
|
|
461
569
|
let used = 0;
|
|
462
570
|
return {
|
|
@@ -468,19 +576,28 @@ function costGuard(options) {
|
|
|
468
576
|
if (used > options.maxTokens) {
|
|
469
577
|
return Promise.reject(new CostBudgetExceededError(used, options.maxTokens));
|
|
470
578
|
}
|
|
471
|
-
return Promise.resolve({
|
|
579
|
+
return Promise.resolve({
|
|
580
|
+
action: "allow"
|
|
581
|
+
});
|
|
472
582
|
}
|
|
473
583
|
};
|
|
474
584
|
}
|
|
585
|
+
__name(costGuard, "costGuard");
|
|
475
586
|
function outputModeration(options) {
|
|
476
587
|
return {
|
|
477
588
|
name: "output-moderation",
|
|
478
589
|
async checkOutput(text) {
|
|
479
590
|
const flagged = await options.moderate(text);
|
|
480
|
-
return flagged ? {
|
|
591
|
+
return flagged ? {
|
|
592
|
+
action: "block",
|
|
593
|
+
reason: "output flagged by moderation predicate"
|
|
594
|
+
} : {
|
|
595
|
+
action: "allow"
|
|
596
|
+
};
|
|
481
597
|
}
|
|
482
598
|
};
|
|
483
599
|
}
|
|
600
|
+
__name(outputModeration, "outputModeration");
|
|
484
601
|
|
|
485
602
|
// src/guardrails/pipeline.ts
|
|
486
603
|
async function runInputGuards(text, guards) {
|
|
@@ -495,6 +612,7 @@ async function runInputGuards(text, guards) {
|
|
|
495
612
|
}
|
|
496
613
|
return current;
|
|
497
614
|
}
|
|
615
|
+
__name(runInputGuards, "runInputGuards");
|
|
498
616
|
async function runOutputGuards(text, guards) {
|
|
499
617
|
let current = text;
|
|
500
618
|
for (const g of guards) {
|
|
@@ -507,6 +625,7 @@ async function runOutputGuards(text, guards) {
|
|
|
507
625
|
}
|
|
508
626
|
return current;
|
|
509
627
|
}
|
|
628
|
+
__name(runOutputGuards, "runOutputGuards");
|
|
510
629
|
|
|
511
630
|
// src/guardrails/stream.ts
|
|
512
631
|
async function* moderateOutputStream(inner, guards, extractText) {
|
|
@@ -526,6 +645,7 @@ async function* moderateOutputStream(inner, guards, extractText) {
|
|
|
526
645
|
for (const event of buffered) yield event;
|
|
527
646
|
return step.value;
|
|
528
647
|
}
|
|
648
|
+
__name(moderateOutputStream, "moderateOutputStream");
|
|
529
649
|
|
|
530
650
|
// src/bridge/tool-hooks-plugin.ts
|
|
531
651
|
function createToolHooksPlugin(hooks) {
|
|
@@ -538,22 +658,30 @@ function createToolHooksPlugin(hooks) {
|
|
|
538
658
|
register(ctx) {
|
|
539
659
|
const { beforeToolCall, afterToolCall, beforeLLMCall, afterLLMCall, processInput } = hooks;
|
|
540
660
|
if (beforeToolCall) {
|
|
541
|
-
ctx.on("pre_tool_call", (c) => beforeToolCall({
|
|
661
|
+
ctx.on("pre_tool_call", (c) => beforeToolCall({
|
|
662
|
+
name: c.name ?? "",
|
|
663
|
+
args: c.args ?? {}
|
|
664
|
+
}));
|
|
542
665
|
}
|
|
543
666
|
if (afterToolCall) {
|
|
544
|
-
ctx.on("post_tool_call", (c) => afterToolCall({
|
|
667
|
+
ctx.on("post_tool_call", (c) => afterToolCall({
|
|
668
|
+
name: c.name ?? "",
|
|
669
|
+
result: c.result
|
|
670
|
+
}));
|
|
545
671
|
}
|
|
546
672
|
if (beforeLLMCall) {
|
|
547
|
-
ctx.on(
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
673
|
+
ctx.on("pre_llm_call", (c) => beforeLLMCall({
|
|
674
|
+
agentId: c.agentId,
|
|
675
|
+
runId: c.runId,
|
|
676
|
+
iteration: c.iteration
|
|
677
|
+
}));
|
|
551
678
|
}
|
|
552
679
|
if (afterLLMCall) {
|
|
553
|
-
ctx.on(
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
680
|
+
ctx.on("post_llm_call", (c) => afterLLMCall({
|
|
681
|
+
agentId: c.agentId,
|
|
682
|
+
runId: c.runId,
|
|
683
|
+
iteration: c.iteration
|
|
684
|
+
}));
|
|
557
685
|
}
|
|
558
686
|
if (processInput) {
|
|
559
687
|
ctx.on("pre_user_send", async (c) => {
|
|
@@ -562,30 +690,49 @@ function createToolHooksPlugin(hooks) {
|
|
|
562
690
|
agentId: c.agentId,
|
|
563
691
|
runId: c.runId
|
|
564
692
|
});
|
|
565
|
-
return injected !== void 0 && injected.length > 0 ? {
|
|
693
|
+
return injected !== void 0 && injected.length > 0 ? {
|
|
694
|
+
recalledContext: injected
|
|
695
|
+
} : void 0;
|
|
566
696
|
});
|
|
567
697
|
}
|
|
568
698
|
}
|
|
569
699
|
};
|
|
570
700
|
}
|
|
701
|
+
__name(createToolHooksPlugin, "createToolHooksPlugin");
|
|
571
702
|
|
|
572
703
|
// src/bridge/model-selection.ts
|
|
573
704
|
var PARAM_THINKING = "thinking";
|
|
574
705
|
function buildModelSelection(model, effort) {
|
|
575
|
-
const base = typeof model === "string" ? {
|
|
706
|
+
const base = typeof model === "string" ? {
|
|
707
|
+
id: model
|
|
708
|
+
} : {
|
|
709
|
+
...model
|
|
710
|
+
};
|
|
576
711
|
if (!effort) return base;
|
|
577
|
-
return {
|
|
712
|
+
return {
|
|
713
|
+
...base,
|
|
714
|
+
params: [
|
|
715
|
+
...base.params ?? [],
|
|
716
|
+
{
|
|
717
|
+
id: PARAM_THINKING,
|
|
718
|
+
value: effort
|
|
719
|
+
}
|
|
720
|
+
]
|
|
721
|
+
};
|
|
578
722
|
}
|
|
723
|
+
__name(buildModelSelection, "buildModelSelection");
|
|
579
724
|
function reasoningEffortOf(model) {
|
|
580
725
|
const params = typeof model === "string" ? void 0 : model.params;
|
|
581
726
|
return params?.find((p) => p.id === PARAM_THINKING)?.value;
|
|
582
727
|
}
|
|
728
|
+
__name(reasoningEffortOf, "reasoningEffortOf");
|
|
583
729
|
|
|
584
730
|
// src/bridge/event-translator.ts
|
|
585
731
|
function asString(value, fallback) {
|
|
586
732
|
if (typeof value === "string") return value;
|
|
587
733
|
return fallback;
|
|
588
734
|
}
|
|
735
|
+
__name(asString, "asString");
|
|
589
736
|
function serializeToolOutput(value, fallback) {
|
|
590
737
|
if (typeof value === "string") return value;
|
|
591
738
|
if (value === void 0 || value === null) return fallback;
|
|
@@ -595,6 +742,7 @@ function serializeToolOutput(value, fallback) {
|
|
|
595
742
|
return typeof value === "bigint" ? value.toString() : fallback;
|
|
596
743
|
}
|
|
597
744
|
}
|
|
745
|
+
__name(serializeToolOutput, "serializeToolOutput");
|
|
598
746
|
function translateSystemEvent(msg, runId) {
|
|
599
747
|
return [
|
|
600
748
|
{
|
|
@@ -605,6 +753,7 @@ function translateSystemEvent(msg, runId) {
|
|
|
605
753
|
}
|
|
606
754
|
];
|
|
607
755
|
}
|
|
756
|
+
__name(translateSystemEvent, "translateSystemEvent");
|
|
608
757
|
function translateAssistantEvent(msg) {
|
|
609
758
|
const events = [];
|
|
610
759
|
const message = msg.message;
|
|
@@ -613,7 +762,10 @@ function translateAssistantEvent(msg) {
|
|
|
613
762
|
for (const block of content) {
|
|
614
763
|
const b = block;
|
|
615
764
|
if (b.type === "text" && b.text) {
|
|
616
|
-
events.push({
|
|
765
|
+
events.push({
|
|
766
|
+
type: "text_delta",
|
|
767
|
+
content: b.text
|
|
768
|
+
});
|
|
617
769
|
}
|
|
618
770
|
if (b.type === "tool_use") {
|
|
619
771
|
events.push({
|
|
@@ -630,6 +782,7 @@ function translateAssistantEvent(msg) {
|
|
|
630
782
|
}
|
|
631
783
|
return events;
|
|
632
784
|
}
|
|
785
|
+
__name(translateAssistantEvent, "translateAssistantEvent");
|
|
633
786
|
function translateToolCallEvent(msg) {
|
|
634
787
|
const status = msg.status;
|
|
635
788
|
const callId = asString(msg.call_id, "");
|
|
@@ -660,11 +813,17 @@ function translateToolCallEvent(msg) {
|
|
|
660
813
|
}
|
|
661
814
|
if (status === "running") {
|
|
662
815
|
return [
|
|
663
|
-
{
|
|
816
|
+
{
|
|
817
|
+
type: "tool_call",
|
|
818
|
+
callId,
|
|
819
|
+
toolName,
|
|
820
|
+
input: msg.args ?? msg.input ?? msg.arguments ?? {}
|
|
821
|
+
}
|
|
664
822
|
];
|
|
665
823
|
}
|
|
666
824
|
return [];
|
|
667
825
|
}
|
|
826
|
+
__name(translateToolCallEvent, "translateToolCallEvent");
|
|
668
827
|
function translateStatusEvent(msg) {
|
|
669
828
|
const s = msg.status;
|
|
670
829
|
if (s === "FINISHED" || s === "CANCELLED") {
|
|
@@ -672,7 +831,11 @@ function translateStatusEvent(msg) {
|
|
|
672
831
|
{
|
|
673
832
|
type: "done",
|
|
674
833
|
result: "",
|
|
675
|
-
usage: {
|
|
834
|
+
usage: {
|
|
835
|
+
inputTokens: 0,
|
|
836
|
+
outputTokens: 0,
|
|
837
|
+
totalTokens: 0
|
|
838
|
+
},
|
|
676
839
|
durationMs: 0,
|
|
677
840
|
cost: 0
|
|
678
841
|
}
|
|
@@ -690,15 +853,17 @@ function translateStatusEvent(msg) {
|
|
|
690
853
|
}
|
|
691
854
|
return [];
|
|
692
855
|
}
|
|
856
|
+
__name(translateStatusEvent, "translateStatusEvent");
|
|
693
857
|
var alreadyWarned = /* @__PURE__ */ new Set();
|
|
694
858
|
function warnIfUnknown(type, deliberatelyIgnored) {
|
|
695
859
|
if (deliberatelyIgnored.has(type) || alreadyWarned.has(type)) return;
|
|
696
860
|
alreadyWarned.add(type);
|
|
697
|
-
console.warn(
|
|
698
|
-
`[theokit] agents.bridge: SDK event "${type}" is not translated and was discarded. If it carries information the UI needs, the translator needs a case for it (#141).`
|
|
699
|
-
);
|
|
861
|
+
console.warn(`[theokit] agents.bridge: SDK event "${type}" is not translated and was discarded. If it carries information the UI needs, the translator needs a case for it (#141).`);
|
|
700
862
|
}
|
|
701
|
-
|
|
863
|
+
__name(warnIfUnknown, "warnIfUnknown");
|
|
864
|
+
var SDK_MESSAGE_IGNORED = /* @__PURE__ */ new Set([
|
|
865
|
+
"user"
|
|
866
|
+
]);
|
|
702
867
|
var INTERACTION_UPDATE_IGNORED = /* @__PURE__ */ new Set([
|
|
703
868
|
"thinking-completed",
|
|
704
869
|
"token-delta",
|
|
@@ -714,11 +879,21 @@ function translateSdkEvent(msg, runId) {
|
|
|
714
879
|
case "tool_call":
|
|
715
880
|
return translateToolCallEvent(msg);
|
|
716
881
|
case "thinking":
|
|
717
|
-
return [
|
|
882
|
+
return [
|
|
883
|
+
{
|
|
884
|
+
type: "thinking",
|
|
885
|
+
content: asString(msg.text, "")
|
|
886
|
+
}
|
|
887
|
+
];
|
|
718
888
|
case "status":
|
|
719
889
|
return translateStatusEvent(msg);
|
|
720
890
|
case "request":
|
|
721
|
-
return [
|
|
891
|
+
return [
|
|
892
|
+
{
|
|
893
|
+
type: "input_requested",
|
|
894
|
+
requestId: asString(msg.request_id, "")
|
|
895
|
+
}
|
|
896
|
+
];
|
|
722
897
|
case "task": {
|
|
723
898
|
const status = typeof msg.status === "string" ? msg.status : void 0;
|
|
724
899
|
const text = typeof msg.text === "string" ? msg.text : void 0;
|
|
@@ -726,8 +901,12 @@ function translateSdkEvent(msg, runId) {
|
|
|
726
901
|
return [
|
|
727
902
|
{
|
|
728
903
|
type: "task_progress",
|
|
729
|
-
...status !== void 0 ? {
|
|
730
|
-
|
|
904
|
+
...status !== void 0 ? {
|
|
905
|
+
status
|
|
906
|
+
} : {},
|
|
907
|
+
...text !== void 0 ? {
|
|
908
|
+
text
|
|
909
|
+
} : {}
|
|
731
910
|
}
|
|
732
911
|
];
|
|
733
912
|
}
|
|
@@ -736,12 +915,23 @@ function translateSdkEvent(msg, runId) {
|
|
|
736
915
|
return [];
|
|
737
916
|
}
|
|
738
917
|
}
|
|
918
|
+
__name(translateSdkEvent, "translateSdkEvent");
|
|
739
919
|
function translateInteractionUpdate(update) {
|
|
740
920
|
switch (update.type) {
|
|
741
921
|
case "text-delta":
|
|
742
|
-
return update.text ? [
|
|
922
|
+
return update.text ? [
|
|
923
|
+
{
|
|
924
|
+
type: "text_delta",
|
|
925
|
+
content: update.text
|
|
926
|
+
}
|
|
927
|
+
] : [];
|
|
743
928
|
case "thinking-delta":
|
|
744
|
-
return update.text ? [
|
|
929
|
+
return update.text ? [
|
|
930
|
+
{
|
|
931
|
+
type: "thinking",
|
|
932
|
+
content: update.text
|
|
933
|
+
}
|
|
934
|
+
] : [];
|
|
745
935
|
case "tool-call-started":
|
|
746
936
|
return [
|
|
747
937
|
{
|
|
@@ -772,12 +962,18 @@ function translateInteractionUpdate(update) {
|
|
|
772
962
|
}
|
|
773
963
|
];
|
|
774
964
|
case "shell-output-delta":
|
|
775
|
-
return [
|
|
965
|
+
return [
|
|
966
|
+
{
|
|
967
|
+
type: "shell_output",
|
|
968
|
+
event: update.event
|
|
969
|
+
}
|
|
970
|
+
];
|
|
776
971
|
default:
|
|
777
972
|
warnIfUnknown(update.type, INTERACTION_UPDATE_IGNORED);
|
|
778
973
|
return [];
|
|
779
974
|
}
|
|
780
975
|
}
|
|
976
|
+
__name(translateInteractionUpdate, "translateInteractionUpdate");
|
|
781
977
|
|
|
782
978
|
// src/bridge/think-tag-extractor.ts
|
|
783
979
|
var TAG = "think";
|
|
@@ -790,10 +986,11 @@ function heldPrefixLength(s, delim) {
|
|
|
790
986
|
}
|
|
791
987
|
return 0;
|
|
792
988
|
}
|
|
989
|
+
__name(heldPrefixLength, "heldPrefixLength");
|
|
793
990
|
function createThinkTagExtractor() {
|
|
794
991
|
let mode = "text";
|
|
795
992
|
let buffer = "";
|
|
796
|
-
const write = (chunk) => {
|
|
993
|
+
const write = /* @__PURE__ */ __name((chunk) => {
|
|
797
994
|
buffer += chunk;
|
|
798
995
|
const out = [];
|
|
799
996
|
for (; ; ) {
|
|
@@ -801,30 +998,52 @@ function createThinkTagExtractor() {
|
|
|
801
998
|
const idx = buffer.indexOf(delim);
|
|
802
999
|
if (idx !== -1) {
|
|
803
1000
|
const content = buffer.slice(0, idx);
|
|
804
|
-
if (content) out.push({
|
|
1001
|
+
if (content) out.push({
|
|
1002
|
+
kind: mode,
|
|
1003
|
+
content
|
|
1004
|
+
});
|
|
805
1005
|
buffer = buffer.slice(idx + delim.length);
|
|
806
1006
|
mode = mode === "text" ? "thinking" : "text";
|
|
807
1007
|
continue;
|
|
808
1008
|
}
|
|
809
1009
|
const keep = heldPrefixLength(buffer, delim);
|
|
810
1010
|
const emit = buffer.slice(0, buffer.length - keep);
|
|
811
|
-
if (emit) out.push({
|
|
1011
|
+
if (emit) out.push({
|
|
1012
|
+
kind: mode,
|
|
1013
|
+
content: emit
|
|
1014
|
+
});
|
|
812
1015
|
buffer = buffer.slice(buffer.length - keep);
|
|
813
1016
|
break;
|
|
814
1017
|
}
|
|
815
1018
|
return out;
|
|
816
|
-
};
|
|
817
|
-
const end = () => {
|
|
1019
|
+
}, "write");
|
|
1020
|
+
const end = /* @__PURE__ */ __name(() => {
|
|
818
1021
|
if (!buffer) return [];
|
|
819
|
-
const seg = {
|
|
1022
|
+
const seg = {
|
|
1023
|
+
kind: mode,
|
|
1024
|
+
content: buffer
|
|
1025
|
+
};
|
|
820
1026
|
buffer = "";
|
|
821
|
-
return [
|
|
1027
|
+
return [
|
|
1028
|
+
seg
|
|
1029
|
+
];
|
|
1030
|
+
}, "end");
|
|
1031
|
+
return {
|
|
1032
|
+
write,
|
|
1033
|
+
end
|
|
822
1034
|
};
|
|
823
|
-
return { write, end };
|
|
824
1035
|
}
|
|
1036
|
+
__name(createThinkTagExtractor, "createThinkTagExtractor");
|
|
825
1037
|
function segmentToEvent(seg) {
|
|
826
|
-
return seg.kind === "thinking" ? {
|
|
1038
|
+
return seg.kind === "thinking" ? {
|
|
1039
|
+
type: "thinking",
|
|
1040
|
+
content: seg.content
|
|
1041
|
+
} : {
|
|
1042
|
+
type: "text_delta",
|
|
1043
|
+
content: seg.content
|
|
1044
|
+
};
|
|
827
1045
|
}
|
|
1046
|
+
__name(segmentToEvent, "segmentToEvent");
|
|
828
1047
|
async function* extractThinkTagStream(source) {
|
|
829
1048
|
const extractor = createThinkTagExtractor();
|
|
830
1049
|
try {
|
|
@@ -839,6 +1058,7 @@ async function* extractThinkTagStream(source) {
|
|
|
839
1058
|
for (const seg of extractor.end()) yield segmentToEvent(seg);
|
|
840
1059
|
}
|
|
841
1060
|
}
|
|
1061
|
+
__name(extractThinkTagStream, "extractThinkTagStream");
|
|
842
1062
|
|
|
843
1063
|
// src/debug-log.ts
|
|
844
1064
|
function debugLog(marker, data) {
|
|
@@ -847,6 +1067,7 @@ function debugLog(marker, data) {
|
|
|
847
1067
|
console.debug(marker, data);
|
|
848
1068
|
}
|
|
849
1069
|
}
|
|
1070
|
+
__name(debugLog, "debugLog");
|
|
850
1071
|
|
|
851
1072
|
// src/bridge/hitl-plugin.ts
|
|
852
1073
|
function createHitlPlugin(wiring) {
|
|
@@ -870,37 +1091,48 @@ function createHitlPlugin(wiring) {
|
|
|
870
1091
|
callbackUrl: `approve/${approvalId}`,
|
|
871
1092
|
timeoutMs: opts.timeout ?? 3e5,
|
|
872
1093
|
// M20 — carry the declared custom-payload schema so the UI knows what to collect.
|
|
873
|
-
...opts.payloadSchema !== void 0 ? {
|
|
1094
|
+
...opts.payloadSchema !== void 0 ? {
|
|
1095
|
+
payloadSchema: opts.payloadSchema
|
|
1096
|
+
} : {}
|
|
874
1097
|
});
|
|
875
1098
|
const raw = await wiring.awaitApproval(approvalId, opts, c.name);
|
|
876
|
-
const decision = typeof raw === "boolean" ? {
|
|
1099
|
+
const decision = typeof raw === "boolean" ? {
|
|
1100
|
+
approved: raw
|
|
1101
|
+
} : raw;
|
|
877
1102
|
if (decision.approved) return void 0;
|
|
878
1103
|
let message = `Tool '${c.name}' denied by human approver`;
|
|
879
1104
|
if (decision.reason) message += `: ${decision.reason}`;
|
|
880
1105
|
if (decision.payload !== void 0) {
|
|
881
1106
|
message += ` (payload: ${JSON.stringify(decision.payload)})`;
|
|
882
1107
|
}
|
|
883
|
-
return {
|
|
1108
|
+
return {
|
|
1109
|
+
block: true,
|
|
1110
|
+
message
|
|
1111
|
+
};
|
|
884
1112
|
});
|
|
885
1113
|
}
|
|
886
1114
|
};
|
|
887
1115
|
}
|
|
1116
|
+
__name(createHitlPlugin, "createHitlPlugin");
|
|
888
1117
|
|
|
889
1118
|
// src/bridge/approval-posture.ts
|
|
890
1119
|
function reasonOf(posturePolicy) {
|
|
891
1120
|
return posturePolicy.kind === "interactive" ? "human approver on this surface" : posturePolicy.reason;
|
|
892
1121
|
}
|
|
1122
|
+
__name(reasonOf, "reasonOf");
|
|
893
1123
|
function applyPosture(extra, m8, posturePolicy, gated) {
|
|
894
1124
|
const ofThePosture = posturePlugins(posturePolicy, gated);
|
|
895
1125
|
if (ofThePosture.length === 0) return;
|
|
896
1126
|
const currentOnes = extra.plugins ?? m8.plugins;
|
|
897
1127
|
if (currentOnes !== void 0 && !Array.isArray(currentOnes)) {
|
|
898
|
-
throw new Error(
|
|
899
|
-
`[@theokit/agents] approval posture "${posturePolicy.kind}" needs to install a plugin, but \`plugins\` was supplied in the legacy object form, which cannot carry both. Pass \`plugins\` as an array so the approval gate is not dropped.`
|
|
900
|
-
);
|
|
1128
|
+
throw new Error(`[@theokit/agents] approval posture "${posturePolicy.kind}" needs to install a plugin, but \`plugins\` was supplied in the legacy object form, which cannot carry both. Pass \`plugins\` as an array so the approval gate is not dropped.`);
|
|
901
1129
|
}
|
|
902
|
-
extra.plugins = [
|
|
1130
|
+
extra.plugins = [
|
|
1131
|
+
...currentOnes ?? [],
|
|
1132
|
+
...ofThePosture
|
|
1133
|
+
];
|
|
903
1134
|
}
|
|
1135
|
+
__name(applyPosture, "applyPosture");
|
|
904
1136
|
function posturePlugins(posturePolicy, gated) {
|
|
905
1137
|
debugLog("[theokit] approval posture", {
|
|
906
1138
|
kind: posturePolicy.kind,
|
|
@@ -919,7 +1151,7 @@ function posturePlugins(posturePolicy, gated) {
|
|
|
919
1151
|
case "auto-approve":
|
|
920
1152
|
return [
|
|
921
1153
|
createToolHooksPlugin({
|
|
922
|
-
beforeToolCall: (ctx) => {
|
|
1154
|
+
beforeToolCall: /* @__PURE__ */ __name((ctx) => {
|
|
923
1155
|
if (gated.has(ctx.name)) {
|
|
924
1156
|
debugLog("[theokit] gated tool auto-approved", {
|
|
925
1157
|
tool: ctx.name,
|
|
@@ -927,7 +1159,7 @@ function posturePlugins(posturePolicy, gated) {
|
|
|
927
1159
|
});
|
|
928
1160
|
}
|
|
929
1161
|
return void 0;
|
|
930
|
-
}
|
|
1162
|
+
}, "beforeToolCall")
|
|
931
1163
|
})
|
|
932
1164
|
];
|
|
933
1165
|
case "auto-reject":
|
|
@@ -935,16 +1167,17 @@ function posturePlugins(posturePolicy, gated) {
|
|
|
935
1167
|
createToolHooksPlugin({
|
|
936
1168
|
// Only GATED tools are refused: the posture describes the gate, not a universal block.
|
|
937
1169
|
// Refusing everything would break every agent with a free tool next to a gated one.
|
|
938
|
-
beforeToolCall: (ctx) => gated.has(ctx.name) ? {
|
|
1170
|
+
beforeToolCall: /* @__PURE__ */ __name((ctx) => gated.has(ctx.name) ? {
|
|
939
1171
|
block: true,
|
|
940
1172
|
message: `Tool '${ctx.name}' requires human approval, and this surface has no approver (approval posture: auto-reject \u2014 ${posturePolicy.reason}). Refused (fail-closed).`
|
|
941
|
-
} : void 0
|
|
1173
|
+
} : void 0, "beforeToolCall")
|
|
942
1174
|
})
|
|
943
1175
|
];
|
|
944
1176
|
case "owned-by-surface":
|
|
945
1177
|
return [];
|
|
946
1178
|
}
|
|
947
1179
|
}
|
|
1180
|
+
__name(posturePlugins, "posturePlugins");
|
|
948
1181
|
|
|
949
1182
|
// src/bridge/definition-or-thunk.ts
|
|
950
1183
|
function project(def, overrides) {
|
|
@@ -956,6 +1189,7 @@ function project(def, overrides) {
|
|
|
956
1189
|
runContext: overrides.runContext ?? compiled.runContext
|
|
957
1190
|
};
|
|
958
1191
|
}
|
|
1192
|
+
__name(project, "project");
|
|
959
1193
|
function resolveProjection(def, overrides) {
|
|
960
1194
|
if (typeof def === "function") {
|
|
961
1195
|
return async (sessionId) => project(await def(sessionId), overrides);
|
|
@@ -963,6 +1197,7 @@ function resolveProjection(def, overrides) {
|
|
|
963
1197
|
const eager = project(def, overrides);
|
|
964
1198
|
return () => Promise.resolve(eager);
|
|
965
1199
|
}
|
|
1200
|
+
__name(resolveProjection, "resolveProjection");
|
|
966
1201
|
|
|
967
1202
|
// src/bridge/sdk-adapter-create-options.ts
|
|
968
1203
|
function assembleM8CreateOptions(compiled) {
|
|
@@ -979,7 +1214,10 @@ function assembleM8CreateOptions(compiled) {
|
|
|
979
1214
|
}
|
|
980
1215
|
const settingSources = resolveSettingSources(compiled);
|
|
981
1216
|
if (settingSources) {
|
|
982
|
-
options.local = {
|
|
1217
|
+
options.local = {
|
|
1218
|
+
...options.local,
|
|
1219
|
+
settingSources
|
|
1220
|
+
};
|
|
983
1221
|
applied.push("settingSources");
|
|
984
1222
|
}
|
|
985
1223
|
if (compiled.context) {
|
|
@@ -1002,23 +1240,32 @@ function assembleM8CreateOptions(compiled) {
|
|
|
1002
1240
|
} else {
|
|
1003
1241
|
const dropped = Object.keys(compiled.memory);
|
|
1004
1242
|
if (dropped.length > 0) {
|
|
1005
|
-
process.stderr.write(
|
|
1006
|
-
|
|
1007
|
-
`
|
|
1008
|
-
);
|
|
1243
|
+
process.stderr.write(`[theokit-agents] @Memory decorator options not yet mapped to the SDK (${dropped.join(", ")}) \u2014 memory enabled with defaults
|
|
1244
|
+
`);
|
|
1009
1245
|
}
|
|
1010
|
-
options.memory = {
|
|
1246
|
+
options.memory = {
|
|
1247
|
+
enabled: true
|
|
1248
|
+
};
|
|
1011
1249
|
}
|
|
1012
1250
|
applied.push("memory");
|
|
1013
1251
|
}
|
|
1014
|
-
return {
|
|
1252
|
+
return {
|
|
1253
|
+
options,
|
|
1254
|
+
applied
|
|
1255
|
+
};
|
|
1015
1256
|
}
|
|
1257
|
+
__name(assembleM8CreateOptions, "assembleM8CreateOptions");
|
|
1016
1258
|
function resolveSettingSources(compiled) {
|
|
1017
1259
|
const explicit = compiled.settingSources;
|
|
1018
|
-
if (explicit && explicit.length > 0) return [
|
|
1019
|
-
|
|
1260
|
+
if (explicit && explicit.length > 0) return [
|
|
1261
|
+
...explicit
|
|
1262
|
+
];
|
|
1263
|
+
if (compiled.skills) return [
|
|
1264
|
+
"project"
|
|
1265
|
+
];
|
|
1020
1266
|
return void 0;
|
|
1021
1267
|
}
|
|
1268
|
+
__name(resolveSettingSources, "resolveSettingSources");
|
|
1022
1269
|
function realUsageDone(result, t0) {
|
|
1023
1270
|
const u = result.usage;
|
|
1024
1271
|
const inputTokens = u?.inputTokens ?? 0;
|
|
@@ -1040,6 +1287,7 @@ function realUsageDone(result, t0) {
|
|
|
1040
1287
|
cost: result.cost?.amount ?? 0
|
|
1041
1288
|
};
|
|
1042
1289
|
}
|
|
1290
|
+
__name(realUsageDone, "realUsageDone");
|
|
1043
1291
|
|
|
1044
1292
|
// src/bridge/sdk-error.ts
|
|
1045
1293
|
function sdkErrorEvent(err) {
|
|
@@ -1053,6 +1301,7 @@ function sdkErrorEvent(err) {
|
|
|
1053
1301
|
retryable: sdkErr.isRetryable === true
|
|
1054
1302
|
};
|
|
1055
1303
|
}
|
|
1304
|
+
__name(sdkErrorEvent, "sdkErrorEvent");
|
|
1056
1305
|
|
|
1057
1306
|
// src/bridge/sdk-timeline.ts
|
|
1058
1307
|
function idsOf(e, raw) {
|
|
@@ -1063,11 +1312,13 @@ function idsOf(e, raw) {
|
|
|
1063
1312
|
if (typeof model === "string" && model !== "" && model !== callId) ids.push(model);
|
|
1064
1313
|
return ids;
|
|
1065
1314
|
}
|
|
1315
|
+
__name(idsOf, "idsOf");
|
|
1066
1316
|
function bucketFor(e, seen) {
|
|
1067
1317
|
if (e.type === "tool_call") return seen.started;
|
|
1068
1318
|
if (e.type === "tool_result") return seen.completed;
|
|
1069
1319
|
return void 0;
|
|
1070
1320
|
}
|
|
1321
|
+
__name(bucketFor, "bucketFor");
|
|
1071
1322
|
function dedupeTools(events, raw, seen) {
|
|
1072
1323
|
return events.filter((e) => {
|
|
1073
1324
|
if (e.type === "thinking") {
|
|
@@ -1084,15 +1335,19 @@ function dedupeTools(events, raw, seen) {
|
|
|
1084
1335
|
return true;
|
|
1085
1336
|
});
|
|
1086
1337
|
}
|
|
1338
|
+
__name(dedupeTools, "dedupeTools");
|
|
1087
1339
|
function createToolSeen() {
|
|
1088
|
-
return {
|
|
1340
|
+
return {
|
|
1341
|
+
started: /* @__PURE__ */ new Set(),
|
|
1342
|
+
completed: /* @__PURE__ */ new Set(),
|
|
1343
|
+
sawThinkingDelta: false
|
|
1344
|
+
};
|
|
1089
1345
|
}
|
|
1346
|
+
__name(createToolSeen, "createToolSeen");
|
|
1090
1347
|
function translateTimelineEvent(ev, runId, seen) {
|
|
1091
1348
|
if (ev.kind === "delta") {
|
|
1092
1349
|
if (ev.update === void 0) return [];
|
|
1093
|
-
const events2 = translateInteractionUpdate(
|
|
1094
|
-
ev.update
|
|
1095
|
-
);
|
|
1350
|
+
const events2 = translateInteractionUpdate(ev.update);
|
|
1096
1351
|
return dedupeTools(events2, ev.update, seen);
|
|
1097
1352
|
}
|
|
1098
1353
|
if (ev.message === void 0) return [];
|
|
@@ -1100,6 +1355,7 @@ function translateTimelineEvent(ev, runId, seen) {
|
|
|
1100
1355
|
const kept = ev.textAlreadyStreamed === true ? events.filter((e) => e.type !== "text_delta") : events;
|
|
1101
1356
|
return dedupeTools(kept, ev.message, seen);
|
|
1102
1357
|
}
|
|
1358
|
+
__name(translateTimelineEvent, "translateTimelineEvent");
|
|
1103
1359
|
|
|
1104
1360
|
// src/bridge/tool-dialect-stripper.ts
|
|
1105
1361
|
var OPEN2 = "<function=";
|
|
@@ -1111,11 +1367,12 @@ function heldPrefixLength2(s, delim) {
|
|
|
1111
1367
|
}
|
|
1112
1368
|
return 0;
|
|
1113
1369
|
}
|
|
1370
|
+
__name(heldPrefixLength2, "heldPrefixLength");
|
|
1114
1371
|
function createToolDialectStripper() {
|
|
1115
1372
|
let mode = "text";
|
|
1116
1373
|
let buffer = "";
|
|
1117
1374
|
let pendingLeak = "";
|
|
1118
|
-
const write = (chunk) => {
|
|
1375
|
+
const write = /* @__PURE__ */ __name((chunk) => {
|
|
1119
1376
|
buffer += chunk;
|
|
1120
1377
|
const out = [];
|
|
1121
1378
|
for (; ; ) {
|
|
@@ -1123,7 +1380,10 @@ function createToolDialectStripper() {
|
|
|
1123
1380
|
const idx2 = buffer.indexOf(OPEN2);
|
|
1124
1381
|
if (idx2 !== -1) {
|
|
1125
1382
|
const content = buffer.slice(0, idx2);
|
|
1126
|
-
if (content) out.push({
|
|
1383
|
+
if (content) out.push({
|
|
1384
|
+
kind: "text",
|
|
1385
|
+
content
|
|
1386
|
+
});
|
|
1127
1387
|
pendingLeak = OPEN2;
|
|
1128
1388
|
buffer = buffer.slice(idx2 + OPEN2.length);
|
|
1129
1389
|
mode = "stripping";
|
|
@@ -1131,7 +1391,10 @@ function createToolDialectStripper() {
|
|
|
1131
1391
|
}
|
|
1132
1392
|
const keep2 = heldPrefixLength2(buffer, OPEN2);
|
|
1133
1393
|
const emit = buffer.slice(0, buffer.length - keep2);
|
|
1134
|
-
if (emit) out.push({
|
|
1394
|
+
if (emit) out.push({
|
|
1395
|
+
kind: "text",
|
|
1396
|
+
content: emit
|
|
1397
|
+
});
|
|
1135
1398
|
buffer = buffer.slice(buffer.length - keep2);
|
|
1136
1399
|
break;
|
|
1137
1400
|
}
|
|
@@ -1148,22 +1411,34 @@ function createToolDialectStripper() {
|
|
|
1148
1411
|
break;
|
|
1149
1412
|
}
|
|
1150
1413
|
return out;
|
|
1151
|
-
};
|
|
1152
|
-
const end = () => {
|
|
1414
|
+
}, "write");
|
|
1415
|
+
const end = /* @__PURE__ */ __name(() => {
|
|
1153
1416
|
const leftover = mode === "stripping" ? pendingLeak + buffer : buffer;
|
|
1154
1417
|
buffer = "";
|
|
1155
1418
|
pendingLeak = "";
|
|
1156
|
-
return leftover ? [
|
|
1419
|
+
return leftover ? [
|
|
1420
|
+
{
|
|
1421
|
+
kind: "text",
|
|
1422
|
+
content: leftover
|
|
1423
|
+
}
|
|
1424
|
+
] : [];
|
|
1425
|
+
}, "end");
|
|
1426
|
+
return {
|
|
1427
|
+
write,
|
|
1428
|
+
end
|
|
1157
1429
|
};
|
|
1158
|
-
return { write, end };
|
|
1159
1430
|
}
|
|
1431
|
+
__name(createToolDialectStripper, "createToolDialectStripper");
|
|
1160
1432
|
async function* stripToolDialectStream(source) {
|
|
1161
1433
|
const stripper = createToolDialectStripper();
|
|
1162
1434
|
try {
|
|
1163
1435
|
for await (const event of source) {
|
|
1164
1436
|
if (event.type === "text_delta" && typeof event.content === "string") {
|
|
1165
1437
|
for (const seg of stripper.write(event.content)) {
|
|
1166
|
-
yield {
|
|
1438
|
+
yield {
|
|
1439
|
+
type: "text_delta",
|
|
1440
|
+
content: seg.content
|
|
1441
|
+
};
|
|
1167
1442
|
}
|
|
1168
1443
|
} else {
|
|
1169
1444
|
yield event;
|
|
@@ -1171,26 +1446,37 @@ async function* stripToolDialectStream(source) {
|
|
|
1171
1446
|
}
|
|
1172
1447
|
} finally {
|
|
1173
1448
|
for (const seg of stripper.end()) {
|
|
1174
|
-
yield {
|
|
1449
|
+
yield {
|
|
1450
|
+
type: "text_delta",
|
|
1451
|
+
content: seg.content
|
|
1452
|
+
};
|
|
1175
1453
|
}
|
|
1176
1454
|
}
|
|
1177
1455
|
}
|
|
1456
|
+
__name(stripToolDialectStream, "stripToolDialectStream");
|
|
1178
1457
|
|
|
1179
1458
|
// src/bridge/sdk-adapter.ts
|
|
1180
1459
|
function withLeakedDialectRecovery(providers) {
|
|
1181
1460
|
return {
|
|
1182
1461
|
...providers,
|
|
1183
|
-
routes: providers.routes.map((route) => ({
|
|
1462
|
+
routes: providers.routes.map((route) => ({
|
|
1463
|
+
...route,
|
|
1464
|
+
extractToolCallsFromContent: true
|
|
1465
|
+
}))
|
|
1184
1466
|
};
|
|
1185
1467
|
}
|
|
1468
|
+
__name(withLeakedDialectRecovery, "withLeakedDialectRecovery");
|
|
1186
1469
|
function buildExtraCreateOptions(overrides, compiled) {
|
|
1187
1470
|
const recoverLeakedToolCalls = overrides.recoverLeakedToolCalls ?? compiled.recoverLeakedToolCalls ?? false;
|
|
1188
1471
|
const extra = {};
|
|
1189
1472
|
if (overrides.plugins !== void 0) {
|
|
1190
|
-
const asArray = (v) => Array.isArray(v) ? v : void 0;
|
|
1473
|
+
const asArray = /* @__PURE__ */ __name((v) => Array.isArray(v) ? v : void 0, "asArray");
|
|
1191
1474
|
const overrideList = asArray(overrides.plugins);
|
|
1192
1475
|
const compiledList = asArray(compiled.plugins);
|
|
1193
|
-
extra.plugins = overrideList !== void 0 && compiledList !== void 0 ? [
|
|
1476
|
+
extra.plugins = overrideList !== void 0 && compiledList !== void 0 ? [
|
|
1477
|
+
...compiledList,
|
|
1478
|
+
...overrideList
|
|
1479
|
+
] : overrides.plugins;
|
|
1194
1480
|
}
|
|
1195
1481
|
if (overrides.providers !== void 0) {
|
|
1196
1482
|
extra.providers = recoverLeakedToolCalls ? withLeakedDialectRecovery(overrides.providers) : overrides.providers;
|
|
@@ -1199,6 +1485,7 @@ function buildExtraCreateOptions(overrides, compiled) {
|
|
|
1199
1485
|
if (overrides.budgetTracker !== void 0) extra.budgetTracker = overrides.budgetTracker;
|
|
1200
1486
|
return extra;
|
|
1201
1487
|
}
|
|
1488
|
+
__name(buildExtraCreateOptions, "buildExtraCreateOptions");
|
|
1202
1489
|
async function loadSdkRuntime() {
|
|
1203
1490
|
try {
|
|
1204
1491
|
const sdk = await import("@theokit/sdk");
|
|
@@ -1208,30 +1495,40 @@ async function loadSdkRuntime() {
|
|
|
1208
1495
|
// `.bind` keeps the static factory callable when detached from `sdk.Tool` (it takes no `this`,
|
|
1209
1496
|
// but binding is explicit + satisfies unbound-method rather than relying on that).
|
|
1210
1497
|
defineTool: sdk.Tool.create.bind(sdk.Tool),
|
|
1211
|
-
...skillReadTool ? {
|
|
1498
|
+
...skillReadTool ? {
|
|
1499
|
+
defineSkillReadTool: /* @__PURE__ */ __name((skills) => skillReadTool.create(skills), "defineSkillReadTool")
|
|
1500
|
+
} : {}
|
|
1212
1501
|
};
|
|
1213
1502
|
} catch (err) {
|
|
1214
1503
|
console.warn("[theokit] @theokit/sdk import failed:", err);
|
|
1215
1504
|
return null;
|
|
1216
1505
|
}
|
|
1217
1506
|
}
|
|
1507
|
+
__name(loadSdkRuntime, "loadSdkRuntime");
|
|
1218
1508
|
function resolveTextTransformFlags(compiled, overrides) {
|
|
1219
1509
|
return {
|
|
1220
1510
|
parseThinkTags: overrides.parseThinkTags ?? compiled.parseThinkTags ?? false,
|
|
1221
1511
|
stripToolDialect: overrides.stripToolDialect ?? compiled.stripToolDialect ?? false
|
|
1222
1512
|
};
|
|
1223
1513
|
}
|
|
1514
|
+
__name(resolveTextTransformFlags, "resolveTextTransformFlags");
|
|
1224
1515
|
function applyTextTransforms(events, opts) {
|
|
1225
1516
|
let out = opts.parseThinkTags ? extractThinkTagStream(events) : events;
|
|
1226
1517
|
if (opts.stripToolDialect) out = stripToolDialectStream(out);
|
|
1227
1518
|
return out;
|
|
1228
1519
|
}
|
|
1520
|
+
__name(applyTextTransforms, "applyTextTransforms");
|
|
1229
1521
|
function hasZodInputSchema(schema) {
|
|
1230
1522
|
return typeof schema?.parse === "function";
|
|
1231
1523
|
}
|
|
1524
|
+
__name(hasZodInputSchema, "hasZodInputSchema");
|
|
1232
1525
|
function withRunContext(handler, runContext) {
|
|
1233
|
-
return (input, ctx) => handler(input, {
|
|
1526
|
+
return (input, ctx) => handler(input, {
|
|
1527
|
+
...ctx,
|
|
1528
|
+
context: runContext
|
|
1529
|
+
});
|
|
1234
1530
|
}
|
|
1531
|
+
__name(withRunContext, "withRunContext");
|
|
1235
1532
|
function buildSdkTools(compiledTools, defineTool, extraSdkTools = [], runContext) {
|
|
1236
1533
|
const has = runContext !== void 0;
|
|
1237
1534
|
return [
|
|
@@ -1244,20 +1541,25 @@ function buildSdkTools(compiledTools, defineTool, extraSdkTools = [], runContext
|
|
|
1244
1541
|
handler: has ? withRunContext(t.handler, runContext) : t.handler
|
|
1245
1542
|
});
|
|
1246
1543
|
}
|
|
1247
|
-
return has ? {
|
|
1544
|
+
return has ? {
|
|
1545
|
+
...t,
|
|
1546
|
+
handler: withRunContext(t.handler, runContext)
|
|
1547
|
+
} : t;
|
|
1248
1548
|
}),
|
|
1249
|
-
...extraSdkTools.map(
|
|
1250
|
-
|
|
1251
|
-
|
|
1549
|
+
...extraSdkTools.map((t) => has ? {
|
|
1550
|
+
...t,
|
|
1551
|
+
handler: withRunContext(t.handler, runContext)
|
|
1552
|
+
} : t)
|
|
1252
1553
|
];
|
|
1253
1554
|
}
|
|
1254
|
-
|
|
1555
|
+
__name(buildSdkTools, "buildSdkTools");
|
|
1556
|
+
var resolverApiKey = /* @__PURE__ */ __name(async (k) => typeof k === "function" ? await k() : k, "resolverApiKey");
|
|
1255
1557
|
function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
|
|
1256
1558
|
const model = overrides.model ?? compiled.model ?? "openai/gpt-4o-mini";
|
|
1257
1559
|
const reasoningEffort = overrides.reasoningEffort ?? compiled.reasoningEffort;
|
|
1258
1560
|
const { parseThinkTags, stripToolDialect } = resolveTextTransformFlags(compiled, overrides);
|
|
1259
1561
|
const runContext = overrides.runContext ?? compiled.runContext;
|
|
1260
|
-
const factory = (message, sessionId, factoryOpts) => ({
|
|
1562
|
+
const factory = /* @__PURE__ */ __name((message, sessionId, factoryOpts) => ({
|
|
1261
1563
|
async *[Symbol.asyncIterator]() {
|
|
1262
1564
|
const runId = `run-${Date.now()}`;
|
|
1263
1565
|
const t0 = Date.now();
|
|
@@ -1306,27 +1608,24 @@ function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
|
|
|
1306
1608
|
yield sdkErrorEvent(err);
|
|
1307
1609
|
}
|
|
1308
1610
|
}
|
|
1611
|
+
}), "factory");
|
|
1612
|
+
return Object.assign(factory, {
|
|
1613
|
+
resolvedModel: model
|
|
1309
1614
|
});
|
|
1310
|
-
return Object.assign(factory, { resolvedModel: model });
|
|
1311
1615
|
}
|
|
1616
|
+
__name(createSdkAgentStream, "createSdkAgentStream");
|
|
1312
1617
|
async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
|
|
1313
1618
|
const { Agent } = rt;
|
|
1314
|
-
const {
|
|
1315
|
-
apiKey,
|
|
1316
|
-
model,
|
|
1317
|
-
reasoningEffort,
|
|
1318
|
-
overrides,
|
|
1319
|
-
parseThinkTags,
|
|
1320
|
-
stripToolDialect,
|
|
1321
|
-
sessionId,
|
|
1322
|
-
message,
|
|
1323
|
-
factoryOpts,
|
|
1324
|
-
runId,
|
|
1325
|
-
t0
|
|
1326
|
-
} = opts;
|
|
1619
|
+
const { apiKey, model, reasoningEffort, overrides, parseThinkTags, stripToolDialect, sessionId, message, factoryOpts, runId, t0 } = opts;
|
|
1327
1620
|
const { options: m8, applied } = assembleM8CreateOptions(compiled);
|
|
1328
|
-
if (overrides.cwd !== void 0) m8.local = {
|
|
1329
|
-
|
|
1621
|
+
if (overrides.cwd !== void 0) m8.local = {
|
|
1622
|
+
...m8.local,
|
|
1623
|
+
cwd: overrides.cwd
|
|
1624
|
+
};
|
|
1625
|
+
if (overrides.baseDir !== void 0) m8.local = {
|
|
1626
|
+
...m8.local,
|
|
1627
|
+
baseDir: overrides.baseDir
|
|
1628
|
+
};
|
|
1330
1629
|
const extra = buildExtraCreateOptions(overrides, compiled);
|
|
1331
1630
|
if (applied.length > 0) {
|
|
1332
1631
|
debugLog("[THEO_AGENT_M8_RUNTIME_APPLIED]", {
|
|
@@ -1343,13 +1642,19 @@ async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
|
|
|
1343
1642
|
...extra
|
|
1344
1643
|
});
|
|
1345
1644
|
try {
|
|
1346
|
-
const state = {
|
|
1645
|
+
const state = {
|
|
1646
|
+
sawError: false,
|
|
1647
|
+
lastEventType: ""
|
|
1648
|
+
};
|
|
1347
1649
|
const sendOptions = {};
|
|
1348
1650
|
if (factoryOpts?.disableTools === true) sendOptions.toolChoice = "none";
|
|
1349
1651
|
if (overrides.onRunEvent !== void 0) sendOptions.onRunEvent = overrides.onRunEvent;
|
|
1350
|
-
const sendInput = overrides.images && overrides.images.length > 0 ? {
|
|
1652
|
+
const sendInput = overrides.images && overrides.images.length > 0 ? {
|
|
1653
|
+
text: message,
|
|
1654
|
+
images: overrides.images
|
|
1655
|
+
} : message;
|
|
1351
1656
|
const sendPromise = agent.send(sendInput, sendOptions);
|
|
1352
|
-
const timeline = async function* () {
|
|
1657
|
+
const timeline = /* @__PURE__ */ __name(async function* () {
|
|
1353
1658
|
const run = await sendPromise;
|
|
1354
1659
|
const seen = createToolSeen();
|
|
1355
1660
|
for await (const ev of run.events()) {
|
|
@@ -1360,7 +1665,7 @@ async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
|
|
|
1360
1665
|
yield event;
|
|
1361
1666
|
}
|
|
1362
1667
|
}
|
|
1363
|
-
};
|
|
1668
|
+
}, "timeline");
|
|
1364
1669
|
for await (const event of applyTextTransforms(timeline(), {
|
|
1365
1670
|
parseThinkTags,
|
|
1366
1671
|
stripToolDialect
|
|
@@ -1383,6 +1688,7 @@ async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
|
|
|
1383
1688
|
await agent.dispose();
|
|
1384
1689
|
}
|
|
1385
1690
|
}
|
|
1691
|
+
__name(streamSdkAgent, "streamSdkAgent");
|
|
1386
1692
|
function toAgentFactory(def, opts) {
|
|
1387
1693
|
const overrides = opts.overrides ?? {};
|
|
1388
1694
|
const projectPerSession = resolveProjection(def, overrides);
|
|
@@ -1390,9 +1696,7 @@ function toAgentFactory(def, opts) {
|
|
|
1390
1696
|
const { compiled, model, reasoningEffort, runContext } = await projectPerSession(sessionId);
|
|
1391
1697
|
const rt = await loadSdkRuntime();
|
|
1392
1698
|
if (!rt) {
|
|
1393
|
-
throw new Error(
|
|
1394
|
-
"[@theokit/agents] @theokit/sdk is not installed \u2014 run: pnpm add @theokit/sdk"
|
|
1395
|
-
);
|
|
1699
|
+
throw new Error("[@theokit/agents] @theokit/sdk is not installed \u2014 run: pnpm add @theokit/sdk");
|
|
1396
1700
|
}
|
|
1397
1701
|
const sdkTools = buildSdkTools(compiled.tools, rt.defineTool, overrides.sdkTools, runContext);
|
|
1398
1702
|
const inlineSkills = compiled.skills?.inline;
|
|
@@ -1400,8 +1704,14 @@ function toAgentFactory(def, opts) {
|
|
|
1400
1704
|
sdkTools.push(rt.defineSkillReadTool(inlineSkills));
|
|
1401
1705
|
}
|
|
1402
1706
|
const { options: m8 } = assembleM8CreateOptions(compiled);
|
|
1403
|
-
if (overrides.cwd !== void 0) m8.local = {
|
|
1404
|
-
|
|
1707
|
+
if (overrides.cwd !== void 0) m8.local = {
|
|
1708
|
+
...m8.local,
|
|
1709
|
+
cwd: overrides.cwd
|
|
1710
|
+
};
|
|
1711
|
+
if (overrides.baseDir !== void 0) m8.local = {
|
|
1712
|
+
...m8.local,
|
|
1713
|
+
baseDir: overrides.baseDir
|
|
1714
|
+
};
|
|
1405
1715
|
const extra = buildExtraCreateOptions(overrides, compiled);
|
|
1406
1716
|
applyPosture(extra, m8, opts.approvals, compiled.hitl);
|
|
1407
1717
|
const agent = await rt.Agent.getOrCreate(sessionId, {
|
|
@@ -1414,37 +1724,53 @@ function toAgentFactory(def, opts) {
|
|
|
1414
1724
|
return withGuardrails(agent, compiled.guardrails);
|
|
1415
1725
|
};
|
|
1416
1726
|
}
|
|
1727
|
+
__name(toAgentFactory, "toAgentFactory");
|
|
1417
1728
|
function withGuardrails(handle, guardrails) {
|
|
1418
1729
|
if (guardrails === void 0 || guardrails.length === 0) return handle;
|
|
1419
1730
|
return {
|
|
1420
1731
|
get agentId() {
|
|
1421
1732
|
return handle.agentId;
|
|
1422
1733
|
},
|
|
1423
|
-
dispose: () => handle.dispose(),
|
|
1424
|
-
send: async (msg, sendOpts) => {
|
|
1734
|
+
dispose: /* @__PURE__ */ __name(() => handle.dispose(), "dispose"),
|
|
1735
|
+
send: /* @__PURE__ */ __name(async (msg, sendOpts) => {
|
|
1425
1736
|
const guarded = await runInputGuards(msg, guardrails);
|
|
1426
1737
|
const turn = await handle.send(guarded, sendOpts);
|
|
1427
1738
|
return {
|
|
1428
|
-
wait: async () => {
|
|
1739
|
+
wait: /* @__PURE__ */ __name(async () => {
|
|
1429
1740
|
const out = await turn.wait();
|
|
1430
1741
|
if (out.result === void 0) return out;
|
|
1431
|
-
return {
|
|
1432
|
-
|
|
1742
|
+
return {
|
|
1743
|
+
...out,
|
|
1744
|
+
result: await runOutputGuards(out.result, guardrails)
|
|
1745
|
+
};
|
|
1746
|
+
}, "wait")
|
|
1433
1747
|
};
|
|
1434
|
-
}
|
|
1748
|
+
}, "send")
|
|
1435
1749
|
};
|
|
1436
1750
|
}
|
|
1751
|
+
__name(withGuardrails, "withGuardrails");
|
|
1437
1752
|
|
|
1438
1753
|
// src/bridge/present-ui-message-stream.ts
|
|
1439
1754
|
import { UIMessageStreamPresenter } from "@theokit/presenter";
|
|
1440
1755
|
function toAgentOutputEvent(e) {
|
|
1441
1756
|
switch (e.type) {
|
|
1442
1757
|
case "text_delta":
|
|
1443
|
-
return {
|
|
1758
|
+
return {
|
|
1759
|
+
type: "text",
|
|
1760
|
+
text: e.content
|
|
1761
|
+
};
|
|
1444
1762
|
case "thinking":
|
|
1445
|
-
return {
|
|
1763
|
+
return {
|
|
1764
|
+
type: "reasoning",
|
|
1765
|
+
text: e.content
|
|
1766
|
+
};
|
|
1446
1767
|
case "tool_call":
|
|
1447
|
-
return {
|
|
1768
|
+
return {
|
|
1769
|
+
type: "tool-call",
|
|
1770
|
+
callId: e.callId,
|
|
1771
|
+
name: e.toolName,
|
|
1772
|
+
input: e.input
|
|
1773
|
+
};
|
|
1448
1774
|
case "tool_result":
|
|
1449
1775
|
return {
|
|
1450
1776
|
type: "tool-result",
|
|
@@ -1457,20 +1783,40 @@ function toAgentOutputEvent(e) {
|
|
|
1457
1783
|
return null;
|
|
1458
1784
|
}
|
|
1459
1785
|
}
|
|
1786
|
+
__name(toAgentOutputEvent, "toAgentOutputEvent");
|
|
1460
1787
|
function doneToMetadata(event) {
|
|
1461
|
-
return event.cost === void 0 ? {
|
|
1788
|
+
return event.cost === void 0 ? {
|
|
1789
|
+
usage: event.usage,
|
|
1790
|
+
durationMs: event.durationMs
|
|
1791
|
+
} : {
|
|
1792
|
+
usage: event.usage,
|
|
1793
|
+
durationMs: event.durationMs,
|
|
1794
|
+
cost: event.cost
|
|
1795
|
+
};
|
|
1462
1796
|
}
|
|
1797
|
+
__name(doneToMetadata, "doneToMetadata");
|
|
1463
1798
|
var ERROR_CODE_DATA_PART = "data-error-code";
|
|
1464
1799
|
var INPUT_REQUESTED_DATA_PART = "data-input-requested";
|
|
1465
1800
|
var TASK_PROGRESS_DATA_PART = "data-task-progress";
|
|
1466
1801
|
var SHELL_OUTPUT_DATA_PART = "data-shell-output";
|
|
1467
1802
|
function dataPart(type, data) {
|
|
1468
|
-
return {
|
|
1803
|
+
return {
|
|
1804
|
+
type,
|
|
1805
|
+
data,
|
|
1806
|
+
transient: true
|
|
1807
|
+
};
|
|
1469
1808
|
}
|
|
1809
|
+
__name(dataPart, "dataPart");
|
|
1470
1810
|
function* errorChunks(errorText, code) {
|
|
1471
|
-
if (code !== void 0) yield dataPart(ERROR_CODE_DATA_PART, {
|
|
1472
|
-
|
|
1811
|
+
if (code !== void 0) yield dataPart(ERROR_CODE_DATA_PART, {
|
|
1812
|
+
code
|
|
1813
|
+
});
|
|
1814
|
+
yield {
|
|
1815
|
+
type: "error",
|
|
1816
|
+
errorText
|
|
1817
|
+
};
|
|
1473
1818
|
}
|
|
1819
|
+
__name(errorChunks, "errorChunks");
|
|
1474
1820
|
function diagnosticDataPart(event) {
|
|
1475
1821
|
switch (event.type) {
|
|
1476
1822
|
case "checkpoint_saved":
|
|
@@ -1483,21 +1829,34 @@ function diagnosticDataPart(event) {
|
|
|
1483
1829
|
// catch-all, which is the reported defect one layer down: translating an event and never
|
|
1484
1830
|
// presenting it leaves the consumer just as blind, minus even the warning.
|
|
1485
1831
|
case "input_requested":
|
|
1486
|
-
return dataPart(INPUT_REQUESTED_DATA_PART, {
|
|
1832
|
+
return dataPart(INPUT_REQUESTED_DATA_PART, {
|
|
1833
|
+
requestId: event.requestId
|
|
1834
|
+
});
|
|
1487
1835
|
case "task_progress":
|
|
1488
1836
|
return dataPart(TASK_PROGRESS_DATA_PART, {
|
|
1489
|
-
...event.status !== void 0 ? {
|
|
1490
|
-
|
|
1837
|
+
...event.status !== void 0 ? {
|
|
1838
|
+
status: event.status
|
|
1839
|
+
} : {},
|
|
1840
|
+
...event.text !== void 0 ? {
|
|
1841
|
+
text: event.text
|
|
1842
|
+
} : {}
|
|
1491
1843
|
});
|
|
1492
1844
|
case "shell_output":
|
|
1493
|
-
return dataPart(SHELL_OUTPUT_DATA_PART, {
|
|
1845
|
+
return dataPart(SHELL_OUTPUT_DATA_PART, {
|
|
1846
|
+
event: event.event
|
|
1847
|
+
});
|
|
1494
1848
|
default:
|
|
1495
1849
|
return null;
|
|
1496
1850
|
}
|
|
1497
1851
|
}
|
|
1852
|
+
__name(diagnosticDataPart, "diagnosticDataPart");
|
|
1498
1853
|
async function* presentUIMessageStream(events, opts) {
|
|
1499
|
-
const presenter = new UIMessageStreamPresenter({
|
|
1500
|
-
|
|
1854
|
+
const presenter = new UIMessageStreamPresenter({
|
|
1855
|
+
textId: opts.textId
|
|
1856
|
+
});
|
|
1857
|
+
yield {
|
|
1858
|
+
type: "start"
|
|
1859
|
+
};
|
|
1501
1860
|
let turnMetadata;
|
|
1502
1861
|
try {
|
|
1503
1862
|
for await (const event of events) {
|
|
@@ -1518,7 +1877,11 @@ async function* presentUIMessageStream(events, opts) {
|
|
|
1518
1877
|
dynamic: true
|
|
1519
1878
|
};
|
|
1520
1879
|
}
|
|
1521
|
-
yield {
|
|
1880
|
+
yield {
|
|
1881
|
+
type: "tool-approval-request",
|
|
1882
|
+
approvalId: event.callId,
|
|
1883
|
+
toolCallId: event.callId
|
|
1884
|
+
};
|
|
1522
1885
|
continue;
|
|
1523
1886
|
}
|
|
1524
1887
|
const diagnostic = diagnosticDataPart(event);
|
|
@@ -1542,46 +1905,105 @@ async function* presentUIMessageStream(events, opts) {
|
|
|
1542
1905
|
}
|
|
1543
1906
|
yield* presenter.finish(turnMetadata);
|
|
1544
1907
|
}
|
|
1908
|
+
__name(presentUIMessageStream, "presentUIMessageStream");
|
|
1545
1909
|
|
|
1546
1910
|
// src/bridge/agent-builder.ts
|
|
1547
1911
|
var ContextualTool = {
|
|
1548
1912
|
/**
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1913
|
+
* Tag a {@link CustomTool} with a literal name (so `.tool()` can accumulate the tool-name union)
|
|
1914
|
+
* and, optionally, a required run-context type. The `requiredContext` argument is a type-only
|
|
1915
|
+
* witness — pass `undefined as C` or a sample value; it is never read at runtime.
|
|
1916
|
+
*/
|
|
1553
1917
|
of(tool, _requiredContext) {
|
|
1554
1918
|
return tool;
|
|
1555
1919
|
}
|
|
1556
1920
|
};
|
|
1557
1921
|
function makeBuilder(config) {
|
|
1558
1922
|
const runtime = {
|
|
1559
|
-
input: (schema) => makeBuilder({
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1923
|
+
input: /* @__PURE__ */ __name((schema) => makeBuilder({
|
|
1924
|
+
...config,
|
|
1925
|
+
input: schema
|
|
1926
|
+
}), "input"),
|
|
1927
|
+
model: /* @__PURE__ */ __name((id) => makeBuilder({
|
|
1928
|
+
...config,
|
|
1929
|
+
model: id
|
|
1930
|
+
}), "model"),
|
|
1931
|
+
system: /* @__PURE__ */ __name((prompt) => makeBuilder({
|
|
1932
|
+
...config,
|
|
1933
|
+
system: prompt
|
|
1934
|
+
}), "system"),
|
|
1935
|
+
reasoningEffort: /* @__PURE__ */ __name((effort) => makeBuilder({
|
|
1936
|
+
...config,
|
|
1937
|
+
reasoningEffort: effort
|
|
1938
|
+
}), "reasoningEffort"),
|
|
1939
|
+
context: /* @__PURE__ */ __name((value) => makeBuilder({
|
|
1940
|
+
...config,
|
|
1941
|
+
context: value
|
|
1942
|
+
}), "context"),
|
|
1943
|
+
tool: /* @__PURE__ */ __name((tool) => makeBuilder({
|
|
1944
|
+
...config,
|
|
1945
|
+
tools: [
|
|
1946
|
+
...config.tools ?? [],
|
|
1947
|
+
tool
|
|
1948
|
+
]
|
|
1949
|
+
}), "tool"),
|
|
1950
|
+
guardrail: /* @__PURE__ */ __name((g) => makeBuilder({
|
|
1951
|
+
...config,
|
|
1952
|
+
guardrails: [
|
|
1953
|
+
...config.guardrails ?? [],
|
|
1954
|
+
g
|
|
1955
|
+
]
|
|
1956
|
+
}), "guardrail"),
|
|
1957
|
+
guardrails: /* @__PURE__ */ __name((gs) => makeBuilder({
|
|
1958
|
+
...config,
|
|
1959
|
+
guardrails: gs
|
|
1960
|
+
}), "guardrails"),
|
|
1961
|
+
approval: /* @__PURE__ */ __name((toolName, options) => makeBuilder({
|
|
1962
|
+
...config,
|
|
1963
|
+
approvals: {
|
|
1964
|
+
...config.approvals ?? {},
|
|
1965
|
+
[toolName]: options
|
|
1966
|
+
}
|
|
1967
|
+
}), "approval"),
|
|
1968
|
+
approvals: /* @__PURE__ */ __name((map) => makeBuilder({
|
|
1969
|
+
...config,
|
|
1970
|
+
approvals: map
|
|
1971
|
+
}), "approvals"),
|
|
1972
|
+
skills: /* @__PURE__ */ __name((selection) => makeBuilder({
|
|
1973
|
+
...config,
|
|
1974
|
+
skills: selection
|
|
1975
|
+
}), "skills"),
|
|
1976
|
+
settingSources: /* @__PURE__ */ __name((sources) => makeBuilder({
|
|
1977
|
+
...config,
|
|
1978
|
+
settingSources: sources
|
|
1979
|
+
}), "settingSources"),
|
|
1980
|
+
memory: /* @__PURE__ */ __name((settings) => makeBuilder({
|
|
1981
|
+
...config,
|
|
1982
|
+
memory: settings
|
|
1983
|
+
}), "memory"),
|
|
1984
|
+
hooks: /* @__PURE__ */ __name((map) => makeBuilder({
|
|
1985
|
+
...config,
|
|
1986
|
+
hooks: map
|
|
1987
|
+
}), "hooks"),
|
|
1988
|
+
plugins: /* @__PURE__ */ __name((list) => makeBuilder({
|
|
1989
|
+
...config,
|
|
1990
|
+
plugins: list
|
|
1991
|
+
}), "plugins"),
|
|
1992
|
+
mcp: /* @__PURE__ */ __name((servers) => makeBuilder({
|
|
1993
|
+
...config,
|
|
1994
|
+
mcpServers: servers
|
|
1995
|
+
}), "mcp"),
|
|
1996
|
+
use: /* @__PURE__ */ __name((preset) => preset(runtime), "use"),
|
|
1997
|
+
build: /* @__PURE__ */ __name(() => defineAgent(config), "build")
|
|
1577
1998
|
};
|
|
1578
1999
|
return runtime;
|
|
1579
2000
|
}
|
|
2001
|
+
__name(makeBuilder, "makeBuilder");
|
|
1580
2002
|
var AgentBuilder = {
|
|
1581
2003
|
/**
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
2004
|
+
* Start a fluent agent definition. Chain `.model()` (required) + `.context()` / `.system()` /
|
|
2005
|
+
* `.input()` / `.tool()` / `.use()`, then `.build()` to get the branded {@link AgentDefinition}.
|
|
2006
|
+
*/
|
|
1585
2007
|
create() {
|
|
1586
2008
|
return makeBuilder({});
|
|
1587
2009
|
}
|
|
@@ -1589,10 +2011,11 @@ var AgentBuilder = {
|
|
|
1589
2011
|
|
|
1590
2012
|
// src/bridge/agent-endpoint.ts
|
|
1591
2013
|
var AgentDefinitionError = class extends Error {
|
|
2014
|
+
static {
|
|
2015
|
+
__name(this, "AgentDefinitionError");
|
|
2016
|
+
}
|
|
1592
2017
|
constructor(source) {
|
|
1593
|
-
super(
|
|
1594
|
-
`[@theokit/agents] ${source}: an agents/ file must default-export a defineAgent(...) value or an @Agent-decorated class.`
|
|
1595
|
-
);
|
|
2018
|
+
super(`[@theokit/agents] ${source}: an agents/ file must default-export a defineAgent(...) value or an @Agent-decorated class.`);
|
|
1596
2019
|
this.name = "AgentDefinitionError";
|
|
1597
2020
|
}
|
|
1598
2021
|
};
|
|
@@ -1602,11 +2025,13 @@ function extractDefaultExport(mod) {
|
|
|
1602
2025
|
}
|
|
1603
2026
|
return mod;
|
|
1604
2027
|
}
|
|
2028
|
+
__name(extractDefaultExport, "extractDefaultExport");
|
|
1605
2029
|
function isCompiledAgentOptions(value) {
|
|
1606
2030
|
if (typeof value !== "object" || value === null) return false;
|
|
1607
2031
|
const v = value;
|
|
1608
2032
|
return Array.isArray(v.tools) && typeof v.agents === "object" && v.agents !== null;
|
|
1609
2033
|
}
|
|
2034
|
+
__name(isCompiledAgentOptions, "isCompiledAgentOptions");
|
|
1610
2035
|
function compileAgentModule(mod, source = "agent module") {
|
|
1611
2036
|
const def = extractDefaultExport(mod);
|
|
1612
2037
|
if (isAgentDefinition(def)) {
|
|
@@ -1615,22 +2040,33 @@ function compileAgentModule(mod, source = "agent module") {
|
|
|
1615
2040
|
if (isCompiledAgentOptions(def)) return def;
|
|
1616
2041
|
throw new AgentDefinitionError(source);
|
|
1617
2042
|
}
|
|
2043
|
+
__name(compileAgentModule, "compileAgentModule");
|
|
1618
2044
|
async function* asAgentStream(events) {
|
|
1619
2045
|
for await (const e of events) yield e;
|
|
1620
2046
|
}
|
|
1621
|
-
|
|
2047
|
+
__name(asAgentStream, "asAgentStream");
|
|
2048
|
+
var EventQueue = class EventQueue2 {
|
|
2049
|
+
static {
|
|
2050
|
+
__name(this, "EventQueue");
|
|
2051
|
+
}
|
|
1622
2052
|
#items = [];
|
|
1623
2053
|
#resolvers = [];
|
|
1624
2054
|
#closed = false;
|
|
1625
2055
|
push(item) {
|
|
1626
2056
|
if (this.#closed) return;
|
|
1627
2057
|
const r = this.#resolvers.shift();
|
|
1628
|
-
if (r) r({
|
|
2058
|
+
if (r) r({
|
|
2059
|
+
value: item,
|
|
2060
|
+
done: false
|
|
2061
|
+
});
|
|
1629
2062
|
else this.#items.push(item);
|
|
1630
2063
|
}
|
|
1631
2064
|
close() {
|
|
1632
2065
|
this.#closed = true;
|
|
1633
|
-
for (const r of this.#resolvers.splice(0)) r({
|
|
2066
|
+
for (const r of this.#resolvers.splice(0)) r({
|
|
2067
|
+
value: void 0,
|
|
2068
|
+
done: true
|
|
2069
|
+
});
|
|
1634
2070
|
}
|
|
1635
2071
|
async *drain() {
|
|
1636
2072
|
for (; ; ) {
|
|
@@ -1647,12 +2083,12 @@ var EventQueue = class {
|
|
|
1647
2083
|
};
|
|
1648
2084
|
async function* appendCheckpointSaved(source, sessionId) {
|
|
1649
2085
|
let emitted = false;
|
|
1650
|
-
const checkpoint = () => ({
|
|
2086
|
+
const checkpoint = /* @__PURE__ */ __name(() => ({
|
|
1651
2087
|
type: "checkpoint_saved",
|
|
1652
2088
|
checkpointId: crypto.randomUUID(),
|
|
1653
2089
|
step: 0,
|
|
1654
2090
|
resumeToken: sessionId
|
|
1655
|
-
});
|
|
2091
|
+
}), "checkpoint");
|
|
1656
2092
|
for await (const ev of source) {
|
|
1657
2093
|
if (ev.type === "done" && !emitted) {
|
|
1658
2094
|
emitted = true;
|
|
@@ -1662,6 +2098,7 @@ async function* appendCheckpointSaved(source, sessionId) {
|
|
|
1662
2098
|
}
|
|
1663
2099
|
if (!emitted) yield checkpoint();
|
|
1664
2100
|
}
|
|
2101
|
+
__name(appendCheckpointSaved, "appendCheckpointSaved");
|
|
1665
2102
|
function streamAgentUIMessages(compiled, apiKey, input) {
|
|
1666
2103
|
const textId = crypto.randomUUID();
|
|
1667
2104
|
const overrides = {};
|
|
@@ -1671,34 +2108,29 @@ function streamAgentUIMessages(compiled, apiKey, input) {
|
|
|
1671
2108
|
if (input.onRunEvent !== void 0) overrides.onRunEvent = input.onRunEvent;
|
|
1672
2109
|
let source;
|
|
1673
2110
|
if (!input.hitl || input.hitl.gated.size === 0) {
|
|
1674
|
-
const events2 = createSdkAgentStream(
|
|
1675
|
-
compiled,
|
|
1676
|
-
compiled.tools,
|
|
1677
|
-
apiKey,
|
|
1678
|
-
overrides
|
|
1679
|
-
)(input.message, input.sessionId);
|
|
2111
|
+
const events2 = createSdkAgentStream(compiled, compiled.tools, apiKey, overrides)(input.message, input.sessionId);
|
|
1680
2112
|
source = asAgentStream(events2);
|
|
1681
2113
|
} else {
|
|
1682
2114
|
const queue = new EventQueue();
|
|
1683
|
-
input.signal?.addEventListener(
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
{ once: true }
|
|
1689
|
-
);
|
|
2115
|
+
input.signal?.addEventListener("abort", () => {
|
|
2116
|
+
queue.close();
|
|
2117
|
+
}, {
|
|
2118
|
+
once: true
|
|
2119
|
+
});
|
|
1690
2120
|
const plugin = createHitlPlugin({
|
|
1691
2121
|
gated: input.hitl.gated,
|
|
1692
|
-
emit: (e) => {
|
|
2122
|
+
emit: /* @__PURE__ */ __name((e) => {
|
|
1693
2123
|
queue.push(e);
|
|
1694
|
-
},
|
|
2124
|
+
}, "emit"),
|
|
1695
2125
|
awaitApproval: input.hitl.awaitApproval
|
|
1696
2126
|
});
|
|
1697
2127
|
const sdkStream = createSdkAgentStream(compiled, compiled.tools, apiKey, {
|
|
1698
2128
|
...overrides,
|
|
1699
2129
|
// The HITL plugin is a structural @theokit/sdk Plugin (createHitlPlugin returns the
|
|
1700
2130
|
// { name, register } shape); the RuntimeOverrides.plugins union is widened at the SDK edge.
|
|
1701
|
-
plugins: [
|
|
2131
|
+
plugins: [
|
|
2132
|
+
plugin
|
|
2133
|
+
]
|
|
1702
2134
|
})(input.message, input.sessionId);
|
|
1703
2135
|
void (async () => {
|
|
1704
2136
|
try {
|
|
@@ -1718,8 +2150,11 @@ function streamAgentUIMessages(compiled, apiKey, input) {
|
|
|
1718
2150
|
}
|
|
1719
2151
|
const durableCheckpoint = compiled.checkpoint?.storage === "filesystem";
|
|
1720
2152
|
const events = durableCheckpoint ? appendCheckpointSaved(source, input.sessionId) : source;
|
|
1721
|
-
return presentUIMessageStream(events, {
|
|
2153
|
+
return presentUIMessageStream(events, {
|
|
2154
|
+
textId
|
|
2155
|
+
});
|
|
1722
2156
|
}
|
|
2157
|
+
__name(streamAgentUIMessages, "streamAgentUIMessages");
|
|
1723
2158
|
|
|
1724
2159
|
// src/loop/compaction-strategy.ts
|
|
1725
2160
|
import { compactTranscript } from "@theokit/sdk/compaction";
|
|
@@ -1730,56 +2165,73 @@ var compactionStrategyConfigSchema = z.object({
|
|
|
1730
2165
|
keepTokens: z.number().int().positive()
|
|
1731
2166
|
});
|
|
1732
2167
|
function resolveCompactionStrategy(name, config) {
|
|
1733
|
-
const cfg = compactionStrategyConfigSchema.parse({
|
|
2168
|
+
const cfg = compactionStrategyConfigSchema.parse({
|
|
2169
|
+
name,
|
|
2170
|
+
keepTokens: config.keepTokens
|
|
2171
|
+
});
|
|
1734
2172
|
return {
|
|
1735
2173
|
name: cfg.name,
|
|
1736
2174
|
keepTokens: cfg.keepTokens,
|
|
1737
|
-
compact: (messages, options) => compactTranscript(messages, {
|
|
2175
|
+
compact: /* @__PURE__ */ __name((messages, options) => compactTranscript(messages, {
|
|
1738
2176
|
keepTokens: options?.keepTokens ?? cfg.keepTokens,
|
|
1739
2177
|
summarize: options?.summarize,
|
|
1740
2178
|
marker: options?.marker,
|
|
1741
2179
|
summaryTemplate: options?.summaryTemplate,
|
|
1742
2180
|
// Default-safe: a thrown summarize keeps the transcript (app opts out via failSafe:false).
|
|
1743
2181
|
failSafe: options?.failSafe ?? true
|
|
1744
|
-
})
|
|
2182
|
+
}), "compact")
|
|
1745
2183
|
};
|
|
1746
2184
|
}
|
|
1747
|
-
|
|
2185
|
+
__name(resolveCompactionStrategy, "resolveCompactionStrategy");
|
|
2186
|
+
var tokenBudgetCompactionStrategy = resolveCompactionStrategy("token-budget", {
|
|
2187
|
+
keepTokens: DEFAULT_KEEP_TOKENS
|
|
2188
|
+
});
|
|
1748
2189
|
|
|
1749
2190
|
// src/loop/loop-strategy.ts
|
|
1750
2191
|
import { z as z2 } from "zod";
|
|
1751
2192
|
var DEFAULT_MAX_ITERATIONS = 8;
|
|
1752
2193
|
var maxIterationsSchema = z2.number().int().min(1);
|
|
1753
2194
|
var loopStrategyConfigSchema = z2.object({
|
|
1754
|
-
name: z2.enum([
|
|
2195
|
+
name: z2.enum([
|
|
2196
|
+
"simple-chat",
|
|
2197
|
+
"plan-act-reflect",
|
|
2198
|
+
"react"
|
|
2199
|
+
]),
|
|
1755
2200
|
maxIterations: maxIterationsSchema
|
|
1756
2201
|
});
|
|
1757
2202
|
function assertValidCustomLoopStrategy(strategy) {
|
|
1758
2203
|
const result = maxIterationsSchema.safeParse(strategy.maxIterations);
|
|
1759
2204
|
if (!result.success) {
|
|
1760
|
-
throw new Error(
|
|
1761
|
-
`loopStrategy: invalid maxIterations (${String(strategy.maxIterations)}) \u2014 must be a finite integer \u2265 1 (otherwise the round < maxIterations ceiling never terminates)`
|
|
1762
|
-
);
|
|
2205
|
+
throw new Error(`loopStrategy: invalid maxIterations (${String(strategy.maxIterations)}) \u2014 must be a finite integer \u2265 1 (otherwise the round < maxIterations ceiling never terminates)`);
|
|
1763
2206
|
}
|
|
1764
2207
|
}
|
|
2208
|
+
__name(assertValidCustomLoopStrategy, "assertValidCustomLoopStrategy");
|
|
1765
2209
|
function resolveLoopStrategy(strategy, maxIterations = DEFAULT_MAX_ITERATIONS) {
|
|
1766
|
-
const cfg = loopStrategyConfigSchema.parse({
|
|
2210
|
+
const cfg = loopStrategyConfigSchema.parse({
|
|
2211
|
+
name: strategy,
|
|
2212
|
+
maxIterations
|
|
2213
|
+
});
|
|
1767
2214
|
if (cfg.name === "simple-chat") {
|
|
1768
|
-
return {
|
|
2215
|
+
return {
|
|
2216
|
+
name: cfg.name,
|
|
2217
|
+
maxIterations: cfg.maxIterations,
|
|
2218
|
+
shouldContinue: /* @__PURE__ */ __name(() => false, "shouldContinue")
|
|
2219
|
+
};
|
|
1769
2220
|
}
|
|
1770
2221
|
if (cfg.name === "plan-act-reflect") {
|
|
1771
2222
|
return {
|
|
1772
2223
|
name: cfg.name,
|
|
1773
2224
|
maxIterations: cfg.maxIterations,
|
|
1774
|
-
shouldContinue: (outcome) => outcome.round < cfg.maxIterations
|
|
2225
|
+
shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.round < cfg.maxIterations, "shouldContinue")
|
|
1775
2226
|
};
|
|
1776
2227
|
}
|
|
1777
2228
|
return {
|
|
1778
2229
|
name: cfg.name,
|
|
1779
2230
|
maxIterations: cfg.maxIterations,
|
|
1780
|
-
shouldContinue: (outcome) => outcome.finishReason === "tool-calls" && outcome.round < cfg.maxIterations
|
|
2231
|
+
shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.finishReason === "tool-calls" && outcome.round < cfg.maxIterations, "shouldContinue")
|
|
1781
2232
|
};
|
|
1782
2233
|
}
|
|
2234
|
+
__name(resolveLoopStrategy, "resolveLoopStrategy");
|
|
1783
2235
|
|
|
1784
2236
|
// src/loop/reflection-strategy.ts
|
|
1785
2237
|
import { z as z3 } from "zod";
|
|
@@ -1795,52 +2247,55 @@ var ladderReflectionStrategy = {
|
|
|
1795
2247
|
continue: true
|
|
1796
2248
|
};
|
|
1797
2249
|
}
|
|
1798
|
-
return {
|
|
2250
|
+
return {
|
|
2251
|
+
continue: false
|
|
2252
|
+
};
|
|
1799
2253
|
}
|
|
1800
2254
|
};
|
|
1801
2255
|
var noopReflectionStrategy = {
|
|
1802
2256
|
name: "noop",
|
|
1803
2257
|
reflect() {
|
|
1804
|
-
return {
|
|
2258
|
+
return {
|
|
2259
|
+
continue: true
|
|
2260
|
+
};
|
|
1805
2261
|
}
|
|
1806
2262
|
};
|
|
1807
2263
|
|
|
1808
2264
|
// src/bridge/delegation-types.ts
|
|
1809
2265
|
var DelegationBudgetExceededError = class extends Error {
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
`Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`
|
|
1813
|
-
);
|
|
1814
|
-
this.agentName = agentName;
|
|
1815
|
-
this.actualCost = actualCost;
|
|
1816
|
-
this.budgetLimit = budgetLimit;
|
|
1817
|
-
this.name = "DelegationBudgetExceededError";
|
|
2266
|
+
static {
|
|
2267
|
+
__name(this, "DelegationBudgetExceededError");
|
|
1818
2268
|
}
|
|
1819
2269
|
agentName;
|
|
1820
2270
|
actualCost;
|
|
1821
2271
|
budgetLimit;
|
|
2272
|
+
constructor(agentName, actualCost, budgetLimit) {
|
|
2273
|
+
super(`Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`), this.agentName = agentName, this.actualCost = actualCost, this.budgetLimit = budgetLimit;
|
|
2274
|
+
this.name = "DelegationBudgetExceededError";
|
|
2275
|
+
}
|
|
1822
2276
|
};
|
|
1823
2277
|
var BudgetExceededError = DelegationBudgetExceededError;
|
|
1824
2278
|
var DelegationError = class extends Error {
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
`Delegation to agent "${agentName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
1828
|
-
);
|
|
1829
|
-
this.agentName = agentName;
|
|
1830
|
-
this.cause = cause;
|
|
1831
|
-
this.name = "DelegationError";
|
|
2279
|
+
static {
|
|
2280
|
+
__name(this, "DelegationError");
|
|
1832
2281
|
}
|
|
1833
2282
|
agentName;
|
|
1834
2283
|
cause;
|
|
2284
|
+
constructor(agentName, cause) {
|
|
2285
|
+
super(`Delegation to agent "${agentName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`), this.agentName = agentName, this.cause = cause;
|
|
2286
|
+
this.name = "DelegationError";
|
|
2287
|
+
}
|
|
1835
2288
|
};
|
|
1836
2289
|
|
|
1837
2290
|
// src/loop/run-reflective-loop.ts
|
|
1838
2291
|
function asString2(value, fallback) {
|
|
1839
2292
|
return typeof value === "string" ? value : fallback;
|
|
1840
2293
|
}
|
|
2294
|
+
__name(asString2, "asString");
|
|
1841
2295
|
function asNumber(value, fallback) {
|
|
1842
2296
|
return typeof value === "number" ? value : fallback;
|
|
1843
2297
|
}
|
|
2298
|
+
__name(asNumber, "asNumber");
|
|
1844
2299
|
var NO_PROGRESS_THRESHOLD = 2;
|
|
1845
2300
|
var MAINLOOP_METRIC = "[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]";
|
|
1846
2301
|
var TOOL_CALLS = "tool-calls";
|
|
@@ -1853,15 +2308,17 @@ function stableStringify(value) {
|
|
|
1853
2308
|
const entries = Object.keys(obj).sort((a, b) => a.localeCompare(b)).map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);
|
|
1854
2309
|
return `{${entries.join(",")}}`;
|
|
1855
2310
|
}
|
|
2311
|
+
__name(stableStringify, "stableStringify");
|
|
1856
2312
|
function roundSignature(toolCalls) {
|
|
1857
2313
|
return toolCalls.map((tc) => `${tc.name}:${stableStringify(tc.input)}`).sort((a, b) => a.localeCompare(b)).join(",");
|
|
1858
2314
|
}
|
|
2315
|
+
__name(roundSignature, "roundSignature");
|
|
1859
2316
|
function terminalReason(reflectionContinue, roundReason, round, maxIterations) {
|
|
1860
|
-
if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations)
|
|
1861
|
-
return "step_limit";
|
|
2317
|
+
if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations) return "step_limit";
|
|
1862
2318
|
if (roundReason === TOOL_CALLS) return "stop";
|
|
1863
2319
|
return roundReason;
|
|
1864
2320
|
}
|
|
2321
|
+
__name(terminalReason, "terminalReason");
|
|
1865
2322
|
var CONTINUE_PROMPT = "Continue from the prior turns above; finish the task and give a final answer.";
|
|
1866
2323
|
function buildPrompt(round, maxIterations, message, feedback) {
|
|
1867
2324
|
const hint = round === maxIterations ? `${STEP_LIMIT_HINT}
|
|
@@ -1871,20 +2328,16 @@ function buildPrompt(round, maxIterations, message, feedback) {
|
|
|
1871
2328
|
const body = round === 1 ? message : continuation;
|
|
1872
2329
|
return hint + body;
|
|
1873
2330
|
}
|
|
2331
|
+
__name(buildPrompt, "buildPrompt");
|
|
1874
2332
|
async function* consumeRoundOrThrow(inputs, agentName) {
|
|
1875
2333
|
try {
|
|
1876
|
-
return yield* consumeOneRound(
|
|
1877
|
-
inputs.factory,
|
|
1878
|
-
inputs.prompt,
|
|
1879
|
-
inputs.sessionId,
|
|
1880
|
-
inputs.signal,
|
|
1881
|
-
inputs.retry
|
|
1882
|
-
);
|
|
2334
|
+
return yield* consumeOneRound(inputs.factory, inputs.prompt, inputs.sessionId, inputs.signal, inputs.retry);
|
|
1883
2335
|
} catch (err) {
|
|
1884
2336
|
if (err instanceof DelegationBudgetExceededError || err instanceof DelegationError) throw err;
|
|
1885
2337
|
throw new DelegationError(agentName, err);
|
|
1886
2338
|
}
|
|
1887
2339
|
}
|
|
2340
|
+
__name(consumeRoundOrThrow, "consumeRoundOrThrow");
|
|
1888
2341
|
function accumulateUsage(acc, r) {
|
|
1889
2342
|
acc.cost += r.cost;
|
|
1890
2343
|
acc.tokens += r.tokens;
|
|
@@ -1894,18 +2347,25 @@ function accumulateUsage(acc, r) {
|
|
|
1894
2347
|
acc.cacheReadTokens = (acc.cacheReadTokens ?? 0) + r.cacheReadTokens;
|
|
1895
2348
|
acc.cacheWriteTokens = (acc.cacheWriteTokens ?? 0) + r.cacheWriteTokens;
|
|
1896
2349
|
}
|
|
2350
|
+
__name(accumulateUsage, "accumulateUsage");
|
|
1897
2351
|
function finalize(acc, round, reason, strategyName) {
|
|
1898
2352
|
acc.rounds = round;
|
|
1899
2353
|
acc.finishReason = reason;
|
|
1900
|
-
debugLog(MAINLOOP_METRIC, {
|
|
2354
|
+
debugLog(MAINLOOP_METRIC, {
|
|
2355
|
+
strategy: strategyName,
|
|
2356
|
+
rounds: round,
|
|
2357
|
+
terminal: reason
|
|
2358
|
+
});
|
|
1901
2359
|
return acc;
|
|
1902
2360
|
}
|
|
2361
|
+
__name(finalize, "finalize");
|
|
1903
2362
|
function deriveFinishReason(signals) {
|
|
1904
2363
|
if (signals.sawError) return "error";
|
|
1905
2364
|
if (signals.sawDone && signals.doneFinishReason === TOOL_CALLS) return TOOL_CALLS;
|
|
1906
2365
|
if (signals.sawToolResult) return TOOL_CALLS;
|
|
1907
2366
|
return "stop";
|
|
1908
2367
|
}
|
|
2368
|
+
__name(deriveFinishReason, "deriveFinishReason");
|
|
1909
2369
|
function pushToolResult(event, r, callInputs) {
|
|
1910
2370
|
const id = asString2(event.callId, "");
|
|
1911
2371
|
const call = callInputs.get(id);
|
|
@@ -1918,6 +2378,7 @@ function pushToolResult(event, r, callInputs) {
|
|
|
1918
2378
|
output: asString2(event.output, "")
|
|
1919
2379
|
});
|
|
1920
2380
|
}
|
|
2381
|
+
__name(pushToolResult, "pushToolResult");
|
|
1921
2382
|
function applyDone(event, r) {
|
|
1922
2383
|
r.cost = asNumber(event.cost, 0);
|
|
1923
2384
|
const usage = event.usage;
|
|
@@ -1928,6 +2389,7 @@ function applyDone(event, r) {
|
|
|
1928
2389
|
r.cacheReadTokens = usage?.cacheReadTokens ?? 0;
|
|
1929
2390
|
r.cacheWriteTokens = usage?.cacheWriteTokens ?? 0;
|
|
1930
2391
|
}
|
|
2392
|
+
__name(applyDone, "applyDone");
|
|
1931
2393
|
function accumulateEvent(event, r, signals, callInputs) {
|
|
1932
2394
|
if (event.type === "text_delta" && typeof event.content === "string") {
|
|
1933
2395
|
r.responseText += event.content;
|
|
@@ -1948,20 +2410,28 @@ function accumulateEvent(event, r, signals, callInputs) {
|
|
|
1948
2410
|
r.errorMessage = asString2(event.message, "Unknown agent error");
|
|
1949
2411
|
}
|
|
1950
2412
|
}
|
|
2413
|
+
__name(accumulateEvent, "accumulateEvent");
|
|
1951
2414
|
async function startRound(factory, prompt, sessionId, signal, retry) {
|
|
1952
|
-
const open = async () => {
|
|
2415
|
+
const open = /* @__PURE__ */ __name(async () => {
|
|
1953
2416
|
const it = factory(prompt, sessionId)[Symbol.asyncIterator]();
|
|
1954
2417
|
try {
|
|
1955
|
-
return {
|
|
2418
|
+
return {
|
|
2419
|
+
it,
|
|
2420
|
+
first: await it.next()
|
|
2421
|
+
};
|
|
1956
2422
|
} catch (err) {
|
|
1957
2423
|
await it.return?.(void 0);
|
|
1958
2424
|
throw err;
|
|
1959
2425
|
}
|
|
1960
|
-
};
|
|
2426
|
+
}, "open");
|
|
1961
2427
|
if (!retry) return open();
|
|
1962
2428
|
const { Retry } = await import("@theokit/sdk/retry");
|
|
1963
|
-
return Retry.create(open, {
|
|
2429
|
+
return Retry.create(open, {
|
|
2430
|
+
...retry,
|
|
2431
|
+
signal: retry.signal ?? signal
|
|
2432
|
+
});
|
|
1964
2433
|
}
|
|
2434
|
+
__name(startRound, "startRound");
|
|
1965
2435
|
async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
|
|
1966
2436
|
const r = {
|
|
1967
2437
|
responseText: "",
|
|
@@ -1997,19 +2467,16 @@ async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
|
|
|
1997
2467
|
r.finishReason = deriveFinishReason(signals);
|
|
1998
2468
|
return r;
|
|
1999
2469
|
}
|
|
2470
|
+
__name(consumeOneRound, "consumeOneRound");
|
|
2000
2471
|
function ceilingRoundFactory(factory, round, maxIterations) {
|
|
2001
2472
|
if (round !== maxIterations) return factory;
|
|
2002
|
-
return (m, s) => factory(m, s, {
|
|
2473
|
+
return (m, s) => factory(m, s, {
|
|
2474
|
+
disableTools: true
|
|
2475
|
+
});
|
|
2003
2476
|
}
|
|
2477
|
+
__name(ceilingRoundFactory, "ceilingRoundFactory");
|
|
2004
2478
|
async function* runReflectiveLoopStream(factory, message, sessionId, config) {
|
|
2005
|
-
const {
|
|
2006
|
-
loop,
|
|
2007
|
-
reflection,
|
|
2008
|
-
budget = Number.POSITIVE_INFINITY,
|
|
2009
|
-
signal,
|
|
2010
|
-
agentName = loop.name,
|
|
2011
|
-
retry
|
|
2012
|
-
} = config;
|
|
2479
|
+
const { loop, reflection, budget = Number.POSITIVE_INFINITY, signal, agentName = loop.name, retry } = config;
|
|
2013
2480
|
const acc = {
|
|
2014
2481
|
response: "",
|
|
2015
2482
|
toolCalls: [],
|
|
@@ -2030,10 +2497,13 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
|
|
|
2030
2497
|
while (!signal?.aborted) {
|
|
2031
2498
|
const prompt = buildPrompt(round, loop.maxIterations, message, feedback);
|
|
2032
2499
|
const roundFactory = ceilingRoundFactory(factory, round, loop.maxIterations);
|
|
2033
|
-
const r = yield* consumeRoundOrThrow(
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2500
|
+
const r = yield* consumeRoundOrThrow({
|
|
2501
|
+
factory: roundFactory,
|
|
2502
|
+
prompt,
|
|
2503
|
+
sessionId,
|
|
2504
|
+
signal,
|
|
2505
|
+
retry
|
|
2506
|
+
}, agentName);
|
|
2037
2507
|
acc.response += r.responseText;
|
|
2038
2508
|
acc.toolCalls.push(...r.toolCalls);
|
|
2039
2509
|
accumulateUsage(acc, r);
|
|
@@ -2055,12 +2525,7 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
|
|
|
2055
2525
|
};
|
|
2056
2526
|
const reflectionResult = reflection.reflect(outcome, reflectionContext);
|
|
2057
2527
|
if (!(reflectionResult.continue && loop.shouldContinue(outcome) && round < loop.maxIterations)) {
|
|
2058
|
-
const reason = terminalReason(
|
|
2059
|
-
reflectionResult.continue,
|
|
2060
|
-
r.finishReason,
|
|
2061
|
-
round,
|
|
2062
|
-
loop.maxIterations
|
|
2063
|
-
);
|
|
2528
|
+
const reason = terminalReason(reflectionResult.continue, r.finishReason, round, loop.maxIterations);
|
|
2064
2529
|
return finalize(acc, round, reason, loop.name);
|
|
2065
2530
|
}
|
|
2066
2531
|
feedback = reflectionResult.feedback;
|
|
@@ -2069,15 +2534,20 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
|
|
|
2069
2534
|
acc.rounds = round - 1;
|
|
2070
2535
|
return acc;
|
|
2071
2536
|
}
|
|
2537
|
+
__name(runReflectiveLoopStream, "runReflectiveLoopStream");
|
|
2072
2538
|
async function runReflectiveLoop(factory, message, sessionId, config) {
|
|
2073
2539
|
const gen = runReflectiveLoopStream(factory, message, sessionId, config);
|
|
2074
2540
|
let res = await gen.next();
|
|
2075
2541
|
while (!res.done) res = await gen.next();
|
|
2076
2542
|
return res.value;
|
|
2077
2543
|
}
|
|
2544
|
+
__name(runReflectiveLoop, "runReflectiveLoop");
|
|
2078
2545
|
|
|
2079
2546
|
// src/loop/agent-runner.ts
|
|
2080
2547
|
var AgentRunner = class {
|
|
2548
|
+
static {
|
|
2549
|
+
__name(this, "AgentRunner");
|
|
2550
|
+
}
|
|
2081
2551
|
compiled;
|
|
2082
2552
|
agentName;
|
|
2083
2553
|
/** The resolved terminal-decision strategy (parity with `delegate()`). */
|
|
@@ -2087,18 +2557,18 @@ var AgentRunner = class {
|
|
|
2087
2557
|
/** The resolved between-round reflection (default or `.reflection(custom)` override). */
|
|
2088
2558
|
reflectionStrategy;
|
|
2089
2559
|
/**
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2560
|
+
* Recorded streaming preference. The reflective loop currently always streams via
|
|
2561
|
+
* the SDK `Run.stream()`; a non-streaming collect mode is future work — the flag is
|
|
2562
|
+
* captured + exposed here, not yet branched on (honest per G10: documented, not a
|
|
2563
|
+
* silent no-op).
|
|
2564
|
+
*/
|
|
2095
2565
|
streamEnabled;
|
|
2096
2566
|
/**
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2567
|
+
* V4-F: the resolved compaction strategy (from `@Compaction` or `.compaction()`),
|
|
2568
|
+
* or `undefined` when neither is declared — compaction is opt-in (EC-4). CALLABLE
|
|
2569
|
+
* by the app (ADR D1: `runner.compaction?.compact(messages, { summarize })`); the
|
|
2570
|
+
* reflective loop does NOT auto-invoke it (the SDK owns per-turn context).
|
|
2571
|
+
*/
|
|
2102
2572
|
compaction;
|
|
2103
2573
|
constructor(state) {
|
|
2104
2574
|
this.compiled = state.compiled;
|
|
@@ -2114,41 +2584,35 @@ var AgentRunner = class {
|
|
|
2114
2584
|
return new AgentRunnerBuilder(spec);
|
|
2115
2585
|
}
|
|
2116
2586
|
/**
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2587
|
+
* V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
|
|
2588
|
+
* the aggregated {@link DelegationResult} as the generator's return value. This is the
|
|
2589
|
+
* on-ramp for streaming-first apps (SSE) — `runReflectiveLoopStream` yields every
|
|
2590
|
+
* round's events before the loop terminates. `streamEnabled` is honored: when the
|
|
2591
|
+
* builder set `.stream(false)`, callers should use {@link run} instead.
|
|
2592
|
+
*/
|
|
2123
2593
|
stream(message, opts) {
|
|
2124
2594
|
const guardrails = this.compiled.guardrails;
|
|
2125
2595
|
if (guardrails && guardrails.length > 0) {
|
|
2126
|
-
const runUnguarded = (m) => this.streamUnguarded(m, opts);
|
|
2127
|
-
return (async function* guarded() {
|
|
2596
|
+
const runUnguarded = /* @__PURE__ */ __name((m) => this.streamUnguarded(m, opts), "runUnguarded");
|
|
2597
|
+
return (/* @__PURE__ */ __name(async function* guarded() {
|
|
2128
2598
|
const safe = await runInputGuards(message, guardrails);
|
|
2129
|
-
return yield* moderateOutputStream(
|
|
2130
|
-
|
|
2131
|
-
guardrails,
|
|
2132
|
-
(e) => e.type === "text_delta" && typeof e.content === "string" ? e.content : void 0
|
|
2133
|
-
);
|
|
2134
|
-
})();
|
|
2599
|
+
return yield* moderateOutputStream(runUnguarded(safe), guardrails, (e) => e.type === "text_delta" && typeof e.content === "string" ? e.content : void 0);
|
|
2600
|
+
}, "guarded"))();
|
|
2135
2601
|
}
|
|
2136
2602
|
return this.streamUnguarded(message, opts);
|
|
2137
2603
|
}
|
|
2138
2604
|
/** The core stream path, after input guardrails have run (M9). */
|
|
2139
2605
|
streamUnguarded(message, opts) {
|
|
2140
|
-
const tools = opts.tools ? [
|
|
2606
|
+
const tools = opts.tools ? [
|
|
2607
|
+
...opts.tools
|
|
2608
|
+
] : this.compiled.tools;
|
|
2141
2609
|
const loop = this.resolvePerRunLoop(opts.maxIterations);
|
|
2142
2610
|
const streamFactory = opts.streamFactory ?? createSdkAgentStream(this.compiled, tools, opts.apiKey, {
|
|
2143
2611
|
model: opts.model,
|
|
2144
2612
|
reasoningEffort: opts.reasoningEffort,
|
|
2145
|
-
// M1: per-run extended-thinking effort
|
|
2146
2613
|
parseThinkTags: opts.parseThinkTags,
|
|
2147
|
-
// M2: per-run <think>-tag extraction opt-in
|
|
2148
2614
|
stripToolDialect: opts.stripToolDialect,
|
|
2149
|
-
// theocode#32: per-run tool-dialect strip opt-in
|
|
2150
2615
|
recoverLeakedToolCalls: opts.recoverLeakedToolCalls,
|
|
2151
|
-
// theokit#58: per-run leaked-dialect recovery opt-in
|
|
2152
2616
|
cwd: opts.cwd,
|
|
2153
2617
|
baseDir: opts.baseDir,
|
|
2154
2618
|
plugins: opts.plugins,
|
|
@@ -2156,7 +2620,6 @@ var AgentRunner = class {
|
|
|
2156
2620
|
agents: opts.agents,
|
|
2157
2621
|
budgetTracker: opts.budgetTracker,
|
|
2158
2622
|
sdkTools: opts.sdkTools
|
|
2159
|
-
// V4-Q: pre-built SDK tools forwarded raw
|
|
2160
2623
|
});
|
|
2161
2624
|
const sessionId = opts.sessionId ?? `runner-${crypto.randomUUID()}`;
|
|
2162
2625
|
return runReflectiveLoopStream(streamFactory, message, sessionId, {
|
|
@@ -2166,17 +2629,16 @@ var AgentRunner = class {
|
|
|
2166
2629
|
agentName: this.agentName,
|
|
2167
2630
|
signal: opts.signal,
|
|
2168
2631
|
retry: opts.retry
|
|
2169
|
-
// V4-P: per-round transient retry (opt-in)
|
|
2170
2632
|
});
|
|
2171
2633
|
}
|
|
2172
2634
|
/** Run the agent to a terminal result via the shared reflective loop (collect mode). */
|
|
2173
2635
|
/**
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2636
|
+
* Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by
|
|
2637
|
+
* name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure
|
|
2638
|
+
* must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),
|
|
2639
|
+
* overriding just that field bounds a custom without touching its logic. A built-in keeps the
|
|
2640
|
+
* by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.
|
|
2641
|
+
*/
|
|
2180
2642
|
resolvePerRunLoop(maxIterations) {
|
|
2181
2643
|
if (maxIterations == null) return this.loopStrategy;
|
|
2182
2644
|
if (this.loopStrategyIsCustom) {
|
|
@@ -2195,37 +2657,40 @@ var AgentRunner = class {
|
|
|
2195
2657
|
}
|
|
2196
2658
|
};
|
|
2197
2659
|
var AgentRunnerBuilder = class {
|
|
2198
|
-
|
|
2199
|
-
this
|
|
2660
|
+
static {
|
|
2661
|
+
__name(this, "AgentRunnerBuilder");
|
|
2200
2662
|
}
|
|
2201
2663
|
spec;
|
|
2202
2664
|
reflectionOverride;
|
|
2203
2665
|
streamEnabled = true;
|
|
2204
2666
|
compactionOverride;
|
|
2205
2667
|
loopStrategyOverride;
|
|
2668
|
+
constructor(spec) {
|
|
2669
|
+
this.spec = spec;
|
|
2670
|
+
}
|
|
2206
2671
|
/** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */
|
|
2207
2672
|
reflection(strategy) {
|
|
2208
2673
|
if (strategy) this.reflectionOverride = strategy;
|
|
2209
2674
|
return this;
|
|
2210
2675
|
}
|
|
2211
2676
|
/**
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2677
|
+
* M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside
|
|
2678
|
+
* `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would
|
|
2679
|
+
* resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at
|
|
2680
|
+
* `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an
|
|
2681
|
+
* infinite loop.
|
|
2682
|
+
*
|
|
2683
|
+
* @example
|
|
2684
|
+
* ```ts
|
|
2685
|
+
* // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.
|
|
2686
|
+
* const stopWhenConfident: LoopStrategy = {
|
|
2687
|
+
* name: 'confident',
|
|
2688
|
+
* maxIterations: 8,
|
|
2689
|
+
* shouldContinue: (o) => !o.responseText.includes('confidence: high'),
|
|
2690
|
+
* }
|
|
2691
|
+
* AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()
|
|
2692
|
+
* ```
|
|
2693
|
+
*/
|
|
2229
2694
|
loopStrategy(custom) {
|
|
2230
2695
|
assertValidCustomLoopStrategy(custom);
|
|
2231
2696
|
this.loopStrategyOverride = custom;
|
|
@@ -2237,12 +2702,15 @@ var AgentRunnerBuilder = class {
|
|
|
2237
2702
|
return this;
|
|
2238
2703
|
}
|
|
2239
2704
|
/**
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2705
|
+
* V4-F: declare the compaction strategy (e.g. `.compaction('token-budget', { keepTokens: 8000 })`).
|
|
2706
|
+
* Resolved + validated at {@link build} (EC-5 — fail-fast there, not here). This builder
|
|
2707
|
+
* call WINS over a `@Compaction` decorator on the same agent (EC-1 — explicit override).
|
|
2708
|
+
*/
|
|
2244
2709
|
compaction(name, options = {}) {
|
|
2245
|
-
this.compactionOverride = {
|
|
2710
|
+
this.compactionOverride = {
|
|
2711
|
+
name,
|
|
2712
|
+
keepTokens: options.keepTokens
|
|
2713
|
+
};
|
|
2246
2714
|
return this;
|
|
2247
2715
|
}
|
|
2248
2716
|
/** Resolve strategies from the spec — the compile→execute boundary (no I/O). */
|
|
@@ -2253,7 +2721,9 @@ var AgentRunnerBuilder = class {
|
|
|
2253
2721
|
const loopStrategy = this.loopStrategyOverride ?? resolveLoopStrategy(strategy, spec.maxIterations);
|
|
2254
2722
|
const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
|
|
2255
2723
|
const compactionDecl = this.compactionOverride ?? spec.compaction;
|
|
2256
|
-
const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
|
|
2724
|
+
const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
|
|
2725
|
+
keepTokens: compactionDecl.keepTokens
|
|
2726
|
+
}) : void 0;
|
|
2257
2727
|
return new AgentRunner({
|
|
2258
2728
|
compiled: spec.compiled,
|
|
2259
2729
|
agentName: spec.name,
|
|
@@ -2270,15 +2740,18 @@ var AgentRunnerBuilder = class {
|
|
|
2270
2740
|
import { runGoalLoop } from "@theokit/sdk";
|
|
2271
2741
|
import { JudgeCredentialError } from "@theokit/sdk";
|
|
2272
2742
|
var GoalRunner = class {
|
|
2743
|
+
static {
|
|
2744
|
+
__name(this, "GoalRunner");
|
|
2745
|
+
}
|
|
2746
|
+
agent;
|
|
2273
2747
|
constructor(agent) {
|
|
2274
2748
|
this.agent = agent;
|
|
2275
2749
|
}
|
|
2276
|
-
agent;
|
|
2277
2750
|
/**
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2751
|
+
* Drive `goal` to completion against the bound agent. Returns the SAME async generator `runGoalLoop`
|
|
2752
|
+
* returns — yielding `GoalEvent`s, resolving a `GoalResult`. `deps` (judge/clock overrides) threads
|
|
2753
|
+
* straight through; a test seam for the judge lives there, exactly as on the free function.
|
|
2754
|
+
*/
|
|
2282
2755
|
run(goal, options, deps) {
|
|
2283
2756
|
return runGoalLoop(this.agent, goal, options, deps);
|
|
2284
2757
|
}
|
|
@@ -2292,14 +2765,22 @@ function requireApiKey(opts, agentName) {
|
|
|
2292
2765
|
}
|
|
2293
2766
|
return apiKey;
|
|
2294
2767
|
}
|
|
2768
|
+
__name(requireApiKey, "requireApiKey");
|
|
2295
2769
|
function mergeTools(parentTools, subTools) {
|
|
2296
2770
|
const subToolNames = new Set(subTools.map((t) => t.name));
|
|
2297
2771
|
const inherited = parentTools.filter((t) => !subToolNames.has(t.name));
|
|
2298
|
-
return [
|
|
2772
|
+
return [
|
|
2773
|
+
...inherited,
|
|
2774
|
+
...subTools
|
|
2775
|
+
];
|
|
2299
2776
|
}
|
|
2777
|
+
__name(mergeTools, "mergeTools");
|
|
2300
2778
|
async function delegate(spec, message, opts = {}) {
|
|
2301
2779
|
const apiKey = requireApiKey(opts, spec.name);
|
|
2302
|
-
const effectiveMessage = opts.onDelegationStart ? await opts.onDelegationStart({
|
|
2780
|
+
const effectiveMessage = opts.onDelegationStart ? await opts.onDelegationStart({
|
|
2781
|
+
subAgent: spec.name,
|
|
2782
|
+
input: message
|
|
2783
|
+
}) : message;
|
|
2303
2784
|
const { compiled } = spec;
|
|
2304
2785
|
const allTools = mergeTools(opts.parentTools ?? [], compiled.tools);
|
|
2305
2786
|
const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity);
|
|
@@ -2313,10 +2794,7 @@ async function delegate(spec, message, opts = {}) {
|
|
|
2313
2794
|
sdkTools: opts.sdkTools
|
|
2314
2795
|
});
|
|
2315
2796
|
const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`;
|
|
2316
|
-
const loopStrategy = resolveLoopStrategy(
|
|
2317
|
-
spec.strategy ?? "simple-chat",
|
|
2318
|
-
opts.maxIterations ?? spec.maxIterations
|
|
2319
|
-
);
|
|
2797
|
+
const loopStrategy = resolveLoopStrategy(spec.strategy ?? "simple-chat", opts.maxIterations ?? spec.maxIterations);
|
|
2320
2798
|
const reflection = opts.reflection ?? (loopStrategy.name === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
|
|
2321
2799
|
const result = await runReflectiveLoop(streamFactory, effectiveMessage, sessionId, {
|
|
2322
2800
|
loop: loopStrategy,
|
|
@@ -2325,13 +2803,16 @@ async function delegate(spec, message, opts = {}) {
|
|
|
2325
2803
|
agentName: spec.name,
|
|
2326
2804
|
signal: opts.signal,
|
|
2327
2805
|
retry: opts.retry
|
|
2328
|
-
// V4-T: per-round transient retry (V4-P) on the delegate path
|
|
2329
2806
|
});
|
|
2330
2807
|
if (opts.onDelegationComplete) {
|
|
2331
|
-
return await opts.onDelegationComplete({
|
|
2808
|
+
return await opts.onDelegationComplete({
|
|
2809
|
+
subAgent: spec.name,
|
|
2810
|
+
result
|
|
2811
|
+
});
|
|
2332
2812
|
}
|
|
2333
2813
|
return result;
|
|
2334
2814
|
}
|
|
2815
|
+
__name(delegate, "delegate");
|
|
2335
2816
|
|
|
2336
2817
|
// src/bridge/api-error-handler.ts
|
|
2337
2818
|
var DEFAULT_MAX_ATTEMPTS = 3;
|
|
@@ -2343,7 +2824,10 @@ async function runWithApiErrorHandling(thunk, policy) {
|
|
|
2343
2824
|
try {
|
|
2344
2825
|
return await thunk();
|
|
2345
2826
|
} catch (error) {
|
|
2346
|
-
const decision = await policy.processApiError({
|
|
2827
|
+
const decision = await policy.processApiError({
|
|
2828
|
+
error,
|
|
2829
|
+
attempt
|
|
2830
|
+
});
|
|
2347
2831
|
if (decision.retry && attempt < maxAttempts) continue;
|
|
2348
2832
|
if (!decision.retry && "fallback" in decision && decision.fallback !== void 0) {
|
|
2349
2833
|
return decision.fallback;
|
|
@@ -2352,9 +2836,11 @@ async function runWithApiErrorHandling(thunk, policy) {
|
|
|
2352
2836
|
}
|
|
2353
2837
|
}
|
|
2354
2838
|
}
|
|
2839
|
+
__name(runWithApiErrorHandling, "runWithApiErrorHandling");
|
|
2355
2840
|
function createApiErrorHandler(policy) {
|
|
2356
2841
|
return (thunk) => runWithApiErrorHandling(thunk, policy);
|
|
2357
2842
|
}
|
|
2843
|
+
__name(createApiErrorHandler, "createApiErrorHandler");
|
|
2358
2844
|
|
|
2359
2845
|
// src/bridge/delegation-scoring.ts
|
|
2360
2846
|
function delegateBackground(subAgent, message, opts = {}) {
|
|
@@ -2365,24 +2851,20 @@ function delegateBackground(subAgent, message, opts = {}) {
|
|
|
2365
2851
|
});
|
|
2366
2852
|
promise.catch(() => void 0);
|
|
2367
2853
|
return {
|
|
2368
|
-
wait: () => promise,
|
|
2369
|
-
settled: () => isSettled
|
|
2854
|
+
wait: /* @__PURE__ */ __name(() => promise, "wait"),
|
|
2855
|
+
settled: /* @__PURE__ */ __name(() => isSettled, "settled")
|
|
2370
2856
|
};
|
|
2371
2857
|
}
|
|
2858
|
+
__name(delegateBackground, "delegateBackground");
|
|
2372
2859
|
var DEFAULT_MAX_ROUNDS = 3;
|
|
2373
2860
|
function defaultFeedbackTemplate(message, feedback) {
|
|
2374
2861
|
return `${message}
|
|
2375
2862
|
|
|
2376
2863
|
Feedback from the reviewer (address this): ${feedback}`;
|
|
2377
2864
|
}
|
|
2865
|
+
__name(defaultFeedbackTemplate, "defaultFeedbackTemplate");
|
|
2378
2866
|
async function delegateWithScoring(subAgent, message, opts) {
|
|
2379
|
-
const {
|
|
2380
|
-
scorer,
|
|
2381
|
-
maxRounds: maxRoundsOpt = DEFAULT_MAX_ROUNDS,
|
|
2382
|
-
delegateFn = delegate,
|
|
2383
|
-
feedbackTemplate = defaultFeedbackTemplate,
|
|
2384
|
-
...delegateOpts
|
|
2385
|
-
} = opts;
|
|
2867
|
+
const { scorer, maxRounds: maxRoundsOpt = DEFAULT_MAX_ROUNDS, delegateFn = delegate, feedbackTemplate = defaultFeedbackTemplate, ...delegateOpts } = opts;
|
|
2386
2868
|
const maxRounds = Math.max(1, maxRoundsOpt);
|
|
2387
2869
|
const verdicts = [];
|
|
2388
2870
|
let currentMessage = message;
|
|
@@ -2393,7 +2875,12 @@ async function delegateWithScoring(subAgent, message, opts) {
|
|
|
2393
2875
|
const verdict = await scorer(result);
|
|
2394
2876
|
verdicts.push(verdict);
|
|
2395
2877
|
if (verdict.pass) {
|
|
2396
|
-
return {
|
|
2878
|
+
return {
|
|
2879
|
+
result,
|
|
2880
|
+
rounds: round,
|
|
2881
|
+
passed: true,
|
|
2882
|
+
verdicts
|
|
2883
|
+
};
|
|
2397
2884
|
}
|
|
2398
2885
|
if (verdict.feedback) currentMessage = feedbackTemplate(message, verdict.feedback);
|
|
2399
2886
|
}
|
|
@@ -2407,6 +2894,7 @@ async function delegateWithScoring(subAgent, message, opts) {
|
|
|
2407
2894
|
verdicts
|
|
2408
2895
|
};
|
|
2409
2896
|
}
|
|
2897
|
+
__name(delegateWithScoring, "delegateWithScoring");
|
|
2410
2898
|
|
|
2411
2899
|
// src/bridge/mcp-resolver.ts
|
|
2412
2900
|
async function resolveMcpServers(selection, ctx) {
|
|
@@ -2418,6 +2906,7 @@ async function resolveMcpServers(selection, ctx) {
|
|
|
2418
2906
|
}
|
|
2419
2907
|
return resolved;
|
|
2420
2908
|
}
|
|
2909
|
+
__name(resolveMcpServers, "resolveMcpServers");
|
|
2421
2910
|
function mcpRegistry(config) {
|
|
2422
2911
|
const registry = config.registry;
|
|
2423
2912
|
if (registry === "composio") {
|
|
@@ -2425,8 +2914,17 @@ function mcpRegistry(config) {
|
|
|
2425
2914
|
return {
|
|
2426
2915
|
composio: {
|
|
2427
2916
|
command: "npx",
|
|
2428
|
-
args: [
|
|
2429
|
-
|
|
2917
|
+
args: [
|
|
2918
|
+
"-y",
|
|
2919
|
+
"@composio/mcp",
|
|
2920
|
+
...apps.length > 0 ? [
|
|
2921
|
+
"--apps",
|
|
2922
|
+
apps.join(",")
|
|
2923
|
+
] : []
|
|
2924
|
+
],
|
|
2925
|
+
env: {
|
|
2926
|
+
COMPOSIO_API_KEY: config.apiKey
|
|
2927
|
+
}
|
|
2430
2928
|
}
|
|
2431
2929
|
};
|
|
2432
2930
|
}
|
|
@@ -2438,23 +2936,30 @@ function mcpRegistry(config) {
|
|
|
2438
2936
|
"-y",
|
|
2439
2937
|
"@mcp.run/cli",
|
|
2440
2938
|
"serve",
|
|
2441
|
-
...config.profile ? [
|
|
2939
|
+
...config.profile ? [
|
|
2940
|
+
"--profile",
|
|
2941
|
+
config.profile
|
|
2942
|
+
] : []
|
|
2442
2943
|
],
|
|
2443
|
-
env: {
|
|
2944
|
+
env: {
|
|
2945
|
+
MCP_RUN_API_KEY: config.apiKey
|
|
2946
|
+
}
|
|
2444
2947
|
}
|
|
2445
2948
|
};
|
|
2446
2949
|
}
|
|
2447
|
-
throw new Error(
|
|
2448
|
-
`mcpRegistry: unknown registry ${JSON.stringify(registry)} (supported: 'composio', 'mcp.run').`
|
|
2449
|
-
);
|
|
2950
|
+
throw new Error(`mcpRegistry: unknown registry ${JSON.stringify(registry)} (supported: 'composio', 'mcp.run').`);
|
|
2450
2951
|
}
|
|
2952
|
+
__name(mcpRegistry, "mcpRegistry");
|
|
2451
2953
|
function mcpToolApprovals(specs) {
|
|
2452
2954
|
const out = {};
|
|
2453
2955
|
for (const [tool, spec] of Object.entries(specs)) {
|
|
2454
|
-
out[tool] = typeof spec === "string" ? {
|
|
2956
|
+
out[tool] = typeof spec === "string" ? {
|
|
2957
|
+
question: spec
|
|
2958
|
+
} : spec;
|
|
2455
2959
|
}
|
|
2456
2960
|
return out;
|
|
2457
2961
|
}
|
|
2962
|
+
__name(mcpToolApprovals, "mcpToolApprovals");
|
|
2458
2963
|
|
|
2459
2964
|
// src/bridge/mcp-file.ts
|
|
2460
2965
|
import { existsSync, readFileSync } from "fs";
|
|
@@ -2466,7 +2971,11 @@ function warningChannel(opts) {
|
|
|
2466
2971
|
`);
|
|
2467
2972
|
});
|
|
2468
2973
|
}
|
|
2974
|
+
__name(warningChannel, "warningChannel");
|
|
2469
2975
|
var McpFileError = class extends TheokitAgentError {
|
|
2976
|
+
static {
|
|
2977
|
+
__name(this, "McpFileError");
|
|
2978
|
+
}
|
|
2470
2979
|
name = "McpFileError";
|
|
2471
2980
|
constructor(message) {
|
|
2472
2981
|
super(`[@theokit/agents] ${message}`);
|
|
@@ -2490,6 +2999,7 @@ function loadMcpJson(cwd, opts = {}) {
|
|
|
2490
2999
|
}
|
|
2491
3000
|
return parseMcpJson(parsed, path, warningChannel(opts));
|
|
2492
3001
|
}
|
|
3002
|
+
__name(loadMcpJson, "loadMcpJson");
|
|
2493
3003
|
function parseMcpJson(raw, source, onWarn) {
|
|
2494
3004
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
2495
3005
|
throw new McpFileError(`${source}: root must be a JSON object with an "mcpServers" key.`);
|
|
@@ -2510,6 +3020,7 @@ function parseMcpJson(raw, source, onWarn) {
|
|
|
2510
3020
|
}
|
|
2511
3021
|
return out;
|
|
2512
3022
|
}
|
|
3023
|
+
__name(parseMcpJson, "parseMcpJson");
|
|
2513
3024
|
function validateEntry(name, entryRaw) {
|
|
2514
3025
|
if (typeof entryRaw !== "object" || entryRaw === null || Array.isArray(entryRaw)) {
|
|
2515
3026
|
return "the entry must be an object.";
|
|
@@ -2521,18 +3032,17 @@ function validateEntry(name, entryRaw) {
|
|
|
2521
3032
|
if (!hasUrl && !hasCommand) return 'requires "command" (stdio) or "url" (http/sse).';
|
|
2522
3033
|
return hasUrl ? validateRemote(entry) : validateStdio(entry);
|
|
2523
3034
|
}
|
|
3035
|
+
__name(validateEntry, "validateEntry");
|
|
2524
3036
|
function validateStdio(entry) {
|
|
2525
3037
|
if (typeof entry.command !== "string" || entry.command.length === 0) {
|
|
2526
3038
|
return 'field "command" must be a non-empty string.';
|
|
2527
3039
|
}
|
|
2528
|
-
if (entry.args !== void 0 && !isStringArray(entry.args))
|
|
2529
|
-
|
|
2530
|
-
if (entry.
|
|
2531
|
-
return 'field "env" must be a map of strings.';
|
|
2532
|
-
if (entry.cwd !== void 0 && typeof entry.cwd !== "string")
|
|
2533
|
-
return 'field "cwd" must be a string.';
|
|
3040
|
+
if (entry.args !== void 0 && !isStringArray(entry.args)) return 'field "args" must be an array of strings.';
|
|
3041
|
+
if (entry.env !== void 0 && !isStringRecord(entry.env)) return 'field "env" must be a map of strings.';
|
|
3042
|
+
if (entry.cwd !== void 0 && typeof entry.cwd !== "string") return 'field "cwd" must be a string.';
|
|
2534
3043
|
return void 0;
|
|
2535
3044
|
}
|
|
3045
|
+
__name(validateStdio, "validateStdio");
|
|
2536
3046
|
function validateRemote(entry) {
|
|
2537
3047
|
if (typeof entry.url !== "string" || entry.url.length === 0) {
|
|
2538
3048
|
return 'field "url" must be a non-empty string.';
|
|
@@ -2553,30 +3063,39 @@ function validateRemote(entry) {
|
|
|
2553
3063
|
}
|
|
2554
3064
|
return void 0;
|
|
2555
3065
|
}
|
|
3066
|
+
__name(validateRemote, "validateRemote");
|
|
2556
3067
|
function buildEntry(entry) {
|
|
2557
3068
|
if (entry.url !== void 0) {
|
|
2558
|
-
const remote = {
|
|
3069
|
+
const remote = {
|
|
3070
|
+
url: entry.url
|
|
3071
|
+
};
|
|
2559
3072
|
if (entry.type !== void 0) remote.type = entry.type;
|
|
2560
3073
|
if (entry.headers !== void 0) remote.headers = entry.headers;
|
|
2561
3074
|
if (entry.auth !== void 0) remote.auth = entry.auth;
|
|
2562
3075
|
if (entry.requestTimeoutMs !== void 0) remote.requestTimeoutMs = entry.requestTimeoutMs;
|
|
2563
3076
|
return remote;
|
|
2564
3077
|
}
|
|
2565
|
-
const stdio = {
|
|
3078
|
+
const stdio = {
|
|
3079
|
+
command: entry.command
|
|
3080
|
+
};
|
|
2566
3081
|
if (entry.args !== void 0) stdio.args = entry.args;
|
|
2567
3082
|
if (entry.env !== void 0) stdio.env = entry.env;
|
|
2568
3083
|
if (entry.cwd !== void 0) stdio.cwd = entry.cwd;
|
|
2569
3084
|
return stdio;
|
|
2570
3085
|
}
|
|
3086
|
+
__name(buildEntry, "buildEntry");
|
|
2571
3087
|
function describeIt(err) {
|
|
2572
3088
|
return err instanceof Error ? err.message : String(err);
|
|
2573
3089
|
}
|
|
3090
|
+
__name(describeIt, "describeIt");
|
|
2574
3091
|
function isStringArray(v) {
|
|
2575
3092
|
return Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
2576
3093
|
}
|
|
3094
|
+
__name(isStringArray, "isStringArray");
|
|
2577
3095
|
function isStringRecord(v) {
|
|
2578
3096
|
return typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
|
|
2579
3097
|
}
|
|
3098
|
+
__name(isStringRecord, "isStringRecord");
|
|
2580
3099
|
|
|
2581
3100
|
// src/manifest/agent-manifest.ts
|
|
2582
3101
|
function generateAgentManifest(sources) {
|
|
@@ -2594,17 +3113,15 @@ function generateAgentManifest(sources) {
|
|
|
2594
3113
|
},
|
|
2595
3114
|
guards: r.guards.map((g) => g.name),
|
|
2596
3115
|
interceptors: r.interceptors.map((i) => i.name),
|
|
2597
|
-
tools: r.toolboxes.flatMap(
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
}))
|
|
2607
|
-
),
|
|
3116
|
+
tools: r.toolboxes.flatMap((tb) => tb.tools.map((t) => ({
|
|
3117
|
+
name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,
|
|
3118
|
+
description: t.config.description,
|
|
3119
|
+
risk: t.config.risk,
|
|
3120
|
+
approval: t.approval !== void 0,
|
|
3121
|
+
capabilities: t.capabilities,
|
|
3122
|
+
trace: t.trace,
|
|
3123
|
+
audit: t.audit
|
|
3124
|
+
}))),
|
|
2608
3125
|
gateway: r.gateway ? {
|
|
2609
3126
|
platforms: r.gateway.platforms,
|
|
2610
3127
|
sessionStrategy: r.gateway.sessionStrategy ?? "per-user"
|
|
@@ -2621,6 +3138,7 @@ function generateAgentManifest(sources) {
|
|
|
2621
3138
|
}))
|
|
2622
3139
|
};
|
|
2623
3140
|
}
|
|
3141
|
+
__name(generateAgentManifest, "generateAgentManifest");
|
|
2624
3142
|
|
|
2625
3143
|
// src/theokit-plugin.ts
|
|
2626
3144
|
function validateUniqueRoutes(results) {
|
|
@@ -2628,13 +3146,12 @@ function validateUniqueRoutes(results) {
|
|
|
2628
3146
|
for (const r of results) {
|
|
2629
3147
|
const existing = seen.get(r.route);
|
|
2630
3148
|
if (existing !== void 0) {
|
|
2631
|
-
throw new Error(
|
|
2632
|
-
`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`
|
|
2633
|
-
);
|
|
3149
|
+
throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
|
|
2634
3150
|
}
|
|
2635
3151
|
seen.set(r.route, r.agentConfig.name);
|
|
2636
3152
|
}
|
|
2637
3153
|
}
|
|
3154
|
+
__name(validateUniqueRoutes, "validateUniqueRoutes");
|
|
2638
3155
|
function agentsPlugin(opts) {
|
|
2639
3156
|
let routes = null;
|
|
2640
3157
|
return {
|
|
@@ -2652,23 +3169,30 @@ function agentsPlugin(opts) {
|
|
|
2652
3169
|
}
|
|
2653
3170
|
};
|
|
2654
3171
|
}
|
|
3172
|
+
__name(agentsPlugin, "agentsPlugin");
|
|
2655
3173
|
function initRoutes(opts) {
|
|
2656
3174
|
const allRoutes = [];
|
|
2657
3175
|
const routeIdentities = [];
|
|
2658
3176
|
for (const entry of opts.agents) {
|
|
2659
|
-
routeIdentities.push({
|
|
3177
|
+
routeIdentities.push({
|
|
3178
|
+
route: entry.route,
|
|
3179
|
+
agentConfig: {
|
|
3180
|
+
name: entry.name
|
|
3181
|
+
}
|
|
3182
|
+
});
|
|
2660
3183
|
const createRun = opts.createRunFactory ? opts.createRunFactory(entry.compiled) : defaultCreateRun(entry.compiled);
|
|
2661
|
-
allRoutes.push(
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
);
|
|
3184
|
+
allRoutes.push(...generateAgentRoutes({
|
|
3185
|
+
walkResult: {
|
|
3186
|
+
route: entry.route
|
|
3187
|
+
},
|
|
3188
|
+
compiledOptions: entry.compiled,
|
|
3189
|
+
createRun
|
|
3190
|
+
}));
|
|
2668
3191
|
}
|
|
2669
3192
|
validateUniqueRoutes(routeIdentities);
|
|
2670
3193
|
return compileRoutePatterns(allRoutes);
|
|
2671
3194
|
}
|
|
3195
|
+
__name(initRoutes, "initRoutes");
|
|
2672
3196
|
function defaultCreateRun(compiled) {
|
|
2673
3197
|
return async function* (_message, _sessionId) {
|
|
2674
3198
|
await Promise.resolve();
|
|
@@ -2685,13 +3209,18 @@ function defaultCreateRun(compiled) {
|
|
|
2685
3209
|
};
|
|
2686
3210
|
};
|
|
2687
3211
|
}
|
|
3212
|
+
__name(defaultCreateRun, "defaultCreateRun");
|
|
2688
3213
|
function compileRoutePatterns(routes) {
|
|
2689
3214
|
return routes.map((r) => {
|
|
2690
3215
|
if (!r.path.includes(":")) return r;
|
|
2691
3216
|
const regexSource = r.path.replace(/:[^/]+/g, "[^/]+");
|
|
2692
|
-
return {
|
|
3217
|
+
return {
|
|
3218
|
+
...r,
|
|
3219
|
+
regex: RegExp(`^${regexSource}$`)
|
|
3220
|
+
};
|
|
2693
3221
|
});
|
|
2694
3222
|
}
|
|
3223
|
+
__name(compileRoutePatterns, "compileRoutePatterns");
|
|
2695
3224
|
function matchRoute(routes, method, pathname) {
|
|
2696
3225
|
return routes.find((r) => {
|
|
2697
3226
|
if (r.method !== method) return false;
|
|
@@ -2699,6 +3228,7 @@ function matchRoute(routes, method, pathname) {
|
|
|
2699
3228
|
return r.path === pathname;
|
|
2700
3229
|
});
|
|
2701
3230
|
}
|
|
3231
|
+
__name(matchRoute, "matchRoute");
|
|
2702
3232
|
|
|
2703
3233
|
export {
|
|
2704
3234
|
ConfigurationError,
|
|
@@ -2779,4 +3309,4 @@ export {
|
|
|
2779
3309
|
generateAgentManifest,
|
|
2780
3310
|
agentsPlugin
|
|
2781
3311
|
};
|
|
2782
|
-
//# sourceMappingURL=chunk-
|
|
3312
|
+
//# sourceMappingURL=chunk-WKBZZQBO.js.map
|