返回 CodeWhale
dsh-tools-compat.js
根目录 / crates / engine / extension-host / src / dsh / dsh-tools-compat.js
1 // @ts-nocheck
2 /**
3 * `@deepseek-ai/dsh-tools` compatibility module for the Codewhale extension host.
4 *
5 * DSH plugins import `defineTool` and its error types from
6 * `@deepseek-ai/dsh-tools` as a peer. The real package also ships the DSH
7 * ToolRuntime service, which would be a second tool authority; Codewhale's
8 * Rust core is the only one. So the host resolves that specifier here, to the
9 * *definition-side* subset only.
10 *
11 * Lines between the VERBATIM markers are copied unchanged from
12 * `@deepseek-ai/dsh-tools@0.2.2-rc.1` `lib/shared-DTdn5dXO.js` (lines 22-548 and
13 * 566-596) and `lib/index.js` (lines 7-377), MIT License, Copyright (c) 2026 DeepSeek. See
14 * ../../LICENSES.txt. Everything outside the markers is Codewhale's.
15 *
16 * `ToolRuntime` is deliberately NOT exported: a plugin that tries to provide
17 * or construct the DSH tool runtime fails to link, loudly.
18 */
19 import { assertNever, isJsonValue, snapshotJsonValue } from '@deepseek-ai/dsh-util-values'
20 import { HarnessError } from './dsh-message-compat.js'
21
22 export { HarnessError }
23
24 // ---- VERBATIM @deepseek-ai/dsh-tools@0.2.2-rc.1 lib/shared-DTdn5dXO.js:22-548 ----
25 //#region lib/types/json-schema.js
26 /**
27 * Enforced JSON Schema subset shared by tool outputs, generated PTC mode
28 * types, subagents, and workflows. The subset accepts any JSON root, an
29 * annotation-only schema for unconstrained JSON, one scalar `type`, object
30 * `properties`/`required`/boolean `additionalProperties`, array `items`,
31 * type-correct scalar `enum`/`const`, and exact-one `oneOf`.
32 *
33 * Unsupported or misplaced keywords reject rather than being accepted without
34 * enforcement. Consumers that require an object root apply
35 * {@link assertObjectJsonSchema} before accepting input.
36 * @module dsh-tools/json-schema
37 */
38 /**
39 * Thrown when a raw schema falls outside the enforced subset. `violations`
40 * lists every offending path instead of stopping at the first author error.
41 */
42 var JsonSchemaError = class extends HarnessError {
43 /** Individual schema violations in walk order. */
44 violations;
45 constructor(violations) {
46 super(`unsupported JSON schema: ${violations.join("; ")}`, "UNSUPPORTED_SCHEMA");
47 this.name = "JsonSchemaError";
48 this.violations = violations;
49 }
50 };
51 const CONSTRAINT_KEYWORDS = new Set([
52 "type",
53 "oneOf",
54 "properties",
55 "required",
56 "additionalProperties",
57 "items",
58 "enum",
59 "const"
60 ]);
61 const ANNOTATION_KEYWORDS = new Set([
62 "description",
63 "title",
64 "default",
65 "examples"
66 ]);
67 const SCHEMA_TYPES = [
68 "object",
69 "array",
70 "string",
71 "number",
72 "integer",
73 "boolean",
74 "null"
75 ];
76 /** Whether a realm-owned intrinsic prototype is backed by its native constructor. */
77 function hasIntrinsicConstructor(prototype, name) {
78 const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
79 if (typeof constructor !== "function") return false;
80 try {
81 return constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;
82 } catch {
83 return false;
84 }
85 }
86 /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
87 function isIntrinsicObjectPrototype(value) {
88 return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, "Object");
89 }
90 /**
91 * Test for a realm-agnostic plain JSON record without accepting arrays or
92 * exotic objects.
93 * @param value - candidate record from any JavaScript realm.
94 * @returns Whether the value has a plain-object prototype chain.
95 */
96 function isPlainJsonRecord(value) {
97 if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
98 try {
99 const prototype = Object.getPrototypeOf(value);
100 return prototype === null || typeof prototype === "object" && isIntrinsicObjectPrototype(prototype);
101 } catch {
102 return false;
103 }
104 }
105 /** Whether an array uses one realm's intrinsic `Array.prototype`. */
106 function hasPlainArrayPrototype(value) {
107 const prototype = Object.getPrototypeOf(value);
108 if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, "Array")) return false;
109 const objectPrototype = Object.getPrototypeOf(prototype);
110 return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);
111 }
112 /** Return whether a record contains only own enumerable string keys. */
113 function hasOnlyEnumerableStringKeys(value) {
114 try {
115 return Reflect.ownKeys(value).every((key) => typeof key === "string" && Object.prototype.propertyIsEnumerable.call(value, key));
116 } catch {
117 return false;
118 }
119 }
120 /**
121 * Test for an ordinary schema record whose keys survive JSON projection.
122 * @param value - candidate record from any JavaScript realm.
123 * @returns Whether the record has an intrinsic prototype and only own enumerable string keys.
124 */
125 function isJsonSchemaRecord(value) {
126 return isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);
127 }
128 /**
129 * Test for a dense ordinary array with no JSON-invisible decorations.
130 * @param value - candidate array from any JavaScript realm.
131 * @returns Whether the array is intrinsic, dense, and undecorated.
132 */
133 function isPlainJsonArray(value) {
134 if (!Array.isArray(value)) return false;
135 try {
136 if (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;
137 for (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;
138 return true;
139 } catch {
140 return false;
141 }
142 }
143 /** Lossless finite JSON number, excluding negative zero. */
144 function isJsonNumber(value) {
145 return typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0);
146 }
147 /** Whether a scalar is valid for one declared schema type. */
148 function scalarMatches(type, value) {
149 switch (type) {
150 case "string": return typeof value === "string";
151 case "number": return isJsonNumber(value);
152 case "integer": return isJsonNumber(value) && Number.isInteger(value);
153 case "boolean": return typeof value === "boolean";
154 case "null": return value === null;
155 /* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */
156 default: return assertNever(type, "JsonSchemaType");
157 }
158 }
159 /** Keywords that are invalid beside `oneOf`. */
160 const ONE_OF_SIBLING_KEYWORDS = [
161 "properties",
162 "required",
163 "additionalProperties",
164 "items",
165 "enum",
166 "const"
167 ];
168 /** Validate object-only fields after its property schemas have been visited. */
169 function checkObjectSchemaTail(node, path, properties, violations) {
170 const hasRequired = Object.hasOwn(node, "required");
171 const required = hasRequired ? node.required : void 0;
172 if (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== "string")) violations.push(`${path}.required must be an array of strings`);
173 else {
174 const declared = isJsonSchemaRecord(properties) ? properties : {};
175 for (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names "${key}" which is not in properties`);
176 }
177 if (Object.hasOwn(node, "additionalProperties") && typeof node.additionalProperties !== "boolean") violations.push(`${path}.additionalProperties must be a boolean`);
178 }
179 /** Collect every violation for one raw schema tree without using the JavaScript call stack. */
180 function checkSchemaNode(root, rootPath, violations, seen) {
181 const tasks = [{
182 kind: "enter",
183 node: root,
184 path: rootPath
185 }];
186 for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
187 if (task.kind === "leave") {
188 seen.delete(task.node);
189 continue;
190 }
191 if (task.kind === "one-of-tail") {
192 for (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);
193 continue;
194 }
195 if (task.kind === "object-tail") {
196 checkObjectSchemaTail(task.node, task.path, task.properties, violations);
197 continue;
198 }
199 const { node, path } = task;
200 if (!isJsonSchemaRecord(node)) {
201 violations.push(`${path} must be a schema object`);
202 continue;
203 }
204 if (seen.has(node)) {
205 violations.push(`${path} is circular`);
206 continue;
207 }
208 seen.add(node);
209 tasks.push({
210 kind: "leave",
211 node
212 });
213 for (const key of Object.keys(node)) {
214 if (CONSTRAINT_KEYWORDS.has(key)) continue;
215 if (ANNOTATION_KEYWORDS.has(key)) {
216 try {
217 if (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);
218 } catch {
219 violations.push(`${path}.${key} annotation must be lossless JSON data`);
220 }
221 continue;
222 }
223 violations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);
224 }
225 if (Object.hasOwn(node, "description") && typeof node.description !== "string") violations.push(`${path}.description must be a string`);
226 if (Object.hasOwn(node, "title") && typeof node.title !== "string") violations.push(`${path}.title must be a string`);
227 const hasType = Object.hasOwn(node, "type");
228 const hasOneOf = Object.hasOwn(node, "oneOf");
229 if (hasType && hasOneOf) {
230 violations.push(`${path} cannot declare both type and oneOf`);
231 continue;
232 }
233 if (!hasType && !hasOneOf) {
234 for (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);
235 continue;
236 }
237 if (hasOneOf) {
238 const oneOf = node.oneOf;
239 tasks.push({
240 kind: "one-of-tail",
241 node,
242 path
243 });
244 if (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);
245 else for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({
246 kind: "enter",
247 node: oneOf[index],
248 path: `${path}.oneOf[${index}]`
249 });
250 continue;
251 }
252 const type = node.type;
253 if (typeof type !== "string" || !SCHEMA_TYPES.includes(type)) {
254 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("/")}`);
255 continue;
256 }
257 const schemaType = type;
258 for (const [key, types] of Object.entries({
259 properties: ["object"],
260 required: ["object"],
261 additionalProperties: ["object"],
262 items: ["array"],
263 enum: [
264 "string",
265 "number",
266 "integer",
267 "boolean",
268 "null"
269 ],
270 const: [
271 "string",
272 "number",
273 "integer",
274 "boolean",
275 "null"
276 ]
277 })) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type "${schemaType}"`);
278 switch (schemaType) {
279 case "object": {
280 const properties = Object.hasOwn(node, "properties") ? node.properties : void 0;
281 tasks.push({
282 kind: "object-tail",
283 node,
284 path,
285 properties
286 });
287 if (Object.hasOwn(node, "properties")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);
288 else {
289 const entries = Object.entries(properties);
290 for (let index = entries.length - 1; index >= 0; index--) {
291 const entry = entries[index];
292 /* v8 ignore next -- the loop is bounded by the captured entry count. */
293 if (entry === void 0) continue;
294 tasks.push({
295 kind: "enter",
296 node: entry[1],
297 path: `${path}.properties.${entry[0]}`
298 });
299 }
300 }
301 break;
302 }
303 case "array":
304 if (Object.hasOwn(node, "items")) tasks.push({
305 kind: "enter",
306 node: node.items,
307 path: `${path}.items`
308 });
309 break;
310 case "string":
311 case "number":
312 case "integer":
313 case "boolean":
314 case "null": {
315 const hasEnum = Object.hasOwn(node, "enum");
316 const allowed = hasEnum ? node.enum : void 0;
317 const enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));
318 if (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);
319 const hasConst = Object.hasOwn(node, "const");
320 const declaredConst = hasConst ? node.const : void 0;
321 const constValid = scalarMatches(schemaType, declaredConst);
322 if (hasConst) {
323 if (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);
324 else if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);
325 }
326 break;
327 }
328 /* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */
329 default: assertNever(schemaType, "JsonSchemaType");
330 }
331 }
332 }
333 /**
334 * Assert that an arbitrary raw schema uses only the enforced subset.
335 * Annotation-only schemas are accepted as the standard unconstrained-JSON
336 * form; callers that require an object root use {@link assertObjectJsonSchema}.
337 * @param schema - untrusted raw JSON Schema.
338 * @returns Assertion that the schema belongs to the supported subset.
339 */
340 function assertSupportedJsonSchema(schema) {
341 const violations = [];
342 checkSchemaNode(schema, "schema", violations, /* @__PURE__ */ new Set());
343 if (violations.length > 0) throw new JsonSchemaError(violations);
344 }
345 /**
346 * Assert the enforced subset plus the object-root constraint retained by
347 * subagent and workflow structured outputs.
348 * @param schema - untrusted caller-supplied schema.
349 * @returns Assertion that the schema belongs to the supported subset and has an object root.
350 */
351 function assertObjectJsonSchema(schema) {
352 const violations = [];
353 checkSchemaNode(schema, "schema", violations, /* @__PURE__ */ new Set());
354 if (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, "type") || schema.type !== "object")) violations.push("schema.type must be \"object\" (structured output is object-rooted)");
355 if (violations.length > 0) throw new JsonSchemaError(violations);
356 }
357 /** Safely test the lossless JSON boundary when a getter may throw. */
358 function safelyIsJsonValue(value) {
359 try {
360 return isJsonValue(value);
361 } catch {
362 return false;
363 }
364 }
365 /** Root-aware diagnostic path for the parameter validator's empty sentinel. */
366 function diagnosticPath(path) {
367 return path === "" ? "arguments" : path;
368 }
369 /** Append one object property without a leading dot at an implicit root. */
370 function propertyPath(path, key) {
371 return path === "" ? key : `${path}.${key}`;
372 }
373 /** The generic exception-containment diagnostic owned by one valid schema node. */
374 function losslessValueViolation(path) {
375 return [`"${diagnosticPath(path)}" must be a lossless JSON value`];
376 }
377 /** Append diagnostics without spreading a potentially wide child result as call arguments. */
378 function appendViolations(target, source) {
379 for (const violation of source) target.push(violation);
380 }
381 /** Initialize one validation frame with empty aggregation state. */
382 function valueFrame(node, value, path) {
383 return {
384 node,
385 value,
386 path,
387 catches: false,
388 phase: "start",
389 children: [],
390 childIndex: 0,
391 violations: [],
392 tailViolations: [],
393 matches: 0
394 };
395 }
396 /** Validate one scalar node after its primitive type check. */
397 function checkScalarValue(node, value, path) {
398 const allowed = Object.hasOwn(node, "enum") ? node.enum : void 0;
399 if (allowed !== void 0 && !allowed.includes(value)) return [`"${diagnosticPath(path)}" must be one of ${JSON.stringify(allowed)}`];
400 if (Object.hasOwn(node, "const") && value !== node.const) return [`"${diagnosticPath(path)}" must be ${JSON.stringify(node.const)}`];
401 return [];
402 }
403 /** Validate one trusted schema/value pair with explicit frames rather than recursive calls. */
404 function checkValue(schema, value, path) {
405 const frames = [valueFrame(schema, value, path)];
406 let rootResult;
407 const receive = (result) => {
408 const parent = frames.at(-1);
409 if (parent === void 0) {
410 rootResult = result;
411 return;
412 }
413 if (parent.kind === "oneOf") {
414 if (result.length === 0) parent.matches++;
415 } else appendViolations(parent.violations, result);
416 };
417 const finish = (result) => {
418 frames.pop();
419 receive(result);
420 };
421 while (frames.length > 0) {
422 const frame = frames.at(-1);
423 /* v8 ignore next -- the loop condition guarantees a current frame. */
424 if (frame === void 0) break;
425 try {
426 if (frame.phase === "children") {
427 if (frame.childIndex < frame.children.length) {
428 const child = frame.children[frame.childIndex];
429 /* v8 ignore next -- childIndex is bounded by children.length. */
430 if (child === void 0) throw new Error("missing schema-value child frame");
431 frame.childIndex++;
432 frames.push(valueFrame(child.node, child.value, child.path));
433 continue;
434 }
435 if (frame.kind === "oneOf") {
436 finish(frame.matches === 1 ? [] : [`"${diagnosticPath(frame.path)}" must match exactly one oneOf branch (matched ${frame.matches})`]);
437 continue;
438 }
439 appendViolations(frame.violations, frame.tailViolations);
440 if (frame.violations.length > 0) finish(frame.violations);
441 else if (frame.kind === "object") finish(safelyIsJsonValue(frame.value) ? [] : [`"${diagnosticPath(frame.path)}" must be a lossless JSON object`]);
442 else finish(safelyIsJsonValue(frame.value) ? [] : [`"${diagnosticPath(frame.path)}" must be a dense lossless JSON array`]);
443 continue;
444 }
445 const nodeType = Object.hasOwn(frame.node, "type") ? frame.node.type : void 0;
446 frame.catches = !(nodeType !== void 0 && !SCHEMA_TYPES.includes(nodeType));
447 const oneOf = Object.hasOwn(frame.node, "oneOf") ? frame.node.oneOf : void 0;
448 if (oneOf !== void 0) {
449 frame.kind = "oneOf";
450 frame.children = Array.from(oneOf, (branch) => ({
451 node: branch,
452 value: frame.value,
453 path: frame.path
454 }));
455 frame.childIndex = 0;
456 frame.matches = 0;
457 frame.phase = "children";
458 continue;
459 }
460 if (nodeType === void 0) {
461 finish(safelyIsJsonValue(frame.value) ? [] : losslessValueViolation(frame.path));
462 continue;
463 }
464 switch (nodeType) {
465 case "object": {
466 if (!isPlainJsonRecord(frame.value)) {
467 finish([`"${diagnosticPath(frame.path)}" must be an object`]);
468 break;
469 }
470 const properties = Object.hasOwn(frame.node, "properties") ? frame.node.properties ?? {} : {};
471 const violations = [];
472 const required = Object.hasOwn(frame.node, "required") ? frame.node.required ?? [] : [];
473 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)}"`);
474 const children = [];
475 for (const [key, child] of Object.entries(properties)) {
476 if (!Object.hasOwn(frame.value, key) || frame.value[key] === void 0) continue;
477 children.push({
478 node: child,
479 value: frame.value[key],
480 path: propertyPath(frame.path, key)
481 });
482 }
483 const tailViolations = [];
484 if (Object.hasOwn(frame.node, "additionalProperties") && frame.node.additionalProperties === false) {
485 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)`);
486 }
487 frame.kind = "object";
488 frame.children = children;
489 frame.childIndex = 0;
490 frame.violations = violations;
491 frame.tailViolations = tailViolations;
492 frame.phase = "children";
493 break;
494 }
495 case "array": {
496 if (!Array.isArray(frame.value)) {
497 finish([`"${diagnosticPath(frame.path)}" must be an array`]);
498 break;
499 }
500 const items = Object.hasOwn(frame.node, "items") ? frame.node.items : void 0;
501 const children = items === void 0 ? [] : frame.value.flatMap((entry, index) => [{
502 node: items,
503 value: entry,
504 path: `${frame.path}[${index}]`
505 }]);
506 frame.kind = "array";
507 frame.children = children;
508 frame.childIndex = 0;
509 frame.violations = [];
510 frame.phase = "children";
511 break;
512 }
513 case "string":
514 finish(typeof frame.value === "string" ? checkScalarValue(frame.node, frame.value, frame.path) : [`"${diagnosticPath(frame.path)}" must be a string`]);
515 break;
516 case "number":
517 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));
518 break;
519 case "integer":
520 finish(!isJsonNumber(frame.value) || !Number.isInteger(frame.value) ? [`"${diagnosticPath(frame.path)}" must be an integer`] : checkScalarValue(frame.node, frame.value, frame.path));
521 break;
522 case "boolean":
523 finish(typeof frame.value === "boolean" ? checkScalarValue(frame.node, frame.value, frame.path) : [`"${diagnosticPath(frame.path)}" must be a boolean`]);
524 break;
525 case "null":
526 finish(frame.value === null ? checkScalarValue(frame.node, frame.value, frame.path) : [`"${diagnosticPath(frame.path)}" must be null`]);
527 break;
528 default: finish(assertNever(nodeType, "JsonSchemaType"));
529 }
530 } catch (error) {
531 let failed = frames.pop();
532 while (failed !== void 0 && !failed.catches) failed = frames.pop();
533 if (failed === void 0) throw error;
534 receive(losslessValueViolation(failed.path));
535 }
536 }
537 /* v8 ignore next -- every root frame finishes or throws. */
538 return rootResult ?? losslessValueViolation(path);
539 }
540 /**
541 * Validate a candidate value against an asserted raw schema. The function is
542 * total for arbitrary values and returns path-qualified violations.
543 * @param schema - a schema accepted by {@link assertSupportedJsonSchema}.
544 * @param value - the candidate JSON value.
545 * @param path - root label used in diagnostics.
546 * @returns All violations in walk order; empty means valid.
547 */
548 function validateJsonSchemaValue(schema, value, path = "value") {
549 return checkValue(schema, value, path);
550 }
551 //#endregion
552 // ---- END VERBATIM ----
553
554 // ---- VERBATIM @deepseek-ai/dsh-tools@0.2.2-rc.1 lib/index.js:7-377 ----
555 //#region lib/types/schema.js
556 /** Unified JSON-value schema DSL, inference, compilation, and tool definition helpers. @module dsh-tools/schema */
557 const ANNOTATION_KEYS = [
558 "description",
559 "title",
560 "default",
561 "examples"
562 ];
563 /** Throw one author-schema violation through the shared schema error type. */
564 function authorError(message) {
565 throw new JsonSchemaError([message]);
566 }
567 /** Copy own annotation fields for validation by the raw-schema boundary. */
568 function copyAnnotations(source, target) {
569 if (Object.hasOwn(source, "description")) target.description = source.description;
570 if (Object.hasOwn(source, "title")) target.title = source.title;
571 if (Object.hasOwn(source, "default")) target.default = source.default;
572 if (Object.hasOwn(source, "examples")) target.examples = source.examples;
573 }
574 /** Reject author-only keys outside one node's declared vocabulary. */
575 function assertAuthorKeys(source, path, allowed) {
576 for (const key of Object.keys(source)) if (!allowed.includes(key)) authorError(`${path}.${key} is not supported by the value schema DSL`);
577 }
578 /** Install a compiled node without giving `__proto__` assignment semantics. */
579 function assignCompiledNode(destination, node) {
580 switch (destination.kind) {
581 case "root":
582 destination.holder.value = node;
583 break;
584 case "property":
585 Object.defineProperty(destination.target, destination.key, {
586 value: node,
587 enumerable: true,
588 configurable: true,
589 writable: true
590 });
591 break;
592 case "item":
593 destination.target.items = node;
594 break;
595 case "one-of":
596 destination.target[destination.index] = node;
597 break;
598 }
599 }
600 /** Install a compiled property map at its root or containing object node. */
601 function assignCompiledPropertyMap(destination, compiled) {
602 if (destination.kind === "root") destination.holder.value = compiled;
603 else destination.target.properties = compiled.properties;
604 }
605 /** Execute an author-schema compilation task graph without recursive descent. */
606 function runSchemaCompiler(initial) {
607 const seen = /* @__PURE__ */ new Set();
608 const tasks = [initial];
609 for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
610 if (task.kind === "leave") {
611 seen.delete(task.input);
612 continue;
613 }
614 if (task.kind === "property-map-tail") {
615 if (task.required.length > 0) {
616 task.compiled.required = task.required;
617 if (task.destination.kind === "object") task.destination.target.required = task.required;
618 }
619 continue;
620 }
621 if (task.kind === "property") {
622 if (!isJsonSchemaRecord(task.property)) authorError(`${task.path} must be a value schema object`);
623 if (Object.hasOwn(task.property, "required") && task.property.required !== true) authorError(`${task.path}.required must be true when present`);
624 if (Object.hasOwn(task.property, "required") && task.property.required === true) task.required.push(task.key);
625 tasks.push({
626 kind: "value",
627 input: task.property,
628 path: task.path,
629 allowRequired: true,
630 destination: {
631 kind: "property",
632 target: task.properties,
633 key: task.key
634 }
635 });
636 continue;
637 }
638 if (task.kind === "property-map") {
639 if (!isJsonSchemaRecord(task.input)) authorError(`${task.path} must be an object of value schemas`);
640 if (seen.has(task.input)) authorError(`${task.path} is circular`);
641 seen.add(task.input);
642 const compiled = { properties: {} };
643 const required = [];
644 assignCompiledPropertyMap(task.destination, compiled);
645 tasks.push({
646 kind: "leave",
647 input: task.input
648 });
649 tasks.push({
650 kind: "property-map-tail",
651 compiled,
652 required,
653 destination: task.destination
654 });
655 const entries = Object.entries(task.input);
656 for (let index = entries.length - 1; index >= 0; index--) {
657 const entry = entries[index];
658 /* v8 ignore next -- the loop is bounded by the captured entry count. */
659 if (entry === void 0) continue;
660 tasks.push({
661 kind: "property",
662 property: entry[1],
663 path: `${task.path}.${entry[0]}`,
664 key: entry[0],
665 properties: compiled.properties,
666 required
667 });
668 }
669 continue;
670 }
671 const { input, path } = task;
672 if (!isJsonSchemaRecord(input)) authorError(`${path} must be a value schema object`);
673 if (seen.has(input)) authorError(`${path} is circular`);
674 seen.add(input);
675 const authorKeys = [...ANNOTATION_KEYS, ...task.allowRequired ? ["required"] : []];
676 const node = {};
677 assignCompiledNode(task.destination, node);
678 tasks.push({
679 kind: "leave",
680 input
681 });
682 if (Object.hasOwn(input, "oneOf")) {
683 assertAuthorKeys(input, path, [
684 ...authorKeys,
685 "oneOf",
686 "type"
687 ]);
688 if (Object.hasOwn(input, "type")) authorError(`${path} cannot declare both type and oneOf`);
689 if (!isPlainJsonArray(input.oneOf)) authorError(`${path}.oneOf must be an array of at least two value schemas`);
690 const branches = [];
691 node.oneOf = branches;
692 copyAnnotations(input, node);
693 for (let index = input.oneOf.length - 1; index >= 0; index--) tasks.push({
694 kind: "value",
695 input: input.oneOf[index],
696 path: `${path}.oneOf[${index}]`,
697 allowRequired: false,
698 destination: {
699 kind: "one-of",
700 target: branches,
701 index
702 }
703 });
704 continue;
705 }
706 const inputType = Object.hasOwn(input, "type") ? input.type : void 0;
707 switch (inputType) {
708 case "json":
709 assertAuthorKeys(input, path, [...authorKeys, "type"]);
710 copyAnnotations(input, node);
711 break;
712 case "object":
713 assertAuthorKeys(input, path, [
714 ...authorKeys,
715 "type",
716 "properties",
717 "additionalProperties"
718 ]);
719 if (!Object.hasOwn(input, "additionalProperties") || typeof input.additionalProperties !== "boolean") authorError(`${path}.additionalProperties must be explicitly true or false`);
720 node.type = "object";
721 copyAnnotations(input, node);
722 node.additionalProperties = input.additionalProperties;
723 if (Object.hasOwn(input, "properties")) tasks.push({
724 kind: "property-map",
725 input: input.properties,
726 path: `${path}.properties`,
727 destination: {
728 kind: "object",
729 target: node
730 }
731 });
732 break;
733 case "array":
734 assertAuthorKeys(input, path, [
735 ...authorKeys,
736 "type",
737 "items"
738 ]);
739 node.type = "array";
740 copyAnnotations(input, node);
741 if (Object.hasOwn(input, "items")) tasks.push({
742 kind: "value",
743 input: input.items,
744 path: `${path}.items`,
745 allowRequired: false,
746 destination: {
747 kind: "item",
748 target: node
749 }
750 });
751 break;
752 case "string":
753 case "number":
754 case "integer":
755 case "boolean":
756 case "null":
757 assertAuthorKeys(input, path, [
758 ...authorKeys,
759 "type",
760 "enum",
761 "const"
762 ]);
763 node.type = inputType;
764 copyAnnotations(input, node);
765 if (Object.hasOwn(input, "enum")) {
766 if (!isPlainJsonArray(input.enum)) authorError(`${path}.enum must be a non-empty array of scalar values`);
767 node.enum = Array.from(input.enum, (entry) => entry);
768 }
769 if (Object.hasOwn(input, "const")) node.const = input.const;
770 break;
771 default: authorError(`${path}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`);
772 }
773 }
774 }
775 /** Compile one implicit property map, collecting per-property requiredness. */
776 function compilePropertyMap(input, path) {
777 const holder = {};
778 runSchemaCompiler({
779 kind: "property-map",
780 input,
781 path,
782 destination: {
783 kind: "root",
784 holder
785 }
786 });
787 /* v8 ignore next -- the root task assigns before scheduling any descendants. */
788 return holder.value ?? authorError(`${path} did not compile`);
789 }
790 /** Compile one author node without applying any consumer root restriction. */
791 function compileValueSchema(input, path) {
792 const holder = {};
793 runSchemaCompiler({
794 kind: "value",
795 input,
796 path,
797 allowRequired: false,
798 destination: {
799 kind: "root",
800 holder
801 }
802 });
803 /* v8 ignore next -- the root task assigns before scheduling any descendants. */
804 return holder.value ?? authorError(`${path} did not compile`);
805 }
806 /**
807 * Compile one author-facing value schema to the enforced raw JSON Schema
808 * subset. The author-only `json` node becomes an annotation-only schema.
809 * @param spec - schema for any JSON-value root.
810 * @returns The asserted raw schema projection.
811 */
812 function valueSchemaSpecToJsonSchema(spec) {
813 const schema = compileValueSchema(spec, "schema");
814 assertSupportedJsonSchema(schema);
815 return schema;
816 }
817 /**
818 * Compile the implicit open parameter object into raw JSON Schema.
819 * @param spec - per-property parameter definitions.
820 * @returns An object-rooted raw schema with no implicit-root openness override.
821 */
822 function parameterSchemaSpecToJsonSchema(spec) {
823 const compiled = compilePropertyMap(spec, "parameters");
824 const schema = {
825 type: "object",
826 properties: compiled.properties,
827 ...compiled.required === void 0 ? {} : { required: compiled.required }
828 };
829 assertSupportedJsonSchema(schema);
830 return schema;
831 }
832 /** Invalid model-generated arguments for a typed tool. */
833 var ToolArgsError = class extends HarnessError {
834 /** Individual violations in schema-walk order. */
835 violations;
836 constructor(violations) {
837 super(`invalid arguments: ${violations.join("; ")}`, "INVALID_ARGS");
838 this.name = "ToolArgsError";
839 this.violations = violations;
840 }
841 };
842 /**
843 * Validate model-generated arguments against an implicit parameter schema.
844 * @param spec - declared parameter schema.
845 * @param args - candidate arguments, however malformed.
846 * @returns Path-qualified violations; empty means valid.
847 */
848 function validateArgs(spec, args) {
849 return validateJsonSchemaValue(parameterSchemaSpecToJsonSchema(spec), args, "");
850 }
851 /**
852 * Define a first-party tool with inferred arguments and strict execution
853 * validation. Replay-only presenters validate softly and fall back to generic
854 * rendering for obsolete logged arguments.
855 * @param options - typed definition and optional finalizer and presenters.
856 * @returns A registry-ready definition.
857 */
858 function defineTool(options) {
859 const userExecute = options.execute;
860 const userFinalizeContent = options.finalizeContent;
861 const userProjectContent = options.projectContent;
862 const userRender = options.output.render;
863 const userPresentationMeta = options.output.presentationMeta;
864 const userPresentCall = options.presentCall;
865 const userPresentResult = options.presentResult;
866 const userIsConcurrencySafe = options.isConcurrencySafe;
867 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`);
868 const parameters = parameterSchemaSpecToJsonSchema(options.parameters);
869 const outputSchema = valueSchemaSpecToJsonSchema(options.output.schema);
870 const validate = (args) => validateJsonSchemaValue(parameters, args, "");
871 const tool = {
872 name: options.name,
873 description: options.description,
874 parameters,
875 output: {
876 schema: outputSchema,
877 render(args, value) {
878 return userRender(args, value);
879 },
880 ...userPresentationMeta !== void 0 ? { presentationMeta(args, value) {
881 return userPresentationMeta(args, value);
882 } } : {}
883 },
884 ...options.deferLoading === true ? { deferLoading: options.deferLoading } : {},
885 ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
886 async execute(args, exec) {
887 const violations = validate(args);
888 if (violations.length > 0) throw new ToolArgsError(violations);
889 return userExecute(args, exec);
890 }
891 };
892 if (userProjectContent) tool.projectContent = (exec, result) => userProjectContent(exec, result);
893 if (userFinalizeContent) tool.finalizeContent = (exec, result) => userFinalizeContent(exec, result);
894 if (userPresentCall) tool.presentCall = (args) => {
895 if (validate(args).length > 0) return void 0;
896 return userPresentCall(args);
897 };
898 if (userPresentResult) tool.presentResult = (args, result) => {
899 if (validate(args).length > 0) return void 0;
900 return userPresentResult(args, result);
901 };
902 if (userIsConcurrencySafe) tool.isConcurrencySafe = (args) => {
903 if (validate(args).length > 0) return false;
904 return userIsConcurrencySafe(args);
905 };
906 return tool;
907 }
908 /**
909 * Omit execution and presentation callbacks from a tool definition.
910 * @param definition - visible capability or executor-owned transport.
911 * @param detachParameters - copy parameters for a caller-owned inspection result.
912 * @returns the model-facing schema fields.
913 */
914 function projectToolSchema(definition, detachParameters) {
915 const { name, description, parameters, deferLoading } = definition;
916 const detached = detachParameters ? snapshotJsonValue(parameters) : parameters;
917 if (detached === void 0) throw new Error(`tool "${name}" parameters must be lossless JSON before schema projection`);
918 return {
919 name,
920 description,
921 parameters: detached,
922 ...deferLoading === true ? { deferLoading } : {}
923 };
924 }
925 //#endregion
926 // ---- END VERBATIM ----
927
928 // ---- VERBATIM @deepseek-ai/dsh-tools@0.2.2-rc.1 lib/shared-DTdn5dXO.js:566-596 ----
929 const TOOL_ABORTED = "ABORTED";
930 /** Canonical error code for cancellation before a tool body was invoked. */
931 const TOOL_ABORTED_BEFORE_DISPATCH = "ABORTED_BEFORE_DISPATCH";
932 /**
933 * Thrown (internally) when the model requests a tool that isn't registered.
934 * Extends {@link HarnessError} (`code: 'UNKNOWN_TOOL'`) so an unknown-tool
935 * failure is as routable as a tool-thrown one — retry/sandbox/replay code can
936 * distinguish it from a tool body's own error.
937 */
938 var ToolNotFoundError = class extends HarnessError {
939 /**
940 * @param toolName - the name the caller asked for.
941 * @param reachableFrom - how the model reaches this tool instead, when the
942 * name IS visible and only the presentation denies calling it directly.
943 * Omitted for a name that is registered nowhere.
944 */
945 constructor(toolName, reachableFrom) {
946 super(reachableFrom === void 0 ? `unknown tool "${toolName}"` : `unknown tool "${toolName}": ${reachableFrom}`, "UNKNOWN_TOOL");
947 this.name = "ToolNotFoundError";
948 }
949 };
950 /** Thrown when a tool body or post-policy value violates its declared output. */
951 var ToolOutputError = class extends HarnessError {
952 /** Schema/value violations in validation order. */
953 violations;
954 constructor(toolName, violations) {
955 super(`tool "${toolName}" returned invalid output: ${violations.join("; ")}`, "INVALID_TOOL_OUTPUT");
956 this.name = "ToolOutputError";
957 this.violations = violations;
958 }
959 };
960 // ---- END VERBATIM ----
961
962 export {
963 JsonSchemaError,
964 TOOL_ABORTED,
965 TOOL_ABORTED_BEFORE_DISPATCH,
966 ToolArgsError,
967 ToolNotFoundError,
968 ToolOutputError,
969 assertObjectJsonSchema,
970 assertSupportedJsonSchema,
971 defineTool,
972 parameterSchemaSpecToJsonSchema,
973 validateArgs,
974 validateJsonSchemaValue,
975 valueSchemaSpecToJsonSchema,
976 }
977
977 lines JAVASCRIPT