@niscorp/cortex 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +695 -0
- package/LICENSE +202 -0
- package/README.md +291 -0
- package/dist/index.cjs +1288 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +450 -0
- package/dist/index.d.ts +450 -0
- package/dist/index.js +1270 -0
- package/dist/index.js.map +1 -0
- package/package.json +57 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1270 @@
|
|
|
1
|
+
import { resolveTransport, RESPOND_TOOL_NAME, deepDecodeJsonish, decodeJsonish } from '@niscorp/signal';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { createStream } from '@niscorp/solid';
|
|
4
|
+
|
|
5
|
+
// src/errors/cortex.errors.ts
|
|
6
|
+
var makeError = (code, message, context) => ({
|
|
7
|
+
code,
|
|
8
|
+
message,
|
|
9
|
+
runId: context.runId,
|
|
10
|
+
agentPath: context.agentPath,
|
|
11
|
+
...context.stop !== void 0 && { stop: context.stop },
|
|
12
|
+
...context.lastOutput !== void 0 && { lastOutput: context.lastOutput },
|
|
13
|
+
...context.cause !== void 0 && { cause: context.cause }
|
|
14
|
+
});
|
|
15
|
+
var throwConfig = (message) => {
|
|
16
|
+
throw new Error(`[cortex:config] ${message}`);
|
|
17
|
+
};
|
|
18
|
+
var ok = (data) => ({ ok: true, data });
|
|
19
|
+
var err = (error) => ({ ok: false, error });
|
|
20
|
+
|
|
21
|
+
// src/types.ts
|
|
22
|
+
var EMPTY_USAGE = { inputTokens: 0, outputTokens: 0, totalTokens: 0, reported: true };
|
|
23
|
+
var addUsage = (a, b) => ({
|
|
24
|
+
inputTokens: a.inputTokens + b.inputTokens,
|
|
25
|
+
outputTokens: a.outputTokens + b.outputTokens,
|
|
26
|
+
totalTokens: a.totalTokens + b.totalTokens,
|
|
27
|
+
reported: a.reported && b.reported
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// src/events/channel.ts
|
|
31
|
+
var createEventChannel = (runId, agentPath) => {
|
|
32
|
+
const listeners = [];
|
|
33
|
+
const buffer = [];
|
|
34
|
+
let closed = false;
|
|
35
|
+
let seq = 0;
|
|
36
|
+
let wake;
|
|
37
|
+
const push = (event) => {
|
|
38
|
+
for (const listener of [...listeners]) {
|
|
39
|
+
try {
|
|
40
|
+
listener(event);
|
|
41
|
+
} catch {
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
buffer.push(event);
|
|
45
|
+
wake?.();
|
|
46
|
+
};
|
|
47
|
+
const emit = (body) => {
|
|
48
|
+
if (closed) return;
|
|
49
|
+
seq += 1;
|
|
50
|
+
push({ runId, agentPath, seq, ts: Date.now(), ...body });
|
|
51
|
+
};
|
|
52
|
+
const forward = (event) => {
|
|
53
|
+
if (closed) return;
|
|
54
|
+
push(event);
|
|
55
|
+
};
|
|
56
|
+
const onEvent = (listener) => {
|
|
57
|
+
listeners.push(listener);
|
|
58
|
+
return () => {
|
|
59
|
+
const index = listeners.indexOf(listener);
|
|
60
|
+
if (index >= 0) listeners.splice(index, 1);
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
const close = () => {
|
|
64
|
+
closed = true;
|
|
65
|
+
wake?.();
|
|
66
|
+
};
|
|
67
|
+
const events = {
|
|
68
|
+
[Symbol.asyncIterator]: () => {
|
|
69
|
+
let cursor = 0;
|
|
70
|
+
return {
|
|
71
|
+
next: async () => {
|
|
72
|
+
while (cursor >= buffer.length) {
|
|
73
|
+
if (closed) return { done: true, value: void 0 };
|
|
74
|
+
await new Promise((resolve) => {
|
|
75
|
+
wake = resolve;
|
|
76
|
+
});
|
|
77
|
+
wake = void 0;
|
|
78
|
+
}
|
|
79
|
+
const value = buffer[cursor];
|
|
80
|
+
cursor += 1;
|
|
81
|
+
if (value === void 0) return { done: true, value: void 0 };
|
|
82
|
+
return { done: false, value };
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
return { emit, forward, onEvent, events, close };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// src/context/assemble.ts
|
|
91
|
+
var isMessageArray = (value) => Array.isArray(value) && value.length > 0 && value.every(
|
|
92
|
+
(item) => typeof item === "object" && item !== null && "role" in item && typeof item.role === "string"
|
|
93
|
+
);
|
|
94
|
+
var inputMessages = (input) => {
|
|
95
|
+
if (typeof input === "string") return [{ role: "user", content: input }];
|
|
96
|
+
if (isMessageArray(input)) return input;
|
|
97
|
+
return [{ role: "user", content: JSON.stringify(input) }];
|
|
98
|
+
};
|
|
99
|
+
var entryMessages = (entry) => {
|
|
100
|
+
if (typeof entry === "string") {
|
|
101
|
+
return entry.length > 0 ? [{ role: "system", content: entry }] : [];
|
|
102
|
+
}
|
|
103
|
+
if (isMessageArray(entry)) return entry;
|
|
104
|
+
return entry.filter((chunk) => typeof chunk === "string" && chunk.length > 0).map((chunk) => ({ role: "system", content: chunk }));
|
|
105
|
+
};
|
|
106
|
+
var assembleContext = async (items, args) => {
|
|
107
|
+
const messages = [];
|
|
108
|
+
for (const item of items) {
|
|
109
|
+
const entry = typeof item === "function" ? await item(args) : item;
|
|
110
|
+
messages.push(...entryMessages(entry));
|
|
111
|
+
}
|
|
112
|
+
return messages;
|
|
113
|
+
};
|
|
114
|
+
var toolGuidesMessage = (tools) => {
|
|
115
|
+
const guides = tools.map((tool) => {
|
|
116
|
+
const guide = tool.config.guide;
|
|
117
|
+
const produced = typeof guide === "function" ? guide() : guide;
|
|
118
|
+
const text = Array.isArray(produced) ? produced.join("\n") : produced;
|
|
119
|
+
return text !== void 0 && text.length > 0 ? `\u2500\u2500 ${tool.config.name} \u2500\u2500
|
|
120
|
+
${text}` : void 0;
|
|
121
|
+
}).filter((section) => section !== void 0);
|
|
122
|
+
if (guides.length === 0) return [];
|
|
123
|
+
return [
|
|
124
|
+
{
|
|
125
|
+
role: "system",
|
|
126
|
+
content: `TOOL GUIDES \u2014 how to use the tools on this run:
|
|
127
|
+
|
|
128
|
+
${guides.join("\n\n")}`
|
|
129
|
+
}
|
|
130
|
+
];
|
|
131
|
+
};
|
|
132
|
+
var estimateTokens = (messages) => {
|
|
133
|
+
let total = 0;
|
|
134
|
+
for (const message of messages) {
|
|
135
|
+
total += 4;
|
|
136
|
+
if (typeof message.content === "string") {
|
|
137
|
+
total += Math.ceil(message.content.length / 4);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
for (const part of message.content) {
|
|
141
|
+
total += part.type === "text" ? Math.ceil(part.text.length / 4) : 256;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return total;
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
// src/context/schema-doc.ts
|
|
148
|
+
var toJsonSchemaString = (schema) => {
|
|
149
|
+
const convert = schema["~standard"].jsonSchema.output;
|
|
150
|
+
try {
|
|
151
|
+
return JSON.stringify(convert({ target: "draft-07" }));
|
|
152
|
+
} catch {
|
|
153
|
+
return JSON.stringify(convert({ target: "draft-07", libraryOptions: { unrepresentable: "any" } }));
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
var schemaDoc = (schema, options) => {
|
|
157
|
+
const title = options?.title ?? "OUTPUT SCHEMA";
|
|
158
|
+
return `${title} \u2014 your output MUST validate against this JSON Schema:
|
|
159
|
+
${toJsonSchemaString(schema)}`;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// src/utils/schema-issues.ts
|
|
163
|
+
var rootScore = (branch) => {
|
|
164
|
+
let score = 0;
|
|
165
|
+
for (const issue of branch) {
|
|
166
|
+
if (issue.path.length !== 0) continue;
|
|
167
|
+
score += issue.code === "invalid_type" ? 100 : issue.code === "unrecognized_keys" ? 1 : 10;
|
|
168
|
+
}
|
|
169
|
+
return score;
|
|
170
|
+
};
|
|
171
|
+
var pickBranch = (branches) => branches.reduce((best, branch) => {
|
|
172
|
+
const byRoot = rootScore(branch) - rootScore(best);
|
|
173
|
+
if (byRoot !== 0) return byRoot < 0 ? branch : best;
|
|
174
|
+
return branch.length < best.length ? branch : best;
|
|
175
|
+
});
|
|
176
|
+
var flattenSchemaIssues = (issues, prefix = []) => issues.flatMap((issue) => {
|
|
177
|
+
const path = [...prefix, ...issue.path];
|
|
178
|
+
if (issue.code !== "invalid_union" || !issue.errors || issue.errors.length === 0) return [{ ...issue, path }];
|
|
179
|
+
return flattenSchemaIssues(pickBranch(issue.errors), path);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
// src/utils/trust.ts
|
|
183
|
+
var trustErased = (value) => value;
|
|
184
|
+
var trustUndefinedData = () => void 0;
|
|
185
|
+
|
|
186
|
+
// src/schemas/envelope.schema.ts
|
|
187
|
+
var RESPONSE_DESCRIPTION = "Human-facing text answer. Plain prose, no JSON.";
|
|
188
|
+
var REASONING_DESCRIPTION = "Short model-authored note, written FIRST: what you are about to do and why. It comes before your answer, so use it to decide rather than to justify.";
|
|
189
|
+
var LOOSE_DATA_DESCRIPTION = "The final answer payload. MUST validate against the OUTPUT SCHEMA documented in the system prompt.";
|
|
190
|
+
var envelopeWireSchema = (spec) => {
|
|
191
|
+
const response = spec.responseMode === "required" ? z.string().describe(RESPONSE_DESCRIPTION) : z.string().nullish().describe(RESPONSE_DESCRIPTION);
|
|
192
|
+
if (spec.schema) {
|
|
193
|
+
return z.object({
|
|
194
|
+
reasoning: z.string().nullish().describe(REASONING_DESCRIPTION),
|
|
195
|
+
response,
|
|
196
|
+
data: spec.schema
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return z.object({
|
|
200
|
+
reasoning: z.string().nullish().describe(REASONING_DESCRIPTION),
|
|
201
|
+
response
|
|
202
|
+
});
|
|
203
|
+
};
|
|
204
|
+
var envelopeLooseWireSchema = (spec) => {
|
|
205
|
+
const response = spec.responseMode === "required" ? z.string().describe(RESPONSE_DESCRIPTION) : z.string().nullish().describe(RESPONSE_DESCRIPTION);
|
|
206
|
+
if (spec.hasData) {
|
|
207
|
+
return z.object({
|
|
208
|
+
reasoning: z.string().nullish().describe(REASONING_DESCRIPTION),
|
|
209
|
+
response,
|
|
210
|
+
// A typed union, not z.unknown(): an empty {} schema gives the
|
|
211
|
+
// model zero type signal and invites stringified payloads.
|
|
212
|
+
data: z.union([z.record(z.string(), z.unknown()), z.array(z.unknown())]).describe(LOOSE_DATA_DESCRIPTION)
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return z.object({
|
|
216
|
+
reasoning: z.string().nullish().describe(REASONING_DESCRIPTION),
|
|
217
|
+
response
|
|
218
|
+
});
|
|
219
|
+
};
|
|
220
|
+
var envelopeAcceptSchema = (_spec) => z.union([z.record(z.string(), z.unknown()), z.array(z.unknown())]);
|
|
221
|
+
var KNOWN_KEYS = /* @__PURE__ */ new Set(["response", "data", "reasoning"]);
|
|
222
|
+
var decodeData = decodeJsonish;
|
|
223
|
+
var tryUnwrap = (record, spec) => {
|
|
224
|
+
if (!spec.schema || spec.responseMode === "required") return void 0;
|
|
225
|
+
const keys = Object.keys(record);
|
|
226
|
+
const looksWrapped = keys.length > 0 && keys.every((key) => KNOWN_KEYS.has(key));
|
|
227
|
+
if (looksWrapped) return void 0;
|
|
228
|
+
const parsed = spec.schema.safeParse(record);
|
|
229
|
+
if (!parsed.success) return void 0;
|
|
230
|
+
return { data: parsed.data };
|
|
231
|
+
};
|
|
232
|
+
var validateEnvelope = (raw, spec) => {
|
|
233
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
234
|
+
return { ok: false, issues: "envelope must be a JSON object with { response?, data?, reasoning? }" };
|
|
235
|
+
}
|
|
236
|
+
const record = { ...raw };
|
|
237
|
+
const issues = [];
|
|
238
|
+
for (const key of Object.keys(record)) {
|
|
239
|
+
if (!KNOWN_KEYS.has(key)) issues.push(`unknown key "${key}" \u2014 only response, data, reasoning are allowed`);
|
|
240
|
+
}
|
|
241
|
+
if (issues.length > 0) {
|
|
242
|
+
const unwrapped = tryUnwrap(record, spec);
|
|
243
|
+
if (unwrapped !== void 0) return { ok: true, envelope: unwrapped };
|
|
244
|
+
}
|
|
245
|
+
const response = record["response"] ?? void 0;
|
|
246
|
+
if (spec.responseMode === "required" && typeof response !== "string") {
|
|
247
|
+
issues.push("response: required \u2014 a plain-text string answer");
|
|
248
|
+
} else if (response !== void 0 && typeof response !== "string") {
|
|
249
|
+
issues.push("response: must be a string");
|
|
250
|
+
}
|
|
251
|
+
const reasoning = record["reasoning"] ?? void 0;
|
|
252
|
+
if (reasoning !== void 0 && typeof reasoning !== "string") {
|
|
253
|
+
issues.push("reasoning: must be a string");
|
|
254
|
+
}
|
|
255
|
+
if (spec.schema) {
|
|
256
|
+
const data = decodeData(record["data"]);
|
|
257
|
+
let parsed = spec.schema.safeParse(data);
|
|
258
|
+
if (!parsed.success) {
|
|
259
|
+
const repaired = spec.schema.safeParse(deepDecodeJsonish(data));
|
|
260
|
+
if (repaired.success) parsed = repaired;
|
|
261
|
+
}
|
|
262
|
+
if (!parsed.success) {
|
|
263
|
+
for (const issue of flattenSchemaIssues(parsed.error.issues)) {
|
|
264
|
+
const path = issue.path.length > 0 ? `data.${issue.path.join(".")}` : "data";
|
|
265
|
+
issues.push(`${path}: ${issue.message}`);
|
|
266
|
+
}
|
|
267
|
+
if (typeof data === "string") {
|
|
268
|
+
issues.push("data arrived as ONE STRING \u2014 pass the payload as a plain JSON value, not a quoted string");
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (issues.length > 0) return { ok: false, issues: issues.join("; ") };
|
|
272
|
+
if (!parsed.success) return { ok: false, issues: "data failed schema validation" };
|
|
273
|
+
const envelope2 = {
|
|
274
|
+
...typeof response === "string" && { response },
|
|
275
|
+
data: parsed.data,
|
|
276
|
+
...typeof reasoning === "string" && { reasoning }
|
|
277
|
+
};
|
|
278
|
+
return { ok: true, envelope: envelope2 };
|
|
279
|
+
}
|
|
280
|
+
if ((record["data"] ?? void 0) !== void 0) {
|
|
281
|
+
issues.push("data: unexpected \u2014 this agent returns no data payload");
|
|
282
|
+
}
|
|
283
|
+
if (issues.length > 0) return { ok: false, issues: issues.join("; ") };
|
|
284
|
+
const envelope = {
|
|
285
|
+
...typeof response === "string" && { response },
|
|
286
|
+
data: trustUndefinedData(),
|
|
287
|
+
...typeof reasoning === "string" && { reasoning }
|
|
288
|
+
};
|
|
289
|
+
return { ok: true, envelope };
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
// src/utils/duration.ts
|
|
293
|
+
var DURATION_REGEX = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/;
|
|
294
|
+
var UNIT_MS = { ms: 1, s: 1e3, m: 6e4, h: 36e5 };
|
|
295
|
+
var parseDuration = (value) => {
|
|
296
|
+
if (typeof value === "number") return value;
|
|
297
|
+
const match = value.trim().match(DURATION_REGEX);
|
|
298
|
+
const unit = match?.[2] !== void 0 ? UNIT_MS[match[2]] : void 0;
|
|
299
|
+
if (!match || match[1] === void 0 || unit === void 0) {
|
|
300
|
+
throw new Error(`[cortex:config] Invalid duration "${value}". Use a number of ms or "<n>ms" / "<n>s" / "<n>m" / "<n>h".`);
|
|
301
|
+
}
|
|
302
|
+
return Math.round(Number(match[1]) * unit);
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
// src/gates/stop.ts
|
|
306
|
+
var stepCount = (max) => (progress) => progress.steps >= max ? { stop: "steps", message: `step limit reached (${max})` } : null;
|
|
307
|
+
var tokens = (max) => (progress) => progress.usage.totalTokens >= max ? { stop: "tokens", message: `token budget reached (${progress.usage.totalTokens}/${max})` } : null;
|
|
308
|
+
var duration = (value) => {
|
|
309
|
+
const maxMs = parseDuration(value);
|
|
310
|
+
return (progress) => progress.elapsedMs >= maxMs ? { stop: "duration", message: `duration limit reached (${maxMs}ms)` } : null;
|
|
311
|
+
};
|
|
312
|
+
var outputRetries = (max) => (progress) => progress.outputRetries >= max ? { stop: "output_retries", message: `output retries exhausted (${max})` } : null;
|
|
313
|
+
var repeatedCalls = (max) => (progress) => progress.repeatedCalls >= max ? { stop: "repeated_calls", message: `the same tool call got the same answer ${progress.repeatedCalls + 1} times in a row` } : null;
|
|
314
|
+
var DEFAULT_STOP_CONDITIONS = [stepCount(20), outputRetries(3)];
|
|
315
|
+
var checkStop = (conditions, progress) => {
|
|
316
|
+
for (const condition of conditions) {
|
|
317
|
+
const verdict = condition(progress);
|
|
318
|
+
if (verdict) return verdict;
|
|
319
|
+
}
|
|
320
|
+
return null;
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
// src/utils/timeout.ts
|
|
324
|
+
var DEFAULT_TOOL_TIMEOUT_MS = 3e4;
|
|
325
|
+
var withTimeout = (promise, timeoutMs, label) => {
|
|
326
|
+
const resolved = Promise.resolve(promise);
|
|
327
|
+
if (timeoutMs <= 0) return resolved;
|
|
328
|
+
return new Promise((resolve, reject) => {
|
|
329
|
+
const timer = setTimeout(() => {
|
|
330
|
+
reject(new Error(`${label} timed out after ${timeoutMs}ms`));
|
|
331
|
+
}, timeoutMs);
|
|
332
|
+
resolved.then(
|
|
333
|
+
(value) => {
|
|
334
|
+
clearTimeout(timer);
|
|
335
|
+
resolve(value);
|
|
336
|
+
},
|
|
337
|
+
(err2) => {
|
|
338
|
+
clearTimeout(timer);
|
|
339
|
+
reject(err2);
|
|
340
|
+
}
|
|
341
|
+
);
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
// src/utils/id.ts
|
|
346
|
+
var randomId = () => {
|
|
347
|
+
const c = globalThis.crypto;
|
|
348
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
349
|
+
return `id_${Date.now().toString(36)}_${Math.floor(Math.random() * 1e9).toString(36)}`;
|
|
350
|
+
};
|
|
351
|
+
var newRunId = () => `run_${randomId()}`;
|
|
352
|
+
var newApprovalId = () => `apr_${randomId()}`;
|
|
353
|
+
|
|
354
|
+
// src/loop/loop.ts
|
|
355
|
+
var isEmptyObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0;
|
|
356
|
+
var stringify = (value) => {
|
|
357
|
+
if (typeof value === "string") return value;
|
|
358
|
+
try {
|
|
359
|
+
const text = JSON.stringify(value);
|
|
360
|
+
return text === void 0 ? String(value) : text;
|
|
361
|
+
} catch {
|
|
362
|
+
return String(value);
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
var buildToolDescriptor = (tool) => ({
|
|
366
|
+
// The model sees the tool's NAME — the field designed for it (prompts
|
|
367
|
+
// say "call `query`"). The id stays the gate/policy/observation
|
|
368
|
+
// identity; the loop resolves calls by either.
|
|
369
|
+
name: tool.config.name,
|
|
370
|
+
description: tool.config.description,
|
|
371
|
+
// The tool's schema converts itself (Standard JSON Schema) — it may come from
|
|
372
|
+
// the caller's zod copy, not ours.
|
|
373
|
+
parameters: tool.config.input["~standard"].jsonSchema.output({ target: "draft-07" })
|
|
374
|
+
});
|
|
375
|
+
var runLoop = async (cfg) => {
|
|
376
|
+
const s = cfg.state;
|
|
377
|
+
const spec = {
|
|
378
|
+
...cfg.outputSchema && { schema: cfg.outputSchema },
|
|
379
|
+
responseMode: cfg.resolved.responseMode
|
|
380
|
+
};
|
|
381
|
+
const elapsedMs = () => s.elapsedBase + (Date.now() - s.startedAt);
|
|
382
|
+
const lastCall = { key: "", repeats: 0 };
|
|
383
|
+
const progress = () => ({
|
|
384
|
+
steps: s.steps,
|
|
385
|
+
usage: s.usage,
|
|
386
|
+
elapsedMs: elapsedMs(),
|
|
387
|
+
outputRetries: s.outputRetries,
|
|
388
|
+
repeatedCalls: lastCall.repeats
|
|
389
|
+
});
|
|
390
|
+
const meta = () => ({
|
|
391
|
+
usage: s.usage,
|
|
392
|
+
strategy: cfg.resolved.transport,
|
|
393
|
+
steps: s.steps,
|
|
394
|
+
outputRetries: s.outputRetries,
|
|
395
|
+
elapsedMs: elapsedMs()
|
|
396
|
+
});
|
|
397
|
+
const errorContext = { runId: cfg.runId, agentPath: cfg.agentPath };
|
|
398
|
+
const fail = (error) => ({ ok: false, error, meta: meta() });
|
|
399
|
+
const failStopped = (verdict) => fail(makeError("stopped", verdict.message, { ...errorContext, stop: verdict.stop }));
|
|
400
|
+
const toolMap = /* @__PURE__ */ new Map();
|
|
401
|
+
for (const tool of cfg.tools) {
|
|
402
|
+
toolMap.set(tool.config.id, tool);
|
|
403
|
+
toolMap.set(tool.config.name, tool);
|
|
404
|
+
}
|
|
405
|
+
const callableNames = cfg.tools.map((tool) => tool.config.name);
|
|
406
|
+
const domainDescriptors = cfg.tools.map(buildToolDescriptor);
|
|
407
|
+
const exitDescriptor = cfg.resolved.respondDescriptor;
|
|
408
|
+
const runCtx = () => ({
|
|
409
|
+
runId: cfg.runId,
|
|
410
|
+
agentId: cfg.agentId,
|
|
411
|
+
agentPath: cfg.agentPath,
|
|
412
|
+
deps: cfg.deps,
|
|
413
|
+
step: s.steps,
|
|
414
|
+
usage: s.usage,
|
|
415
|
+
signal: cfg.abort
|
|
416
|
+
});
|
|
417
|
+
const toolContext = () => ({
|
|
418
|
+
runId: cfg.runId,
|
|
419
|
+
agentId: cfg.agentId,
|
|
420
|
+
agentPath: cfg.agentPath,
|
|
421
|
+
signal: cfg.abort,
|
|
422
|
+
forward: cfg.forwardEvent
|
|
423
|
+
});
|
|
424
|
+
const appendToolMessage = (call, content) => {
|
|
425
|
+
s.messages.push({ role: "tool", toolCallId: call.id, name: call.toolId, content });
|
|
426
|
+
};
|
|
427
|
+
const record = (call, observation, message) => {
|
|
428
|
+
cfg.emit({ type: "tool-end", observation });
|
|
429
|
+
appendToolMessage(call, message);
|
|
430
|
+
const key = JSON.stringify([observation.toolId, observation.args, message]);
|
|
431
|
+
lastCall.repeats = key === lastCall.key ? lastCall.repeats + 1 : 0;
|
|
432
|
+
lastCall.key = key;
|
|
433
|
+
};
|
|
434
|
+
const executeCall = async (call, remaining) => {
|
|
435
|
+
if (cfg.abort.aborted) return fail(makeError("aborted", "run aborted", errorContext));
|
|
436
|
+
cfg.emit({ type: "tool-start", call: { id: call.id, toolId: call.toolId, args: call.args } });
|
|
437
|
+
const tool = toolMap.get(call.toolId);
|
|
438
|
+
if (!tool) {
|
|
439
|
+
record(
|
|
440
|
+
call,
|
|
441
|
+
{ kind: "unknown-tool", callId: call.id, toolId: call.toolId, args: call.args },
|
|
442
|
+
`error: unknown tool "${call.toolId}" \u2014 the available tools are: ${callableNames.join(", ")}`
|
|
443
|
+
);
|
|
444
|
+
return void 0;
|
|
445
|
+
}
|
|
446
|
+
const toolId = tool.config.id;
|
|
447
|
+
let args = call.args;
|
|
448
|
+
let denial;
|
|
449
|
+
for (const gate of cfg.gates) {
|
|
450
|
+
const decision = await gate(
|
|
451
|
+
{
|
|
452
|
+
id: call.id,
|
|
453
|
+
toolId,
|
|
454
|
+
args,
|
|
455
|
+
...tool.config.riskLevel !== void 0 && { riskLevel: tool.config.riskLevel }
|
|
456
|
+
},
|
|
457
|
+
runCtx()
|
|
458
|
+
);
|
|
459
|
+
if ("deny" in decision) {
|
|
460
|
+
denial = decision.deny;
|
|
461
|
+
break;
|
|
462
|
+
}
|
|
463
|
+
if ("ask" in decision) {
|
|
464
|
+
const approvalId = newApprovalId();
|
|
465
|
+
s.pending = { approvalId, call: { ...call, args }, remaining, reason: decision.ask.reason };
|
|
466
|
+
const askPromise = cfg.approvals.ask(approvalId, cfg.approvalTimeoutMs);
|
|
467
|
+
cfg.emit({
|
|
468
|
+
type: "approval-required",
|
|
469
|
+
approval: { id: approvalId, toolId, callId: call.id, args, reason: decision.ask.reason }
|
|
470
|
+
});
|
|
471
|
+
const outcome = await new Promise((resolve) => {
|
|
472
|
+
const onAbort = () => resolve({ approved: false, reason: "aborted" });
|
|
473
|
+
if (cfg.abort.aborted) {
|
|
474
|
+
onAbort();
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
cfg.abort.addEventListener("abort", onAbort, { once: true });
|
|
478
|
+
void askPromise.then((askDecision) => {
|
|
479
|
+
cfg.abort.removeEventListener("abort", onAbort);
|
|
480
|
+
resolve(askDecision);
|
|
481
|
+
});
|
|
482
|
+
});
|
|
483
|
+
if (cfg.abort.aborted) return fail(makeError("aborted", "run aborted", errorContext));
|
|
484
|
+
s.pending = void 0;
|
|
485
|
+
if (!outcome.approved) {
|
|
486
|
+
denial = outcome.reason;
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
if (outcome.args !== void 0) args = outcome.args;
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
if (decision.args !== void 0) args = decision.args;
|
|
493
|
+
}
|
|
494
|
+
if (denial !== void 0) {
|
|
495
|
+
record(
|
|
496
|
+
call,
|
|
497
|
+
{ kind: "denied", callId: call.id, toolId, args, reason: denial },
|
|
498
|
+
`error: denied: ${denial}`
|
|
499
|
+
);
|
|
500
|
+
return void 0;
|
|
501
|
+
}
|
|
502
|
+
let parsedArgs = tool.config.input.safeParse(args);
|
|
503
|
+
if (!parsedArgs.success) {
|
|
504
|
+
const repaired = tool.config.input.safeParse(deepDecodeJsonish(args));
|
|
505
|
+
if (repaired.success) parsedArgs = repaired;
|
|
506
|
+
}
|
|
507
|
+
if (!parsedArgs.success) {
|
|
508
|
+
const issues = parsedArgs.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
|
|
509
|
+
const hint = typeof args === "string" ? ' (your arguments arrived as ONE STRING \u2014 call again with a plain JSON object, e.g. {"key": "value"})' : isEmptyObject(args) ? ` (your arguments arrived EMPTY \u2014 nothing was sent. Call ${toolId} again with its arguments filled in, as its parameters describe)` : "";
|
|
510
|
+
record(
|
|
511
|
+
call,
|
|
512
|
+
{
|
|
513
|
+
kind: "error",
|
|
514
|
+
callId: call.id,
|
|
515
|
+
toolId,
|
|
516
|
+
args,
|
|
517
|
+
error: `input_invalid: ${issues}${hint}`,
|
|
518
|
+
durationMs: 0
|
|
519
|
+
},
|
|
520
|
+
`error: input_invalid: ${issues}${hint}`
|
|
521
|
+
);
|
|
522
|
+
return void 0;
|
|
523
|
+
}
|
|
524
|
+
const started = Date.now();
|
|
525
|
+
try {
|
|
526
|
+
const timeoutMs = tool.config.timeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;
|
|
527
|
+
const value = await withTimeout(
|
|
528
|
+
Promise.resolve(tool.config.execute(parsedArgs.data, toolContext())),
|
|
529
|
+
timeoutMs,
|
|
530
|
+
`tool ${toolId}`
|
|
531
|
+
);
|
|
532
|
+
let observation = {
|
|
533
|
+
kind: "result",
|
|
534
|
+
callId: call.id,
|
|
535
|
+
toolId,
|
|
536
|
+
args: parsedArgs.data,
|
|
537
|
+
result: value,
|
|
538
|
+
durationMs: Date.now() - started
|
|
539
|
+
};
|
|
540
|
+
for (const hook of cfg.resultHooks) {
|
|
541
|
+
const outcome = await hook(observation, runCtx());
|
|
542
|
+
if (outcome && outcome.result !== void 0) {
|
|
543
|
+
observation = { ...observation, result: outcome.result };
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
const finalResult = observation.kind === "result" ? observation.result : void 0;
|
|
547
|
+
record(call, observation, stringify(finalResult));
|
|
548
|
+
} catch (cause) {
|
|
549
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
550
|
+
record(
|
|
551
|
+
call,
|
|
552
|
+
{
|
|
553
|
+
kind: "error",
|
|
554
|
+
callId: call.id,
|
|
555
|
+
toolId,
|
|
556
|
+
args: parsedArgs.data,
|
|
557
|
+
error: message,
|
|
558
|
+
durationMs: Date.now() - started
|
|
559
|
+
},
|
|
560
|
+
`error: ${message}`
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
return void 0;
|
|
564
|
+
};
|
|
565
|
+
const processBatch = async (calls) => {
|
|
566
|
+
for (let index = 0; index < calls.length; index += 1) {
|
|
567
|
+
const call = calls[index];
|
|
568
|
+
if (call === void 0) continue;
|
|
569
|
+
const structural = await executeCall(call, calls.slice(index + 1));
|
|
570
|
+
if (structural) return structural;
|
|
571
|
+
}
|
|
572
|
+
return void 0;
|
|
573
|
+
};
|
|
574
|
+
const validateOutput = async (raw) => {
|
|
575
|
+
const verdict = validateEnvelope(raw, spec);
|
|
576
|
+
if (!verdict.ok) return verdict;
|
|
577
|
+
if (cfg.outputValidate) {
|
|
578
|
+
const validated = await cfg.outputValidate(verdict.envelope);
|
|
579
|
+
if (!("ok" in validated)) return { ok: false, issues: validated.retry };
|
|
580
|
+
}
|
|
581
|
+
return verdict;
|
|
582
|
+
};
|
|
583
|
+
const streamEmittedOutput = cfg.resolved.transport !== "respond";
|
|
584
|
+
const streamOneStep = async (llm, request) => {
|
|
585
|
+
if (cfg.transport === "step") {
|
|
586
|
+
try {
|
|
587
|
+
return ok(await llm.step(request));
|
|
588
|
+
} catch (cause) {
|
|
589
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
590
|
+
return err(makeError("model_call_failed", message, { ...errorContext, cause }));
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
let final;
|
|
594
|
+
const respondIndices = /* @__PURE__ */ new Set();
|
|
595
|
+
try {
|
|
596
|
+
for await (const event of llm.stepStream(request, { signal: cfg.abort })) {
|
|
597
|
+
if (cfg.abort.aborted) break;
|
|
598
|
+
if (event.type === "text") {
|
|
599
|
+
cfg.emit({ type: "model-delta", text: event.text, channel: "text" });
|
|
600
|
+
if (streamEmittedOutput) {
|
|
601
|
+
cfg.emit({ type: "output-delta", text: event.text });
|
|
602
|
+
cfg.partials.write(event.text);
|
|
603
|
+
}
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (event.type === "reasoning") {
|
|
607
|
+
cfg.emit({ type: "model-delta", text: event.text, channel: "reasoning" });
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
if (event.type === "tool_call_delta") {
|
|
611
|
+
if (event.name !== void 0 && event.name === cfg.resolved.outputToolName) respondIndices.add(event.index);
|
|
612
|
+
if (respondIndices.has(event.index) && event.argsText.length > 0) {
|
|
613
|
+
cfg.emit({ type: "output-delta", text: event.argsText });
|
|
614
|
+
cfg.partials.write(event.argsText);
|
|
615
|
+
}
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
final = event.result;
|
|
619
|
+
}
|
|
620
|
+
} catch (cause) {
|
|
621
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
622
|
+
return err(makeError("model_call_failed", message, { ...errorContext, cause }));
|
|
623
|
+
}
|
|
624
|
+
if (final) return ok(final);
|
|
625
|
+
if (cfg.abort.aborted) return err(makeError("aborted", "run aborted during model call", errorContext));
|
|
626
|
+
return err(makeError("model_call_failed", "stream ended without a done event", errorContext));
|
|
627
|
+
};
|
|
628
|
+
let lastAttempt;
|
|
629
|
+
const retryOutput = (kind, issues, attempt) => {
|
|
630
|
+
if (attempt !== void 0) lastAttempt = attempt;
|
|
631
|
+
s.outputRetries += 1;
|
|
632
|
+
cfg.emit({ type: "retry", kind, attempt: s.outputRetries, issues });
|
|
633
|
+
cfg.partials.reset();
|
|
634
|
+
const verdict = checkStop(cfg.stopWhen, progress());
|
|
635
|
+
if (verdict) {
|
|
636
|
+
return fail(
|
|
637
|
+
makeError("stopped", verdict.message, {
|
|
638
|
+
...errorContext,
|
|
639
|
+
stop: verdict.stop,
|
|
640
|
+
...lastAttempt !== void 0 && { lastOutput: lastAttempt }
|
|
641
|
+
})
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
return void 0;
|
|
645
|
+
};
|
|
646
|
+
if (cfg.resumePending) {
|
|
647
|
+
const structural = await processBatch([cfg.resumePending.call, ...cfg.resumePending.remaining]);
|
|
648
|
+
if (structural) return structural;
|
|
649
|
+
}
|
|
650
|
+
let providerRetries = 0;
|
|
651
|
+
let transportRetries = 0;
|
|
652
|
+
while (true) {
|
|
653
|
+
if (cfg.abort.aborted) return fail(makeError("aborted", "run aborted", errorContext));
|
|
654
|
+
const stopVerdict = checkStop(cfg.stopWhen, progress());
|
|
655
|
+
if (stopVerdict) return failStopped(stopVerdict);
|
|
656
|
+
let domain = domainDescriptors;
|
|
657
|
+
let llm = cfg.llm;
|
|
658
|
+
let toolChoice = cfg.resolved.toolChoice;
|
|
659
|
+
if (cfg.prepareStep) {
|
|
660
|
+
const prepared = await cfg.prepareStep({
|
|
661
|
+
step: s.steps + 1,
|
|
662
|
+
messages: s.messages,
|
|
663
|
+
usage: s.usage,
|
|
664
|
+
tools: domain.map((descriptor) => descriptor.name),
|
|
665
|
+
deps: cfg.deps
|
|
666
|
+
});
|
|
667
|
+
if (prepared) {
|
|
668
|
+
if (prepared.activeTools) {
|
|
669
|
+
const active = new Set(prepared.activeTools);
|
|
670
|
+
domain = domain.filter((descriptor) => active.has(descriptor.name));
|
|
671
|
+
}
|
|
672
|
+
if (prepared.toolChoice !== void 0) toolChoice = prepared.toolChoice;
|
|
673
|
+
if (prepared.inject) s.messages.push(...prepared.inject);
|
|
674
|
+
if (prepared.llm) llm = prepared.llm;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
const descriptors = [...domain, ...exitDescriptor ? [exitDescriptor] : []];
|
|
678
|
+
s.steps += 1;
|
|
679
|
+
cfg.emit({ type: "step-start", step: s.steps });
|
|
680
|
+
const request = {
|
|
681
|
+
messages: [...s.messages],
|
|
682
|
+
...descriptors.length > 0 && { tools: descriptors },
|
|
683
|
+
...toolChoice !== void 0 && { toolChoice },
|
|
684
|
+
...cfg.resolved.responseFormat !== void 0 && { responseFormat: cfg.resolved.responseFormat },
|
|
685
|
+
output: {
|
|
686
|
+
accept: cfg.accept,
|
|
687
|
+
...cfg.resolved.outputToolName !== void 0 && { outputTool: cfg.resolved.outputToolName }
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
const stepOutcome = await streamOneStep(llm, request);
|
|
691
|
+
if (!stepOutcome.ok) return fail(stepOutcome.error);
|
|
692
|
+
const result = stepOutcome.data;
|
|
693
|
+
s.usage = addUsage(s.usage, result.usage);
|
|
694
|
+
const outcome = result.outcome ?? {
|
|
695
|
+
kind: "failed",
|
|
696
|
+
evidence: "model call produced no routed outcome"
|
|
697
|
+
};
|
|
698
|
+
const wasRejected = result.finishReason === "error_recovered";
|
|
699
|
+
if (wasRejected) {
|
|
700
|
+
cfg.partials.reset();
|
|
701
|
+
if (outcome.kind === "failed") {
|
|
702
|
+
providerRetries += 1;
|
|
703
|
+
cfg.emit({
|
|
704
|
+
type: "retry",
|
|
705
|
+
kind: "provider",
|
|
706
|
+
attempt: providerRetries,
|
|
707
|
+
issues: `provider rejected the attempt \u2014 ${outcome.evidence}`
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
if (outcome.kind === "tool_calls") {
|
|
712
|
+
s.messages.push({
|
|
713
|
+
role: "assistant",
|
|
714
|
+
content: result.content,
|
|
715
|
+
toolCalls: outcome.calls.map((call) => ({ id: call.id, name: call.name, args: stringify(call.args) }))
|
|
716
|
+
});
|
|
717
|
+
const calls = outcome.calls.map((call) => ({
|
|
718
|
+
id: call.id,
|
|
719
|
+
toolId: call.name,
|
|
720
|
+
args: call.args
|
|
721
|
+
}));
|
|
722
|
+
const structural = await processBatch(calls);
|
|
723
|
+
if (structural) return structural;
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
if (outcome.kind === "output") {
|
|
727
|
+
const validated = await validateOutput(outcome.value);
|
|
728
|
+
if (validated.ok) return { ok: true, output: validated.envelope, meta: meta() };
|
|
729
|
+
s.messages.push({
|
|
730
|
+
role: "assistant",
|
|
731
|
+
content: result.content.length > 0 ? result.content : stringify(outcome.value)
|
|
732
|
+
});
|
|
733
|
+
if (wasRejected) {
|
|
734
|
+
providerRetries += 1;
|
|
735
|
+
cfg.emit({
|
|
736
|
+
type: "retry",
|
|
737
|
+
kind: "provider",
|
|
738
|
+
attempt: providerRetries,
|
|
739
|
+
issues: `provider rejected the attempt \u2014 recovered but invalid: ${validated.issues}`
|
|
740
|
+
});
|
|
741
|
+
} else {
|
|
742
|
+
const stopped = retryOutput("output", validated.issues, outcome.value);
|
|
743
|
+
if (stopped) return stopped;
|
|
744
|
+
}
|
|
745
|
+
s.messages.push({
|
|
746
|
+
role: "system",
|
|
747
|
+
content: cfg.resolved.corrections.invalidOutput.replace("{issues}", validated.issues)
|
|
748
|
+
});
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
if (result.content.length > 0) {
|
|
752
|
+
s.messages.push({ role: "assistant", content: result.content });
|
|
753
|
+
}
|
|
754
|
+
if (!wasRejected) {
|
|
755
|
+
transportRetries += 1;
|
|
756
|
+
cfg.emit({ type: "retry", kind: "termination", attempt: transportRetries, issues: outcome.evidence });
|
|
757
|
+
cfg.partials.reset();
|
|
758
|
+
}
|
|
759
|
+
s.messages.push({
|
|
760
|
+
role: "system",
|
|
761
|
+
content: cfg.resolved.corrections.invalidOutput.replace("{issues}", outcome.evidence)
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
var createPartialTracker = (config) => {
|
|
766
|
+
let stream;
|
|
767
|
+
let dead = false;
|
|
768
|
+
const open = () => {
|
|
769
|
+
if (stream !== void 0 || dead) return;
|
|
770
|
+
try {
|
|
771
|
+
const created = createStream({ schema: config.wireSchema, mode: "recover" });
|
|
772
|
+
created.on((value) => config.emit(value));
|
|
773
|
+
created.onError(() => {
|
|
774
|
+
dead = true;
|
|
775
|
+
});
|
|
776
|
+
created.final().catch(() => {
|
|
777
|
+
});
|
|
778
|
+
stream = created;
|
|
779
|
+
} catch {
|
|
780
|
+
dead = true;
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
const dispose = () => {
|
|
784
|
+
if (stream !== void 0) {
|
|
785
|
+
try {
|
|
786
|
+
stream.destroy();
|
|
787
|
+
} catch {
|
|
788
|
+
}
|
|
789
|
+
stream = void 0;
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
return {
|
|
793
|
+
write: (text) => {
|
|
794
|
+
if (dead) return;
|
|
795
|
+
open();
|
|
796
|
+
if (stream === void 0) return;
|
|
797
|
+
try {
|
|
798
|
+
stream.write(text);
|
|
799
|
+
} catch {
|
|
800
|
+
dead = true;
|
|
801
|
+
dispose();
|
|
802
|
+
}
|
|
803
|
+
},
|
|
804
|
+
reset: () => {
|
|
805
|
+
dispose();
|
|
806
|
+
dead = false;
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
// src/gates/approval.ts
|
|
812
|
+
var createApprovalBridge = () => {
|
|
813
|
+
const pending = /* @__PURE__ */ new Map();
|
|
814
|
+
const settle = (approvalId, decision) => {
|
|
815
|
+
const resolve = pending.get(approvalId);
|
|
816
|
+
if (!resolve) return;
|
|
817
|
+
pending.delete(approvalId);
|
|
818
|
+
resolve(decision);
|
|
819
|
+
};
|
|
820
|
+
return {
|
|
821
|
+
ask: (approvalId, timeoutMs) => new Promise((resolve) => {
|
|
822
|
+
pending.set(approvalId, resolve);
|
|
823
|
+
if (timeoutMs !== void 0 && timeoutMs > 0) {
|
|
824
|
+
setTimeout(() => settle(approvalId, { approved: false, reason: "approval timeout" }), timeoutMs);
|
|
825
|
+
}
|
|
826
|
+
}),
|
|
827
|
+
approve: (approvalId, options) => settle(approvalId, {
|
|
828
|
+
approved: true,
|
|
829
|
+
...options?.args !== void 0 && { args: options.args }
|
|
830
|
+
}),
|
|
831
|
+
deny: (approvalId, reason) => settle(approvalId, { approved: false, reason: reason ?? "denied" })
|
|
832
|
+
};
|
|
833
|
+
};
|
|
834
|
+
|
|
835
|
+
// src/gates/policy.ts
|
|
836
|
+
var RISK_RANK = { low: 0, medium: 1, high: 2 };
|
|
837
|
+
var riskOf = (call) => RISK_RANK[call.riskLevel ?? "low"];
|
|
838
|
+
var policyGate = (policy) => {
|
|
839
|
+
const tools = policy.tools ?? {};
|
|
840
|
+
const deny = new Set(tools.deny ?? []);
|
|
841
|
+
const allow = tools.allow ? new Set(tools.allow) : void 0;
|
|
842
|
+
const requireApproval = new Set(tools.requireApproval ?? []);
|
|
843
|
+
const maxRisk = tools.maxRiskLevel !== void 0 ? RISK_RANK[tools.maxRiskLevel] : void 0;
|
|
844
|
+
return (call) => {
|
|
845
|
+
if (deny.has(call.toolId)) return { deny: `tool "${call.toolId}" is denied by policy` };
|
|
846
|
+
if (allow && !allow.has(call.toolId)) return { deny: `tool "${call.toolId}" is not on the policy allow list` };
|
|
847
|
+
if (maxRisk !== void 0 && riskOf(call) > maxRisk) {
|
|
848
|
+
return { deny: `tool "${call.toolId}" exceeds the policy risk ceiling (${tools.maxRiskLevel})` };
|
|
849
|
+
}
|
|
850
|
+
if (requireApproval.has(call.toolId)) return { ask: { reason: `policy requires approval for "${call.toolId}"` } };
|
|
851
|
+
return { allow: true };
|
|
852
|
+
};
|
|
853
|
+
};
|
|
854
|
+
|
|
855
|
+
// src/agent/run.ts
|
|
856
|
+
var wireRun = (wiring) => {
|
|
857
|
+
const { definition, input, options } = wiring;
|
|
858
|
+
const config = definition.config;
|
|
859
|
+
const llm = options?.llm ?? config.llm;
|
|
860
|
+
if (!llm) throwConfig(`agent "${config.id}" has no llm \u2014 set config.llm or pass options.llm`);
|
|
861
|
+
const tools = [...config.tools ?? [], ...options?.tools ?? []];
|
|
862
|
+
const taken = /* @__PURE__ */ new Set();
|
|
863
|
+
for (const tool of tools) {
|
|
864
|
+
for (const key of tool.config.name === tool.config.id ? [tool.config.id] : [tool.config.id, tool.config.name]) {
|
|
865
|
+
if (taken.has(key)) throwConfig(`duplicate tool id/name "${key}" on run of "${config.id}"`);
|
|
866
|
+
taken.add(key);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
const outputSchema = config.output?.schema;
|
|
870
|
+
const responseMode = config.output?.response ?? (outputSchema ? "optional" : "required");
|
|
871
|
+
const resolved = resolveTransport(
|
|
872
|
+
{
|
|
873
|
+
wire: envelopeWireSchema({ ...outputSchema && { schema: outputSchema }, responseMode }),
|
|
874
|
+
looseWire: envelopeLooseWireSchema({ hasData: outputSchema !== void 0, responseMode }),
|
|
875
|
+
responseMode,
|
|
876
|
+
hasData: outputSchema !== void 0,
|
|
877
|
+
hasTools: tools.length > 0,
|
|
878
|
+
...config.output?.strategy && { choice: config.output.strategy },
|
|
879
|
+
...config.output?.forceTool && { forceTool: true }
|
|
880
|
+
},
|
|
881
|
+
llm.describe().capabilities
|
|
882
|
+
);
|
|
883
|
+
if (resolved.respondDescriptor && taken.has(RESPOND_TOOL_NAME)) {
|
|
884
|
+
throwConfig(`agent "${config.id}": a tool named "respond" collides with the transport's exit tool`);
|
|
885
|
+
}
|
|
886
|
+
const accept = envelopeAcceptSchema({ ...outputSchema && { schema: outputSchema }});
|
|
887
|
+
const agentPath = options?.agentPath ? [...options.agentPath, config.id] : [config.id];
|
|
888
|
+
const channel = createEventChannel(wiring.runId, agentPath);
|
|
889
|
+
if (options?.onEvent) channel.onEvent(options.onEvent);
|
|
890
|
+
const approvals = createApprovalBridge();
|
|
891
|
+
const controller = new AbortController();
|
|
892
|
+
const externalSignal = options?.signal;
|
|
893
|
+
const onExternalAbort = () => controller.abort();
|
|
894
|
+
if (externalSignal) {
|
|
895
|
+
if (externalSignal.aborted) controller.abort();
|
|
896
|
+
else externalSignal.addEventListener("abort", onExternalAbort);
|
|
897
|
+
}
|
|
898
|
+
const deps = trustErased(options?.deps);
|
|
899
|
+
const state = {
|
|
900
|
+
messages: wiring.seeded ? [...wiring.seeded.messages] : [],
|
|
901
|
+
steps: wiring.seeded?.steps ?? 0,
|
|
902
|
+
usage: wiring.seeded?.usage ?? EMPTY_USAGE,
|
|
903
|
+
outputRetries: wiring.seeded?.outputRetries ?? 0,
|
|
904
|
+
startedAt: Date.now(),
|
|
905
|
+
elapsedBase: wiring.seeded?.elapsedMs ?? 0
|
|
906
|
+
};
|
|
907
|
+
const gates = [
|
|
908
|
+
...config.policy ? [policyGate(config.policy)] : [],
|
|
909
|
+
...config.toolGates ?? [],
|
|
910
|
+
...options?.gates ?? []
|
|
911
|
+
];
|
|
912
|
+
const partials = createPartialTracker({
|
|
913
|
+
wireSchema: envelopeWireSchema({
|
|
914
|
+
...outputSchema && { schema: outputSchema },
|
|
915
|
+
responseMode: resolved.responseMode
|
|
916
|
+
}),
|
|
917
|
+
emit: (partial) => channel.emit({ type: "output-partial", output: partial })
|
|
918
|
+
});
|
|
919
|
+
const errorContext = { runId: wiring.runId, agentPath };
|
|
920
|
+
const result = (async () => {
|
|
921
|
+
channel.emit({ type: "run-start", input });
|
|
922
|
+
let outcome;
|
|
923
|
+
try {
|
|
924
|
+
if (!wiring.seeded) {
|
|
925
|
+
const args = {
|
|
926
|
+
deps,
|
|
927
|
+
input,
|
|
928
|
+
agent: { id: config.id, ...config.description !== void 0 && { description: config.description } }
|
|
929
|
+
};
|
|
930
|
+
const items = [
|
|
931
|
+
config.instructions,
|
|
932
|
+
...config.context ?? [],
|
|
933
|
+
...options?.producers ?? []
|
|
934
|
+
];
|
|
935
|
+
const contextMessages = await assembleContext(items, args);
|
|
936
|
+
const doc = config.output?.doc ?? "auto";
|
|
937
|
+
const docMessage = resolved.injectSchemaDoc && doc !== "off" && outputSchema ? [{ role: "system", content: typeof doc === "string" && doc !== "auto" ? doc : schemaDoc(outputSchema) }] : [];
|
|
938
|
+
const finishMessage = { role: "system", content: resolved.finishProtocol };
|
|
939
|
+
const [identity, ...rest] = contextMessages;
|
|
940
|
+
state.messages = [
|
|
941
|
+
...identity ? [identity] : [],
|
|
942
|
+
...toolGuidesMessage(tools),
|
|
943
|
+
...docMessage,
|
|
944
|
+
finishMessage,
|
|
945
|
+
...rest,
|
|
946
|
+
...inputMessages(input)
|
|
947
|
+
];
|
|
948
|
+
}
|
|
949
|
+
outcome = await runLoop({
|
|
950
|
+
runId: wiring.runId,
|
|
951
|
+
agentId: config.id,
|
|
952
|
+
agentPath,
|
|
953
|
+
llm,
|
|
954
|
+
transport: config.transport ?? "stream",
|
|
955
|
+
tools,
|
|
956
|
+
resolved,
|
|
957
|
+
accept,
|
|
958
|
+
...outputSchema && { outputSchema },
|
|
959
|
+
...config.output?.validate && { outputValidate: config.output.validate },
|
|
960
|
+
gates,
|
|
961
|
+
resultHooks: [...config.onToolResult ?? [], ...options?.onToolResult ?? []],
|
|
962
|
+
...config.prepareStep && { prepareStep: config.prepareStep },
|
|
963
|
+
stopWhen: config.stopWhen ?? DEFAULT_STOP_CONDITIONS,
|
|
964
|
+
...config.policy?.approvalTimeoutMs !== void 0 && {
|
|
965
|
+
approvalTimeoutMs: config.policy.approvalTimeoutMs
|
|
966
|
+
},
|
|
967
|
+
deps,
|
|
968
|
+
emit: channel.emit,
|
|
969
|
+
forwardEvent: channel.forward,
|
|
970
|
+
approvals,
|
|
971
|
+
abort: controller.signal,
|
|
972
|
+
partials,
|
|
973
|
+
state,
|
|
974
|
+
...wiring.seeded?.pending && { resumePending: wiring.seeded.pending }
|
|
975
|
+
});
|
|
976
|
+
} catch (cause) {
|
|
977
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
978
|
+
const error = makeError("unknown", message, { ...errorContext, cause });
|
|
979
|
+
outcome = {
|
|
980
|
+
ok: false,
|
|
981
|
+
error,
|
|
982
|
+
meta: {
|
|
983
|
+
usage: state.usage,
|
|
984
|
+
strategy: resolved.transport,
|
|
985
|
+
steps: state.steps,
|
|
986
|
+
outputRetries: state.outputRetries,
|
|
987
|
+
elapsedMs: state.elapsedBase + (Date.now() - state.startedAt)
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
channel.emit({ type: "run-end", result: outcome, meta: outcome.meta });
|
|
992
|
+
channel.close();
|
|
993
|
+
if (externalSignal) externalSignal.removeEventListener("abort", onExternalAbort);
|
|
994
|
+
return outcome;
|
|
995
|
+
})();
|
|
996
|
+
return {
|
|
997
|
+
runId: wiring.runId,
|
|
998
|
+
agentPath,
|
|
999
|
+
events: channel.events,
|
|
1000
|
+
onEvent: channel.onEvent,
|
|
1001
|
+
result,
|
|
1002
|
+
approve: approvals.approve,
|
|
1003
|
+
deny: approvals.deny,
|
|
1004
|
+
snapshot: () => ({
|
|
1005
|
+
version: 1,
|
|
1006
|
+
runId: wiring.runId,
|
|
1007
|
+
agentId: config.id,
|
|
1008
|
+
input,
|
|
1009
|
+
messages: [...state.messages],
|
|
1010
|
+
steps: state.steps,
|
|
1011
|
+
usage: state.usage,
|
|
1012
|
+
outputRetries: state.outputRetries,
|
|
1013
|
+
elapsedMs: state.elapsedBase + (Date.now() - state.startedAt),
|
|
1014
|
+
...state.pending && { pending: state.pending }
|
|
1015
|
+
}),
|
|
1016
|
+
abort: () => controller.abort()
|
|
1017
|
+
};
|
|
1018
|
+
};
|
|
1019
|
+
var createRun = (definition, input, options) => wireRun({ definition, input, options, runId: newRunId() });
|
|
1020
|
+
var resumeRun = (definition, snapshot, ...args) => {
|
|
1021
|
+
if (snapshot.agentId !== definition.agentId) {
|
|
1022
|
+
throwConfig(`snapshot belongs to agent "${snapshot.agentId}", not "${definition.agentId}"`);
|
|
1023
|
+
}
|
|
1024
|
+
return wireRun({
|
|
1025
|
+
definition,
|
|
1026
|
+
input: snapshot.input,
|
|
1027
|
+
options: args[0],
|
|
1028
|
+
runId: snapshot.runId,
|
|
1029
|
+
seeded: {
|
|
1030
|
+
messages: snapshot.messages,
|
|
1031
|
+
steps: snapshot.steps,
|
|
1032
|
+
usage: snapshot.usage,
|
|
1033
|
+
outputRetries: snapshot.outputRetries,
|
|
1034
|
+
elapsedMs: snapshot.elapsedMs,
|
|
1035
|
+
...snapshot.pending && { pending: snapshot.pending }
|
|
1036
|
+
}
|
|
1037
|
+
});
|
|
1038
|
+
};
|
|
1039
|
+
var FALLBACK_CAPABILITIES = {
|
|
1040
|
+
nativeTools: true,
|
|
1041
|
+
nativeJsonSchema: false,
|
|
1042
|
+
nativeJsonMode: false,
|
|
1043
|
+
toolsWithStructuredOutput: false,
|
|
1044
|
+
validatesToolArgs: false,
|
|
1045
|
+
manglesNestedToolArgs: false,
|
|
1046
|
+
multimodal: false,
|
|
1047
|
+
supportsEmbedding: false
|
|
1048
|
+
};
|
|
1049
|
+
var previewAgent = async (definition, input, options) => {
|
|
1050
|
+
const config = definition.config;
|
|
1051
|
+
const llm = options?.llm ?? config.llm;
|
|
1052
|
+
const capabilities = llm ? llm.describe().capabilities : FALLBACK_CAPABILITIES;
|
|
1053
|
+
const allTools = [...config.tools ?? [], ...options?.tools ?? []];
|
|
1054
|
+
const outputSchema = config.output?.schema;
|
|
1055
|
+
const responseMode = config.output?.response ?? (outputSchema ? "optional" : "required");
|
|
1056
|
+
const resolved = resolveTransport(
|
|
1057
|
+
{
|
|
1058
|
+
wire: envelopeWireSchema({ ...outputSchema && { schema: outputSchema }, responseMode }),
|
|
1059
|
+
looseWire: envelopeLooseWireSchema({ hasData: outputSchema !== void 0, responseMode }),
|
|
1060
|
+
responseMode,
|
|
1061
|
+
hasData: outputSchema !== void 0,
|
|
1062
|
+
hasTools: allTools.length > 0,
|
|
1063
|
+
...config.output?.strategy && { choice: config.output.strategy },
|
|
1064
|
+
...config.output?.forceTool && { forceTool: true }
|
|
1065
|
+
},
|
|
1066
|
+
capabilities
|
|
1067
|
+
);
|
|
1068
|
+
const deps = trustErased(options?.deps);
|
|
1069
|
+
const args = {
|
|
1070
|
+
deps,
|
|
1071
|
+
input,
|
|
1072
|
+
agent: { id: config.id, ...config.description !== void 0 && { description: config.description } }
|
|
1073
|
+
};
|
|
1074
|
+
const items = [
|
|
1075
|
+
config.instructions,
|
|
1076
|
+
...config.context ?? [],
|
|
1077
|
+
...options?.producers ?? []
|
|
1078
|
+
];
|
|
1079
|
+
const contextMessages = await assembleContext(items, args);
|
|
1080
|
+
const doc = config.output?.doc ?? "auto";
|
|
1081
|
+
const docMessage = resolved.injectSchemaDoc && doc !== "off" && outputSchema ? [{ role: "system", content: typeof doc === "string" && doc !== "auto" ? doc : schemaDoc(outputSchema) }] : [];
|
|
1082
|
+
const finishMessage = { role: "system", content: resolved.finishProtocol };
|
|
1083
|
+
const [identity, ...rest] = contextMessages;
|
|
1084
|
+
const messages = [
|
|
1085
|
+
...identity ? [identity] : [],
|
|
1086
|
+
...toolGuidesMessage(allTools),
|
|
1087
|
+
...docMessage,
|
|
1088
|
+
finishMessage,
|
|
1089
|
+
...rest,
|
|
1090
|
+
...inputMessages(input)
|
|
1091
|
+
];
|
|
1092
|
+
const tools = [
|
|
1093
|
+
// The run's own builder — the preview shows the model-visible NAME,
|
|
1094
|
+
// not the id, or it would explain a request that never goes out.
|
|
1095
|
+
...allTools.map(buildToolDescriptor),
|
|
1096
|
+
...resolved.respondDescriptor ? [resolved.respondDescriptor] : []
|
|
1097
|
+
];
|
|
1098
|
+
return {
|
|
1099
|
+
strategy: resolved.transport,
|
|
1100
|
+
...resolved.respondDetail && { respondDetail: resolved.respondDetail },
|
|
1101
|
+
messages,
|
|
1102
|
+
tools,
|
|
1103
|
+
estimatedTokens: estimateTokens(messages)
|
|
1104
|
+
};
|
|
1105
|
+
};
|
|
1106
|
+
|
|
1107
|
+
// src/agent/define-agent.ts
|
|
1108
|
+
var defineAgent = (config) => {
|
|
1109
|
+
if (config.id.length === 0) throwConfig("agent id must not be empty");
|
|
1110
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1111
|
+
for (const tool of config.tools ?? []) {
|
|
1112
|
+
if (seen.has(tool.config.id)) {
|
|
1113
|
+
throwConfig(`duplicate tool id "${tool.config.id}" on agent "${config.id}"`);
|
|
1114
|
+
}
|
|
1115
|
+
seen.add(tool.config.id);
|
|
1116
|
+
}
|
|
1117
|
+
const definition = {
|
|
1118
|
+
agentId: config.id,
|
|
1119
|
+
config,
|
|
1120
|
+
run: (input, ...args) => createRun(definition, input, args[0]),
|
|
1121
|
+
preview: (input, ...args) => previewAgent(definition, input, args[0])
|
|
1122
|
+
};
|
|
1123
|
+
return definition;
|
|
1124
|
+
};
|
|
1125
|
+
var ToolRiskLevelSchema = z.enum(["low", "medium", "high"]);
|
|
1126
|
+
var ToolConfigSchema = z.object({
|
|
1127
|
+
id: z.string().describe("Unique tool identifier."),
|
|
1128
|
+
name: z.string().describe("Human-readable tool name."),
|
|
1129
|
+
description: z.string().describe("What this tool does, for the model to read."),
|
|
1130
|
+
category: z.string().optional().describe("Tool category for grouping."),
|
|
1131
|
+
riskLevel: ToolRiskLevelSchema.optional().describe("Risk level: low, medium, or high."),
|
|
1132
|
+
timeoutMs: z.number().int().positive().optional().describe("Max execution time in ms. Default: 30000.")
|
|
1133
|
+
}).strict();
|
|
1134
|
+
|
|
1135
|
+
// src/tool/define-tool.ts
|
|
1136
|
+
var defineTool = (config) => {
|
|
1137
|
+
const { input, output, guide, execute, ...serializable } = config;
|
|
1138
|
+
const parsed = ToolConfigSchema.parse(serializable);
|
|
1139
|
+
const wrappedExecute = (rawInput, context) => {
|
|
1140
|
+
const validated = input.parse(rawInput);
|
|
1141
|
+
return execute(validated, context);
|
|
1142
|
+
};
|
|
1143
|
+
return {
|
|
1144
|
+
toolId: parsed.id,
|
|
1145
|
+
config: {
|
|
1146
|
+
...parsed,
|
|
1147
|
+
input,
|
|
1148
|
+
...output !== void 0 && { output },
|
|
1149
|
+
...guide !== void 0 && { guide },
|
|
1150
|
+
execute: wrappedExecute
|
|
1151
|
+
}
|
|
1152
|
+
};
|
|
1153
|
+
};
|
|
1154
|
+
var DEFAULT_AGENT_TOOL_TIMEOUT_MS = 3e5;
|
|
1155
|
+
var buildAgentTool = (core) => defineTool({
|
|
1156
|
+
id: core.id,
|
|
1157
|
+
name: core.id,
|
|
1158
|
+
description: core.description,
|
|
1159
|
+
timeoutMs: core.timeoutMs,
|
|
1160
|
+
input: z.object({
|
|
1161
|
+
input: z.string().describe("The task for the delegate agent, fully self-contained.")
|
|
1162
|
+
}),
|
|
1163
|
+
execute: async ({ input }, ctx) => {
|
|
1164
|
+
const handle = core.start(input, {
|
|
1165
|
+
signal: ctx.signal,
|
|
1166
|
+
agentPath: ctx.agentPath,
|
|
1167
|
+
onEvent: ctx.forward
|
|
1168
|
+
});
|
|
1169
|
+
const result = await handle.result;
|
|
1170
|
+
if (!result.ok) return `error: ${result.error.message}`;
|
|
1171
|
+
if (core.select) return core.select(result.output);
|
|
1172
|
+
return result.output.data !== void 0 ? result.output.data : result.output.response ?? "";
|
|
1173
|
+
}
|
|
1174
|
+
});
|
|
1175
|
+
var asTool = (agent, ...args) => {
|
|
1176
|
+
const options = args[0];
|
|
1177
|
+
const erased = trustErased(agent);
|
|
1178
|
+
return buildAgentTool({
|
|
1179
|
+
id: options?.id ?? agent.agentId,
|
|
1180
|
+
description: options?.description ?? agent.config.description ?? `Delegate the task to agent "${agent.agentId}".`,
|
|
1181
|
+
timeoutMs: options?.timeoutMs ?? DEFAULT_AGENT_TOOL_TIMEOUT_MS,
|
|
1182
|
+
...options?.select && { select: options.select },
|
|
1183
|
+
start: (input, context) => {
|
|
1184
|
+
const runOptions = {
|
|
1185
|
+
...options?.deps !== void 0 && { deps: options.deps },
|
|
1186
|
+
...options?.llm && { llm: options.llm },
|
|
1187
|
+
signal: context.signal,
|
|
1188
|
+
agentPath: context.agentPath,
|
|
1189
|
+
onEvent: context.onEvent
|
|
1190
|
+
};
|
|
1191
|
+
return erased.run(input, runOptions);
|
|
1192
|
+
}
|
|
1193
|
+
});
|
|
1194
|
+
};
|
|
1195
|
+
|
|
1196
|
+
// src/manifold/manifold.ts
|
|
1197
|
+
var DEFAULT_AGENT_TOOL_TIMEOUT_MS2 = 3e5;
|
|
1198
|
+
var createManifold = (config = {}) => {
|
|
1199
|
+
const agents = /* @__PURE__ */ new Map();
|
|
1200
|
+
const tools = /* @__PURE__ */ new Map();
|
|
1201
|
+
const requireAgent = (agentId) => {
|
|
1202
|
+
const agent = agents.get(agentId);
|
|
1203
|
+
if (!agent) throwConfig(`agent "${agentId}" is not registered on this manifold`);
|
|
1204
|
+
return agent;
|
|
1205
|
+
};
|
|
1206
|
+
const mergedOptions = (agent, options) => {
|
|
1207
|
+
const llm = options?.llm ?? agent.config.llm ?? config.llm;
|
|
1208
|
+
const gates = [...config.gates ?? [], ...options?.gates ?? []];
|
|
1209
|
+
return {
|
|
1210
|
+
...options,
|
|
1211
|
+
...llm && { llm },
|
|
1212
|
+
...gates.length > 0 && { gates }
|
|
1213
|
+
};
|
|
1214
|
+
};
|
|
1215
|
+
const run = (agentId, input, options) => {
|
|
1216
|
+
const agent = requireAgent(agentId);
|
|
1217
|
+
const handle = agent.run(input, mergedOptions(agent, options));
|
|
1218
|
+
config.onRun?.(handle);
|
|
1219
|
+
return trustErased(handle);
|
|
1220
|
+
};
|
|
1221
|
+
return {
|
|
1222
|
+
register: (...definitions) => {
|
|
1223
|
+
for (const definition of definitions) {
|
|
1224
|
+
if ("agentId" in definition) {
|
|
1225
|
+
if (agents.has(definition.agentId)) throwConfig(`duplicate agent id "${definition.agentId}"`);
|
|
1226
|
+
agents.set(definition.agentId, trustErased(definition));
|
|
1227
|
+
continue;
|
|
1228
|
+
}
|
|
1229
|
+
if (tools.has(definition.toolId)) throwConfig(`duplicate tool id "${definition.toolId}"`);
|
|
1230
|
+
tools.set(definition.toolId, trustErased(definition));
|
|
1231
|
+
}
|
|
1232
|
+
},
|
|
1233
|
+
run,
|
|
1234
|
+
preview: (agentId, input, options) => {
|
|
1235
|
+
const agent = requireAgent(agentId);
|
|
1236
|
+
return agent.preview(input, mergedOptions(agent, options));
|
|
1237
|
+
},
|
|
1238
|
+
asTool: (agentId, options) => {
|
|
1239
|
+
const agent = requireAgent(agentId);
|
|
1240
|
+
return buildAgentTool({
|
|
1241
|
+
id: options?.id ?? agent.agentId,
|
|
1242
|
+
description: options?.description ?? agent.config.description ?? `Delegate the task to agent "${agent.agentId}".`,
|
|
1243
|
+
timeoutMs: options?.timeoutMs ?? DEFAULT_AGENT_TOOL_TIMEOUT_MS2,
|
|
1244
|
+
...options?.select && { select: options.select },
|
|
1245
|
+
start: (input, context) => {
|
|
1246
|
+
const handle = run(agent.agentId, input, {
|
|
1247
|
+
...options?.deps !== void 0 && { deps: options.deps },
|
|
1248
|
+
...options?.llm && { llm: options.llm },
|
|
1249
|
+
signal: context.signal,
|
|
1250
|
+
agentPath: context.agentPath,
|
|
1251
|
+
onEvent: context.onEvent
|
|
1252
|
+
});
|
|
1253
|
+
return handle;
|
|
1254
|
+
}
|
|
1255
|
+
});
|
|
1256
|
+
},
|
|
1257
|
+
agent: requireAgent,
|
|
1258
|
+
tool: (toolId) => {
|
|
1259
|
+
const tool = tools.get(toolId);
|
|
1260
|
+
if (!tool) throwConfig(`tool "${toolId}" is not registered on this manifold`);
|
|
1261
|
+
return tool;
|
|
1262
|
+
},
|
|
1263
|
+
agents: () => [...agents.values()],
|
|
1264
|
+
tools: () => [...tools.values()]
|
|
1265
|
+
};
|
|
1266
|
+
};
|
|
1267
|
+
|
|
1268
|
+
export { DEFAULT_STOP_CONDITIONS, asTool, createManifold, defineAgent, defineTool, duration, estimateTokens, flattenSchemaIssues, inputMessages, outputRetries, policyGate, repeatedCalls, resumeRun, schemaDoc, stepCount, tokens, toolGuidesMessage };
|
|
1269
|
+
//# sourceMappingURL=index.js.map
|
|
1270
|
+
//# sourceMappingURL=index.js.map
|