dsh-message-gateway 0.1.11 → 0.1.12
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/README.en.md +1 -0
- package/README.es.md +1 -0
- package/README.md +1 -0
- package/lib/index.js +3125 -6
- package/lib/index.js.map +4 -4
- package/package.json +3 -1
package/lib/index.js
CHANGED
|
@@ -1,3 +1,3075 @@
|
|
|
1
|
+
// node_modules/@deepseek-ai/dsh-tools/lib/index.js
|
|
2
|
+
import { Service } from "@deepseek-ai/cordis";
|
|
3
|
+
import z from "@deepseek-ai/schemastery";
|
|
4
|
+
|
|
5
|
+
// node_modules/@deepseek-ai/dsh-scope/lib/index.js
|
|
6
|
+
import { Context } from "@deepseek-ai/cordis";
|
|
7
|
+
var NamedEntries = class {
|
|
8
|
+
duplicateError;
|
|
9
|
+
data = /* @__PURE__ */ new Map();
|
|
10
|
+
constructor(duplicateError) {
|
|
11
|
+
this.duplicateError = duplicateError;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Insert one unique name.
|
|
15
|
+
* @param name - name unique within this table.
|
|
16
|
+
* @param value - borrowed value to retain.
|
|
17
|
+
* @returns an idempotent undo that removes only this insertion.
|
|
18
|
+
*/
|
|
19
|
+
insert(name, value) {
|
|
20
|
+
const data = this.data;
|
|
21
|
+
if (data.has(name)) throw this.duplicateError(name);
|
|
22
|
+
data.set(name, value);
|
|
23
|
+
let active = true;
|
|
24
|
+
return () => {
|
|
25
|
+
if (!active) return;
|
|
26
|
+
active = false;
|
|
27
|
+
data.delete(name);
|
|
28
|
+
if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Read one named value.
|
|
33
|
+
* @param name - name to resolve.
|
|
34
|
+
* @returns the retained value, or `undefined` when absent.
|
|
35
|
+
*/
|
|
36
|
+
get(name) {
|
|
37
|
+
return this.data.get(name);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Test one name for membership.
|
|
41
|
+
* @param name - name to test.
|
|
42
|
+
* @returns whether the table contains that name.
|
|
43
|
+
*/
|
|
44
|
+
has(name) {
|
|
45
|
+
return this.data.has(name);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Iterate live names in insertion order.
|
|
49
|
+
* @returns the native live key iterator.
|
|
50
|
+
*/
|
|
51
|
+
keys() {
|
|
52
|
+
return this.data.keys();
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Iterate live entries in insertion order.
|
|
56
|
+
* @returns the native live entry iterator.
|
|
57
|
+
*/
|
|
58
|
+
entries() {
|
|
59
|
+
return this.data.entries();
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Iterate live values in insertion order.
|
|
63
|
+
* @returns the native live value iterator.
|
|
64
|
+
*/
|
|
65
|
+
values() {
|
|
66
|
+
return this.data.values();
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Test whether this table has no entries.
|
|
70
|
+
* @returns whether the table is empty.
|
|
71
|
+
*/
|
|
72
|
+
isEmpty() {
|
|
73
|
+
return this.data.size === 0;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
var AnonymousEntries = class {
|
|
77
|
+
data = /* @__PURE__ */ new Map();
|
|
78
|
+
/**
|
|
79
|
+
* Append one independently owned value.
|
|
80
|
+
* @param value - borrowed value to retain.
|
|
81
|
+
* @returns an idempotent undo for this exact append.
|
|
82
|
+
*/
|
|
83
|
+
append(value) {
|
|
84
|
+
const data = this.data;
|
|
85
|
+
const key = Symbol();
|
|
86
|
+
data.set(key, value);
|
|
87
|
+
let active = true;
|
|
88
|
+
return () => {
|
|
89
|
+
if (!active) return;
|
|
90
|
+
active = false;
|
|
91
|
+
data.delete(key);
|
|
92
|
+
if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Iterate live values in insertion order.
|
|
97
|
+
* @returns the native live value iterator.
|
|
98
|
+
*/
|
|
99
|
+
values() {
|
|
100
|
+
return this.data.values();
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Test whether this table has no entries.
|
|
104
|
+
* @returns whether the table is empty.
|
|
105
|
+
*/
|
|
106
|
+
isEmpty() {
|
|
107
|
+
return this.data.size === 0;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var ScopedLayers = class {
|
|
111
|
+
createLayer;
|
|
112
|
+
onChange;
|
|
113
|
+
/** The eagerly constructed context-global layer. */
|
|
114
|
+
global;
|
|
115
|
+
scoped = /* @__PURE__ */ new Map();
|
|
116
|
+
constructor(createLayer, onChange) {
|
|
117
|
+
this.createLayer = createLayer;
|
|
118
|
+
this.onChange = onChange;
|
|
119
|
+
this.global = createLayer(void 0);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Read an existing exact-scope overlay. Deliberately chain-blind: callers
|
|
123
|
+
* addressing one scope's OWN contributions (its restrictions, its guards)
|
|
124
|
+
* must not silently pick up an ancestor's — use {@link chainLayers} where
|
|
125
|
+
* inheritance is the point.
|
|
126
|
+
* @param scope - exact scope key; `undefined` denotes no overlay.
|
|
127
|
+
* @returns the existing scoped layer, or `undefined` without creating one.
|
|
128
|
+
*/
|
|
129
|
+
peek(scope) {
|
|
130
|
+
if (scope === void 0) return void 0;
|
|
131
|
+
return this.scoped.get(scope);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Existing overlays along the scope's parent chain ({@link scopeChainOf}),
|
|
135
|
+
* farthest ancestor first and the exact scope last, so a caller layering
|
|
136
|
+
* them in order gives the nearest scope the final word.
|
|
137
|
+
* @param scope - viewing scope, or `undefined` for no overlays.
|
|
138
|
+
* @returns the existing layers, nearest last; absent overlays are skipped.
|
|
139
|
+
*/
|
|
140
|
+
chainLayers(scope) {
|
|
141
|
+
const layers = [];
|
|
142
|
+
for (const key of scopeChainOf(scope).reverse()) {
|
|
143
|
+
const layer = this.scoped.get(key);
|
|
144
|
+
if (layer !== void 0) layers.push(layer);
|
|
145
|
+
}
|
|
146
|
+
return layers;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Materialize global named entries followed by scope-chain shadows,
|
|
150
|
+
* farthest ancestor first, so the nearest scope's entry wins a name.
|
|
151
|
+
* @param scope - viewing scope, or `undefined` for the global view.
|
|
152
|
+
* @param pick - select the named table from a layer.
|
|
153
|
+
* @returns an insertion-ordered effective map.
|
|
154
|
+
*/
|
|
155
|
+
merge(scope, pick) {
|
|
156
|
+
const merged = new Map(pick(this.global).entries());
|
|
157
|
+
for (const layer of this.chainLayers(scope)) for (const [name, value] of pick(layer).entries()) merged.set(name, value);
|
|
158
|
+
return merged;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Attach one synchronous layer mutation to its registration context.
|
|
162
|
+
* @param ctx - context that determines both scope visibility and effect ownership.
|
|
163
|
+
* @param action - atomic mutation returning its synchronous undo.
|
|
164
|
+
* @param options - Cordis effect label and optional change notification.
|
|
165
|
+
* @returns the exact disposer returned by `ctx.effect()`.
|
|
166
|
+
*/
|
|
167
|
+
effect(ctx, action, options) {
|
|
168
|
+
const scope = scopeOf(ctx);
|
|
169
|
+
const notify = options.notify ?? true;
|
|
170
|
+
return ctx.effect(function* () {
|
|
171
|
+
let layer;
|
|
172
|
+
let created = false;
|
|
173
|
+
if (scope === void 0) layer = this.global;
|
|
174
|
+
else {
|
|
175
|
+
const existing = this.scoped.get(scope);
|
|
176
|
+
if (existing === void 0) {
|
|
177
|
+
layer = this.createLayer(scope);
|
|
178
|
+
this.scoped.set(scope, layer);
|
|
179
|
+
created = true;
|
|
180
|
+
} else layer = existing;
|
|
181
|
+
}
|
|
182
|
+
let undo;
|
|
183
|
+
try {
|
|
184
|
+
undo = action(layer);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (scope !== void 0 && created && layer.isEmpty()) this.scoped.delete(scope);
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
yield () => {
|
|
190
|
+
undo();
|
|
191
|
+
if (scope !== void 0 && layer.isEmpty()) this.scoped.delete(scope);
|
|
192
|
+
if (notify) this.onChange();
|
|
193
|
+
};
|
|
194
|
+
if (notify) this.onChange();
|
|
195
|
+
}.bind(this), options.label);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
var kScope = Symbol("dsh.scope");
|
|
199
|
+
var carrierKeys = /* @__PURE__ */ new WeakMap();
|
|
200
|
+
var scopeParents = /* @__PURE__ */ new WeakMap();
|
|
201
|
+
function scopeChainOf(key) {
|
|
202
|
+
const chain = [];
|
|
203
|
+
for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) chain.push(cursor);
|
|
204
|
+
return chain;
|
|
205
|
+
}
|
|
206
|
+
function scopeOf(ctx) {
|
|
207
|
+
return ctx[kScope];
|
|
208
|
+
}
|
|
209
|
+
function scopeTarget(base, key) {
|
|
210
|
+
const baseFilter = base[Context.filter];
|
|
211
|
+
const carrier = { [Context.filter](ctx) {
|
|
212
|
+
if (baseFilter !== void 0 && !baseFilter.call(base, ctx)) return false;
|
|
213
|
+
const tag = scopeOf(ctx);
|
|
214
|
+
if (tag === void 0) return true;
|
|
215
|
+
for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) if (cursor === tag) return true;
|
|
216
|
+
return false;
|
|
217
|
+
} };
|
|
218
|
+
carrierKeys.set(carrier, key);
|
|
219
|
+
return carrier;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// node_modules/@deepseek-ai/dsh-tools/lib/index.js
|
|
223
|
+
import { CallId, HarnessError, assertNever, deepFreeze } from "@deepseek-ai/dsh-llm";
|
|
224
|
+
import { isJsonValue, snapshotJsonValue } from "@deepseek-ai/dsh-session";
|
|
225
|
+
var JsonSchemaError = class extends HarnessError {
|
|
226
|
+
/** Individual schema violations in walk order. */
|
|
227
|
+
violations;
|
|
228
|
+
constructor(violations) {
|
|
229
|
+
super(`unsupported JSON schema: ${violations.join("; ")}`, "UNSUPPORTED_SCHEMA");
|
|
230
|
+
this.name = "JsonSchemaError";
|
|
231
|
+
this.violations = violations;
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
var CONSTRAINT_KEYWORDS = /* @__PURE__ */ new Set([
|
|
235
|
+
"type",
|
|
236
|
+
"oneOf",
|
|
237
|
+
"properties",
|
|
238
|
+
"required",
|
|
239
|
+
"additionalProperties",
|
|
240
|
+
"items",
|
|
241
|
+
"enum",
|
|
242
|
+
"const"
|
|
243
|
+
]);
|
|
244
|
+
var ANNOTATION_KEYWORDS = /* @__PURE__ */ new Set([
|
|
245
|
+
"description",
|
|
246
|
+
"title",
|
|
247
|
+
"default",
|
|
248
|
+
"examples"
|
|
249
|
+
]);
|
|
250
|
+
var SCHEMA_TYPES = [
|
|
251
|
+
"object",
|
|
252
|
+
"array",
|
|
253
|
+
"string",
|
|
254
|
+
"number",
|
|
255
|
+
"integer",
|
|
256
|
+
"boolean",
|
|
257
|
+
"null"
|
|
258
|
+
];
|
|
259
|
+
function hasIntrinsicConstructor(prototype, name) {
|
|
260
|
+
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
|
261
|
+
if (typeof constructor !== "function") return false;
|
|
262
|
+
try {
|
|
263
|
+
return constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;
|
|
264
|
+
} catch {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function isIntrinsicObjectPrototype(value) {
|
|
269
|
+
return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, "Object");
|
|
270
|
+
}
|
|
271
|
+
function isPlainJsonRecord(value) {
|
|
272
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
273
|
+
try {
|
|
274
|
+
const prototype = Object.getPrototypeOf(value);
|
|
275
|
+
return prototype === null || typeof prototype === "object" && isIntrinsicObjectPrototype(prototype);
|
|
276
|
+
} catch {
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
function hasPlainArrayPrototype(value) {
|
|
281
|
+
const prototype = Object.getPrototypeOf(value);
|
|
282
|
+
if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, "Array")) return false;
|
|
283
|
+
const objectPrototype = Object.getPrototypeOf(prototype);
|
|
284
|
+
return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);
|
|
285
|
+
}
|
|
286
|
+
function hasOnlyEnumerableStringKeys(value) {
|
|
287
|
+
try {
|
|
288
|
+
return Reflect.ownKeys(value).every((key) => typeof key === "string" && Object.prototype.propertyIsEnumerable.call(value, key));
|
|
289
|
+
} catch {
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
function isJsonSchemaRecord(value) {
|
|
294
|
+
return isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);
|
|
295
|
+
}
|
|
296
|
+
function isPlainJsonArray(value) {
|
|
297
|
+
if (!Array.isArray(value)) return false;
|
|
298
|
+
try {
|
|
299
|
+
if (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;
|
|
300
|
+
for (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;
|
|
301
|
+
return true;
|
|
302
|
+
} catch {
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function isJsonNumber(value) {
|
|
307
|
+
return typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0);
|
|
308
|
+
}
|
|
309
|
+
function scalarMatches(type, value) {
|
|
310
|
+
switch (type) {
|
|
311
|
+
case "string":
|
|
312
|
+
return typeof value === "string";
|
|
313
|
+
case "number":
|
|
314
|
+
return isJsonNumber(value);
|
|
315
|
+
case "integer":
|
|
316
|
+
return isJsonNumber(value) && Number.isInteger(value);
|
|
317
|
+
case "boolean":
|
|
318
|
+
return typeof value === "boolean";
|
|
319
|
+
case "null":
|
|
320
|
+
return value === null;
|
|
321
|
+
/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */
|
|
322
|
+
default:
|
|
323
|
+
return assertNever(type, "JsonSchemaType");
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
var ONE_OF_SIBLING_KEYWORDS = [
|
|
327
|
+
"properties",
|
|
328
|
+
"required",
|
|
329
|
+
"additionalProperties",
|
|
330
|
+
"items",
|
|
331
|
+
"enum",
|
|
332
|
+
"const"
|
|
333
|
+
];
|
|
334
|
+
function checkObjectSchemaTail(node, path, properties, violations) {
|
|
335
|
+
const hasRequired = Object.hasOwn(node, "required");
|
|
336
|
+
const required = hasRequired ? node.required : void 0;
|
|
337
|
+
if (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== "string")) violations.push(`${path}.required must be an array of strings`);
|
|
338
|
+
else {
|
|
339
|
+
const declared = isJsonSchemaRecord(properties) ? properties : {};
|
|
340
|
+
for (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names "${key}" which is not in properties`);
|
|
341
|
+
}
|
|
342
|
+
if (Object.hasOwn(node, "additionalProperties") && typeof node.additionalProperties !== "boolean") violations.push(`${path}.additionalProperties must be a boolean`);
|
|
343
|
+
}
|
|
344
|
+
function checkSchemaNode(root, rootPath, violations, seen) {
|
|
345
|
+
const tasks = [{
|
|
346
|
+
kind: "enter",
|
|
347
|
+
node: root,
|
|
348
|
+
path: rootPath
|
|
349
|
+
}];
|
|
350
|
+
for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
|
|
351
|
+
if (task.kind === "leave") {
|
|
352
|
+
seen.delete(task.node);
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (task.kind === "one-of-tail") {
|
|
356
|
+
for (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (task.kind === "object-tail") {
|
|
360
|
+
checkObjectSchemaTail(task.node, task.path, task.properties, violations);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const { node, path } = task;
|
|
364
|
+
if (!isJsonSchemaRecord(node)) {
|
|
365
|
+
violations.push(`${path} must be a schema object`);
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
if (seen.has(node)) {
|
|
369
|
+
violations.push(`${path} is circular`);
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
seen.add(node);
|
|
373
|
+
tasks.push({
|
|
374
|
+
kind: "leave",
|
|
375
|
+
node
|
|
376
|
+
});
|
|
377
|
+
for (const key of Object.keys(node)) {
|
|
378
|
+
if (CONSTRAINT_KEYWORDS.has(key)) continue;
|
|
379
|
+
if (ANNOTATION_KEYWORDS.has(key)) {
|
|
380
|
+
try {
|
|
381
|
+
if (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);
|
|
382
|
+
} catch {
|
|
383
|
+
violations.push(`${path}.${key} annotation must be lossless JSON data`);
|
|
384
|
+
}
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
violations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);
|
|
388
|
+
}
|
|
389
|
+
if (Object.hasOwn(node, "description") && typeof node.description !== "string") violations.push(`${path}.description must be a string`);
|
|
390
|
+
if (Object.hasOwn(node, "title") && typeof node.title !== "string") violations.push(`${path}.title must be a string`);
|
|
391
|
+
const hasType = Object.hasOwn(node, "type");
|
|
392
|
+
const hasOneOf = Object.hasOwn(node, "oneOf");
|
|
393
|
+
if (hasType && hasOneOf) {
|
|
394
|
+
violations.push(`${path} cannot declare both type and oneOf`);
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
if (!hasType && !hasOneOf) {
|
|
398
|
+
for (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
if (hasOneOf) {
|
|
402
|
+
const oneOf = node.oneOf;
|
|
403
|
+
tasks.push({
|
|
404
|
+
kind: "one-of-tail",
|
|
405
|
+
node,
|
|
406
|
+
path
|
|
407
|
+
});
|
|
408
|
+
if (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);
|
|
409
|
+
else for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({
|
|
410
|
+
kind: "enter",
|
|
411
|
+
node: oneOf[index],
|
|
412
|
+
path: `${path}.oneOf[${index}]`
|
|
413
|
+
});
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
const type = node.type;
|
|
417
|
+
if (typeof type !== "string" || !SCHEMA_TYPES.includes(type)) {
|
|
418
|
+
violations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join("/")}`);
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
const schemaType = type;
|
|
422
|
+
for (const [key, types] of Object.entries({
|
|
423
|
+
properties: ["object"],
|
|
424
|
+
required: ["object"],
|
|
425
|
+
additionalProperties: ["object"],
|
|
426
|
+
items: ["array"],
|
|
427
|
+
enum: [
|
|
428
|
+
"string",
|
|
429
|
+
"number",
|
|
430
|
+
"integer",
|
|
431
|
+
"boolean",
|
|
432
|
+
"null"
|
|
433
|
+
],
|
|
434
|
+
const: [
|
|
435
|
+
"string",
|
|
436
|
+
"number",
|
|
437
|
+
"integer",
|
|
438
|
+
"boolean",
|
|
439
|
+
"null"
|
|
440
|
+
]
|
|
441
|
+
})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type "${schemaType}"`);
|
|
442
|
+
switch (schemaType) {
|
|
443
|
+
case "object": {
|
|
444
|
+
const properties = Object.hasOwn(node, "properties") ? node.properties : void 0;
|
|
445
|
+
tasks.push({
|
|
446
|
+
kind: "object-tail",
|
|
447
|
+
node,
|
|
448
|
+
path,
|
|
449
|
+
properties
|
|
450
|
+
});
|
|
451
|
+
if (Object.hasOwn(node, "properties")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);
|
|
452
|
+
else {
|
|
453
|
+
const entries = Object.entries(properties);
|
|
454
|
+
for (let index = entries.length - 1; index >= 0; index--) {
|
|
455
|
+
const entry = entries[index];
|
|
456
|
+
if (entry === void 0) continue;
|
|
457
|
+
tasks.push({
|
|
458
|
+
kind: "enter",
|
|
459
|
+
node: entry[1],
|
|
460
|
+
path: `${path}.properties.${entry[0]}`
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
case "array":
|
|
467
|
+
if (Object.hasOwn(node, "items")) tasks.push({
|
|
468
|
+
kind: "enter",
|
|
469
|
+
node: node.items,
|
|
470
|
+
path: `${path}.items`
|
|
471
|
+
});
|
|
472
|
+
break;
|
|
473
|
+
case "string":
|
|
474
|
+
case "number":
|
|
475
|
+
case "integer":
|
|
476
|
+
case "boolean":
|
|
477
|
+
case "null": {
|
|
478
|
+
const hasEnum = Object.hasOwn(node, "enum");
|
|
479
|
+
const allowed = hasEnum ? node.enum : void 0;
|
|
480
|
+
const enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));
|
|
481
|
+
if (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);
|
|
482
|
+
const hasConst = Object.hasOwn(node, "const");
|
|
483
|
+
const declaredConst = hasConst ? node.const : void 0;
|
|
484
|
+
const constValid = scalarMatches(schemaType, declaredConst);
|
|
485
|
+
if (hasConst) {
|
|
486
|
+
if (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);
|
|
487
|
+
else if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);
|
|
488
|
+
}
|
|
489
|
+
break;
|
|
490
|
+
}
|
|
491
|
+
/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */
|
|
492
|
+
default:
|
|
493
|
+
assertNever(schemaType, "JsonSchemaType");
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function assertSupportedJsonSchema(schema) {
|
|
498
|
+
const violations = [];
|
|
499
|
+
checkSchemaNode(schema, "schema", violations, /* @__PURE__ */ new Set());
|
|
500
|
+
if (violations.length > 0) throw new JsonSchemaError(violations);
|
|
501
|
+
}
|
|
502
|
+
function safelyIsJsonValue(value) {
|
|
503
|
+
try {
|
|
504
|
+
return isJsonValue(value);
|
|
505
|
+
} catch {
|
|
506
|
+
return false;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function diagnosticPath(path) {
|
|
510
|
+
return path === "" ? "arguments" : path;
|
|
511
|
+
}
|
|
512
|
+
function propertyPath(path, key) {
|
|
513
|
+
return path === "" ? key : `${path}.${key}`;
|
|
514
|
+
}
|
|
515
|
+
function losslessValueViolation(path) {
|
|
516
|
+
return [`"${diagnosticPath(path)}" must be a lossless JSON value`];
|
|
517
|
+
}
|
|
518
|
+
function appendViolations(target, source) {
|
|
519
|
+
for (const violation of source) target.push(violation);
|
|
520
|
+
}
|
|
521
|
+
function valueFrame(node, value, path) {
|
|
522
|
+
return {
|
|
523
|
+
node,
|
|
524
|
+
value,
|
|
525
|
+
path,
|
|
526
|
+
catches: false,
|
|
527
|
+
phase: "start",
|
|
528
|
+
children: [],
|
|
529
|
+
childIndex: 0,
|
|
530
|
+
violations: [],
|
|
531
|
+
tailViolations: [],
|
|
532
|
+
matches: 0
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function checkScalarValue(node, value, path) {
|
|
536
|
+
const allowed = Object.hasOwn(node, "enum") ? node.enum : void 0;
|
|
537
|
+
if (allowed !== void 0 && !allowed.includes(value)) return [`"${diagnosticPath(path)}" must be one of ${JSON.stringify(allowed)}`];
|
|
538
|
+
if (Object.hasOwn(node, "const") && value !== node.const) return [`"${diagnosticPath(path)}" must be ${JSON.stringify(node.const)}`];
|
|
539
|
+
return [];
|
|
540
|
+
}
|
|
541
|
+
function checkValue(schema, value, path) {
|
|
542
|
+
const frames = [valueFrame(schema, value, path)];
|
|
543
|
+
let rootResult;
|
|
544
|
+
const receive = (result) => {
|
|
545
|
+
const parent = frames.at(-1);
|
|
546
|
+
if (parent === void 0) {
|
|
547
|
+
rootResult = result;
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
if (parent.kind === "oneOf") {
|
|
551
|
+
if (result.length === 0) parent.matches++;
|
|
552
|
+
} else appendViolations(parent.violations, result);
|
|
553
|
+
};
|
|
554
|
+
const finish = (result) => {
|
|
555
|
+
frames.pop();
|
|
556
|
+
receive(result);
|
|
557
|
+
};
|
|
558
|
+
while (frames.length > 0) {
|
|
559
|
+
const frame = frames.at(-1);
|
|
560
|
+
if (frame === void 0) break;
|
|
561
|
+
try {
|
|
562
|
+
if (frame.phase === "children") {
|
|
563
|
+
if (frame.childIndex < frame.children.length) {
|
|
564
|
+
const child = frame.children[frame.childIndex];
|
|
565
|
+
if (child === void 0) throw new Error("missing schema-value child frame");
|
|
566
|
+
frame.childIndex++;
|
|
567
|
+
frames.push(valueFrame(child.node, child.value, child.path));
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
if (frame.kind === "oneOf") {
|
|
571
|
+
finish(frame.matches === 1 ? [] : [`"${diagnosticPath(frame.path)}" must match exactly one oneOf branch (matched ${frame.matches})`]);
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
appendViolations(frame.violations, frame.tailViolations);
|
|
575
|
+
if (frame.violations.length > 0) finish(frame.violations);
|
|
576
|
+
else if (frame.kind === "object") finish(safelyIsJsonValue(frame.value) ? [] : [`"${diagnosticPath(frame.path)}" must be a lossless JSON object`]);
|
|
577
|
+
else finish(safelyIsJsonValue(frame.value) ? [] : [`"${diagnosticPath(frame.path)}" must be a dense lossless JSON array`]);
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
const nodeType = Object.hasOwn(frame.node, "type") ? frame.node.type : void 0;
|
|
581
|
+
frame.catches = !(nodeType !== void 0 && !SCHEMA_TYPES.includes(nodeType));
|
|
582
|
+
const oneOf = Object.hasOwn(frame.node, "oneOf") ? frame.node.oneOf : void 0;
|
|
583
|
+
if (oneOf !== void 0) {
|
|
584
|
+
frame.kind = "oneOf";
|
|
585
|
+
frame.children = Array.from(oneOf, (branch) => ({
|
|
586
|
+
node: branch,
|
|
587
|
+
value: frame.value,
|
|
588
|
+
path: frame.path
|
|
589
|
+
}));
|
|
590
|
+
frame.childIndex = 0;
|
|
591
|
+
frame.matches = 0;
|
|
592
|
+
frame.phase = "children";
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
if (nodeType === void 0) {
|
|
596
|
+
finish(safelyIsJsonValue(frame.value) ? [] : losslessValueViolation(frame.path));
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
switch (nodeType) {
|
|
600
|
+
case "object": {
|
|
601
|
+
if (!isPlainJsonRecord(frame.value)) {
|
|
602
|
+
finish([`"${diagnosticPath(frame.path)}" must be an object`]);
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
const properties = Object.hasOwn(frame.node, "properties") ? frame.node.properties ?? {} : {};
|
|
606
|
+
const violations = [];
|
|
607
|
+
const required = Object.hasOwn(frame.node, "required") ? frame.node.required ?? [] : [];
|
|
608
|
+
for (const key of required) if (!Object.hasOwn(frame.value, key) || frame.value[key] === void 0) violations.push(`missing required property "${propertyPath(frame.path, key)}"`);
|
|
609
|
+
const children = [];
|
|
610
|
+
for (const [key, child] of Object.entries(properties)) {
|
|
611
|
+
if (!Object.hasOwn(frame.value, key) || frame.value[key] === void 0) continue;
|
|
612
|
+
children.push({
|
|
613
|
+
node: child,
|
|
614
|
+
value: frame.value[key],
|
|
615
|
+
path: propertyPath(frame.path, key)
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
const tailViolations = [];
|
|
619
|
+
if (Object.hasOwn(frame.node, "additionalProperties") && frame.node.additionalProperties === false) {
|
|
620
|
+
for (const key of Object.keys(frame.value)) if (!Object.hasOwn(properties, key)) tailViolations.push(`"${propertyPath(frame.path, key)}" is not a declared property (additionalProperties: false)`);
|
|
621
|
+
}
|
|
622
|
+
frame.kind = "object";
|
|
623
|
+
frame.children = children;
|
|
624
|
+
frame.childIndex = 0;
|
|
625
|
+
frame.violations = violations;
|
|
626
|
+
frame.tailViolations = tailViolations;
|
|
627
|
+
frame.phase = "children";
|
|
628
|
+
break;
|
|
629
|
+
}
|
|
630
|
+
case "array": {
|
|
631
|
+
if (!Array.isArray(frame.value)) {
|
|
632
|
+
finish([`"${diagnosticPath(frame.path)}" must be an array`]);
|
|
633
|
+
break;
|
|
634
|
+
}
|
|
635
|
+
const items = Object.hasOwn(frame.node, "items") ? frame.node.items : void 0;
|
|
636
|
+
const children = items === void 0 ? [] : frame.value.flatMap((entry, index) => [{
|
|
637
|
+
node: items,
|
|
638
|
+
value: entry,
|
|
639
|
+
path: `${frame.path}[${index}]`
|
|
640
|
+
}]);
|
|
641
|
+
frame.kind = "array";
|
|
642
|
+
frame.children = children;
|
|
643
|
+
frame.childIndex = 0;
|
|
644
|
+
frame.violations = [];
|
|
645
|
+
frame.phase = "children";
|
|
646
|
+
break;
|
|
647
|
+
}
|
|
648
|
+
case "string":
|
|
649
|
+
finish(typeof frame.value === "string" ? checkScalarValue(frame.node, frame.value, frame.path) : [`"${diagnosticPath(frame.path)}" must be a string`]);
|
|
650
|
+
break;
|
|
651
|
+
case "number":
|
|
652
|
+
finish(typeof frame.value !== "number" ? [`"${diagnosticPath(frame.path)}" must be a number`] : !isJsonNumber(frame.value) ? [`"${diagnosticPath(frame.path)}" must be a finite JSON number`] : checkScalarValue(frame.node, frame.value, frame.path));
|
|
653
|
+
break;
|
|
654
|
+
case "integer":
|
|
655
|
+
finish(!isJsonNumber(frame.value) || !Number.isInteger(frame.value) ? [`"${diagnosticPath(frame.path)}" must be an integer`] : checkScalarValue(frame.node, frame.value, frame.path));
|
|
656
|
+
break;
|
|
657
|
+
case "boolean":
|
|
658
|
+
finish(typeof frame.value === "boolean" ? checkScalarValue(frame.node, frame.value, frame.path) : [`"${diagnosticPath(frame.path)}" must be a boolean`]);
|
|
659
|
+
break;
|
|
660
|
+
case "null":
|
|
661
|
+
finish(frame.value === null ? checkScalarValue(frame.node, frame.value, frame.path) : [`"${diagnosticPath(frame.path)}" must be null`]);
|
|
662
|
+
break;
|
|
663
|
+
default:
|
|
664
|
+
finish(assertNever(nodeType, "JsonSchemaType"));
|
|
665
|
+
}
|
|
666
|
+
} catch (error) {
|
|
667
|
+
let failed = frames.pop();
|
|
668
|
+
while (failed !== void 0 && !failed.catches) failed = frames.pop();
|
|
669
|
+
if (failed === void 0) throw error;
|
|
670
|
+
receive(losslessValueViolation(failed.path));
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return rootResult ?? losslessValueViolation(path);
|
|
674
|
+
}
|
|
675
|
+
function validateJsonSchemaValue(schema, value, path = "value") {
|
|
676
|
+
return checkValue(schema, value, path);
|
|
677
|
+
}
|
|
678
|
+
var ANNOTATION_KEYS = [
|
|
679
|
+
"description",
|
|
680
|
+
"title",
|
|
681
|
+
"default",
|
|
682
|
+
"examples"
|
|
683
|
+
];
|
|
684
|
+
function authorError(message) {
|
|
685
|
+
throw new JsonSchemaError([message]);
|
|
686
|
+
}
|
|
687
|
+
function copyAnnotations(source, target) {
|
|
688
|
+
if (Object.hasOwn(source, "description")) target.description = source.description;
|
|
689
|
+
if (Object.hasOwn(source, "title")) target.title = source.title;
|
|
690
|
+
if (Object.hasOwn(source, "default")) target.default = source.default;
|
|
691
|
+
if (Object.hasOwn(source, "examples")) target.examples = source.examples;
|
|
692
|
+
}
|
|
693
|
+
function assertAuthorKeys(source, path, allowed) {
|
|
694
|
+
for (const key of Object.keys(source)) if (!allowed.includes(key)) authorError(`${path}.${key} is not supported by the value schema DSL`);
|
|
695
|
+
}
|
|
696
|
+
function assignCompiledNode(destination, node) {
|
|
697
|
+
switch (destination.kind) {
|
|
698
|
+
case "root":
|
|
699
|
+
destination.holder.value = node;
|
|
700
|
+
break;
|
|
701
|
+
case "property":
|
|
702
|
+
Object.defineProperty(destination.target, destination.key, {
|
|
703
|
+
value: node,
|
|
704
|
+
enumerable: true,
|
|
705
|
+
configurable: true,
|
|
706
|
+
writable: true
|
|
707
|
+
});
|
|
708
|
+
break;
|
|
709
|
+
case "item":
|
|
710
|
+
destination.target.items = node;
|
|
711
|
+
break;
|
|
712
|
+
case "one-of":
|
|
713
|
+
destination.target[destination.index] = node;
|
|
714
|
+
break;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
function assignCompiledPropertyMap(destination, compiled) {
|
|
718
|
+
if (destination.kind === "root") destination.holder.value = compiled;
|
|
719
|
+
else destination.target.properties = compiled.properties;
|
|
720
|
+
}
|
|
721
|
+
function runSchemaCompiler(initial) {
|
|
722
|
+
const seen = /* @__PURE__ */ new Set();
|
|
723
|
+
const tasks = [initial];
|
|
724
|
+
for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
|
|
725
|
+
if (task.kind === "leave") {
|
|
726
|
+
seen.delete(task.input);
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
if (task.kind === "property-map-tail") {
|
|
730
|
+
if (task.required.length > 0) {
|
|
731
|
+
task.compiled.required = task.required;
|
|
732
|
+
if (task.destination.kind === "object") task.destination.target.required = task.required;
|
|
733
|
+
}
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
if (task.kind === "property") {
|
|
737
|
+
if (!isJsonSchemaRecord(task.property)) authorError(`${task.path} must be a value schema object`);
|
|
738
|
+
if (Object.hasOwn(task.property, "required") && task.property.required !== true) authorError(`${task.path}.required must be true when present`);
|
|
739
|
+
if (Object.hasOwn(task.property, "required") && task.property.required === true) task.required.push(task.key);
|
|
740
|
+
tasks.push({
|
|
741
|
+
kind: "value",
|
|
742
|
+
input: task.property,
|
|
743
|
+
path: task.path,
|
|
744
|
+
allowRequired: true,
|
|
745
|
+
destination: {
|
|
746
|
+
kind: "property",
|
|
747
|
+
target: task.properties,
|
|
748
|
+
key: task.key
|
|
749
|
+
}
|
|
750
|
+
});
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
if (task.kind === "property-map") {
|
|
754
|
+
if (!isJsonSchemaRecord(task.input)) authorError(`${task.path} must be an object of value schemas`);
|
|
755
|
+
if (seen.has(task.input)) authorError(`${task.path} is circular`);
|
|
756
|
+
seen.add(task.input);
|
|
757
|
+
const compiled = { properties: {} };
|
|
758
|
+
const required = [];
|
|
759
|
+
assignCompiledPropertyMap(task.destination, compiled);
|
|
760
|
+
tasks.push({
|
|
761
|
+
kind: "leave",
|
|
762
|
+
input: task.input
|
|
763
|
+
});
|
|
764
|
+
tasks.push({
|
|
765
|
+
kind: "property-map-tail",
|
|
766
|
+
compiled,
|
|
767
|
+
required,
|
|
768
|
+
destination: task.destination
|
|
769
|
+
});
|
|
770
|
+
const entries = Object.entries(task.input);
|
|
771
|
+
for (let index = entries.length - 1; index >= 0; index--) {
|
|
772
|
+
const entry = entries[index];
|
|
773
|
+
if (entry === void 0) continue;
|
|
774
|
+
tasks.push({
|
|
775
|
+
kind: "property",
|
|
776
|
+
property: entry[1],
|
|
777
|
+
path: `${task.path}.${entry[0]}`,
|
|
778
|
+
key: entry[0],
|
|
779
|
+
properties: compiled.properties,
|
|
780
|
+
required
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
continue;
|
|
784
|
+
}
|
|
785
|
+
const { input, path } = task;
|
|
786
|
+
if (!isJsonSchemaRecord(input)) authorError(`${path} must be a value schema object`);
|
|
787
|
+
if (seen.has(input)) authorError(`${path} is circular`);
|
|
788
|
+
seen.add(input);
|
|
789
|
+
const authorKeys = [...ANNOTATION_KEYS, ...task.allowRequired ? ["required"] : []];
|
|
790
|
+
const node = {};
|
|
791
|
+
assignCompiledNode(task.destination, node);
|
|
792
|
+
tasks.push({
|
|
793
|
+
kind: "leave",
|
|
794
|
+
input
|
|
795
|
+
});
|
|
796
|
+
if (Object.hasOwn(input, "oneOf")) {
|
|
797
|
+
assertAuthorKeys(input, path, [
|
|
798
|
+
...authorKeys,
|
|
799
|
+
"oneOf",
|
|
800
|
+
"type"
|
|
801
|
+
]);
|
|
802
|
+
if (Object.hasOwn(input, "type")) authorError(`${path} cannot declare both type and oneOf`);
|
|
803
|
+
if (!isPlainJsonArray(input.oneOf)) authorError(`${path}.oneOf must be an array of at least two value schemas`);
|
|
804
|
+
const branches = [];
|
|
805
|
+
node.oneOf = branches;
|
|
806
|
+
copyAnnotations(input, node);
|
|
807
|
+
for (let index = input.oneOf.length - 1; index >= 0; index--) tasks.push({
|
|
808
|
+
kind: "value",
|
|
809
|
+
input: input.oneOf[index],
|
|
810
|
+
path: `${path}.oneOf[${index}]`,
|
|
811
|
+
allowRequired: false,
|
|
812
|
+
destination: {
|
|
813
|
+
kind: "one-of",
|
|
814
|
+
target: branches,
|
|
815
|
+
index
|
|
816
|
+
}
|
|
817
|
+
});
|
|
818
|
+
continue;
|
|
819
|
+
}
|
|
820
|
+
const inputType = Object.hasOwn(input, "type") ? input.type : void 0;
|
|
821
|
+
switch (inputType) {
|
|
822
|
+
case "json":
|
|
823
|
+
assertAuthorKeys(input, path, [...authorKeys, "type"]);
|
|
824
|
+
copyAnnotations(input, node);
|
|
825
|
+
break;
|
|
826
|
+
case "object":
|
|
827
|
+
assertAuthorKeys(input, path, [
|
|
828
|
+
...authorKeys,
|
|
829
|
+
"type",
|
|
830
|
+
"properties",
|
|
831
|
+
"additionalProperties"
|
|
832
|
+
]);
|
|
833
|
+
if (!Object.hasOwn(input, "additionalProperties") || typeof input.additionalProperties !== "boolean") authorError(`${path}.additionalProperties must be explicitly true or false`);
|
|
834
|
+
node.type = "object";
|
|
835
|
+
copyAnnotations(input, node);
|
|
836
|
+
node.additionalProperties = input.additionalProperties;
|
|
837
|
+
if (Object.hasOwn(input, "properties")) tasks.push({
|
|
838
|
+
kind: "property-map",
|
|
839
|
+
input: input.properties,
|
|
840
|
+
path: `${path}.properties`,
|
|
841
|
+
destination: {
|
|
842
|
+
kind: "object",
|
|
843
|
+
target: node
|
|
844
|
+
}
|
|
845
|
+
});
|
|
846
|
+
break;
|
|
847
|
+
case "array":
|
|
848
|
+
assertAuthorKeys(input, path, [
|
|
849
|
+
...authorKeys,
|
|
850
|
+
"type",
|
|
851
|
+
"items"
|
|
852
|
+
]);
|
|
853
|
+
node.type = "array";
|
|
854
|
+
copyAnnotations(input, node);
|
|
855
|
+
if (Object.hasOwn(input, "items")) tasks.push({
|
|
856
|
+
kind: "value",
|
|
857
|
+
input: input.items,
|
|
858
|
+
path: `${path}.items`,
|
|
859
|
+
allowRequired: false,
|
|
860
|
+
destination: {
|
|
861
|
+
kind: "item",
|
|
862
|
+
target: node
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
break;
|
|
866
|
+
case "string":
|
|
867
|
+
case "number":
|
|
868
|
+
case "integer":
|
|
869
|
+
case "boolean":
|
|
870
|
+
case "null":
|
|
871
|
+
assertAuthorKeys(input, path, [
|
|
872
|
+
...authorKeys,
|
|
873
|
+
"type",
|
|
874
|
+
"enum",
|
|
875
|
+
"const"
|
|
876
|
+
]);
|
|
877
|
+
node.type = inputType;
|
|
878
|
+
copyAnnotations(input, node);
|
|
879
|
+
if (Object.hasOwn(input, "enum")) {
|
|
880
|
+
if (!isPlainJsonArray(input.enum)) authorError(`${path}.enum must be a non-empty array of scalar values`);
|
|
881
|
+
node.enum = Array.from(input.enum, (entry) => entry);
|
|
882
|
+
}
|
|
883
|
+
if (Object.hasOwn(input, "const")) node.const = input.const;
|
|
884
|
+
break;
|
|
885
|
+
default:
|
|
886
|
+
authorError(`${path}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
function compilePropertyMap(input, path) {
|
|
891
|
+
const holder = {};
|
|
892
|
+
runSchemaCompiler({
|
|
893
|
+
kind: "property-map",
|
|
894
|
+
input,
|
|
895
|
+
path,
|
|
896
|
+
destination: {
|
|
897
|
+
kind: "root",
|
|
898
|
+
holder
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
return holder.value ?? authorError(`${path} did not compile`);
|
|
902
|
+
}
|
|
903
|
+
function compileValueSchema(input, path) {
|
|
904
|
+
const holder = {};
|
|
905
|
+
runSchemaCompiler({
|
|
906
|
+
kind: "value",
|
|
907
|
+
input,
|
|
908
|
+
path,
|
|
909
|
+
allowRequired: false,
|
|
910
|
+
destination: {
|
|
911
|
+
kind: "root",
|
|
912
|
+
holder
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
return holder.value ?? authorError(`${path} did not compile`);
|
|
916
|
+
}
|
|
917
|
+
function valueSchemaSpecToJsonSchema(spec) {
|
|
918
|
+
const schema = compileValueSchema(spec, "schema");
|
|
919
|
+
assertSupportedJsonSchema(schema);
|
|
920
|
+
return schema;
|
|
921
|
+
}
|
|
922
|
+
function parameterSchemaSpecToJsonSchema(spec) {
|
|
923
|
+
const compiled = compilePropertyMap(spec, "parameters");
|
|
924
|
+
const schema = {
|
|
925
|
+
type: "object",
|
|
926
|
+
properties: compiled.properties,
|
|
927
|
+
...compiled.required === void 0 ? {} : { required: compiled.required }
|
|
928
|
+
};
|
|
929
|
+
assertSupportedJsonSchema(schema);
|
|
930
|
+
return schema;
|
|
931
|
+
}
|
|
932
|
+
var ToolArgsError = class extends HarnessError {
|
|
933
|
+
/** Individual violations in schema-walk order. */
|
|
934
|
+
violations;
|
|
935
|
+
constructor(violations) {
|
|
936
|
+
super(`invalid arguments: ${violations.join("; ")}`, "INVALID_ARGS");
|
|
937
|
+
this.name = "ToolArgsError";
|
|
938
|
+
this.violations = violations;
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
function defineTool(options) {
|
|
942
|
+
const userExecute = options.execute;
|
|
943
|
+
const userFinalizeContent = options.finalizeContent;
|
|
944
|
+
const userRender = options.output.render;
|
|
945
|
+
const userPresentationMeta = options.output.presentationMeta;
|
|
946
|
+
const userPresentCall = options.presentCall;
|
|
947
|
+
const userPresentResult = options.presentResult;
|
|
948
|
+
const userIsConcurrencySafe = options.isConcurrencySafe;
|
|
949
|
+
if (options.timeoutMs !== void 0 && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) throw new Error(`defineTool(${options.name}): timeoutMs must be a positive finite number`);
|
|
950
|
+
const parameters = parameterSchemaSpecToJsonSchema(options.parameters);
|
|
951
|
+
const outputSchema = valueSchemaSpecToJsonSchema(options.output.schema);
|
|
952
|
+
const validate = (args) => validateJsonSchemaValue(parameters, args, "");
|
|
953
|
+
const tool = {
|
|
954
|
+
name: options.name,
|
|
955
|
+
description: options.description,
|
|
956
|
+
parameters,
|
|
957
|
+
output: {
|
|
958
|
+
schema: outputSchema,
|
|
959
|
+
render(args, value) {
|
|
960
|
+
return userRender(args, value);
|
|
961
|
+
},
|
|
962
|
+
...userPresentationMeta !== void 0 ? { presentationMeta(args, value) {
|
|
963
|
+
return userPresentationMeta(args, value);
|
|
964
|
+
} } : {}
|
|
965
|
+
},
|
|
966
|
+
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
967
|
+
async execute(args, exec) {
|
|
968
|
+
const violations = validate(args);
|
|
969
|
+
if (violations.length > 0) throw new ToolArgsError(violations);
|
|
970
|
+
return userExecute(args, exec);
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
if (userFinalizeContent) tool.finalizeContent = (exec, result) => userFinalizeContent(exec, result);
|
|
974
|
+
if (userPresentCall) tool.presentCall = (args) => {
|
|
975
|
+
if (validate(args).length > 0) return void 0;
|
|
976
|
+
return userPresentCall(args);
|
|
977
|
+
};
|
|
978
|
+
if (userPresentResult) tool.presentResult = (args, result) => {
|
|
979
|
+
if (validate(args).length > 0) return void 0;
|
|
980
|
+
return userPresentResult(args, result);
|
|
981
|
+
};
|
|
982
|
+
if (userIsConcurrencySafe) tool.isConcurrencySafe = (args) => {
|
|
983
|
+
if (validate(args).length > 0) return false;
|
|
984
|
+
return userIsConcurrencySafe(args);
|
|
985
|
+
};
|
|
986
|
+
return tool;
|
|
987
|
+
}
|
|
988
|
+
var RUN_CODE_NAME = "run_code";
|
|
989
|
+
var TYPESCRIPT_FLAVOR = {
|
|
990
|
+
description: "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return comes back \u2014 curate it.",
|
|
991
|
+
codeDescription: "The program: the body of an async TypeScript function."
|
|
992
|
+
};
|
|
993
|
+
var RUN_CODE_FLAVORS = {
|
|
994
|
+
typescript: TYPESCRIPT_FLAVOR,
|
|
995
|
+
python: {
|
|
996
|
+
description: "Execute a Python program against the available tools. Takes two required arguments: `code`, the BODY of an async function (top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Answer with `print(...)` and/or `return <value>` \u2014 only that comes back, so curate it.",
|
|
997
|
+
codeDescription: "The program: the body of an async Python function."
|
|
998
|
+
}
|
|
999
|
+
};
|
|
1000
|
+
var RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION = 'Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: "Count TODO markers across packages"; "Read failing test and its fixture"; "Rename config key in every cordis.yml".';
|
|
1001
|
+
function resolveFlavor(peekRuntime) {
|
|
1002
|
+
const runtime = peekRuntime();
|
|
1003
|
+
if (runtime === void 0) return TYPESCRIPT_FLAVOR;
|
|
1004
|
+
const flavor = RUN_CODE_FLAVORS[runtime.language];
|
|
1005
|
+
if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language) || flavor === void 0) {
|
|
1006
|
+
const known = Object.keys(RUN_CODE_FLAVORS).map((name) => JSON.stringify(name)).join(", ");
|
|
1007
|
+
throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`);
|
|
1008
|
+
}
|
|
1009
|
+
return flavor;
|
|
1010
|
+
}
|
|
1011
|
+
var CodeRunFailedError = class extends HarnessError {
|
|
1012
|
+
constructor(message) {
|
|
1013
|
+
super(message, "CODE_RUN_FAILED");
|
|
1014
|
+
this.name = "CodeRunFailedError";
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
function jsonNormalizeArgs(value) {
|
|
1018
|
+
let snapshot;
|
|
1019
|
+
try {
|
|
1020
|
+
snapshot = snapshotJsonValue(value);
|
|
1021
|
+
} catch (error) {
|
|
1022
|
+
throw new Error(`tool arguments must be lossless JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
1023
|
+
}
|
|
1024
|
+
if (snapshot === void 0) throw new Error("tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)");
|
|
1025
|
+
const logged = snapshotJsonValue(snapshot);
|
|
1026
|
+
if (logged === void 0) throw new Error("tool arguments could not be detached for durable logging");
|
|
1027
|
+
return {
|
|
1028
|
+
dispatched: snapshot,
|
|
1029
|
+
logged
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
var JSON_INDENT = " ";
|
|
1033
|
+
var MAX_JSON_INDENT_CHARS = 10;
|
|
1034
|
+
function renderJsonValue(value) {
|
|
1035
|
+
const chunks = [];
|
|
1036
|
+
const tasks = [{
|
|
1037
|
+
kind: "value",
|
|
1038
|
+
value,
|
|
1039
|
+
depth: 0,
|
|
1040
|
+
compact: false
|
|
1041
|
+
}];
|
|
1042
|
+
for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
|
|
1043
|
+
if (task.kind === "text") {
|
|
1044
|
+
chunks.push(task.text);
|
|
1045
|
+
continue;
|
|
1046
|
+
}
|
|
1047
|
+
const current = task.value;
|
|
1048
|
+
if (current === null || typeof current === "boolean" || typeof current === "number") {
|
|
1049
|
+
chunks.push(String(current));
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
if (typeof current === "string") {
|
|
1053
|
+
chunks.push(JSON.stringify(current));
|
|
1054
|
+
continue;
|
|
1055
|
+
}
|
|
1056
|
+
const compact = task.compact || (task.depth + 1) * 2 > MAX_JSON_INDENT_CHARS;
|
|
1057
|
+
const childDepth = task.depth + 1;
|
|
1058
|
+
if (Array.isArray(current)) {
|
|
1059
|
+
chunks.push("[");
|
|
1060
|
+
if (current.length === 0) {
|
|
1061
|
+
chunks.push("]");
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
tasks.push({
|
|
1065
|
+
kind: "text",
|
|
1066
|
+
text: compact ? "]" : `
|
|
1067
|
+
${JSON_INDENT.repeat(task.depth)}]`
|
|
1068
|
+
});
|
|
1069
|
+
for (let index = current.length - 1; index >= 0; index--) {
|
|
1070
|
+
const item = current[index];
|
|
1071
|
+
if (item === void 0) throw new Error("cannot render a sparse JSON array");
|
|
1072
|
+
tasks.push({
|
|
1073
|
+
kind: "value",
|
|
1074
|
+
value: item,
|
|
1075
|
+
depth: childDepth,
|
|
1076
|
+
compact
|
|
1077
|
+
});
|
|
1078
|
+
tasks.push({
|
|
1079
|
+
kind: "text",
|
|
1080
|
+
text: compact ? index === 0 ? "" : "," : `${index === 0 ? "\n" : ",\n"}${JSON_INDENT.repeat(childDepth)}`
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
const keys = Object.keys(current);
|
|
1086
|
+
chunks.push("{");
|
|
1087
|
+
if (keys.length === 0) {
|
|
1088
|
+
chunks.push("}");
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
tasks.push({
|
|
1092
|
+
kind: "text",
|
|
1093
|
+
text: compact ? "}" : `
|
|
1094
|
+
${JSON_INDENT.repeat(task.depth)}}`
|
|
1095
|
+
});
|
|
1096
|
+
for (let index = keys.length - 1; index >= 0; index--) {
|
|
1097
|
+
const key = keys[index];
|
|
1098
|
+
if (key === void 0) throw new Error("cannot render a missing JSON object key");
|
|
1099
|
+
const item = current[key];
|
|
1100
|
+
if (item === void 0) throw new Error("cannot render an undefined JSON object property");
|
|
1101
|
+
tasks.push({
|
|
1102
|
+
kind: "value",
|
|
1103
|
+
value: item,
|
|
1104
|
+
depth: childDepth,
|
|
1105
|
+
compact
|
|
1106
|
+
});
|
|
1107
|
+
tasks.push({
|
|
1108
|
+
kind: "text",
|
|
1109
|
+
text: compact ? `${index === 0 ? "" : ","}${JSON.stringify(key)}:` : `${index === 0 ? "\n" : ",\n"}${JSON_INDENT.repeat(childDepth)}${JSON.stringify(key)}: `
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
return chunks.join("");
|
|
1114
|
+
}
|
|
1115
|
+
function renderValue(value) {
|
|
1116
|
+
return typeof value === "string" ? value : renderJsonValue(value);
|
|
1117
|
+
}
|
|
1118
|
+
function createRunCodeTool(registry, options) {
|
|
1119
|
+
const { requireRuntime, peekRuntime, maxParallel, shapeDispatchLog } = options;
|
|
1120
|
+
const definition = defineTool({
|
|
1121
|
+
name: RUN_CODE_NAME,
|
|
1122
|
+
description: TYPESCRIPT_FLAVOR.description,
|
|
1123
|
+
parameters: {
|
|
1124
|
+
code: {
|
|
1125
|
+
type: "string",
|
|
1126
|
+
required: true,
|
|
1127
|
+
description: TYPESCRIPT_FLAVOR.codeDescription
|
|
1128
|
+
},
|
|
1129
|
+
description: {
|
|
1130
|
+
type: "string",
|
|
1131
|
+
required: true,
|
|
1132
|
+
description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION
|
|
1133
|
+
}
|
|
1134
|
+
},
|
|
1135
|
+
output: {
|
|
1136
|
+
schema: {
|
|
1137
|
+
type: "object",
|
|
1138
|
+
additionalProperties: false,
|
|
1139
|
+
properties: {
|
|
1140
|
+
logs: {
|
|
1141
|
+
type: "array",
|
|
1142
|
+
required: true,
|
|
1143
|
+
items: { type: "string" }
|
|
1144
|
+
},
|
|
1145
|
+
result: { type: "json" }
|
|
1146
|
+
}
|
|
1147
|
+
},
|
|
1148
|
+
render: (_args, value) => {
|
|
1149
|
+
const rendered = value.result === void 0 ? "" : renderValue(value.result);
|
|
1150
|
+
const parts = [value.logs.join("\n"), rendered].filter((part) => part.length > 0);
|
|
1151
|
+
return [{
|
|
1152
|
+
type: "text",
|
|
1153
|
+
text: parts.length > 0 ? parts.join("\n") : "(run_code completed with no output)"
|
|
1154
|
+
}];
|
|
1155
|
+
}
|
|
1156
|
+
},
|
|
1157
|
+
async execute(args, exec) {
|
|
1158
|
+
if (args.description.trim().length === 0) throw new Error("invalid description: expected a non-empty string");
|
|
1159
|
+
const runtime = requireRuntime();
|
|
1160
|
+
const runController = new AbortController();
|
|
1161
|
+
const onOuterAbort = () => {
|
|
1162
|
+
runController.abort(exec.signal.reason);
|
|
1163
|
+
};
|
|
1164
|
+
exec.signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
1165
|
+
let dispatches = 0;
|
|
1166
|
+
const pendingQueue = [];
|
|
1167
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
1168
|
+
const logWork = /* @__PURE__ */ new Set();
|
|
1169
|
+
const commitQueue = [];
|
|
1170
|
+
let exclusiveActive = false;
|
|
1171
|
+
let driving = false;
|
|
1172
|
+
let driverRun = Promise.resolve();
|
|
1173
|
+
let wake;
|
|
1174
|
+
const wakeup = () => {
|
|
1175
|
+
const release = wake;
|
|
1176
|
+
wake = void 0;
|
|
1177
|
+
release?.();
|
|
1178
|
+
};
|
|
1179
|
+
const drive = () => {
|
|
1180
|
+
if (driving) return driverRun;
|
|
1181
|
+
driving = true;
|
|
1182
|
+
driverRun = (async () => {
|
|
1183
|
+
try {
|
|
1184
|
+
for (; ; ) {
|
|
1185
|
+
const signal = new Promise((resolve) => {
|
|
1186
|
+
wake = resolve;
|
|
1187
|
+
});
|
|
1188
|
+
const commitHead = commitQueue[0];
|
|
1189
|
+
if (commitHead !== void 0 && commitHead.settled) {
|
|
1190
|
+
commitQueue.shift();
|
|
1191
|
+
await commitHead.commit();
|
|
1192
|
+
if (commitHead.mode === "exclusive") exclusiveActive = false;
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
const head = pendingQueue[0];
|
|
1196
|
+
if (head !== void 0) {
|
|
1197
|
+
if (runController.signal.aborted) {
|
|
1198
|
+
pendingQueue.shift();
|
|
1199
|
+
head.abandon();
|
|
1200
|
+
continue;
|
|
1201
|
+
}
|
|
1202
|
+
const mode = head.classify();
|
|
1203
|
+
if (!exclusiveActive && (mode === "exclusive" ? inFlight.size === 0 : inFlight.size < maxParallel)) {
|
|
1204
|
+
if (mode === "exclusive") exclusiveActive = true;
|
|
1205
|
+
head.mode = mode;
|
|
1206
|
+
pendingQueue.shift();
|
|
1207
|
+
commitQueue.push(head);
|
|
1208
|
+
await head.start();
|
|
1209
|
+
const flight = head.flight.finally(() => {
|
|
1210
|
+
inFlight.delete(flight);
|
|
1211
|
+
wakeup();
|
|
1212
|
+
});
|
|
1213
|
+
inFlight.add(flight);
|
|
1214
|
+
continue;
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
if (pendingQueue.length === 0 && commitQueue.length === 0 && inFlight.size === 0) return;
|
|
1218
|
+
await signal;
|
|
1219
|
+
}
|
|
1220
|
+
} finally {
|
|
1221
|
+
driving = false;
|
|
1222
|
+
wake = void 0;
|
|
1223
|
+
}
|
|
1224
|
+
})();
|
|
1225
|
+
return driverRun;
|
|
1226
|
+
};
|
|
1227
|
+
const drainDispatches = async () => {
|
|
1228
|
+
await drive();
|
|
1229
|
+
while (logWork.size > 0) await Promise.allSettled([...logWork]);
|
|
1230
|
+
};
|
|
1231
|
+
const runOver = () => runController.signal.aborted;
|
|
1232
|
+
const binding = (name) => async (rawArgs) => {
|
|
1233
|
+
if (runOver()) throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`);
|
|
1234
|
+
const normalized = jsonNormalizeArgs(rawArgs);
|
|
1235
|
+
const n = ++dispatches;
|
|
1236
|
+
const subCallId = CallId(`${String(exec.callId)}:code:${n}`);
|
|
1237
|
+
const input = {
|
|
1238
|
+
callId: subCallId,
|
|
1239
|
+
rootCallId: exec.rootCallId,
|
|
1240
|
+
name,
|
|
1241
|
+
arguments: normalized.dispatched,
|
|
1242
|
+
...exec.agent ? { agent: exec.agent } : {},
|
|
1243
|
+
parent: exec.token,
|
|
1244
|
+
signal: runController.signal
|
|
1245
|
+
};
|
|
1246
|
+
const scheduler = registry[TOOL_RUNTIME_SCHEDULER];
|
|
1247
|
+
const outcome = await new Promise((resolve, reject) => {
|
|
1248
|
+
let parked;
|
|
1249
|
+
const settle = (result) => {
|
|
1250
|
+
resolve(result.isError ? {
|
|
1251
|
+
isError: true,
|
|
1252
|
+
message: result.error.message
|
|
1253
|
+
} : {
|
|
1254
|
+
isError: false,
|
|
1255
|
+
value: result.value
|
|
1256
|
+
});
|
|
1257
|
+
const agent = exec.agent;
|
|
1258
|
+
if (agent === void 0) return;
|
|
1259
|
+
const task = (async () => {
|
|
1260
|
+
const logged = await shapeDispatchLog({
|
|
1261
|
+
exec,
|
|
1262
|
+
agent,
|
|
1263
|
+
subCallId,
|
|
1264
|
+
name,
|
|
1265
|
+
isError: result.isError,
|
|
1266
|
+
content: result.content
|
|
1267
|
+
});
|
|
1268
|
+
agent.session.append("tool/code-dispatch", {
|
|
1269
|
+
rootCallId: exec.rootCallId,
|
|
1270
|
+
parentCallId: exec.callId,
|
|
1271
|
+
subCallId,
|
|
1272
|
+
name,
|
|
1273
|
+
arguments: normalized.logged,
|
|
1274
|
+
isError: result.isError,
|
|
1275
|
+
content: logged
|
|
1276
|
+
});
|
|
1277
|
+
})().finally(() => {
|
|
1278
|
+
logWork.delete(task);
|
|
1279
|
+
});
|
|
1280
|
+
logWork.add(task);
|
|
1281
|
+
};
|
|
1282
|
+
pendingQueue.push({
|
|
1283
|
+
flight: Promise.resolve(),
|
|
1284
|
+
settled: false,
|
|
1285
|
+
classify: () => registry.executionMode(input).kind,
|
|
1286
|
+
abandon: () => {
|
|
1287
|
+
reject(/* @__PURE__ */ new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`));
|
|
1288
|
+
},
|
|
1289
|
+
async start() {
|
|
1290
|
+
exec.agent?.session.append("tool/code-dispatch-start", {
|
|
1291
|
+
rootCallId: exec.rootCallId,
|
|
1292
|
+
parentCallId: exec.callId,
|
|
1293
|
+
subCallId,
|
|
1294
|
+
name,
|
|
1295
|
+
arguments: normalized.logged
|
|
1296
|
+
});
|
|
1297
|
+
const prepared = await scheduler.prepare(input);
|
|
1298
|
+
if (prepared.kind === "dispatch") {
|
|
1299
|
+
this.flight = scheduler.dispatch(prepared.exec).then((dispatchOutcome) => {
|
|
1300
|
+
parked = {
|
|
1301
|
+
kind: dispatchOutcome.kind,
|
|
1302
|
+
exec: prepared.exec,
|
|
1303
|
+
result: dispatchOutcome.result
|
|
1304
|
+
};
|
|
1305
|
+
this.settled = true;
|
|
1306
|
+
});
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
parked = {
|
|
1310
|
+
kind: prepared.kind,
|
|
1311
|
+
exec: prepared.exec,
|
|
1312
|
+
result: prepared.result
|
|
1313
|
+
};
|
|
1314
|
+
this.settled = true;
|
|
1315
|
+
},
|
|
1316
|
+
async commit() {
|
|
1317
|
+
if (parked === void 0) return;
|
|
1318
|
+
const result = parked.kind === "post-result" ? await scheduler.finalize(parked.exec, parked.result) : scheduler.finish(parked.exec, parked.result);
|
|
1319
|
+
for (const context of result.additionalContexts ?? []) exec.deferContext(context);
|
|
1320
|
+
if (result.concludesTurn) exec.concludeTurn();
|
|
1321
|
+
settle(result);
|
|
1322
|
+
while (logWork.size > maxParallel) await Promise.race(logWork);
|
|
1323
|
+
}
|
|
1324
|
+
});
|
|
1325
|
+
wakeup();
|
|
1326
|
+
drive();
|
|
1327
|
+
});
|
|
1328
|
+
if (runOver()) throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`);
|
|
1329
|
+
if (outcome.isError) throw new Error(outcome.message);
|
|
1330
|
+
return outcome.value;
|
|
1331
|
+
};
|
|
1332
|
+
const functions = /* @__PURE__ */ Object.create(null);
|
|
1333
|
+
for (const schema of registry.schemas(exec.agent)) {
|
|
1334
|
+
if (schema.name === "run_code") continue;
|
|
1335
|
+
Object.defineProperty(functions, schema.name, {
|
|
1336
|
+
enumerable: true,
|
|
1337
|
+
value: binding(schema.name)
|
|
1338
|
+
});
|
|
1339
|
+
}
|
|
1340
|
+
try {
|
|
1341
|
+
let result;
|
|
1342
|
+
try {
|
|
1343
|
+
result = await runtime.run({
|
|
1344
|
+
program: args.code,
|
|
1345
|
+
bindings: [{
|
|
1346
|
+
global: "tools",
|
|
1347
|
+
functions,
|
|
1348
|
+
errorClass: {
|
|
1349
|
+
name: "ToolCallError",
|
|
1350
|
+
memberNameProperty: "toolName"
|
|
1351
|
+
}
|
|
1352
|
+
}],
|
|
1353
|
+
signal: runController.signal
|
|
1354
|
+
});
|
|
1355
|
+
} finally {
|
|
1356
|
+
runController.abort("run_code settled");
|
|
1357
|
+
await drainDispatches();
|
|
1358
|
+
}
|
|
1359
|
+
if (result.error) {
|
|
1360
|
+
const logsText = result.logs.length > 0 ? `
|
|
1361
|
+
Captured output:
|
|
1362
|
+
${result.logs.join("\n")}` : "";
|
|
1363
|
+
throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}`);
|
|
1364
|
+
}
|
|
1365
|
+
return {
|
|
1366
|
+
logs: result.logs,
|
|
1367
|
+
...result.value !== void 0 ? { result: result.value } : {}
|
|
1368
|
+
};
|
|
1369
|
+
} finally {
|
|
1370
|
+
exec.signal.removeEventListener("abort", onOuterAbort);
|
|
1371
|
+
}
|
|
1372
|
+
},
|
|
1373
|
+
presentCall: (args) => ({
|
|
1374
|
+
card: "generic",
|
|
1375
|
+
title: args.description,
|
|
1376
|
+
kind: "execute",
|
|
1377
|
+
rawInput: args.code
|
|
1378
|
+
})
|
|
1379
|
+
});
|
|
1380
|
+
Object.defineProperty(definition, "description", {
|
|
1381
|
+
enumerable: true,
|
|
1382
|
+
get: () => resolveFlavor(peekRuntime).description
|
|
1383
|
+
});
|
|
1384
|
+
Object.defineProperty(definition, "parameters", {
|
|
1385
|
+
enumerable: true,
|
|
1386
|
+
get: () => parameterSchemaSpecToJsonSchema({
|
|
1387
|
+
code: {
|
|
1388
|
+
type: "string",
|
|
1389
|
+
required: true,
|
|
1390
|
+
description: resolveFlavor(peekRuntime).codeDescription
|
|
1391
|
+
},
|
|
1392
|
+
description: {
|
|
1393
|
+
type: "string",
|
|
1394
|
+
required: true,
|
|
1395
|
+
description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION
|
|
1396
|
+
}
|
|
1397
|
+
})
|
|
1398
|
+
});
|
|
1399
|
+
return definition;
|
|
1400
|
+
}
|
|
1401
|
+
var IDENTIFIER$1 = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
1402
|
+
function renderKey(name) {
|
|
1403
|
+
return IDENTIFIER$1.test(name) ? name : JSON.stringify(name);
|
|
1404
|
+
}
|
|
1405
|
+
function pad$1(indent) {
|
|
1406
|
+
return " ".repeat(indent);
|
|
1407
|
+
}
|
|
1408
|
+
function docLines$1(description, indent) {
|
|
1409
|
+
if (typeof description !== "string" || description.length === 0) return [];
|
|
1410
|
+
const collapsed = description.replace(/\s+/g, " ").trim();
|
|
1411
|
+
return [`${pad$1(indent)}/** ${collapsed.replaceAll("*/", String.raw`*\/`)} */`];
|
|
1412
|
+
}
|
|
1413
|
+
function renderScalar(value) {
|
|
1414
|
+
return JSON.stringify(value);
|
|
1415
|
+
}
|
|
1416
|
+
function renderConstrainedScalar$1(node, type) {
|
|
1417
|
+
const broad = type === "integer" ? "number" : type;
|
|
1418
|
+
if (Object.hasOwn(node, "const")) return renderScalar(node.const);
|
|
1419
|
+
if (Object.hasOwn(node, "enum")) return node.enum.map(renderScalar).join(" | ");
|
|
1420
|
+
return broad;
|
|
1421
|
+
}
|
|
1422
|
+
function typeDocumentFrom(parts) {
|
|
1423
|
+
return {
|
|
1424
|
+
parts,
|
|
1425
|
+
containsUnionOrIntersection: parts.some((part) => typeof part === "string" ? part.includes("|") || part.includes("&") : part.containsUnionOrIntersection)
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
function typeDocument(...parts) {
|
|
1429
|
+
return typeDocumentFrom(parts);
|
|
1430
|
+
}
|
|
1431
|
+
function flattenTypeDocument(document) {
|
|
1432
|
+
const chunks = [];
|
|
1433
|
+
const tasks = [document];
|
|
1434
|
+
for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
|
|
1435
|
+
if (typeof task === "string") {
|
|
1436
|
+
chunks.push(task);
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1439
|
+
for (let index = task.parts.length - 1; index >= 0; index--) {
|
|
1440
|
+
const part = task.parts[index];
|
|
1441
|
+
if (part !== void 0) tasks.push(part);
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
return chunks.join("");
|
|
1445
|
+
}
|
|
1446
|
+
function schemaRenderFrame(node, indent) {
|
|
1447
|
+
return {
|
|
1448
|
+
node,
|
|
1449
|
+
indent,
|
|
1450
|
+
phase: "start",
|
|
1451
|
+
children: [],
|
|
1452
|
+
childIndex: 0,
|
|
1453
|
+
childDocuments: [],
|
|
1454
|
+
entries: []
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
function renderSupportedSchema(schema, indent) {
|
|
1458
|
+
const frames = [schemaRenderFrame(schema, indent)];
|
|
1459
|
+
let rootDocument;
|
|
1460
|
+
const finish = (document) => {
|
|
1461
|
+
frames.pop();
|
|
1462
|
+
const parent = frames.at(-1);
|
|
1463
|
+
if (parent === void 0) rootDocument = document;
|
|
1464
|
+
else parent.childDocuments.push(document);
|
|
1465
|
+
};
|
|
1466
|
+
while (frames.length > 0) {
|
|
1467
|
+
const frame = frames.at(-1);
|
|
1468
|
+
if (frame === void 0) break;
|
|
1469
|
+
if (frame.phase === "children") {
|
|
1470
|
+
if (frame.childIndex < frame.children.length) {
|
|
1471
|
+
const child = frame.children[frame.childIndex];
|
|
1472
|
+
if (child === void 0) throw new Error("missing schema render child");
|
|
1473
|
+
frame.childIndex++;
|
|
1474
|
+
frames.push(schemaRenderFrame(child.node, child.indent));
|
|
1475
|
+
continue;
|
|
1476
|
+
}
|
|
1477
|
+
if (frame.kind === "oneOf") {
|
|
1478
|
+
const parts2 = [];
|
|
1479
|
+
for (let index = 0; index < frame.childDocuments.length; index++) {
|
|
1480
|
+
if (index > 0) parts2.push(" | ");
|
|
1481
|
+
const child = frame.childDocuments[index];
|
|
1482
|
+
if (child !== void 0) parts2.push(child);
|
|
1483
|
+
}
|
|
1484
|
+
finish(typeDocumentFrom(parts2));
|
|
1485
|
+
continue;
|
|
1486
|
+
}
|
|
1487
|
+
if (frame.kind === "array") {
|
|
1488
|
+
const child = frame.childDocuments[0];
|
|
1489
|
+
if (child === void 0) throw new Error("missing array item type");
|
|
1490
|
+
finish(child.containsUnionOrIntersection ? typeDocument("(", child, ")[]") : typeDocument(child, "[]"));
|
|
1491
|
+
continue;
|
|
1492
|
+
}
|
|
1493
|
+
const required = new Set(frame.node.required);
|
|
1494
|
+
const parts = ["{"];
|
|
1495
|
+
for (let index = 0; index < frame.entries.length; index++) {
|
|
1496
|
+
const entry = frame.entries[index];
|
|
1497
|
+
const child = frame.childDocuments[index];
|
|
1498
|
+
if (entry === void 0 || child === void 0) throw new Error("missing object property type");
|
|
1499
|
+
const [name, prop] = entry;
|
|
1500
|
+
for (const line of docLines$1(prop.description, frame.indent + 1)) parts.push("\n", line);
|
|
1501
|
+
parts.push("\n", `${pad$1(frame.indent + 1)}${renderKey(name)}${required.has(name) ? "" : "?"}: `, child, ";");
|
|
1502
|
+
}
|
|
1503
|
+
parts.push("\n", `${pad$1(frame.indent)}}`);
|
|
1504
|
+
const declared = typeDocumentFrom(parts);
|
|
1505
|
+
finish(frame.node.additionalProperties === false ? declared : typeDocument(declared, " & Record<string, JsonValue>"));
|
|
1506
|
+
continue;
|
|
1507
|
+
}
|
|
1508
|
+
const node = frame.node;
|
|
1509
|
+
if (node.oneOf !== void 0) {
|
|
1510
|
+
frame.kind = "oneOf";
|
|
1511
|
+
frame.children = Array.from(node.oneOf, (child) => ({
|
|
1512
|
+
node: child,
|
|
1513
|
+
indent: frame.indent
|
|
1514
|
+
}));
|
|
1515
|
+
frame.childIndex = 0;
|
|
1516
|
+
frame.childDocuments = [];
|
|
1517
|
+
frame.phase = "children";
|
|
1518
|
+
continue;
|
|
1519
|
+
}
|
|
1520
|
+
if (node.type === void 0) {
|
|
1521
|
+
finish(typeDocument("JsonValue"));
|
|
1522
|
+
continue;
|
|
1523
|
+
}
|
|
1524
|
+
switch (node.type) {
|
|
1525
|
+
case "string":
|
|
1526
|
+
case "number":
|
|
1527
|
+
case "integer":
|
|
1528
|
+
case "boolean":
|
|
1529
|
+
case "null":
|
|
1530
|
+
finish(typeDocument(renderConstrainedScalar$1(node, node.type)));
|
|
1531
|
+
break;
|
|
1532
|
+
case "array":
|
|
1533
|
+
if (node.items === void 0) finish(typeDocument("JsonValue[]"));
|
|
1534
|
+
else {
|
|
1535
|
+
frame.kind = "array";
|
|
1536
|
+
frame.children = [{
|
|
1537
|
+
node: node.items,
|
|
1538
|
+
indent: frame.indent
|
|
1539
|
+
}];
|
|
1540
|
+
frame.childIndex = 0;
|
|
1541
|
+
frame.childDocuments = [];
|
|
1542
|
+
frame.phase = "children";
|
|
1543
|
+
}
|
|
1544
|
+
break;
|
|
1545
|
+
case "object": {
|
|
1546
|
+
const open = node.additionalProperties !== false;
|
|
1547
|
+
const entries = Object.entries(node.properties ?? {});
|
|
1548
|
+
if (entries.length === 0) finish(typeDocument(open ? "Record<string, JsonValue>" : "Record<string, never>"));
|
|
1549
|
+
else {
|
|
1550
|
+
frame.kind = "object";
|
|
1551
|
+
frame.entries = entries;
|
|
1552
|
+
frame.children = entries.map(([, child]) => ({
|
|
1553
|
+
node: child,
|
|
1554
|
+
indent: frame.indent + 1
|
|
1555
|
+
}));
|
|
1556
|
+
frame.childIndex = 0;
|
|
1557
|
+
frame.childDocuments = [];
|
|
1558
|
+
frame.phase = "children";
|
|
1559
|
+
}
|
|
1560
|
+
break;
|
|
1561
|
+
}
|
|
1562
|
+
/* v8 ignore next -- assertSupportedJsonSchema narrowed this closed type union. */
|
|
1563
|
+
default:
|
|
1564
|
+
finish(typeDocument("unknown"));
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
return rootDocument ?? typeDocument("unknown");
|
|
1568
|
+
}
|
|
1569
|
+
function jsonSchemaToTs(schema, indent = 0) {
|
|
1570
|
+
try {
|
|
1571
|
+
assertSupportedJsonSchema(schema);
|
|
1572
|
+
return flattenTypeDocument(renderSupportedSchema(schema, indent));
|
|
1573
|
+
} catch {
|
|
1574
|
+
return "unknown";
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
var SDK_INSTRUCTIONS$1 = `## Writing code for run_code
|
|
1578
|
+
|
|
1579
|
+
\`run_code\` takes two required arguments: \`code\` \u2014 the body of an async TypeScript function (erasable syntax only \u2014 no \`enum\` or namespaces; type annotations are advisory, the code runs type-stripped) \u2014 and \`description\`, a short summary of what the program does. Inside the program:
|
|
1580
|
+
|
|
1581
|
+
- Call tools as \`await tools.name(args)\` \u2014 quoted access for exotic names: \`tools["my-tool"](args)\`. Every call resolves to the tool's typed canonical JSON value. Tool arguments must be lossless JSON.
|
|
1582
|
+
- A FAILED tool call rejects with \`ToolCallError\`, whose \`toolName\` identifies the failed tool and whose \`message\` is human-readable \u2014 \`try/catch\` it to handle and continue.
|
|
1583
|
+
- Independent read-only calls MAY overlap under \`Promise.all\` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with \`await\`.
|
|
1584
|
+
- Emit results with \`return\` and/or \`console.log(...)\`. ONLY what you print or return comes back to you \u2014 intermediate tool results never enter the conversation, so extract just what you need.
|
|
1585
|
+
|
|
1586
|
+
The available tools:`;
|
|
1587
|
+
function renderToolsSdk(schemas) {
|
|
1588
|
+
const sorted = [...schemas].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
1589
|
+
const argsMembers = [];
|
|
1590
|
+
const outputMembers = [];
|
|
1591
|
+
for (const schema of sorted) {
|
|
1592
|
+
argsMembers.push(...docLines$1(schema.description, 1));
|
|
1593
|
+
argsMembers.push(`${pad$1(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1)};`);
|
|
1594
|
+
outputMembers.push(`${pad$1(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.output, 1)};`);
|
|
1595
|
+
}
|
|
1596
|
+
return `${SDK_INSTRUCTIONS$1}
|
|
1597
|
+
|
|
1598
|
+
\`\`\`ts
|
|
1599
|
+
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
|
|
1600
|
+
|
|
1601
|
+
${[
|
|
1602
|
+
`interface ToolArgsMap {${argsMembers.length > 0 ? `
|
|
1603
|
+
${argsMembers.join("\n")}
|
|
1604
|
+
` : ""}}`,
|
|
1605
|
+
`interface ToolOutputMap {${outputMembers.length > 0 ? `
|
|
1606
|
+
${outputMembers.join("\n")}
|
|
1607
|
+
` : ""}}`,
|
|
1608
|
+
"type ToolName = keyof ToolOutputMap",
|
|
1609
|
+
[
|
|
1610
|
+
"declare class ToolCallError extends Error {",
|
|
1611
|
+
' readonly name: "ToolCallError";',
|
|
1612
|
+
" readonly toolName: ToolName;",
|
|
1613
|
+
"}"
|
|
1614
|
+
].join("\n"),
|
|
1615
|
+
[
|
|
1616
|
+
"declare const tools: {",
|
|
1617
|
+
" [K in ToolName]: (args: ToolArgsMap[K]) => Promise<ToolOutputMap[K]>;",
|
|
1618
|
+
"}"
|
|
1619
|
+
].join("\n")
|
|
1620
|
+
].join("\n\n")}
|
|
1621
|
+
\`\`\``;
|
|
1622
|
+
}
|
|
1623
|
+
var IDENTIFIER = new RegExp("^[\\p{XID_Start}_]\\p{XID_Continue}*$", "u");
|
|
1624
|
+
function isBareIdentifier(name) {
|
|
1625
|
+
return IDENTIFIER.test(name) && name.normalize("NFKC") === name;
|
|
1626
|
+
}
|
|
1627
|
+
var RESERVED = /* @__PURE__ */ new Set([
|
|
1628
|
+
"False",
|
|
1629
|
+
"None",
|
|
1630
|
+
"True",
|
|
1631
|
+
"and",
|
|
1632
|
+
"as",
|
|
1633
|
+
"assert",
|
|
1634
|
+
"async",
|
|
1635
|
+
"await",
|
|
1636
|
+
"break",
|
|
1637
|
+
"class",
|
|
1638
|
+
"continue",
|
|
1639
|
+
"def",
|
|
1640
|
+
"del",
|
|
1641
|
+
"elif",
|
|
1642
|
+
"else",
|
|
1643
|
+
"except",
|
|
1644
|
+
"finally",
|
|
1645
|
+
"for",
|
|
1646
|
+
"from",
|
|
1647
|
+
"global",
|
|
1648
|
+
"if",
|
|
1649
|
+
"import",
|
|
1650
|
+
"in",
|
|
1651
|
+
"is",
|
|
1652
|
+
"lambda",
|
|
1653
|
+
"nonlocal",
|
|
1654
|
+
"not",
|
|
1655
|
+
"or",
|
|
1656
|
+
"pass",
|
|
1657
|
+
"raise",
|
|
1658
|
+
"return",
|
|
1659
|
+
"try",
|
|
1660
|
+
"while",
|
|
1661
|
+
"with",
|
|
1662
|
+
"yield",
|
|
1663
|
+
"__debug__"
|
|
1664
|
+
]);
|
|
1665
|
+
var TYPING_ORDER = [
|
|
1666
|
+
"Any",
|
|
1667
|
+
"Literal",
|
|
1668
|
+
"NotRequired",
|
|
1669
|
+
"Protocol",
|
|
1670
|
+
"TypedDict"
|
|
1671
|
+
];
|
|
1672
|
+
function pad(indent) {
|
|
1673
|
+
return " ".repeat(indent);
|
|
1674
|
+
}
|
|
1675
|
+
var UNPRINTABLE = /[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/g;
|
|
1676
|
+
var LONE_SURROGATE = /[\ud800-\udfff]/gu;
|
|
1677
|
+
function describe(schema) {
|
|
1678
|
+
const description = schema.description;
|
|
1679
|
+
if (typeof description !== "string") return void 0;
|
|
1680
|
+
const collapsed = description.replace(/\s+/g, " ").replace(UNPRINTABLE, (char) => `\\x${char.charCodeAt(0).toString(16).padStart(2, "0")}`).replace(LONE_SURROGATE, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`).trim();
|
|
1681
|
+
return collapsed.length === 0 ? void 0 : collapsed;
|
|
1682
|
+
}
|
|
1683
|
+
function docLines(description, indent) {
|
|
1684
|
+
const collapsed = describe({ description });
|
|
1685
|
+
if (collapsed === void 0) return [];
|
|
1686
|
+
const escaped = collapsed.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
|
|
1687
|
+
return [`${pad(indent)}"""${escaped}"""`];
|
|
1688
|
+
}
|
|
1689
|
+
function camelCase(raw) {
|
|
1690
|
+
const joined = raw.split(/[^\p{XID_Continue}]+|_+/u).filter((part) => part.length > 0).map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join("").normalize("NFKC");
|
|
1691
|
+
return (new RegExp("^\\p{XID_Start}", "u").test(joined) ? joined : `Tool${joined}`).normalize("NFKC");
|
|
1692
|
+
}
|
|
1693
|
+
var MAX_CLASS_NAME_BASE = 120;
|
|
1694
|
+
var MAX_LIST_NESTING = 180;
|
|
1695
|
+
function capClassNameBase(base) {
|
|
1696
|
+
if (base.length <= MAX_CLASS_NAME_BASE) return base;
|
|
1697
|
+
const capped = base.slice(0, MAX_CLASS_NAME_BASE);
|
|
1698
|
+
return /[\uD800-\uDBFF]$/.test(capped) ? capped.slice(0, -1) : capped;
|
|
1699
|
+
}
|
|
1700
|
+
function allocateClassName(base, state) {
|
|
1701
|
+
const capped = capClassNameBase(base);
|
|
1702
|
+
let name = capped;
|
|
1703
|
+
if (state.usedClassNames.has(name)) {
|
|
1704
|
+
let n = state.nextClassCounter.get(capped) ?? 2;
|
|
1705
|
+
while (state.usedClassNames.has(`${capped}${n}`)) n++;
|
|
1706
|
+
name = `${capped}${n}`;
|
|
1707
|
+
state.nextClassCounter.set(capped, n + 1);
|
|
1708
|
+
}
|
|
1709
|
+
state.usedClassNames.add(name);
|
|
1710
|
+
return name;
|
|
1711
|
+
}
|
|
1712
|
+
function childClassName(base, segment) {
|
|
1713
|
+
return capClassNameBase(`${base}${segment}`.normalize("NFKC"));
|
|
1714
|
+
}
|
|
1715
|
+
function pyScalar(value) {
|
|
1716
|
+
if (value === true) return "True";
|
|
1717
|
+
if (value === false) return "False";
|
|
1718
|
+
if (typeof value === "string") return JSON.stringify(value);
|
|
1719
|
+
if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) return BigInt(value).toString();
|
|
1720
|
+
return String(value);
|
|
1721
|
+
}
|
|
1722
|
+
function renderConstrainedScalar(node, broad, state) {
|
|
1723
|
+
if (node.const !== void 0) {
|
|
1724
|
+
state.typing.add("Literal");
|
|
1725
|
+
return `Literal[${pyScalar(node.const)}]`;
|
|
1726
|
+
}
|
|
1727
|
+
if (node.enum !== void 0) {
|
|
1728
|
+
state.typing.add("Literal");
|
|
1729
|
+
return `Literal[${node.enum.map(pyScalar).join(", ")}]`;
|
|
1730
|
+
}
|
|
1731
|
+
return broad;
|
|
1732
|
+
}
|
|
1733
|
+
function renderType(schema, className, state) {
|
|
1734
|
+
const newFrame = (schema2, className2, listDepth) => ({
|
|
1735
|
+
schema: schema2,
|
|
1736
|
+
className: className2,
|
|
1737
|
+
phase: "start",
|
|
1738
|
+
listDepth,
|
|
1739
|
+
children: [],
|
|
1740
|
+
childIndex: 0,
|
|
1741
|
+
childTypes: [],
|
|
1742
|
+
entries: []
|
|
1743
|
+
});
|
|
1744
|
+
try {
|
|
1745
|
+
assertSupportedJsonSchema(schema);
|
|
1746
|
+
const frames = [newFrame(schema, className, 0)];
|
|
1747
|
+
let result;
|
|
1748
|
+
const finish = (type) => {
|
|
1749
|
+
frames.pop();
|
|
1750
|
+
const parent = frames.at(-1);
|
|
1751
|
+
if (parent === void 0) result = type;
|
|
1752
|
+
else parent.childTypes.push(type);
|
|
1753
|
+
};
|
|
1754
|
+
while (frames.length > 0) {
|
|
1755
|
+
const frame = frames.at(-1);
|
|
1756
|
+
if (frame === void 0) break;
|
|
1757
|
+
if (frame.phase === "children") {
|
|
1758
|
+
if (frame.childIndex < frame.children.length) {
|
|
1759
|
+
const child = frame.children[frame.childIndex];
|
|
1760
|
+
if (child === void 0) throw new Error("missing python render child");
|
|
1761
|
+
frame.childIndex++;
|
|
1762
|
+
frames.push(newFrame(child.schema, child.className, child.listDepth));
|
|
1763
|
+
continue;
|
|
1764
|
+
}
|
|
1765
|
+
if (frame.kind === "oneOf") {
|
|
1766
|
+
let union = "";
|
|
1767
|
+
for (const [index, childType] of frame.childTypes.entries()) union = index === 0 ? childType : `${union} | ${childType}`;
|
|
1768
|
+
finish(union);
|
|
1769
|
+
continue;
|
|
1770
|
+
}
|
|
1771
|
+
if (frame.kind === "array") {
|
|
1772
|
+
finish(`list[${frame.childTypes[0] ?? "Any"}]`);
|
|
1773
|
+
continue;
|
|
1774
|
+
}
|
|
1775
|
+
const node2 = frame.node;
|
|
1776
|
+
const name = frame.allocated;
|
|
1777
|
+
if (node2 === void 0 || name === void 0) throw new Error("missing typeddict frame state");
|
|
1778
|
+
const required = new Set(node2.required);
|
|
1779
|
+
const lines = [`class ${name}(TypedDict):`];
|
|
1780
|
+
for (let index = 0; index < frame.entries.length; index++) {
|
|
1781
|
+
const entry = frame.entries[index];
|
|
1782
|
+
const fieldType = frame.childTypes[index];
|
|
1783
|
+
if (entry === void 0 || fieldType === void 0) throw new Error("missing typeddict field type");
|
|
1784
|
+
const [field, fieldSchema] = entry;
|
|
1785
|
+
const description = describe(fieldSchema);
|
|
1786
|
+
if (description !== void 0) lines.push(`${pad(1)}# ${description}`);
|
|
1787
|
+
if (required.has(field)) lines.push(`${pad(1)}${field}: ${fieldType}`);
|
|
1788
|
+
else {
|
|
1789
|
+
state.typing.add("NotRequired");
|
|
1790
|
+
lines.push(`${pad(1)}${field}: NotRequired[${fieldType}]`);
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
if (node2.additionalProperties !== false) lines.push(`${pad(1)}# Additional keys beyond those declared are allowed.`);
|
|
1794
|
+
if (lines.length === 1) lines.push(`${pad(1)}pass`);
|
|
1795
|
+
state.classes.push(lines.join("\n"));
|
|
1796
|
+
finish(name);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
frame.phase = "children";
|
|
1800
|
+
const node = frame.schema;
|
|
1801
|
+
if (node.oneOf !== void 0) {
|
|
1802
|
+
frame.kind = "oneOf";
|
|
1803
|
+
frame.children = node.oneOf.map((branch, index) => ({
|
|
1804
|
+
schema: branch,
|
|
1805
|
+
className: childClassName(frame.className, `${index + 1}`),
|
|
1806
|
+
listDepth: frame.listDepth
|
|
1807
|
+
}));
|
|
1808
|
+
continue;
|
|
1809
|
+
}
|
|
1810
|
+
if (node.type === void 0) {
|
|
1811
|
+
state.typing.add("Any");
|
|
1812
|
+
finish("Any");
|
|
1813
|
+
continue;
|
|
1814
|
+
}
|
|
1815
|
+
switch (node.type) {
|
|
1816
|
+
case "string":
|
|
1817
|
+
finish(renderConstrainedScalar(node, "str", state));
|
|
1818
|
+
break;
|
|
1819
|
+
case "number":
|
|
1820
|
+
finish(renderConstrainedScalar(node, "float", state));
|
|
1821
|
+
break;
|
|
1822
|
+
case "integer":
|
|
1823
|
+
finish(renderConstrainedScalar(node, "int", state));
|
|
1824
|
+
break;
|
|
1825
|
+
case "boolean":
|
|
1826
|
+
finish(renderConstrainedScalar(node, "bool", state));
|
|
1827
|
+
break;
|
|
1828
|
+
case "null":
|
|
1829
|
+
finish("None");
|
|
1830
|
+
break;
|
|
1831
|
+
case "array":
|
|
1832
|
+
if (node.items === void 0) {
|
|
1833
|
+
state.typing.add("Any");
|
|
1834
|
+
finish("list[Any]");
|
|
1835
|
+
break;
|
|
1836
|
+
}
|
|
1837
|
+
if (frame.listDepth >= MAX_LIST_NESTING) {
|
|
1838
|
+
state.typing.add("Any");
|
|
1839
|
+
finish("Any");
|
|
1840
|
+
break;
|
|
1841
|
+
}
|
|
1842
|
+
frame.kind = "array";
|
|
1843
|
+
frame.children = [{
|
|
1844
|
+
schema: node.items,
|
|
1845
|
+
className: frame.className,
|
|
1846
|
+
listDepth: frame.listDepth + 1
|
|
1847
|
+
}];
|
|
1848
|
+
break;
|
|
1849
|
+
case "object": {
|
|
1850
|
+
const entries = Object.entries(node.properties ?? {});
|
|
1851
|
+
if (className === "" || !entries.every(([name]) => isBareIdentifier(name) && !RESERVED.has(name) && !(name.startsWith("__") && !name.endsWith("__")))) {
|
|
1852
|
+
state.typing.add("Any");
|
|
1853
|
+
finish("dict[str, Any]");
|
|
1854
|
+
break;
|
|
1855
|
+
}
|
|
1856
|
+
if (entries.length === 0 && node.additionalProperties !== false) {
|
|
1857
|
+
state.typing.add("Any");
|
|
1858
|
+
finish("dict[str, Any]");
|
|
1859
|
+
break;
|
|
1860
|
+
}
|
|
1861
|
+
frame.kind = "typeddict";
|
|
1862
|
+
frame.node = node;
|
|
1863
|
+
frame.allocated = allocateClassName(frame.className, state);
|
|
1864
|
+
state.typing.add("TypedDict");
|
|
1865
|
+
frame.entries = entries;
|
|
1866
|
+
frame.children = entries.map(([field, child]) => ({
|
|
1867
|
+
schema: child,
|
|
1868
|
+
className: childClassName(frame.allocated ?? "", camelCase(field)),
|
|
1869
|
+
listDepth: 1
|
|
1870
|
+
}));
|
|
1871
|
+
break;
|
|
1872
|
+
}
|
|
1873
|
+
/* v8 ignore next 4 -- assertSupportedJsonSchema narrowed this closed type union. */
|
|
1874
|
+
default:
|
|
1875
|
+
state.typing.add("Any");
|
|
1876
|
+
finish("Any");
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
return result ?? "Any";
|
|
1880
|
+
} catch {
|
|
1881
|
+
state.typing.add("Any");
|
|
1882
|
+
return "Any";
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
var SDK_INSTRUCTIONS = `## Writing code for run_code
|
|
1886
|
+
|
|
1887
|
+
\`run_code\` takes two required arguments: \`code\` \u2014 the body of an async Python function (top-level \`await\` and \`return\` both work) \u2014 and \`description\`, a short summary of what the program does. At run time exactly two of the names declared below are bound: \`tools\` and \`ToolCallError\`. Everything else is a STATIC STUB describing argument and return types \u2014 in particular the \`TypedDict\` classes do NOT exist at run time, so build arguments as plain \`dict\`/\`list\` JSON values: \`await tools.name({"field": 1})\`, never \`FooArgs(field=1)\`, which raises \`NameError\`. Inside the program:
|
|
1888
|
+
|
|
1889
|
+
- Call tools as \`await tools.name(args)\` \u2014 subscript access for exotic, reserved, or underscore-leading names: \`await tools["my-tool"](args)\`. Every call resolves to the tool's typed canonical JSON value (each method's return type below). Tool arguments must be lossless JSON.
|
|
1890
|
+
- A FAILED tool call raises \`ToolCallError\`, whose \`toolName\` identifies the failed tool and whose message is human-readable \u2014 wrap in \`try/except\` to handle and continue.
|
|
1891
|
+
- Independent read-only calls MAY overlap under \`asyncio.gather\` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with \`await\`.
|
|
1892
|
+
- Emit the run's answer with \`print(...)\` and/or a top-level \`return <value>\`; the returned value must be lossless JSON. ONLY what you print and the returned value come back \u2014 intermediate tool results never enter the conversation, so extract just what you need.
|
|
1893
|
+
|
|
1894
|
+
The available tools:`;
|
|
1895
|
+
function renderToolsSdkPy(schemas) {
|
|
1896
|
+
const sorted = [...schemas].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
1897
|
+
const state = {
|
|
1898
|
+
classes: [],
|
|
1899
|
+
usedClassNames: /* @__PURE__ */ new Set(),
|
|
1900
|
+
nextClassCounter: /* @__PURE__ */ new Map(),
|
|
1901
|
+
typing: /* @__PURE__ */ new Set(["Protocol"])
|
|
1902
|
+
};
|
|
1903
|
+
const members = [];
|
|
1904
|
+
let statements = 0;
|
|
1905
|
+
for (const schema of sorted) {
|
|
1906
|
+
const argType = renderType(schema.parameters, `${camelCase(schema.name)}Args`, state);
|
|
1907
|
+
const outputType = renderType(schema.output, `${camelCase(schema.name)}Output`, state);
|
|
1908
|
+
if (isBareIdentifier(schema.name) && !RESERVED.has(schema.name) && !schema.name.startsWith("_")) {
|
|
1909
|
+
const doc = docLines(schema.description, 2);
|
|
1910
|
+
members.push(doc.length > 0 ? `${pad(1)}async def ${schema.name}(self, args: ${argType}) -> ${outputType}:` : `${pad(1)}async def ${schema.name}(self, args: ${argType}) -> ${outputType}: ...`);
|
|
1911
|
+
members.push(...doc);
|
|
1912
|
+
statements += 1;
|
|
1913
|
+
} else {
|
|
1914
|
+
members.push(`${pad(1)}# tools[${JSON.stringify(schema.name)}](args: ${argType}) -> ${outputType}`);
|
|
1915
|
+
const description = describe(schema);
|
|
1916
|
+
if (description !== void 0) members.push(`${pad(1)}# ${description}`);
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
const body = (statements > 0 ? members : [`${pad(1)}pass`, ...members]).join("\n");
|
|
1920
|
+
const imports = TYPING_ORDER.filter((symbol) => state.typing.has(symbol));
|
|
1921
|
+
const classBlock = state.classes.length > 0 ? `${state.classes.join("\n\n")}
|
|
1922
|
+
|
|
1923
|
+
` : "";
|
|
1924
|
+
return `${SDK_INSTRUCTIONS}
|
|
1925
|
+
|
|
1926
|
+
\`\`\`python
|
|
1927
|
+
${`from typing import ${imports.join(", ")}
|
|
1928
|
+
|
|
1929
|
+
class ToolCallError(Exception):
|
|
1930
|
+
toolName: str
|
|
1931
|
+
|
|
1932
|
+
${classBlock}class Tools(Protocol):
|
|
1933
|
+
${body}
|
|
1934
|
+
|
|
1935
|
+
tools: Tools`}
|
|
1936
|
+
\`\`\``;
|
|
1937
|
+
}
|
|
1938
|
+
var COLLAPSE_SECTION_ORDER = 99;
|
|
1939
|
+
var CODE_ONLY_INSTRUCTION = `\`${RUN_CODE_NAME}\` is the only tool you can call directly \u2014 a tool call naming any other tool fails. Reach every tool the SDK declares below from inside the program.`;
|
|
1940
|
+
var SDK_RENDERERS = {
|
|
1941
|
+
typescript: renderToolsSdk,
|
|
1942
|
+
python: renderToolsSdkPy
|
|
1943
|
+
};
|
|
1944
|
+
var TOOL_RUNTIME_SCHEDULER = Symbol("@deepseek-ai/dsh-tools.scheduler");
|
|
1945
|
+
var TOOL_ABORTED = "ABORTED";
|
|
1946
|
+
var TOOL_ABORTED_BEFORE_DISPATCH = "ABORTED_BEFORE_DISPATCH";
|
|
1947
|
+
var ToolNotFoundError = class extends HarnessError {
|
|
1948
|
+
/**
|
|
1949
|
+
* @param toolName - the name the caller asked for.
|
|
1950
|
+
* @param reachableFrom - how the model reaches this tool instead, when the
|
|
1951
|
+
* name IS visible and only the presentation denies calling it directly.
|
|
1952
|
+
* Omitted for a name that is registered nowhere.
|
|
1953
|
+
*/
|
|
1954
|
+
constructor(toolName, reachableFrom) {
|
|
1955
|
+
super(reachableFrom === void 0 ? `unknown tool "${toolName}"` : `unknown tool "${toolName}": ${reachableFrom}`, "UNKNOWN_TOOL");
|
|
1956
|
+
this.name = "ToolNotFoundError";
|
|
1957
|
+
}
|
|
1958
|
+
};
|
|
1959
|
+
var ToolOutputError = class extends HarnessError {
|
|
1960
|
+
/** Schema/value violations in validation order. */
|
|
1961
|
+
violations;
|
|
1962
|
+
constructor(toolName, violations) {
|
|
1963
|
+
super(`tool "${toolName}" returned invalid output: ${violations.join("; ")}`, "INVALID_TOOL_OUTPUT");
|
|
1964
|
+
this.name = "ToolOutputError";
|
|
1965
|
+
this.violations = violations;
|
|
1966
|
+
}
|
|
1967
|
+
};
|
|
1968
|
+
function projectionError(toolName, projector, error) {
|
|
1969
|
+
return new ToolOutputError(toolName, [`output.${projector} failed: ${errorMessage(error)}`]);
|
|
1970
|
+
}
|
|
1971
|
+
function snapshotProjection(toolName, projector, candidate) {
|
|
1972
|
+
try {
|
|
1973
|
+
const detached = snapshotJsonValue(candidate);
|
|
1974
|
+
if (detached === void 0) throw new ToolOutputError(toolName, [`output.${projector} returned non-lossless JSON`]);
|
|
1975
|
+
return detached;
|
|
1976
|
+
} catch (error) {
|
|
1977
|
+
if (error instanceof ToolOutputError) throw error;
|
|
1978
|
+
throw projectionError(toolName, projector, error);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
function snapshotToolValue(toolName, candidate) {
|
|
1982
|
+
try {
|
|
1983
|
+
const detached = snapshotJsonValue(candidate);
|
|
1984
|
+
if (detached === void 0) throw new ToolOutputError(toolName, ["value is not lossless JSON"]);
|
|
1985
|
+
return detached;
|
|
1986
|
+
} catch (error) {
|
|
1987
|
+
if (error instanceof ToolOutputError) throw error;
|
|
1988
|
+
throw new ToolOutputError(toolName, [`value snapshot failed: ${errorMessage(error)}`]);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
function errorMessage(error) {
|
|
1992
|
+
try {
|
|
1993
|
+
if (error instanceof Error) return error.message;
|
|
1994
|
+
if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
|
|
1995
|
+
return String(error);
|
|
1996
|
+
} catch {
|
|
1997
|
+
return "<unprintable thrown value>";
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
function failureMessageFromContent(content) {
|
|
2001
|
+
const text = content.map((block) => block.type === "text" ? block.text : `[${block.type} content]`).join("\n");
|
|
2002
|
+
return text.length > 0 ? text : "tool result blocked by post-execute policy";
|
|
2003
|
+
}
|
|
2004
|
+
function materializePresentation(candidate) {
|
|
2005
|
+
const detached = snapshotJsonValue(candidate);
|
|
2006
|
+
if (detached === void 0) throw new TypeError("tool result must be losslessly JSON-serializable");
|
|
2007
|
+
return deepFreeze(detached);
|
|
2008
|
+
}
|
|
2009
|
+
function errorInfo(error) {
|
|
2010
|
+
try {
|
|
2011
|
+
return error instanceof HarnessError ? {
|
|
2012
|
+
name: error.name,
|
|
2013
|
+
code: error.code
|
|
2014
|
+
} : void 0;
|
|
2015
|
+
} catch {
|
|
2016
|
+
return;
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
var ToolLayer = class {
|
|
2020
|
+
tools;
|
|
2021
|
+
restrictions = new AnonymousEntries();
|
|
2022
|
+
guards = new AnonymousEntries();
|
|
2023
|
+
/**
|
|
2024
|
+
* Presentation this scope's agent declared for itself, shadowing the
|
|
2025
|
+
* deployment default. One cell rather than an entry table: two answers to
|
|
2026
|
+
* "which form does the model see" is a contradiction, not a merge.
|
|
2027
|
+
*/
|
|
2028
|
+
mode;
|
|
2029
|
+
constructor(scope) {
|
|
2030
|
+
this.tools = new NamedEntries((name) => /* @__PURE__ */ new Error(scope === void 0 ? `tool "${name}" is already registered (for a per-agent variant, register through that agent's \`agent.ctx\` instead)` : `tool "${name}" is already registered in this scope`));
|
|
2031
|
+
}
|
|
2032
|
+
/** Whether every contribution table in this aggregate layer is empty. */
|
|
2033
|
+
isEmpty() {
|
|
2034
|
+
return this.tools.isEmpty() && this.restrictions.isEmpty() && this.guards.isEmpty() && this.mode === void 0;
|
|
2035
|
+
}
|
|
2036
|
+
/** Whether every compiled restriction in this layer admits a global tool name. */
|
|
2037
|
+
admits(name) {
|
|
2038
|
+
for (const filter of this.restrictions.values()) if (filter.allow !== void 0 && !filter.allow.has(name) || filter.deny !== void 0 && filter.deny.has(name)) return false;
|
|
2039
|
+
return true;
|
|
2040
|
+
}
|
|
2041
|
+
/** First monotonic denial from this layer's live guard registrations. */
|
|
2042
|
+
guardReason(exec) {
|
|
2043
|
+
for (const guard of this.guards.values()) {
|
|
2044
|
+
const reason = guard(exec);
|
|
2045
|
+
if (reason !== void 0) return reason;
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
};
|
|
2049
|
+
function resolveMaxParallelSubCalls(value) {
|
|
2050
|
+
const maxParallelSubCalls = value ?? 10;
|
|
2051
|
+
if (!Number.isInteger(maxParallelSubCalls) || maxParallelSubCalls < 1) throw new Error("maxParallelSubCalls must be a positive integer");
|
|
2052
|
+
return maxParallelSubCalls;
|
|
2053
|
+
}
|
|
2054
|
+
var ToolRuntime = class extends Service {
|
|
2055
|
+
static inject = ["systemPrompt"];
|
|
2056
|
+
static Config = z.object({
|
|
2057
|
+
mode: z.union([
|
|
2058
|
+
"native",
|
|
2059
|
+
"code",
|
|
2060
|
+
"both"
|
|
2061
|
+
]).default("native"),
|
|
2062
|
+
maxParallelSubCalls: z.natural().min(1).default(10)
|
|
2063
|
+
});
|
|
2064
|
+
/** Internal staged view consumed by `dsh-agent-loop`'s parallel scheduler. */
|
|
2065
|
+
[TOOL_RUNTIME_SCHEDULER] = {
|
|
2066
|
+
prepare: (exec) => this.prepareScheduledExecution(exec),
|
|
2067
|
+
dispatch: (exec) => this.dispatchScheduledExecution(exec),
|
|
2068
|
+
finalize: (exec, result) => this.finalizeScheduledExecution(exec, result),
|
|
2069
|
+
finish: (exec, result) => this.finishScheduledExecution(exec, result)
|
|
2070
|
+
};
|
|
2071
|
+
/** Context deferred by a running tool body, keyed by its scheduler-owned execution. */
|
|
2072
|
+
deferredContexts = /* @__PURE__ */ new WeakMap();
|
|
2073
|
+
/** Executions whose tool body declared the current turn complete. */
|
|
2074
|
+
concludingExecutions = /* @__PURE__ */ new WeakSet();
|
|
2075
|
+
/** Original caller cancellation, kept outside the wrapper-mutable execution object. */
|
|
2076
|
+
cancellationStates = /* @__PURE__ */ new WeakMap();
|
|
2077
|
+
/** Definition-owned final content transform snapshotted before policy begins. */
|
|
2078
|
+
contentFinalizers = /* @__PURE__ */ new WeakMap();
|
|
2079
|
+
layers = new ScopedLayers((scope) => new ToolLayer(scope), () => {
|
|
2080
|
+
this.ctx.emit("tools/change");
|
|
2081
|
+
});
|
|
2082
|
+
/** Presentation for scopes that declare none; {@link presentAs} shadows it per scope. */
|
|
2083
|
+
defaultMode;
|
|
2084
|
+
maxParallelSubCalls;
|
|
2085
|
+
/**
|
|
2086
|
+
* Reserved presentation transport, kept outside the filterable registration
|
|
2087
|
+
* layers. Built on first need rather than at construction: which agents run
|
|
2088
|
+
* a code mode is no longer known when the service is constructed, and the
|
|
2089
|
+
* transport is stateless beyond its closures over `this`.
|
|
2090
|
+
*/
|
|
2091
|
+
codeTransport;
|
|
2092
|
+
constructor(ctx, config = {}) {
|
|
2093
|
+
super(ctx, "tools");
|
|
2094
|
+
this.defaultMode = config.mode ?? "native";
|
|
2095
|
+
this.maxParallelSubCalls = resolveMaxParallelSubCalls(config.maxParallelSubCalls);
|
|
2096
|
+
ctx.systemPrompt.tools((context) => this.wireSchemas(context.scope));
|
|
2097
|
+
if (this.defaultMode !== "native") {
|
|
2098
|
+
ctx.systemPrompt.section(this.collapseSection());
|
|
2099
|
+
ctx.systemPrompt.section(this.sdkSection());
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* The prompt statement of the `code` executor collapse, registered wherever
|
|
2104
|
+
* {@link sdkSection} is and rendering empty outside an effective `code`.
|
|
2105
|
+
*
|
|
2106
|
+
* Every tool contributes its own guidance section naming its tool, none of
|
|
2107
|
+
* them qualify how that tool is reached, and they all render before the SDK
|
|
2108
|
+
* (orders 100-199 against {@link SDK_SECTION_ORDER}). Without this the model
|
|
2109
|
+
* reads a catalog of tools it is told to use and no statement that only
|
|
2110
|
+
* `run_code` may be called, so it emits a native call, receives
|
|
2111
|
+
* `UNKNOWN_TOOL` for a tool the prompt just declared, and concludes the
|
|
2112
|
+
* deployment is inconsistent. {@link COLLAPSE_SECTION_ORDER} places the rule
|
|
2113
|
+
* before that guidance rather than after it.
|
|
2114
|
+
*
|
|
2115
|
+
* `both` renders empty: native calls do execute there, so the rule is false.
|
|
2116
|
+
* @returns the section registration.
|
|
2117
|
+
*/
|
|
2118
|
+
collapseSection() {
|
|
2119
|
+
return {
|
|
2120
|
+
name: "tools:code-only",
|
|
2121
|
+
order: COLLAPSE_SECTION_ORDER,
|
|
2122
|
+
text: (context) => this.modeFor(context.scope) === "code" ? CODE_ONLY_INSTRUCTION : ""
|
|
2123
|
+
};
|
|
2124
|
+
}
|
|
2125
|
+
/**
|
|
2126
|
+
* The generated-SDK prompt section, registered globally by a code-mode
|
|
2127
|
+
* deployment and per scope by {@link presentAs}.
|
|
2128
|
+
*
|
|
2129
|
+
* The body regenerates from the CALLING scope, and renders empty for an
|
|
2130
|
+
* agent presenting natively — an agent that opted out under a code-mode
|
|
2131
|
+
* deployment still sees the global registration, and an empty section is
|
|
2132
|
+
* dropped from the rendered prompt.
|
|
2133
|
+
* @returns the section registration.
|
|
2134
|
+
*/
|
|
2135
|
+
sdkSection() {
|
|
2136
|
+
return {
|
|
2137
|
+
name: "tools:sdk",
|
|
2138
|
+
order: 150,
|
|
2139
|
+
text: (context) => {
|
|
2140
|
+
const mode = this.modeFor(context.scope);
|
|
2141
|
+
if (mode === "native") return "";
|
|
2142
|
+
const runtime = this.requireCodeRuntime(mode);
|
|
2143
|
+
const render = SDK_RENDERERS[runtime.language];
|
|
2144
|
+
if (render === void 0) throw new Error(`dsh-tools: no SDK renderer for ${runtime.language}`);
|
|
2145
|
+
return render(this.sdkSchemas(context.scope));
|
|
2146
|
+
}
|
|
2147
|
+
};
|
|
2148
|
+
}
|
|
2149
|
+
/**
|
|
2150
|
+
* The presentation one scope's agent sees: its own declaration, else the
|
|
2151
|
+
* deployment default.
|
|
2152
|
+
* @param scope - the calling agent, or undefined for the global view.
|
|
2153
|
+
* @returns the resolved presentation mode.
|
|
2154
|
+
*/
|
|
2155
|
+
modeFor(scope) {
|
|
2156
|
+
const layers = this.layers.chainLayers(scope);
|
|
2157
|
+
for (let index = layers.length - 1; index >= 0; index -= 1) {
|
|
2158
|
+
const mode = layers[index]?.mode;
|
|
2159
|
+
if (mode !== void 0) return mode;
|
|
2160
|
+
}
|
|
2161
|
+
return this.defaultMode;
|
|
2162
|
+
}
|
|
2163
|
+
/**
|
|
2164
|
+
* The reserved `run_code` transport, built on first need.
|
|
2165
|
+
*
|
|
2166
|
+
* It never enters the global layer: per-agent restrictions must not remove
|
|
2167
|
+
* it, and a scoped registration must not shadow it. The visibility resolver
|
|
2168
|
+
* appends it after resolving the filterable global/scoped capability layers,
|
|
2169
|
+
* and only for scopes whose mode actually presents it.
|
|
2170
|
+
* @returns the shared transport definition.
|
|
2171
|
+
*/
|
|
2172
|
+
requireCodeTransport() {
|
|
2173
|
+
this.codeTransport ??= createRunCodeTool(this, {
|
|
2174
|
+
requireRuntime: () => this.requireCodeRuntime(this.defaultMode),
|
|
2175
|
+
peekRuntime: () => this.ctx.get("codeRuntime"),
|
|
2176
|
+
maxParallel: this.maxParallelSubCalls,
|
|
2177
|
+
shapeDispatchLog: (dispatch) => this.shapeDispatchLog(dispatch)
|
|
2178
|
+
});
|
|
2179
|
+
return this.codeTransport;
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* Present the calling scope's tools in `mode` instead of the deployment
|
|
2183
|
+
* default. Nearest scope on the chain wins, so a preset's standing
|
|
2184
|
+
* declaration covers every agent joined under it.
|
|
2185
|
+
*
|
|
2186
|
+
* Scoped only, and one declaration per scope: this is how an agent preset
|
|
2187
|
+
* composes Code Mode agents beside native ones in the same process, and a
|
|
2188
|
+
* process-global override would be the `mode` config field instead.
|
|
2189
|
+
* @param mode - the presentation the covered agents' models see.
|
|
2190
|
+
* @returns the exact disposer that restores the deployment default.
|
|
2191
|
+
*/
|
|
2192
|
+
presentAs(mode) {
|
|
2193
|
+
const ctx = this.ctx;
|
|
2194
|
+
if (scopeOf(ctx) === void 0) throw new Error("tools.presentAs() requires a scoped context (agent.ctx): a context-global presentation is the `mode` config field on the tools row");
|
|
2195
|
+
return ctx.effect(function* () {
|
|
2196
|
+
yield this.layers.effect(ctx, (layer) => {
|
|
2197
|
+
if (layer.mode !== void 0) throw new Error(`tools.presentAs("${mode}") conflicts with "${layer.mode}" already declared for this scope; one composition selects one presentation`);
|
|
2198
|
+
layer.mode = mode;
|
|
2199
|
+
return () => {
|
|
2200
|
+
layer.mode = void 0;
|
|
2201
|
+
};
|
|
2202
|
+
}, { label: "tools.presentAs()" });
|
|
2203
|
+
if (mode !== "native") {
|
|
2204
|
+
yield ctx.systemPrompt.section(this.collapseSection());
|
|
2205
|
+
yield ctx.systemPrompt.section(this.sdkSection());
|
|
2206
|
+
}
|
|
2207
|
+
}.bind(this), "tools.presentAs()");
|
|
2208
|
+
}
|
|
2209
|
+
/**
|
|
2210
|
+
* Build one scope's wire schemas and names for prompt-order validation.
|
|
2211
|
+
* Restrictions do not make known tools invalid, but a mode collapse does.
|
|
2212
|
+
*/
|
|
2213
|
+
wireSchemas(scope) {
|
|
2214
|
+
const view = this.view(scope);
|
|
2215
|
+
const mode = this.modeFor(scope);
|
|
2216
|
+
if (mode === "native") return {
|
|
2217
|
+
schemas: [...view.visible.values()].map((definition) => this.schemaOf(definition, false)),
|
|
2218
|
+
knownNames: [...view.knownNames]
|
|
2219
|
+
};
|
|
2220
|
+
this.requireCodeRuntime(mode);
|
|
2221
|
+
const schemas = [...view.visible.values()].map((definition) => this.schemaOf(definition, false));
|
|
2222
|
+
if (mode === "code") return {
|
|
2223
|
+
schemas: schemas.filter((schema) => schema.name === RUN_CODE_NAME),
|
|
2224
|
+
knownNames: [RUN_CODE_NAME]
|
|
2225
|
+
};
|
|
2226
|
+
return {
|
|
2227
|
+
schemas,
|
|
2228
|
+
knownNames: [...view.knownNames, RUN_CODE_NAME]
|
|
2229
|
+
};
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* Resolve the code runtime or throw the actionable misconfiguration error.
|
|
2233
|
+
* Read at use time (assembly / run_code execution), NOT via static
|
|
2234
|
+
* `inject`: an inject entry would hold `ctx.tools` — and every tool plugin
|
|
2235
|
+
* behind it — hostage to a code runtime existing even under `mode:
|
|
2236
|
+
* 'native'` (the loop's optional-backend idiom, same as
|
|
2237
|
+
* `sessionPersistence`).
|
|
2238
|
+
*
|
|
2239
|
+
* Assembly and `run_code` execution read separately, so the language is not
|
|
2240
|
+
* bound to a request. Harmless while one published backend exists — both
|
|
2241
|
+
* reads return the same flavor — but a reload that swapped in a second
|
|
2242
|
+
* language between them would hand a program written against one SDK to the
|
|
2243
|
+
* other. Binding it is deferred until a second backend ships (the first
|
|
2244
|
+
* point it is testable); rationale in the
|
|
2245
|
+
* [language-dispatch note](../../../../.agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.md).
|
|
2246
|
+
*/
|
|
2247
|
+
requireCodeRuntime(mode) {
|
|
2248
|
+
const runtime = this.ctx.get("codeRuntime");
|
|
2249
|
+
if (!runtime) throw new Error(`dsh-tools: mode "${mode}" requires a code runtime \u2014 load a ctx.codeRuntime implementation (e.g. @deepseek-ai/dsh-code-runtime-worker-thread) or set tools mode to "native"`);
|
|
2250
|
+
if (!Object.hasOwn(SDK_RENDERERS, runtime.language)) {
|
|
2251
|
+
const known = Object.keys(SDK_RENDERERS).map((name) => JSON.stringify(name)).join(", ");
|
|
2252
|
+
throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`);
|
|
2253
|
+
}
|
|
2254
|
+
return runtime;
|
|
2255
|
+
}
|
|
2256
|
+
/**
|
|
2257
|
+
* Register globally or in the calling agent scope. Scoped tools shadow
|
|
2258
|
+
* globals; duplicates within one layer and the reserved `run_code` name fail.
|
|
2259
|
+
* @param definition - tool schema, execution, and optional finalization/presentation callbacks.
|
|
2260
|
+
* @returns the exact disposer that unregisters the tool.
|
|
2261
|
+
*/
|
|
2262
|
+
register(definition) {
|
|
2263
|
+
const name = definition.name;
|
|
2264
|
+
const output = definition.output;
|
|
2265
|
+
if (output === void 0 || typeof output !== "object" || typeof output.render !== "function" || output.presentationMeta !== void 0 && typeof output.presentationMeta !== "function") throw new TypeError(`tool "${name}" must declare output { schema, render, presentationMeta? }`);
|
|
2266
|
+
assertSupportedJsonSchema(output.schema);
|
|
2267
|
+
const timeoutMs = definition.timeoutMs;
|
|
2268
|
+
if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new TypeError(`tool "${name}" timeoutMs must be a positive finite number`);
|
|
2269
|
+
if (name === "run_code") throw new Error(`tool name "${RUN_CODE_NAME}" is reserved for the Code Mode presentation transport and cannot be registered or shadowed`);
|
|
2270
|
+
return this.layers.effect(this.ctx, (layer) => layer.tools.insert(name, definition), { label: "tools.register()" });
|
|
2271
|
+
}
|
|
2272
|
+
/**
|
|
2273
|
+
* Restrict global tools for the calling agent scope. Empty filters, unknown
|
|
2274
|
+
* names, scope-local names, and reserved transport names fail. Restrictions
|
|
2275
|
+
* intersect; scoped registrations remain visible.
|
|
2276
|
+
* @param filter - global-tool mask: `allow` (keep only) and/or `deny` (remove).
|
|
2277
|
+
* @returns the exact disposer that lifts this restriction.
|
|
2278
|
+
*/
|
|
2279
|
+
restrict(filter) {
|
|
2280
|
+
const scope = scopeOf(this.ctx);
|
|
2281
|
+
if (scope === void 0) throw new Error("tools.restrict() requires a scoped context (agent.ctx): a context-global restriction would mask every agent \u2014 deny the tool for the intended agent instead");
|
|
2282
|
+
const allow = filter.allow;
|
|
2283
|
+
const deny = filter.deny;
|
|
2284
|
+
if (allow === void 0 && deny === void 0) throw new Error("tools.restrict({}) is a no-op: pass `allow` and/or `deny` (an empty filter is almost always a materialized-empty-config bug)");
|
|
2285
|
+
const compiled = {
|
|
2286
|
+
...allow !== void 0 ? { allow: new Set(allow) } : {},
|
|
2287
|
+
...deny !== void 0 ? { deny: new Set(deny) } : {}
|
|
2288
|
+
};
|
|
2289
|
+
if ([...allow ?? [], ...deny ?? []].includes("run_code")) throw new Error(`tools.restrict() cannot name reserved Code Mode presentation transport "${RUN_CODE_NAME}"; restrict end-capability tools instead`);
|
|
2290
|
+
const known = this.view(scope).restrictableNames;
|
|
2291
|
+
const unknown = [...allow ?? [], ...deny ?? []].filter((name) => !known.has(name));
|
|
2292
|
+
if (unknown.length > 0) throw new Error(`tools.restrict() names unknown global tool${unknown.length > 1 ? "s" : ""} ${unknown.map((n) => `"${n}"`).join(", ")}; known global tools: ${[...known].sort().join(", ") || "(none)"}`);
|
|
2293
|
+
return this.layers.effect(this.ctx, (layer) => layer.restrictions.append(compiled), { label: "tools.restrict()" });
|
|
2294
|
+
}
|
|
2295
|
+
/**
|
|
2296
|
+
* Register a monotonic guard after the extensible `tools/pre-execute`
|
|
2297
|
+
* waterfall. A plain-context guard applies globally; one registered through
|
|
2298
|
+
* `agent.ctx` applies only to that agent. Any matching guard may deny by
|
|
2299
|
+
* returning a reason, while no guard can force-allow a call another guard
|
|
2300
|
+
* denied. The exact effect disposer is returned for ordered ownership and
|
|
2301
|
+
* HMR cleanup.
|
|
2302
|
+
* @param guard - synchronous check; a returned string denies the execution.
|
|
2303
|
+
* @returns the exact disposer that unregisters the guard.
|
|
2304
|
+
*/
|
|
2305
|
+
guard(guard) {
|
|
2306
|
+
return this.layers.effect(this.ctx, (layer) => layer.guards.append(guard), {
|
|
2307
|
+
label: "tools.guard()",
|
|
2308
|
+
notify: false
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
/** First monotonic denial from the global then the scope chain's guard layers, farthest first. */
|
|
2312
|
+
guardReason(exec) {
|
|
2313
|
+
const globalReason = this.layers.global.guardReason(exec);
|
|
2314
|
+
if (globalReason !== void 0) return globalReason;
|
|
2315
|
+
if (exec.agent === void 0) return void 0;
|
|
2316
|
+
for (const layer of this.layers.chainLayers(exec.agent)) {
|
|
2317
|
+
const reason = layer.guardReason(exec);
|
|
2318
|
+
if (reason !== void 0) return reason;
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
/**
|
|
2322
|
+
* Resolve every registry fact one scope needs in one layer traversal. The
|
|
2323
|
+
* visible map applies restrictions to the INHERITED surface, then the
|
|
2324
|
+
* scope's own registrations and the reserved presentation transport; the
|
|
2325
|
+
* other sets retain the pre-restriction facts needed by restriction and
|
|
2326
|
+
* prompt-order validation.
|
|
2327
|
+
*
|
|
2328
|
+
* A restriction filters what a scope inherits — the global layer and every
|
|
2329
|
+
* ancestor layer on its chain — and never what its OWN layer registers.
|
|
2330
|
+
* That exemption is what a per-child capability filter has to keep intact:
|
|
2331
|
+
* the delegation runtime registers a child's reporting and structured-output
|
|
2332
|
+
* tools into the child's own layer, and a filter naming the capabilities the
|
|
2333
|
+
* child may use must not strip the machinery it answers through.
|
|
2334
|
+
*
|
|
2335
|
+
* Reading the exempt set as "the global layer" instead of "not mine" held
|
|
2336
|
+
* only while every model-facing tool sat in the host composition. Once
|
|
2337
|
+
* presets moved them onto the agent plane they became an ANCESTOR
|
|
2338
|
+
* contribution, so a child's filter silently stopped constraining anything
|
|
2339
|
+
* it was given.
|
|
2340
|
+
* @param scope - the viewing scope (the agent), or undefined for the global view.
|
|
2341
|
+
* @returns the complete derived view for that scope.
|
|
2342
|
+
*/
|
|
2343
|
+
view(scope) {
|
|
2344
|
+
const layers = this.layers.chainLayers(scope);
|
|
2345
|
+
const own = this.layers.peek(scope);
|
|
2346
|
+
const inherited = new Map(this.layers.global.tools.entries());
|
|
2347
|
+
for (const layer of layers) {
|
|
2348
|
+
if (layer === own) continue;
|
|
2349
|
+
for (const [name, definition] of layer.tools.entries()) inherited.set(name, definition);
|
|
2350
|
+
}
|
|
2351
|
+
const visible = /* @__PURE__ */ new Map();
|
|
2352
|
+
const knownNames = /* @__PURE__ */ new Set();
|
|
2353
|
+
const restrictableNames = /* @__PURE__ */ new Set();
|
|
2354
|
+
for (const [name, definition] of inherited) {
|
|
2355
|
+
knownNames.add(name);
|
|
2356
|
+
restrictableNames.add(name);
|
|
2357
|
+
if (layers.every((layer) => layer.admits(name))) visible.set(name, definition);
|
|
2358
|
+
}
|
|
2359
|
+
if (own !== void 0) for (const [name, definition] of own.tools.entries()) {
|
|
2360
|
+
knownNames.add(name);
|
|
2361
|
+
visible.set(name, definition);
|
|
2362
|
+
}
|
|
2363
|
+
if (this.modeFor(scope) !== "native") visible.set(RUN_CODE_NAME, this.requireCodeTransport());
|
|
2364
|
+
return {
|
|
2365
|
+
visible,
|
|
2366
|
+
knownNames,
|
|
2367
|
+
restrictableNames
|
|
2368
|
+
};
|
|
2369
|
+
}
|
|
2370
|
+
/**
|
|
2371
|
+
* Look up a tool as one scope sees it (scoped
|
|
2372
|
+
* shadows global; a restricted-away global reads as absent). Presenters pass
|
|
2373
|
+
* the calling agent so the rendered card matches the definition that
|
|
2374
|
+
* actually executed.
|
|
2375
|
+
* @param name - the tool name as registered.
|
|
2376
|
+
* @param scope - the viewing scope (the agent); omitted = the global view.
|
|
2377
|
+
* @returns the definition the scope resolves, or undefined when none is visible.
|
|
2378
|
+
*/
|
|
2379
|
+
get(name, scope) {
|
|
2380
|
+
return this.view(scope).visible.get(name);
|
|
2381
|
+
}
|
|
2382
|
+
/**
|
|
2383
|
+
* Resolve the definition that MAY EXECUTE for a call, applying the mode
|
|
2384
|
+
* collapse at the operation boundary that owns it. The registry view
|
|
2385
|
+
* (`get`) is presentation-agnostic; here a MODEL-DIRECT call under `code`
|
|
2386
|
+
* may only name the reserved `run_code` transport, while a nested
|
|
2387
|
+
* sub-dispatch (a `parent` token set — the `run_code` SDK calling a tool
|
|
2388
|
+
* it bound) may call any visible tool. Denial surfaces as `UNKNOWN_TOOL`
|
|
2389
|
+
* through the executor, matching an absent definition.
|
|
2390
|
+
* @param name - the tool name as registered.
|
|
2391
|
+
* @param scope - the viewing scope (the agent); omitted = the global view.
|
|
2392
|
+
* @param nested - whether the call is a transport sub-dispatch, not a model-direct call.
|
|
2393
|
+
* @returns the definition that may run, or undefined when the call must be rejected.
|
|
2394
|
+
*/
|
|
2395
|
+
resolveExecution(name, scope, nested) {
|
|
2396
|
+
const tool = this.get(name, scope);
|
|
2397
|
+
if (tool === void 0) return void 0;
|
|
2398
|
+
if (this.collapses(name, scope, nested)) return void 0;
|
|
2399
|
+
return tool;
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* Project visible definitions onto the allowlisted model-facing schema fields,
|
|
2403
|
+
* excluding execution and presentation callbacks.
|
|
2404
|
+
* @param scope - the viewing scope (the agent); omitted = the global view.
|
|
2405
|
+
* @returns one deep-cloned schema per visible tool.
|
|
2406
|
+
*/
|
|
2407
|
+
schemas(scope) {
|
|
2408
|
+
return [...this.view(scope).visible.values()].map((definition) => this.schemaOf(definition, true));
|
|
2409
|
+
}
|
|
2410
|
+
/** Project visible callable tools onto the generated Code Mode SDK contract. */
|
|
2411
|
+
sdkSchemas(scope) {
|
|
2412
|
+
return [...this.view(scope).visible.values()].filter((definition) => definition.name !== RUN_CODE_NAME).map((definition) => {
|
|
2413
|
+
const output = snapshotJsonValue(definition.output.schema);
|
|
2414
|
+
if (output === void 0) throw new Error(`tool "${definition.name}" output schema must be lossless JSON before SDK projection`);
|
|
2415
|
+
return {
|
|
2416
|
+
...this.schemaOf(definition, true),
|
|
2417
|
+
output
|
|
2418
|
+
};
|
|
2419
|
+
});
|
|
2420
|
+
}
|
|
2421
|
+
/** Project one definition onto the model-facing schema fields. */
|
|
2422
|
+
schemaOf(definition, detachParameters) {
|
|
2423
|
+
const { name, description, parameters } = definition;
|
|
2424
|
+
const detached = detachParameters ? snapshotJsonValue(parameters) : parameters;
|
|
2425
|
+
if (detached === void 0) throw new Error(`tool "${name}" parameters must be lossless JSON before schema projection`);
|
|
2426
|
+
return {
|
|
2427
|
+
name,
|
|
2428
|
+
description,
|
|
2429
|
+
parameters: detached
|
|
2430
|
+
};
|
|
2431
|
+
}
|
|
2432
|
+
/**
|
|
2433
|
+
* Classify a pending call through the caller's visible tool definition. Only
|
|
2434
|
+
* an exact `true` is parallel; unknown, hidden, undeclared, invalid, or
|
|
2435
|
+
* throwing classifiers are exclusive.
|
|
2436
|
+
* @param exec - call name, parsed arguments, and optional agent scope.
|
|
2437
|
+
* @returns the fail-closed scheduling mode.
|
|
2438
|
+
*/
|
|
2439
|
+
executionMode(exec) {
|
|
2440
|
+
const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);
|
|
2441
|
+
if (!tool?.isConcurrencySafe) return { kind: "exclusive" };
|
|
2442
|
+
try {
|
|
2443
|
+
return tool.isConcurrencySafe(exec.arguments) === true ? { kind: "parallel" } : { kind: "exclusive" };
|
|
2444
|
+
} catch {
|
|
2445
|
+
return { kind: "exclusive" };
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
/**
|
|
2449
|
+
* Run the `tools/code-dispatch-log` waterfall over one settled sub-dispatch
|
|
2450
|
+
* and return the content the bridge should log on `tool/code-dispatch`.
|
|
2451
|
+
* Contained: when a listener throws, the method logs the original settled
|
|
2452
|
+
* content; that failure must not fail the dispatch or omit the settle event. Private:
|
|
2453
|
+
* the ONE consumer is the `run_code` bridge this registry constructs, which
|
|
2454
|
+
* receives it as a capability parameter (the `requireRuntime` idiom) — the
|
|
2455
|
+
* waterfall, not this invoker, is the public extension point.
|
|
2456
|
+
*/
|
|
2457
|
+
async shapeDispatchLog(dispatch) {
|
|
2458
|
+
try {
|
|
2459
|
+
return await this.ctx.waterfall(scopeTarget(this, dispatch.agent), "tools/code-dispatch-log", dispatch, () => Promise.resolve(dispatch.content));
|
|
2460
|
+
} catch (error) {
|
|
2461
|
+
this.ctx.logger.warn(`tools: code-dispatch-log listener failed for ${dispatch.name}: ${errorMessage(error)}; logging the original settled content`);
|
|
2462
|
+
return dispatch.content;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
/**
|
|
2466
|
+
* Whether the `code` mode collapse denies a model-direct call: only the
|
|
2467
|
+
* reserved `run_code` transport may be named. Nested sub-dispatches (a
|
|
2468
|
+
* `parent` token set) bypass the collapse. One home for the
|
|
2469
|
+
* security-relevant predicate, shared by {@link resolveExecution} and
|
|
2470
|
+
* {@link createExecution} so the two can never drift apart.
|
|
2471
|
+
*
|
|
2472
|
+
* Resolved through {@link modeFor}, NOT `defaultMode`: an agent given `code`
|
|
2473
|
+
* by an agent preset under a native deployment is the composition
|
|
2474
|
+
* `dsh-agent-tool-presentation` exists for, and reading the deployment default would
|
|
2475
|
+
* leave exactly that agent uncollapsed — announcing one surface while
|
|
2476
|
+
* executing another, which is the bypass this collapse closes.
|
|
2477
|
+
* @param name - the tool name as registered.
|
|
2478
|
+
* @param scope - the viewing scope whose effective presentation mode applies.
|
|
2479
|
+
* @param nested - whether the call is a transport sub-dispatch, not a model-direct call.
|
|
2480
|
+
*/
|
|
2481
|
+
collapses(name, scope, nested) {
|
|
2482
|
+
return !nested && this.modeFor(scope) === "code" && name !== "run_code";
|
|
2483
|
+
}
|
|
2484
|
+
/**
|
|
2485
|
+
* Execute through pre-policy, guards, around-dispatch, post-policy,
|
|
2486
|
+
* definition-owned content finalization, and final notification. Tool and
|
|
2487
|
+
* listener failures resolve as materialized error results; an invisible tool
|
|
2488
|
+
* reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen
|
|
2489
|
+
* snapshot final observers receive. Cancellation
|
|
2490
|
+
* arriving after entry and before final result materialization skips a
|
|
2491
|
+
* not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a
|
|
2492
|
+
* successful started outcome with `ABORTED`; already-started work is still
|
|
2493
|
+
* drained and may retain a tool-owned structured error.
|
|
2494
|
+
* @param exec - the typed same-process call input. The registry assigns its
|
|
2495
|
+
* correlation token before policy begins.
|
|
2496
|
+
* @returns the materialized final result.
|
|
2497
|
+
*/
|
|
2498
|
+
async execute(exec) {
|
|
2499
|
+
return this.prepareExecution(exec, (prepared) => this.completeScheduledExecution(prepared));
|
|
2500
|
+
}
|
|
2501
|
+
async completeScheduledExecution(prepared) {
|
|
2502
|
+
switch (prepared.kind) {
|
|
2503
|
+
case "dispatch": {
|
|
2504
|
+
const dispatched = await this.dispatchScheduledExecution(prepared.exec);
|
|
2505
|
+
return dispatched.kind === "post-result" ? await this.finalizeScheduledExecution(prepared.exec, dispatched.result) : this.finishScheduledExecution(prepared.exec, dispatched.result);
|
|
2506
|
+
}
|
|
2507
|
+
case "post-result":
|
|
2508
|
+
return await this.finalizeScheduledExecution(prepared.exec, prepared.result);
|
|
2509
|
+
case "final-result":
|
|
2510
|
+
return this.finishScheduledExecution(prepared.exec, prepared.result);
|
|
2511
|
+
/* v8 ignore next -- closed-union exhaustiveness guard */
|
|
2512
|
+
default:
|
|
2513
|
+
return assertNever(prepared, "scheduled tool preparation");
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2516
|
+
createExecution(exec) {
|
|
2517
|
+
const deferredContexts = [];
|
|
2518
|
+
const token = createExecutionToken();
|
|
2519
|
+
const callId = exec.callId;
|
|
2520
|
+
const rootCallId = exec.rootCallId ?? callId;
|
|
2521
|
+
const name = exec.name;
|
|
2522
|
+
const agent = exec.agent;
|
|
2523
|
+
const parent = exec.parent;
|
|
2524
|
+
const signal = exec.signal;
|
|
2525
|
+
const visible = this.get(name, agent);
|
|
2526
|
+
const collapsed = visible !== void 0 && this.collapses(name, agent, parent !== void 0);
|
|
2527
|
+
const concludingExecutions = this.concludingExecutions;
|
|
2528
|
+
const base = {
|
|
2529
|
+
token,
|
|
2530
|
+
callId,
|
|
2531
|
+
rootCallId,
|
|
2532
|
+
name,
|
|
2533
|
+
signal,
|
|
2534
|
+
...agent !== void 0 ? { agent } : {},
|
|
2535
|
+
...parent !== void 0 ? { parent } : {},
|
|
2536
|
+
deferContext(context) {
|
|
2537
|
+
deferredContexts.push(context);
|
|
2538
|
+
},
|
|
2539
|
+
concludeTurn() {
|
|
2540
|
+
concludingExecutions.add(this);
|
|
2541
|
+
}
|
|
2542
|
+
};
|
|
2543
|
+
const capturedFinalizer = visible?.finalizeContent?.bind(visible);
|
|
2544
|
+
const finalizerFor = () => collapsed && !signal.aborted ? void 0 : capturedFinalizer;
|
|
2545
|
+
try {
|
|
2546
|
+
const detached = snapshotJsonValue(exec.arguments);
|
|
2547
|
+
if (detached === void 0) throw new TypeError("tool execution arguments must be losslessly JSON-serializable");
|
|
2548
|
+
const execution = {
|
|
2549
|
+
...base,
|
|
2550
|
+
arguments: deepFreeze(detached)
|
|
2551
|
+
};
|
|
2552
|
+
this.deferredContexts.set(execution, deferredContexts);
|
|
2553
|
+
this.contentFinalizers.set(execution, finalizerFor());
|
|
2554
|
+
this.cancellationStates.set(execution, {
|
|
2555
|
+
callerSignal: signal,
|
|
2556
|
+
bodyInvoked: false
|
|
2557
|
+
});
|
|
2558
|
+
if (collapsed) {
|
|
2559
|
+
if (signal.aborted) return {
|
|
2560
|
+
kind: "final-result",
|
|
2561
|
+
exec: execution,
|
|
2562
|
+
result: toolAbortedBeforeDispatchResult()
|
|
2563
|
+
};
|
|
2564
|
+
return {
|
|
2565
|
+
kind: "final-result",
|
|
2566
|
+
exec: execution,
|
|
2567
|
+
result: toolErrorResult(new ToolNotFoundError(name, `only \`${RUN_CODE_NAME}\` is callable directly \u2014 call \`${name}\` from inside a \`${RUN_CODE_NAME}\` program instead`))
|
|
2568
|
+
};
|
|
2569
|
+
}
|
|
2570
|
+
return {
|
|
2571
|
+
kind: "ready",
|
|
2572
|
+
exec: execution
|
|
2573
|
+
};
|
|
2574
|
+
} catch (error) {
|
|
2575
|
+
const execution = {
|
|
2576
|
+
...base,
|
|
2577
|
+
arguments: void 0
|
|
2578
|
+
};
|
|
2579
|
+
this.contentFinalizers.set(execution, finalizerFor());
|
|
2580
|
+
return {
|
|
2581
|
+
kind: "final-result",
|
|
2582
|
+
exec: execution,
|
|
2583
|
+
result: toolErrorResult(error)
|
|
2584
|
+
};
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
/**
|
|
2588
|
+
* Run the ordered pre-execute and monotonic guard stages for the scheduler.
|
|
2589
|
+
* @param input - the caller-supplied execution input.
|
|
2590
|
+
* @returns the prepared execution plus the next scheduler stage.
|
|
2591
|
+
* @internal
|
|
2592
|
+
*/
|
|
2593
|
+
async prepareScheduledExecution(input) {
|
|
2594
|
+
return this.prepareExecution(input, (prepared) => prepared);
|
|
2595
|
+
}
|
|
2596
|
+
async prepareExecution(input, next) {
|
|
2597
|
+
const created = this.createExecution(input);
|
|
2598
|
+
if (created.kind !== "ready") return next(created);
|
|
2599
|
+
const exec = created.exec;
|
|
2600
|
+
if (this.callerCancelled(exec)) return next({
|
|
2601
|
+
kind: "final-result",
|
|
2602
|
+
exec,
|
|
2603
|
+
result: toolAbortedBeforeDispatchResult()
|
|
2604
|
+
});
|
|
2605
|
+
try {
|
|
2606
|
+
const carrier = scopeTarget(this, exec.agent);
|
|
2607
|
+
const gate = await this.ctx.waterfall(carrier, "tools/pre-execute", exec, () => Promise.resolve({ kind: "allow" }));
|
|
2608
|
+
const askResolution = gate.kind === "ask" ? await this.serviceAsk(exec, gate) : {
|
|
2609
|
+
decision: gate,
|
|
2610
|
+
approvalCancelled: false
|
|
2611
|
+
};
|
|
2612
|
+
const { decision } = askResolution;
|
|
2613
|
+
if (this.callerCancelled(exec) && askResolution.approvalCancelled) return await next({
|
|
2614
|
+
kind: "post-result",
|
|
2615
|
+
exec,
|
|
2616
|
+
result: toolAbortedBeforeDispatchResult()
|
|
2617
|
+
});
|
|
2618
|
+
const denialReason = decision.kind === "allow" ? this.guardReason(exec) : decision.reason;
|
|
2619
|
+
if (denialReason !== void 0) return await next({
|
|
2620
|
+
kind: "post-result",
|
|
2621
|
+
exec,
|
|
2622
|
+
result: this.materializeFinalResult({
|
|
2623
|
+
content: [{
|
|
2624
|
+
type: "text",
|
|
2625
|
+
text: `Error: ${denialReason}`
|
|
2626
|
+
}],
|
|
2627
|
+
isError: true,
|
|
2628
|
+
error: { message: denialReason }
|
|
2629
|
+
})
|
|
2630
|
+
});
|
|
2631
|
+
if (this.callerCancelled(exec)) return await next({
|
|
2632
|
+
kind: "post-result",
|
|
2633
|
+
exec,
|
|
2634
|
+
result: toolAbortedBeforeDispatchResult()
|
|
2635
|
+
});
|
|
2636
|
+
return await next({
|
|
2637
|
+
kind: "dispatch",
|
|
2638
|
+
exec
|
|
2639
|
+
});
|
|
2640
|
+
} catch (error) {
|
|
2641
|
+
return next({
|
|
2642
|
+
kind: "final-result",
|
|
2643
|
+
exec,
|
|
2644
|
+
result: toolErrorResult(error)
|
|
2645
|
+
});
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2648
|
+
/** Whether the original caller signal is currently aborted. */
|
|
2649
|
+
callerCancelled(exec) {
|
|
2650
|
+
const state = this.cancellationStates.get(exec);
|
|
2651
|
+
if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
|
|
2652
|
+
return state.callerSignal.aborted;
|
|
2653
|
+
}
|
|
2654
|
+
/** Canonical cancellation outcome selected by whether the tool body started. */
|
|
2655
|
+
cancellationResult(exec, prior) {
|
|
2656
|
+
const state = this.cancellationStates.get(exec);
|
|
2657
|
+
if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
|
|
2658
|
+
return state.bodyInvoked ? toolAbortedResult(prior) : toolAbortedBeforeDispatchResult(prior);
|
|
2659
|
+
}
|
|
2660
|
+
/**
|
|
2661
|
+
* Dispatch the registered body with the original caller signal fused back
|
|
2662
|
+
* into any around-wrapper replacement. Cancellation never abandons the body:
|
|
2663
|
+
* a started promise reaches quiescence before its outcome becomes `ABORTED`.
|
|
2664
|
+
*/
|
|
2665
|
+
async dispatchToolBody(exec) {
|
|
2666
|
+
const state = this.cancellationStates.get(exec);
|
|
2667
|
+
if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
|
|
2668
|
+
const wrapperSignal = exec.signal;
|
|
2669
|
+
const fused = fuseToolSignals(state.callerSignal, wrapperSignal);
|
|
2670
|
+
const signal = fused.signal;
|
|
2671
|
+
if (isAborted(signal)) {
|
|
2672
|
+
fused.dispose();
|
|
2673
|
+
return toolAbortedBeforeDispatchResult();
|
|
2674
|
+
}
|
|
2675
|
+
exec.signal = signal;
|
|
2676
|
+
try {
|
|
2677
|
+
const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);
|
|
2678
|
+
if (!tool) throw new ToolNotFoundError(exec.name);
|
|
2679
|
+
state.bodyInvoked = true;
|
|
2680
|
+
const returned = await tool.execute(exec.arguments, exec);
|
|
2681
|
+
const result = this.createSuccessResult(exec, tool, returned);
|
|
2682
|
+
return isAborted(signal) ? toolAbortedResult(result) : result;
|
|
2683
|
+
} catch (error) {
|
|
2684
|
+
return toolErrorResult(error);
|
|
2685
|
+
} finally {
|
|
2686
|
+
fused.dispose();
|
|
2687
|
+
exec.signal = wrapperSignal;
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
/**
|
|
2691
|
+
* Run around-dispatch and the tool body. Tool and unknown-tool failures still
|
|
2692
|
+
* receive post-execute; pipeline failures are already final.
|
|
2693
|
+
* @param exec - the prepared execution.
|
|
2694
|
+
* @returns whether the result still needs post-execute.
|
|
2695
|
+
* @internal
|
|
2696
|
+
*/
|
|
2697
|
+
async dispatchScheduledExecution(exec) {
|
|
2698
|
+
try {
|
|
2699
|
+
const mutableExec = exec;
|
|
2700
|
+
const carrier = scopeTarget(this, exec.agent);
|
|
2701
|
+
const result = await this.ctx.waterfall(carrier, "tools/execute", mutableExec, () => this.dispatchToolBody(mutableExec));
|
|
2702
|
+
const normalized = this.normalizeDispatchResult(exec, result);
|
|
2703
|
+
const deferredContexts = this.deferredContexts.get(exec);
|
|
2704
|
+
if (deferredContexts === void 0) throw new Error("tool registry scheduler invariant violated: unprepared execution");
|
|
2705
|
+
const resultWithDeferredContexts = deferredContexts.length === 0 ? normalized : this.markCanonical(exec, {
|
|
2706
|
+
...normalized,
|
|
2707
|
+
additionalContexts: [...deferredContexts, ...normalized.additionalContexts ?? []]
|
|
2708
|
+
});
|
|
2709
|
+
return {
|
|
2710
|
+
kind: "post-result",
|
|
2711
|
+
result: this.callerCancelled(exec) && !resultWithDeferredContexts.isError ? this.cancellationResult(exec, resultWithDeferredContexts) : resultWithDeferredContexts
|
|
2712
|
+
};
|
|
2713
|
+
} catch (error) {
|
|
2714
|
+
return {
|
|
2715
|
+
kind: "final-result",
|
|
2716
|
+
result: toolErrorResult(error)
|
|
2717
|
+
};
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
/**
|
|
2721
|
+
* Run ordered post-execute, then apply definition-owned content finalization,
|
|
2722
|
+
* materialize, and notify the final outcome.
|
|
2723
|
+
* @param exec - the prepared execution.
|
|
2724
|
+
* @param result - dispatch/pre result that still needs post-execute.
|
|
2725
|
+
* @returns the materialized final result.
|
|
2726
|
+
* @internal
|
|
2727
|
+
*/
|
|
2728
|
+
async finalizeScheduledExecution(exec, result) {
|
|
2729
|
+
try {
|
|
2730
|
+
const postResult = await this.postExecute(exec, result);
|
|
2731
|
+
return this.finishScheduledExecution(exec, this.callerCancelled(exec) && !postResult.isError ? this.cancellationResult(exec, postResult) : postResult);
|
|
2732
|
+
} catch (error) {
|
|
2733
|
+
return this.finishScheduledExecution(exec, toolErrorResult(error));
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
/**
|
|
2737
|
+
* Materialize the candidate, apply definition-owned content finalization,
|
|
2738
|
+
* then materialize and notify the authoritative result.
|
|
2739
|
+
* @param exec - the prepared execution.
|
|
2740
|
+
* @param result - final result.
|
|
2741
|
+
* @returns the materialized final result.
|
|
2742
|
+
* @internal
|
|
2743
|
+
*/
|
|
2744
|
+
finishScheduledExecution(exec, result) {
|
|
2745
|
+
let materializedResult;
|
|
2746
|
+
try {
|
|
2747
|
+
materializedResult = this.materializeFinalResult(result);
|
|
2748
|
+
} catch (error) {
|
|
2749
|
+
materializedResult = this.materializeFinalResult(toolErrorResult(error));
|
|
2750
|
+
}
|
|
2751
|
+
let finalResult;
|
|
2752
|
+
try {
|
|
2753
|
+
finalResult = this.materializeFinalResult(this.applyFinalContent(exec, materializedResult));
|
|
2754
|
+
} catch (error) {
|
|
2755
|
+
finalResult = this.materializeFinalResult(toolErrorResult(error));
|
|
2756
|
+
}
|
|
2757
|
+
this.notifyResult(exec, finalResult);
|
|
2758
|
+
return finalResult;
|
|
2759
|
+
}
|
|
2760
|
+
/** Apply the snapshotted tool-owned content transform without exposing other result fields. */
|
|
2761
|
+
applyFinalContent(exec, result) {
|
|
2762
|
+
const finalizeContent = this.contentFinalizers.get(exec);
|
|
2763
|
+
if (finalizeContent === void 0) return result;
|
|
2764
|
+
const content = finalizeContent(exec, result);
|
|
2765
|
+
return content === void 0 ? result : {
|
|
2766
|
+
...result,
|
|
2767
|
+
content
|
|
2768
|
+
};
|
|
2769
|
+
}
|
|
2770
|
+
/** Notify observers without exposing a mutation or error channel into the outcome. */
|
|
2771
|
+
notifyResult(exec, result) {
|
|
2772
|
+
Object.freeze(exec);
|
|
2773
|
+
const { name: toolName, callId } = exec;
|
|
2774
|
+
const reportFailure = (error) => {
|
|
2775
|
+
this.ctx.logger.warn(`tool "${toolName}" (${callId}): tools/result observer failed: ${errorMessage(error)}`);
|
|
2776
|
+
};
|
|
2777
|
+
const callbacks = this.ctx.events.dispatch("emit", [
|
|
2778
|
+
scopeTarget(this, exec.agent),
|
|
2779
|
+
"tools/result",
|
|
2780
|
+
exec,
|
|
2781
|
+
result
|
|
2782
|
+
]);
|
|
2783
|
+
for (const callback of callbacks) try {
|
|
2784
|
+
const returned = callback(exec, result);
|
|
2785
|
+
Promise.resolve(returned).catch(reportFailure);
|
|
2786
|
+
} catch (error) {
|
|
2787
|
+
reportFailure(error);
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
/**
|
|
2791
|
+
* Resolve an `ask` decision to allow/deny through the approval seam. The
|
|
2792
|
+
* seam is consumed opportunistically with `ctx.get('approval')` — a
|
|
2793
|
+
* deployment that composes no ApprovalService keeps the historical degrade
|
|
2794
|
+
* to deny, and an unmount mid-session degrades the same way on the next ask.
|
|
2795
|
+
* An agent-less execution also degrades: without an agent there is no
|
|
2796
|
+
* session to audit to and no UI to route to. Otherwise the outcome maps
|
|
2797
|
+
* one-to-one — `allowed-once` proceeds; the three non-grants deny with
|
|
2798
|
+
* distinct reasons so the model can tell a human "no" from an absent
|
|
2799
|
+
* approval channel.
|
|
2800
|
+
*/
|
|
2801
|
+
async serviceAsk(exec, ask) {
|
|
2802
|
+
const approval = this.ctx.get("approval");
|
|
2803
|
+
if (approval === void 0) return {
|
|
2804
|
+
decision: {
|
|
2805
|
+
kind: "deny",
|
|
2806
|
+
reason: ask.reason ?? `tool "${exec.name}" requires approval (not yet supported)`
|
|
2807
|
+
},
|
|
2808
|
+
approvalCancelled: false
|
|
2809
|
+
};
|
|
2810
|
+
if (exec.agent === void 0) return {
|
|
2811
|
+
decision: {
|
|
2812
|
+
kind: "deny",
|
|
2813
|
+
reason: `tool "${exec.name}" requires approval, but the call has no agent to route it through`
|
|
2814
|
+
},
|
|
2815
|
+
approvalCancelled: false
|
|
2816
|
+
};
|
|
2817
|
+
const outcome = await approval.request({
|
|
2818
|
+
agent: exec.agent,
|
|
2819
|
+
toolName: exec.name,
|
|
2820
|
+
callId: exec.callId,
|
|
2821
|
+
...ask.reason !== void 0 ? { reason: ask.reason } : {},
|
|
2822
|
+
signal: exec.signal
|
|
2823
|
+
});
|
|
2824
|
+
switch (outcome) {
|
|
2825
|
+
case "allowed-once":
|
|
2826
|
+
return {
|
|
2827
|
+
decision: { kind: "allow" },
|
|
2828
|
+
approvalCancelled: false
|
|
2829
|
+
};
|
|
2830
|
+
case "rejected":
|
|
2831
|
+
return {
|
|
2832
|
+
decision: {
|
|
2833
|
+
kind: "deny",
|
|
2834
|
+
reason: `the user rejected tool "${exec.name}"`
|
|
2835
|
+
},
|
|
2836
|
+
approvalCancelled: false
|
|
2837
|
+
};
|
|
2838
|
+
case "cancelled":
|
|
2839
|
+
return {
|
|
2840
|
+
decision: {
|
|
2841
|
+
kind: "deny",
|
|
2842
|
+
reason: `approval for tool "${exec.name}" was cancelled`
|
|
2843
|
+
},
|
|
2844
|
+
approvalCancelled: true
|
|
2845
|
+
};
|
|
2846
|
+
case "unavailable":
|
|
2847
|
+
return {
|
|
2848
|
+
decision: {
|
|
2849
|
+
kind: "deny",
|
|
2850
|
+
reason: `tool "${exec.name}" requires approval, but no approval channel is available`
|
|
2851
|
+
},
|
|
2852
|
+
approvalCancelled: false
|
|
2853
|
+
};
|
|
2854
|
+
default:
|
|
2855
|
+
return assertNever(outcome, "ApprovalOutcome");
|
|
2856
|
+
}
|
|
2857
|
+
}
|
|
2858
|
+
/**
|
|
2859
|
+
* Run the `tools/post-execute` waterfall over a dispatched `result` and apply
|
|
2860
|
+
* its {@link PostToolDecision}: `accept` keeps the call successful (replacing
|
|
2861
|
+
* `content` when given), `block` turns it into an `isError` whose content is
|
|
2862
|
+
* the corrective `feedback`. Either decision may attach `additionalContexts`,
|
|
2863
|
+
* which are ferried on the returned result for the loop's active-batch FIFO.
|
|
2864
|
+
* Context deferred by the tool body survives an accepted result but is
|
|
2865
|
+
* discarded when the outer call is blocked; a block exposes only context the
|
|
2866
|
+
* blocking decision explicitly supplied.
|
|
2867
|
+
* Runs inside `execute`'s outer try/catch (a throwing listener → isError).
|
|
2868
|
+
*/
|
|
2869
|
+
async postExecute(exec, result) {
|
|
2870
|
+
const decision = await this.ctx.waterfall(scopeTarget(this, exec.agent), "tools/post-execute", exec, result, () => Promise.resolve({ kind: "accept" }));
|
|
2871
|
+
const decisionContexts = decision.additionalContexts ?? [];
|
|
2872
|
+
if (decision.kind === "block") {
|
|
2873
|
+
const message = failureMessageFromContent(decision.feedback);
|
|
2874
|
+
return this.markCanonical(exec, {
|
|
2875
|
+
content: decision.feedback,
|
|
2876
|
+
isError: true,
|
|
2877
|
+
error: { message },
|
|
2878
|
+
...decisionContexts.length > 0 ? { additionalContexts: decisionContexts } : {}
|
|
2879
|
+
});
|
|
2880
|
+
}
|
|
2881
|
+
if (Object.hasOwn(decision, "content") && Object.hasOwn(decision, "value")) throw new TypeError("tools/post-execute accept decision cannot replace both value and content");
|
|
2882
|
+
const additionalContexts = [...result.additionalContexts ?? [], ...decisionContexts];
|
|
2883
|
+
if (Object.hasOwn(decision, "value")) {
|
|
2884
|
+
if (result.isError) throw new TypeError("tools/post-execute cannot replace the value of a failed result");
|
|
2885
|
+
const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);
|
|
2886
|
+
if (tool === void 0) throw new ToolNotFoundError(exec.name);
|
|
2887
|
+
const replaced = this.createSuccessResult(exec, tool, decision.value);
|
|
2888
|
+
return this.markCanonical(exec, {
|
|
2889
|
+
...replaced,
|
|
2890
|
+
...additionalContexts.length > 0 ? { additionalContexts } : {}
|
|
2891
|
+
});
|
|
2892
|
+
}
|
|
2893
|
+
return this.markCanonical(exec, {
|
|
2894
|
+
...result,
|
|
2895
|
+
...decision.content !== void 0 ? { content: decision.content } : {},
|
|
2896
|
+
...additionalContexts.length > 0 ? { additionalContexts } : {}
|
|
2897
|
+
});
|
|
2898
|
+
}
|
|
2899
|
+
/** Registry-normalized results and the exact dispatch that validated each value. */
|
|
2900
|
+
canonicalResults = /* @__PURE__ */ new WeakMap();
|
|
2901
|
+
/** Mark one registry-normalized result as canonical only for its owning dispatch. */
|
|
2902
|
+
markCanonical(exec, result) {
|
|
2903
|
+
this.canonicalResults.set(result, exec.token);
|
|
2904
|
+
return result;
|
|
2905
|
+
}
|
|
2906
|
+
/** Snapshot, validate, render, and optionally project one successful body value. */
|
|
2907
|
+
createSuccessResult(exec, tool, candidate) {
|
|
2908
|
+
const detached = snapshotToolValue(tool.name, candidate);
|
|
2909
|
+
const violations = validateJsonSchemaValue(tool.output.schema, detached, "value");
|
|
2910
|
+
if (violations.length > 0) throw new ToolOutputError(tool.name, violations);
|
|
2911
|
+
const value = deepFreeze(detached);
|
|
2912
|
+
let rendered;
|
|
2913
|
+
try {
|
|
2914
|
+
rendered = tool.output.render(exec.arguments, value);
|
|
2915
|
+
} catch (error) {
|
|
2916
|
+
throw projectionError(tool.name, "render", error);
|
|
2917
|
+
}
|
|
2918
|
+
const content = snapshotProjection(tool.name, "render", rendered);
|
|
2919
|
+
let meta;
|
|
2920
|
+
if (exec.parent === void 0 && tool.output.presentationMeta !== void 0) {
|
|
2921
|
+
let projected;
|
|
2922
|
+
try {
|
|
2923
|
+
projected = tool.output.presentationMeta(exec.arguments, value);
|
|
2924
|
+
} catch (error) {
|
|
2925
|
+
throw projectionError(tool.name, "presentationMeta", error);
|
|
2926
|
+
}
|
|
2927
|
+
meta = snapshotProjection(tool.name, "presentationMeta", projected);
|
|
2928
|
+
}
|
|
2929
|
+
const concludesTurn = this.concludingExecutions.has(exec);
|
|
2930
|
+
return this.markCanonical(exec, this.materializeFinalResult({
|
|
2931
|
+
isError: false,
|
|
2932
|
+
value,
|
|
2933
|
+
content,
|
|
2934
|
+
...meta !== void 0 ? { meta } : {},
|
|
2935
|
+
...concludesTurn ? { concludesTurn: true } : {}
|
|
2936
|
+
}));
|
|
2937
|
+
}
|
|
2938
|
+
/** Normalize an around-dispatch wrapper's authored result through the owning output contract. */
|
|
2939
|
+
normalizeDispatchResult(exec, result) {
|
|
2940
|
+
if (this.canonicalResults.get(result) === exec.token) return result;
|
|
2941
|
+
if (result.isError) return this.markCanonical(exec, {
|
|
2942
|
+
isError: true,
|
|
2943
|
+
error: result.error,
|
|
2944
|
+
content: result.content,
|
|
2945
|
+
...result.meta !== void 0 ? { meta: result.meta } : {},
|
|
2946
|
+
...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
|
|
2947
|
+
});
|
|
2948
|
+
const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== void 0);
|
|
2949
|
+
if (tool === void 0) throw new ToolNotFoundError(exec.name);
|
|
2950
|
+
const normalized = this.createSuccessResult(exec, tool, result.value);
|
|
2951
|
+
return this.markCanonical(exec, {
|
|
2952
|
+
...normalized,
|
|
2953
|
+
...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
|
|
2954
|
+
});
|
|
2955
|
+
}
|
|
2956
|
+
/** Materialize the authoritative commit outcome once, immediately before `tools/result`. */
|
|
2957
|
+
materializeFinalResult(result) {
|
|
2958
|
+
const presentation = {
|
|
2959
|
+
content: result.content,
|
|
2960
|
+
...result.meta !== void 0 ? { meta: result.meta } : {},
|
|
2961
|
+
...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
|
|
2962
|
+
};
|
|
2963
|
+
if (result.isError) return materializePresentation({
|
|
2964
|
+
isError: true,
|
|
2965
|
+
error: result.error,
|
|
2966
|
+
...presentation
|
|
2967
|
+
});
|
|
2968
|
+
return deepFreeze({
|
|
2969
|
+
...materializePresentation({
|
|
2970
|
+
isError: false,
|
|
2971
|
+
...presentation,
|
|
2972
|
+
...result.concludesTurn === true ? { concludesTurn: true } : {}
|
|
2973
|
+
}),
|
|
2974
|
+
value: result.value
|
|
2975
|
+
});
|
|
2976
|
+
}
|
|
2977
|
+
};
|
|
2978
|
+
function createExecutionToken() {
|
|
2979
|
+
return Symbol("dsh.tool.execution");
|
|
2980
|
+
}
|
|
2981
|
+
function toolErrorResult(error) {
|
|
2982
|
+
const info = errorInfo(error);
|
|
2983
|
+
const message = errorMessage(error);
|
|
2984
|
+
return {
|
|
2985
|
+
content: [{
|
|
2986
|
+
type: "text",
|
|
2987
|
+
text: `Error: ${message}`
|
|
2988
|
+
}],
|
|
2989
|
+
isError: true,
|
|
2990
|
+
error: {
|
|
2991
|
+
message,
|
|
2992
|
+
...info ? { info } : {}
|
|
2993
|
+
}
|
|
2994
|
+
};
|
|
2995
|
+
}
|
|
2996
|
+
function isAborted(signal) {
|
|
2997
|
+
return signal.aborted;
|
|
2998
|
+
}
|
|
2999
|
+
function fuseToolSignals(caller, wrapper) {
|
|
3000
|
+
if (caller === wrapper) return {
|
|
3001
|
+
signal: caller,
|
|
3002
|
+
dispose() {
|
|
3003
|
+
}
|
|
3004
|
+
};
|
|
3005
|
+
const controller = new AbortController();
|
|
3006
|
+
let listening = false;
|
|
3007
|
+
const dispose = () => {
|
|
3008
|
+
if (!listening) return;
|
|
3009
|
+
listening = false;
|
|
3010
|
+
caller.removeEventListener("abort", abortFromCaller);
|
|
3011
|
+
wrapper.removeEventListener("abort", abortFromWrapper);
|
|
3012
|
+
};
|
|
3013
|
+
const abortFrom = (source) => {
|
|
3014
|
+
const reason = source.reason;
|
|
3015
|
+
controller.abort(reason);
|
|
3016
|
+
dispose();
|
|
3017
|
+
};
|
|
3018
|
+
const abortFromCaller = () => {
|
|
3019
|
+
abortFrom(caller);
|
|
3020
|
+
};
|
|
3021
|
+
const abortFromWrapper = () => {
|
|
3022
|
+
abortFrom(wrapper);
|
|
3023
|
+
};
|
|
3024
|
+
if (wrapper.aborted) abortFromWrapper();
|
|
3025
|
+
else if (caller.aborted) abortFromCaller();
|
|
3026
|
+
else {
|
|
3027
|
+
listening = true;
|
|
3028
|
+
caller.addEventListener("abort", abortFromCaller, { once: true });
|
|
3029
|
+
wrapper.addEventListener("abort", abortFromWrapper, { once: true });
|
|
3030
|
+
}
|
|
3031
|
+
return {
|
|
3032
|
+
signal: controller.signal,
|
|
3033
|
+
dispose
|
|
3034
|
+
};
|
|
3035
|
+
}
|
|
3036
|
+
function toolAbortedResult(prior) {
|
|
3037
|
+
const additionalContexts = prior?.additionalContexts ?? [];
|
|
3038
|
+
return {
|
|
3039
|
+
content: [{
|
|
3040
|
+
type: "text",
|
|
3041
|
+
text: "Error: tool call aborted"
|
|
3042
|
+
}],
|
|
3043
|
+
isError: true,
|
|
3044
|
+
error: {
|
|
3045
|
+
message: "tool call aborted",
|
|
3046
|
+
info: {
|
|
3047
|
+
name: "AbortError",
|
|
3048
|
+
code: TOOL_ABORTED
|
|
3049
|
+
}
|
|
3050
|
+
},
|
|
3051
|
+
...additionalContexts.length > 0 ? { additionalContexts } : {}
|
|
3052
|
+
};
|
|
3053
|
+
}
|
|
3054
|
+
function toolAbortedBeforeDispatchResult(prior) {
|
|
3055
|
+
const additionalContexts = prior?.additionalContexts ?? [];
|
|
3056
|
+
return {
|
|
3057
|
+
content: [{
|
|
3058
|
+
type: "text",
|
|
3059
|
+
text: "Error: tool call aborted before dispatch"
|
|
3060
|
+
}],
|
|
3061
|
+
isError: true,
|
|
3062
|
+
error: {
|
|
3063
|
+
message: "tool call aborted before dispatch",
|
|
3064
|
+
info: {
|
|
3065
|
+
name: "AbortError",
|
|
3066
|
+
code: TOOL_ABORTED_BEFORE_DISPATCH
|
|
3067
|
+
}
|
|
3068
|
+
},
|
|
3069
|
+
...additionalContexts.length > 0 ? { additionalContexts } : {}
|
|
3070
|
+
};
|
|
3071
|
+
}
|
|
3072
|
+
|
|
1
3073
|
// src/host/bridge-manager.ts
|
|
2
3074
|
import { installModelSelection } from "@deepseek-ai/dsh-agent";
|
|
3
3075
|
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
@@ -2450,11 +5522,11 @@ function xmlEncrypt(xml) {
|
|
|
2450
5522
|
return xmlField(xml, "Encrypt");
|
|
2451
5523
|
}
|
|
2452
5524
|
function unpad(data) {
|
|
2453
|
-
const
|
|
2454
|
-
if (
|
|
2455
|
-
return data.subarray(0, data.length -
|
|
5525
|
+
const pad3 = data[data.length - 1];
|
|
5526
|
+
if (pad3 < 1 || pad3 > 32) return data;
|
|
5527
|
+
return data.subarray(0, data.length - pad3);
|
|
2456
5528
|
}
|
|
2457
|
-
function
|
|
5529
|
+
function pad2(data, blockSize = 32) {
|
|
2458
5530
|
const len = blockSize - data.length % blockSize;
|
|
2459
5531
|
return Buffer.concat([data, Buffer.alloc(len, len)]);
|
|
2460
5532
|
}
|
|
@@ -2500,7 +5572,7 @@ var WecomAppBridge = class {
|
|
|
2500
5572
|
Buffer.from(this.corpId, "utf8")
|
|
2501
5573
|
]);
|
|
2502
5574
|
const cipher = createCipheriv("aes-256-cbc", key, key.subarray(0, 16));
|
|
2503
|
-
return Buffer.concat([cipher.update(
|
|
5575
|
+
return Buffer.concat([cipher.update(pad2(payload)), cipher.final()]).toString("base64");
|
|
2504
5576
|
}
|
|
2505
5577
|
/** 解析解密后的消息 XML → { from, text }。 */
|
|
2506
5578
|
parseMessage(xml) {
|
|
@@ -3164,7 +6236,7 @@ var Config = Schema.object({
|
|
|
3164
6236
|
});
|
|
3165
6237
|
|
|
3166
6238
|
// src/index.ts
|
|
3167
|
-
var inject = ["webServer", "sessions", "agents", "agentDefaultModel"];
|
|
6239
|
+
var inject = ["webServer", "sessions", "agents", "agentDefaultModel", "tools"];
|
|
3168
6240
|
function apply(ctx, config = Config({})) {
|
|
3169
6241
|
const manager = new BridgeManager(ctx, config);
|
|
3170
6242
|
ctx.effect(() => {
|
|
@@ -3196,7 +6268,54 @@ function apply(ctx, config = Config({})) {
|
|
|
3196
6268
|
}
|
|
3197
6269
|
});
|
|
3198
6270
|
const disposeRoutes = registerGatewayRoutes(ctx, manager);
|
|
6271
|
+
let disposeTool;
|
|
6272
|
+
if (ctx.tools) {
|
|
6273
|
+
disposeTool = ctx.tools.register(defineTool({
|
|
6274
|
+
name: "send_chat_message",
|
|
6275
|
+
description: "\u5411\u5DF2\u8FDE\u63A5\u7684\u6D88\u606F\u5E73\u53F0\uFF08Telegram / Discord / \u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA / Email \u7B49\uFF09\u4E3B\u52A8\u63A8\u9001\u6587\u672C\u6D88\u606F\u3002\u4F8B\u5982\u628A\u4EE3\u7801\u603B\u7ED3\u3001\u4EFB\u52A1\u7ED3\u679C\u63A8\u9001\u81F3\u6307\u5B9A\u7684\u7FA4\u804A\u6216\u79C1\u4FE1\u9891\u9053\u3002",
|
|
6276
|
+
parameters: {
|
|
6277
|
+
platform: {
|
|
6278
|
+
type: "string",
|
|
6279
|
+
required: true,
|
|
6280
|
+
description: "\u76EE\u6807\u5E73\u53F0 id\uFF1Atelegram / discord / wecom-aibot / email"
|
|
6281
|
+
},
|
|
6282
|
+
target: {
|
|
6283
|
+
type: "string",
|
|
6284
|
+
required: true,
|
|
6285
|
+
description: "\u63A8\u9001\u76EE\u6807\uFF08telegram=chatId \u6570\u5B57\uFF1Bdiscord=channelId\uFF1Bwecom-aibot=userid/\u7FA4ID\uFF1Bemail=\u6536\u4EF6\u4EBA\u5730\u5740\uFF09"
|
|
6286
|
+
},
|
|
6287
|
+
message: {
|
|
6288
|
+
type: "string",
|
|
6289
|
+
required: true,
|
|
6290
|
+
description: "\u8981\u63A8\u9001\u7684\u6587\u672C\u6B63\u6587\u5185\u5BB9\uFF08\u652F\u6301 Markdown\uFF09"
|
|
6291
|
+
},
|
|
6292
|
+
title: {
|
|
6293
|
+
type: "string",
|
|
6294
|
+
description: "\u53EF\u9009\u6807\u9898\uFF08email \u4F5C\u4E3A\u4E3B\u9898\uFF0C\u5176\u4ED6\u5E73\u53F0\u4F5C\u4E3A\u9996\u884C\u52A0\u7C97\u524D\u7F00\uFF09"
|
|
6295
|
+
}
|
|
6296
|
+
},
|
|
6297
|
+
output: {
|
|
6298
|
+
schema: { type: "string" },
|
|
6299
|
+
render: (_args, value) => [{ type: "text", text: String(value) }]
|
|
6300
|
+
},
|
|
6301
|
+
async execute(args) {
|
|
6302
|
+
const platform = String(args.platform ?? "").trim();
|
|
6303
|
+
const target = String(args.target ?? "").trim();
|
|
6304
|
+
const message = String(args.message ?? "").trim();
|
|
6305
|
+
const title = args.title !== void 0 ? String(args.title).trim() : void 0;
|
|
6306
|
+
if (!platform || !target || !message) {
|
|
6307
|
+
return "\u9519\u8BEF\uFF1Aplatform, target \u4E0E message \u5747\u4E3A\u5FC5\u586B\u53C2\u6570";
|
|
6308
|
+
}
|
|
6309
|
+
const res = await manager.pushMessage(platform, target, message, { title });
|
|
6310
|
+
if (res.ok) {
|
|
6311
|
+
return `\u6D88\u606F\u5DF2\u6210\u529F\u63A8\u9001\u81F3 [${platform}] \u76EE\u6807 ${target}`;
|
|
6312
|
+
}
|
|
6313
|
+
return `\u63A8\u9001\u5931\u8D25\uFF1A${res.detail}`;
|
|
6314
|
+
}
|
|
6315
|
+
}));
|
|
6316
|
+
}
|
|
3199
6317
|
return () => {
|
|
6318
|
+
disposeTool?.();
|
|
3200
6319
|
disposeRoutes();
|
|
3201
6320
|
void manager.dispose();
|
|
3202
6321
|
};
|