@linxin666/dsh-client-ui-browser-view 0.4.21 → 0.4.23

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/lib/index.js CHANGED
@@ -1716,6 +1716,10 @@ function isLoopbackRequest(request) {
1716
1716
  * (`ctx.connection.authenticatedUrl`), which is what makes the retry possible
1717
1717
  * without this package depending on that SDK.
1718
1718
  *
1719
+ * With the official remote-connection plugin mounted, the same 401 renders
1720
+ * that plugin's localized sign-in page instead of the sentence; it is
1721
+ * recognized by {@link LOGIN_PAGE_EXPRESSION}.
1722
+ *
1719
1723
  * If DSH rewords the challenge, {@link AUTH_CHALLENGE_TEXT} simply stops
1720
1724
  * matching: the capability degrades to showing the authentication page exactly
1721
1725
  * as before, and no other site's page is ever mistaken for ours.
@@ -1740,6 +1744,17 @@ const ADMISSION_REJECTION_TEXT = /^\s*unauthorized\s*$/i;
1740
1744
  */
1741
1745
  const DOCUMENT_TEXT_EXPRESSION = "document.body ? document.body.innerText : ''";
1742
1746
  /**
1747
+ * Script that recognizes the sign-in page a Host serves at its root once the
1748
+ * official remote-connection plugin is mounted ("Connect to this Host"). Its
1749
+ * copy is localized and has no fixed sentence to match, so the page is read
1750
+ * by structure instead: the `h1#title` heading plus at least one sign-in
1751
+ * method, the token form or the device-pairing element. Rendering one without
1752
+ * the other is possible when the operator disables a method, which is why
1753
+ * either counts. Like the bare refusal, this shape is not unique on its own,
1754
+ * so a caller must also know the page came from this host's own listener.
1755
+ */
1756
+ const LOGIN_PAGE_EXPRESSION = "document.querySelector('h1#title') !== null && document.querySelector('form#token-form, dsh-device-pairing') !== null";
1757
+ /**
1743
1758
  * Whether a page's visible text is DSH's authentication challenge.
1744
1759
  * @param text - `document.body.innerText` of the page that just loaded.
1745
1760
  * @returns true when the document is the challenge rather than a real page.
@@ -2737,12 +2752,13 @@ var BrowserViewService = class {
2737
2752
  }
2738
2753
  }
2739
2754
  /**
2740
- * Whether the tab's current document is DSH's authentication page. Two
2741
- * pages count: the token exchange's own sentence, and the bare
2742
- * `unauthorized` a post-#8266 Host answers when route admission refuses the
2743
- * site root before that exchange runs. The bare refusal is generic to every
2744
- * local service, so it only counts when the requested URL names this host's
2745
- * own listener.
2755
+ * Whether the tab's current document is DSH's authentication page. Three
2756
+ * pages count: the token exchange's own sentence, the bare `unauthorized` a
2757
+ * post-#8266 Host answers when route admission refuses the site root before
2758
+ * that exchange runs, and the "Connect to this Host" sign-in page the
2759
+ * official remote-connection plugin renders at the root. The last two are
2760
+ * generic to any local service, so they only count when the requested URL
2761
+ * is the root of this host's own listener.
2746
2762
  * @param tabId - tab to read.
2747
2763
  * @param url - the URL the caller asked to open.
2748
2764
  * @returns true when the page body is the challenge.
@@ -2756,9 +2772,13 @@ var BrowserViewService = class {
2756
2772
  }, scope.tabs.sessionOf(tabId))).result?.value;
2757
2773
  if (typeof text !== "string") return false;
2758
2774
  if (isAuthChallengeText(text)) return true;
2759
- if (!isAdmissionRejectionText(text)) return false;
2760
2775
  const origin = this.hostOrigin?.();
2761
- return origin !== void 0 && isSameLoopbackOrigin(url, origin) && isHostRootUrl(url);
2776
+ if (origin === void 0 || !isSameLoopbackOrigin(url, origin) || !isHostRootUrl(url)) return false;
2777
+ if (isAdmissionRejectionText(text)) return true;
2778
+ return (await scope.transport.send("Runtime.evaluate", {
2779
+ expression: LOGIN_PAGE_EXPRESSION,
2780
+ returnByValue: true
2781
+ }, scope.tabs.sessionOf(tabId))).result?.value === true;
2762
2782
  } catch {
2763
2783
  return false;
2764
2784
  }
@@ -3417,189 +3437,335 @@ function writeJson(res, status, body) {
3417
3437
  res.end(text);
3418
3438
  }
3419
3439
  //#endregion
3420
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
3421
- /** The one Remote failure class shared by owners, the Gateway, and consumers. */
3440
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3/node_modules/@deepseek-ai/dsh-scope/lib/index.js
3422
3441
  /**
3423
- * One Remote call failure: a real Error carrying its stable code and typed
3424
- * details. Owners throw it at the failure point; the Host Gateway encodes it
3425
- * onto the wire unchanged; the Client face rebuilds an instance for the
3426
- * `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
3427
- * Discrimination is always by `code`, never by instanceof.
3442
+ * Shared insertion-ordered storage and effect ownership for scope-aware registries.
3443
+ *
3444
+ * @module @deepseek-ai/dsh-scope
3428
3445
  */
3429
- var RemoteError = class extends Error {
3430
- code;
3431
- details;
3432
- /** Structural marker: cross-realm/bundle identification never uses instanceof. */
3433
- isDSHRemoteError = true;
3446
+ /**
3447
+ * Insertion-ordered named entries with caller-owned duplicate diagnostics.
3448
+ *
3449
+ * Values are borrowed. Iterators are live within one nonempty table
3450
+ * generation; draining the table detaches them from later insertions. Each
3451
+ * successful insertion returns an idempotent undo for that exact entry.
3452
+ */
3453
+ var NamedEntries = class {
3454
+ duplicateError;
3455
+ data = /* @__PURE__ */ new Map();
3456
+ constructor(duplicateError) {
3457
+ this.duplicateError = duplicateError;
3458
+ }
3434
3459
  /**
3435
- * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
3436
- * @param message - human diagnostic carried across the wire.
3437
- * @param details - structured payload typed by the code.
3438
- * @param options - standard Error options (`cause` survives in-process only).
3460
+ * Insert one unique name.
3461
+ * @param name - name unique within this table.
3462
+ * @param value - borrowed value to retain.
3463
+ * @returns an idempotent undo that removes only this insertion.
3439
3464
  */
3440
- constructor(code, message, details, options) {
3441
- super(message, options);
3442
- this.code = code;
3443
- this.details = details;
3444
- this.name = "RemoteError";
3465
+ insert(name, value) {
3466
+ const data = this.data;
3467
+ if (data.has(name)) throw this.duplicateError(name);
3468
+ data.set(name, value);
3469
+ let active = true;
3470
+ return () => {
3471
+ if (!active) return;
3472
+ active = false;
3473
+ data.delete(name);
3474
+ if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
3475
+ };
3476
+ }
3477
+ /**
3478
+ * Read one named value.
3479
+ * @param name - name to resolve.
3480
+ * @returns the retained value, or `undefined` when absent.
3481
+ */
3482
+ get(name) {
3483
+ return this.data.get(name);
3484
+ }
3485
+ /**
3486
+ * Test one name for membership.
3487
+ * @param name - name to test.
3488
+ * @returns whether the table contains that name.
3489
+ */
3490
+ has(name) {
3491
+ return this.data.has(name);
3492
+ }
3493
+ /**
3494
+ * Iterate live names in insertion order.
3495
+ * @returns the native live key iterator.
3496
+ */
3497
+ keys() {
3498
+ return this.data.keys();
3499
+ }
3500
+ /**
3501
+ * Iterate live entries in insertion order.
3502
+ * @returns the native live entry iterator.
3503
+ */
3504
+ entries() {
3505
+ return this.data.entries();
3506
+ }
3507
+ /**
3508
+ * Iterate live values in insertion order.
3509
+ * @returns the native live value iterator.
3510
+ */
3511
+ values() {
3512
+ return this.data.values();
3513
+ }
3514
+ /**
3515
+ * Test whether this table has no entries.
3516
+ * @returns whether the table is empty.
3517
+ */
3518
+ isEmpty() {
3519
+ return this.data.size === 0;
3445
3520
  }
3446
3521
  };
3447
3522
  /**
3448
- * Remote decorators and explicit Gateway bindings backed by versioned
3449
- * descriptors carried on decorated class prototypes. Strict reflection
3450
- * remains a Typert compiler responsibility.
3451
- * @module @deepseek-ai/dsh-typert-protocol
3452
- */
3453
- const TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
3454
- /**
3455
- * Test one generated Remote name against the Connection endpoint grammar.
3456
- * @param value - namespace, method, lookup, or Context segment.
3457
- * @returns whether the value can cross the shared RPC carrier unchanged.
3458
- */
3459
- function isTypertRemoteSegment(value) {
3460
- return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
3461
- }
3462
- const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
3463
- /**
3464
- * Bind one visible Service field to a Cordis key and Remote namespace. A
3465
- * service that owns a Cordis Context also gives its tree `ctx.invocation`,
3466
- * `undefined` outside a Remote call, so no `TypertRemoteService` is needed for
3467
- * a Host composition to read it.
3468
- * @param service - owning Service instance, normally `this`.
3469
- * @param serviceKey - exact Cordis service key.
3470
- * @param options - optional wire namespace.
3471
- * @returns a frozen, inspectable binding with no compiler-injected metadata.
3523
+ * Insertion-ordered anonymous entries with independent registration identity.
3524
+ *
3525
+ * Equal values remain separate registrations. Values are borrowed, and
3526
+ * iterators are live within one nonempty table generation; draining the table
3527
+ * detaches them from later appends.
3472
3528
  */
3473
- function bindTypertRemote(service, serviceKey, options = {}) {
3474
- validateName("service key", serviceKey);
3475
- const namespace = options.namespace ?? serviceKey;
3476
- validateName("namespace", namespace);
3477
- const ctx = Reflect.get(service, "ctx");
3478
- if (Context.is(ctx)) provideInvocationAccessor(ctx);
3479
- return Object.freeze({
3480
- service,
3481
- serviceKey,
3482
- namespace
3483
- });
3484
- }
3485
- /** Cordis Service base that exposes its registered name through Typert Gateway. */
3486
- var TypertRemoteService = class extends Service {
3487
- /** Visible binding consumed by the Gateway's source-mode discovery. */
3488
- typertRemote;
3529
+ var AnonymousEntries = class {
3530
+ data = /* @__PURE__ */ new Map();
3489
3531
  /**
3490
- * Register the Service and bind the same key to Typert Gateway.
3491
- * @param ctx - owning Cordis Context.
3492
- * @param serviceKey - exact Cordis service key and default wire namespace.
3493
- * @param options - optional wire namespace.
3532
+ * Append one independently owned value.
3533
+ * @param value - borrowed value to retain.
3534
+ * @returns an idempotent undo for this exact append.
3494
3535
  */
3495
- constructor(ctx, serviceKey, options = {}) {
3496
- super(ctx, serviceKey);
3497
- this.typertRemote = bindTypertRemote(this, this.name, options);
3536
+ append(value) {
3537
+ const data = this.data;
3538
+ const key = Symbol();
3539
+ data.set(key, value);
3540
+ let active = true;
3541
+ return () => {
3542
+ if (!active) return;
3543
+ active = false;
3544
+ data.delete(key);
3545
+ if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
3546
+ };
3547
+ }
3548
+ /**
3549
+ * Iterate live values in insertion order.
3550
+ * @returns the native live value iterator.
3551
+ */
3552
+ values() {
3553
+ return this.data.values();
3554
+ }
3555
+ /**
3556
+ * Test whether this table has no entries.
3557
+ * @returns whether the table is empty.
3558
+ */
3559
+ isEmpty() {
3560
+ return this.data.size === 0;
3498
3561
  }
3499
3562
  };
3500
3563
  /**
3501
- * Make `ctx.invocation` read as `undefined` outside a Remote call instead of the
3502
- * reflect service's "cannot get property" error; a call-derived Context shadows
3503
- * the accessor with its own property. The first Remote Service constructed in a
3504
- * tree registers it on the root, where it outlives any one Service.
3564
+ * Own the global and exact-scope layers for one registry.
3565
+ *
3566
+ * Reads never create scoped layers. Registrations derive both visibility and
3567
+ * effect ownership from the supplied Cordis context, collect undo before
3568
+ * notification, and reclaim only a completely empty aggregate layer.
3505
3569
  */
3506
- function provideInvocationAccessor(ctx) {
3507
- if (Object.hasOwn(ctx.root.reflect.props, "invocation")) return;
3508
- ctx.root.accessor("invocation", { get: () => void 0 });
3509
- }
3510
- function Remote(methodExportOrOptions, context) {
3511
- if (typeof methodExportOrOptions === "string") {
3512
- validateName("Remote export name", methodExportOrOptions);
3513
- return remoteDecorator({ kind: "direct" }, { exportName: methodExportOrOptions });
3570
+ var ScopedLayers = class {
3571
+ createLayer;
3572
+ onChange;
3573
+ /** The eagerly constructed context-global layer. */
3574
+ global;
3575
+ scoped = /* @__PURE__ */ new Map();
3576
+ constructor(createLayer, onChange) {
3577
+ this.createLayer = createLayer;
3578
+ this.onChange = onChange;
3579
+ this.global = createLayer(void 0);
3514
3580
  }
3515
- if (typeof methodExportOrOptions === "object") return remoteDecorator({ kind: "direct" }, markerOptions(methodExportOrOptions, REMOTE_OPTION_KEYS, "Remote options require name, mode: \"stream\", or resources"));
3516
- if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
3517
- addMarkerInitializer(context, { kind: "direct" });
3518
- }
3519
- const REMOTE_OPTION_KEYS = /* @__PURE__ */ new Set([
3520
- "name",
3521
- "mode",
3522
- "resources"
3523
- ]);
3524
- /** Validate one decorator options object against its accepted keys and select the marker fields. */
3525
- function markerOptions(options, accepted, requirement) {
3526
- const keys = Reflect.ownKeys(options);
3527
- if (keys.length === 0 || keys.some((key) => typeof key !== "string" || !accepted.has(key)) || Object.hasOwn(options, "mode") && options.mode !== "stream") throw new TypeError(`typert-protocol: ${requirement}`);
3528
- const { mode, name, resources } = options;
3529
- if (name !== void 0) validateName("Remote export name", name);
3530
- return {
3531
- ...mode === void 0 ? {} : { mode },
3532
- ...name === void 0 ? {} : { exportName: name },
3533
- ...resources === void 0 ? {} : { resources: resourceReaders(resources) }
3534
- };
3535
- }
3536
- /** Freeze declared readers into the marker record; a misdeclared reader fails at decoration. */
3537
- function resourceReaders(resources) {
3538
- const readers = {};
3539
- for (const [kind, reader] of Object.entries(resources)) {
3540
- if (typeof reader !== "function") throw new TypeError(`typert-protocol: Remote resource reader "${kind}" must be a function`);
3541
- readers[kind] = reader;
3581
+ /**
3582
+ * Read an existing exact-scope overlay. Deliberately chain-blind: callers
3583
+ * addressing one scope's OWN contributions (its restrictions, its guards)
3584
+ * must not silently pick up an ancestor's — use {@link chainLayers} where
3585
+ * inheritance is the point.
3586
+ * @param scope - exact scope key; `undefined` denotes no overlay.
3587
+ * @returns the existing scoped layer, or `undefined` without creating one.
3588
+ */
3589
+ peek(scope) {
3590
+ if (scope === void 0) return void 0;
3591
+ return this.scoped.get(scope);
3542
3592
  }
3543
- if (Object.keys(readers).length === 0) throw new TypeError("typert-protocol: Remote resources require at least one reader");
3544
- return Object.freeze(readers);
3545
- }
3546
- function remoteDecorator(invocation, options = {}) {
3547
- return function(_method, context) {
3548
- addMarkerInitializer(context, invocation, options);
3549
- };
3550
- }
3551
- function readRemoteMethodDescriptor(prototype) {
3552
- const property = Object.getOwnPropertyDescriptor(prototype, REMOTE_METHOD_DESCRIPTOR);
3553
- if (property === void 0) return void 0;
3554
- const descriptor = property.value;
3555
- if (descriptor === null || typeof descriptor !== "object") throw new TypeError("typert-protocol: Remote method descriptor must be an object");
3556
- const version = Reflect.get(descriptor, "version");
3557
- if (version !== 1) throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(version)}`);
3558
- const methods = Reflect.get(descriptor, "methods");
3559
- if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
3560
- return descriptor;
3593
+ /**
3594
+ * Existing overlays along the scope's parent chain ({@link scopeChainOf}),
3595
+ * farthest ancestor first and the exact scope last, so a caller layering
3596
+ * them in order gives the nearest scope the final word.
3597
+ * @param scope - viewing scope, or `undefined` for no overlays.
3598
+ * @returns the existing layers, nearest last; absent overlays are skipped.
3599
+ */
3600
+ chainLayers(scope) {
3601
+ const layers = [];
3602
+ for (const key of scopeChainOf(scope).reverse()) {
3603
+ const layer = this.scoped.get(key);
3604
+ if (layer !== void 0) layers.push(layer);
3605
+ }
3606
+ return layers;
3607
+ }
3608
+ /**
3609
+ * Materialize global named entries followed by scope-chain shadows,
3610
+ * farthest ancestor first, so the nearest scope's entry wins a name.
3611
+ * @param scope - viewing scope, or `undefined` for the global view.
3612
+ * @param pick - select the named table from a layer.
3613
+ * @returns an insertion-ordered effective map.
3614
+ */
3615
+ merge(scope, pick) {
3616
+ const merged = new Map(pick(this.global).entries());
3617
+ for (const layer of this.chainLayers(scope)) for (const [name, value] of pick(layer).entries()) merged.set(name, value);
3618
+ return merged;
3619
+ }
3620
+ /**
3621
+ * Attach one synchronous layer mutation to its registration context.
3622
+ * @param ctx - context that determines both scope visibility and effect ownership.
3623
+ * @param action - atomic mutation returning its synchronous undo.
3624
+ * @param options - Cordis effect label and optional change notification.
3625
+ * @returns the exact disposer returned by `ctx.effect()`.
3626
+ */
3627
+ effect(ctx, action, options) {
3628
+ const scope = scopeOf(ctx);
3629
+ const notify = options.notify ?? true;
3630
+ return ctx.effect(function* () {
3631
+ let layer;
3632
+ let created = false;
3633
+ if (scope === void 0) layer = this.global;
3634
+ else {
3635
+ const existing = this.scoped.get(scope);
3636
+ if (existing === void 0) {
3637
+ layer = this.createLayer(scope);
3638
+ this.scoped.set(scope, layer);
3639
+ created = true;
3640
+ } else layer = existing;
3641
+ }
3642
+ let undo;
3643
+ try {
3644
+ undo = action(layer);
3645
+ } catch (error) {
3646
+ if (scope !== void 0 && created && layer.isEmpty()) this.scoped.delete(scope);
3647
+ throw error;
3648
+ }
3649
+ yield () => {
3650
+ undo();
3651
+ if (scope !== void 0 && layer.isEmpty()) this.scoped.delete(scope);
3652
+ if (notify) this.onChange();
3653
+ };
3654
+ if (notify) this.onChange();
3655
+ }.bind(this), options.label);
3656
+ }
3657
+ };
3658
+ /**
3659
+ * Scoped-context primitive: mint a Cordis context that tags registrations with
3660
+ * an opaque identity and build routing-only event carriers for that identity.
3661
+ *
3662
+ * @module @deepseek-ai/dsh-scope
3663
+ */
3664
+ /** Context tag written by {@link createScope}. */
3665
+ const kScope = Symbol("dsh.scope");
3666
+ /** The key associated with each carrier. Presence distinguishes an unkeyed carrier from a non-carrier. */
3667
+ const carrierKeys = /* @__PURE__ */ new WeakMap();
3668
+ /**
3669
+ * The enclosing scope of each key. One relation powers both directions of
3670
+ * scope nesting: registration views inherit DOWN the chain (a child scope
3671
+ * sees its ancestors' layers — {@link ScopedLayers}), and event admission
3672
+ * extends UP it (a listener tagged with an ancestor receives events dispatched
3673
+ * to a descendant key — {@link scopeTarget}).
3674
+ */
3675
+ const scopeParents = /* @__PURE__ */ new WeakMap();
3676
+ /**
3677
+ * The chain from a key to its root ancestor.
3678
+ * @param key - the starting key, or `undefined` for the empty chain.
3679
+ * @returns keys nearest-first: `[key, parent, grandparent, …]`.
3680
+ */
3681
+ function scopeChainOf(key) {
3682
+ const chain = [];
3683
+ for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) chain.push(cursor);
3684
+ return chain;
3561
3685
  }
3562
- function addMarkerInitializer(context, invocation, options = {}) {
3563
- if (context.private || context.static || typeof context.name !== "string") throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");
3564
- const method = context.name;
3565
- context.addInitializer(function() {
3566
- const prototype = Object.getPrototypeOf(this);
3567
- if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
3568
- mark(prototype, method, invocation, options);
3569
- });
3686
+ /**
3687
+ * Read the nearest scope tag inherited by a context.
3688
+ * @param ctx - context to inspect.
3689
+ * @returns its scope key, or `undefined` for an unscoped context.
3690
+ */
3691
+ function scopeOf(ctx) {
3692
+ return ctx[kScope];
3570
3693
  }
3571
- function mark(prototype, method, invocation, { mode, exportName, resources }) {
3572
- const descriptor = readRemoteMethodDescriptor(prototype);
3573
- const marker = Object.freeze({
3574
- method,
3575
- ...exportName === void 0 || exportName === method ? {} : { exportName },
3576
- ...mode === void 0 ? {} : { mode },
3577
- invocation: Object.freeze(invocation),
3578
- ...resources === void 0 ? {} : { resources }
3579
- });
3580
- const current = descriptor?.methods.find((candidate) => candidate.method === method);
3581
- if (current !== void 0) {
3582
- if (current.exportName === marker.exportName && current.mode === marker.mode && current.resources === marker.resources && sameInvocation(current.invocation, invocation)) return;
3583
- throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
3584
- }
3585
- Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
3586
- configurable: true,
3587
- value: Object.freeze({
3588
- version: 1,
3589
- methods: Object.freeze([...descriptor?.methods ?? [], marker])
3590
- })
3591
- });
3694
+ /**
3695
+ * Build an opaque receiver that preserves the base filter, admits untagged
3696
+ * listeners globally, and admits tagged listeners for a matching key or any
3697
+ * of its ancestors ({@link bindScopeParent}): a listener owned by an enclosing
3698
+ * scope receives every descendant scope's events, which is what lets one
3699
+ * standing composition observe each of the agents composed under it. A tag
3700
+ * BELOW the dispatch key stays excluded — events flow up the chain, never
3701
+ * down.
3702
+ * @param base - subject or service whose existing Cordis filter is preserved.
3703
+ * @param key - routed scope identity, or `undefined` for an unscoped subject.
3704
+ * @returns a carrier whose subject remains available only through event arguments.
3705
+ */
3706
+ function scopeTarget(base, key) {
3707
+ const baseFilter = base[Context.filter];
3708
+ const carrier = { [Context.filter](ctx) {
3709
+ if (baseFilter !== void 0 && !baseFilter.call(base, ctx)) return false;
3710
+ const tag = scopeOf(ctx);
3711
+ if (tag === void 0) return true;
3712
+ for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) if (cursor === tag) return true;
3713
+ return false;
3714
+ } };
3715
+ carrierKeys.set(carrier, key);
3716
+ return carrier;
3592
3717
  }
3593
- function sameInvocation(left, right) {
3594
- if (left.kind === "direct") return right.kind === "direct";
3595
- if (right.kind === "direct") return false;
3596
- return left.context === right.context;
3718
+ //#endregion
3719
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-error@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3/node_modules/@deepseek-ai/dsh-error/lib/index.js
3720
+ /**
3721
+ * Harness error base with a stable machine-routable code and chained cause.
3722
+ * Package errors extend it so tool results and replay can retain failure class.
3723
+ * @module @deepseek-ai/dsh-error
3724
+ */
3725
+ /**
3726
+ * Base class for all harness errors. Carries a `code` (stable, programmatic —
3727
+ * e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the
3728
+ * human-readable `message`, and supports `cause` chaining via the standard
3729
+ * `ErrorOptions`. `name` defaults to the subclass constructor name.
3730
+ */
3731
+ var HarnessError = class extends Error {
3732
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
3733
+ code;
3734
+ constructor(message, code, options) {
3735
+ super(message, options);
3736
+ this.code = code;
3737
+ this.name = new.target.name;
3738
+ }
3739
+ };
3740
+ /**
3741
+ * Render one thrown value as readable text for a log line, tool result, or UI
3742
+ * message. An `Error` contributes its `message`, and another object with a
3743
+ * string `message` contributes that message; every other value is rendered as
3744
+ * JSON when it survives `JSON.stringify`, so a cancelled operation's reason
3745
+ * object reads as its fields instead of `[object Object]`.
3746
+ * @param error - thrown value, `AbortSignal.reason`, or rejected promise value.
3747
+ * @returns readable text, total even for hostile values that trap property reads or coercion.
3748
+ */
3749
+ function errorMessage$1(error) {
3750
+ try {
3751
+ if (error instanceof Error) return error.message;
3752
+ if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
3753
+ return renderValue(error);
3754
+ } catch {
3755
+ return "<unprintable thrown value>";
3756
+ }
3597
3757
  }
3598
- function validateName(subject, value) {
3599
- if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
3758
+ /** JSON text for a structured thrown value; primitives keep their default coercion and objects without JSON text get a fixed label. */
3759
+ function renderValue(value) {
3760
+ if (typeof value !== "object" || value === null) return String(value);
3761
+ let json;
3762
+ try {
3763
+ json = JSON.stringify(value);
3764
+ } catch (_unrepresentable) {}
3765
+ return typeof json === "string" ? json : "<unrepresentable thrown value>";
3600
3766
  }
3601
3767
  //#endregion
3602
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
3768
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
3603
3769
  /**
3604
3770
  * Lazily scanned view of one JSON object's top-level fields, built from text
3605
3771
  * that may still be streaming or from an already parsed object. Nothing is
@@ -4243,13 +4409,14 @@ function hasIntrinsicConstructor$1(prototype, name) {
4243
4409
  return false;
4244
4410
  }
4245
4411
  }
4246
- /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
4412
+ /** Whether a candidate is this or another realm's intrinsic `Object.prototype`. */
4247
4413
  function isIntrinsicObjectPrototype$1(value) {
4248
- return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, "Object");
4414
+ return value === Object.prototype || Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, "Object");
4249
4415
  }
4250
4416
  /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
4251
4417
  function hasPlainArrayPrototype$1(value) {
4252
4418
  const prototype = Object.getPrototypeOf(value);
4419
+ if (prototype === Array.prototype) return true;
4253
4420
  if (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, "Array")) return false;
4254
4421
  const objectPrototype = Object.getPrototypeOf(prototype);
4255
4422
  return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);
@@ -4418,71 +4585,290 @@ function deepFreeze(value) {
4418
4585
  return value;
4419
4586
  }
4420
4587
  //#endregion
4421
- //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.9.0/node_modules/@deepseek-ai/cosmokit/lib/index.js
4422
- /** Return true when a value is `null` or `undefined`. */
4423
- function isNullable(value) {
4424
- return value === null || value === void 0;
4425
- }
4426
- /** Return true for non-array object values. */
4427
- function isPlainObject(data) {
4428
- return data && typeof data === "object" && !Array.isArray(data);
4429
- }
4430
- /** Filter object entries and return a new object. */
4431
- function filterKeys(object, filter) {
4432
- return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
4433
- }
4434
- /** Map object values while preserving the original key set. */
4435
- function mapValues(object, transform) {
4436
- return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
4437
- }
4438
- /** Pick selected keys from an object, optionally including `undefined` values. */
4439
- function pick(source, keys, forced) {
4440
- if (!keys) return { ...source };
4441
- const result = {};
4442
- for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
4443
- return result;
4444
- }
4445
- /** Shared config references used by schema validators and plugin runtimes. */
4446
- const write = Symbol.for("cosmokit.volatile.write");
4447
- function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
4448
- if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
4449
- if (value === null || typeof value !== "object") return value;
4450
- if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
4451
- ancestors.add(value);
4452
- try {
4453
- if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
4454
- if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
4455
- return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
4456
- } finally {
4457
- ancestors.delete(value);
4588
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3_@deeps_5d4ee3c030944b2c94628f6c418d6feb/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
4589
+ /** The one Remote failure class shared by owners, the Gateway, and consumers. */
4590
+ /**
4591
+ * One Remote call failure: a `HarnessError` carrying its stable code and typed
4592
+ * details. Owners throw it at the failure point; the Host Gateway encodes it
4593
+ * onto the wire unchanged; the Client face rebuilds an instance for the
4594
+ * `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
4595
+ * A tool body that throws it records `name: 'RemoteError'` and its Remote code
4596
+ * on `tool/result`. Discrimination is always by `code`, never by instanceof.
4597
+ */
4598
+ var RemoteError = class extends HarnessError {
4599
+ code;
4600
+ details;
4601
+ /** Structural marker: cross-realm/bundle identification never uses instanceof. */
4602
+ isDSHRemoteError = true;
4603
+ /**
4604
+ * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
4605
+ * @param message - human diagnostic carried across the wire.
4606
+ * @param details - structured payload typed by the code.
4607
+ * @param options - standard Error options (`cause` survives in-process only).
4608
+ */
4609
+ constructor(code, message, details, options) {
4610
+ super(message, code, options);
4611
+ this.code = code;
4612
+ this.details = details;
4613
+ this.name = "RemoteError";
4458
4614
  }
4459
- }
4615
+ };
4460
4616
  /**
4461
- * Create a detached reference containing an immutable copy of the supplied data.
4462
- * @param value - validated config data; class instances and functions are unsupported.
4463
- * @returns a reference whose value is updated only by its owning runtime.
4617
+ * Remote decorators and explicit Gateway bindings backed by versioned
4618
+ * descriptors carried on decorated class prototypes. Strict reflection
4619
+ * remains a Typert compiler responsibility.
4620
+ * @module @deepseek-ai/dsh-typert-protocol
4464
4621
  */
4465
- function createVolatile(value) {
4466
- let current = snapshot(value);
4467
- return Object.freeze({
4468
- get: () => current,
4469
- [write]: (value) => {
4470
- current = value;
4471
- }
4472
- });
4473
- }
4622
+ const TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
4474
4623
  /**
4475
- * Identify references across ESM/CJS copies of the shared library.
4476
- * @param value - a parsed config value.
4477
- * @returns whether the value implements the shared reference protocol.
4624
+ * Test one generated Remote name against the Connection endpoint grammar.
4625
+ * @param value - namespace, method, lookup, or Context segment.
4626
+ * @returns whether the value can cross the shared RPC carrier unchanged.
4478
4627
  */
4479
- function isVolatile(value) {
4480
- return typeof value === "object" && value !== null && write in value;
4628
+ function isTypertRemoteSegment(value) {
4629
+ return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
4481
4630
  }
4482
- /** Test values using `instanceof` with a `toStringTag` fallback. */
4483
- function is(type, value) {
4484
- if (arguments.length === 1) return (value) => is(type, value);
4485
- return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
4631
+ const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
4632
+ /**
4633
+ * Bind one visible Service field to a Cordis key and Remote namespace. A
4634
+ * service that owns a Cordis Context also gives its tree `ctx.invocation`,
4635
+ * `undefined` outside a Remote call, so no `TypertRemoteService` is needed for
4636
+ * a Host composition to read it.
4637
+ * @param service - owning Service instance, normally `this`.
4638
+ * @param serviceKey - exact Cordis service key.
4639
+ * @param options - optional wire namespace.
4640
+ * @returns a frozen, inspectable binding with no compiler-injected metadata.
4641
+ */
4642
+ function bindTypertRemote(service, serviceKey, options = {}) {
4643
+ validateName("service key", serviceKey);
4644
+ const namespace = options.namespace ?? serviceKey;
4645
+ validateName("namespace", namespace);
4646
+ const ctx = Reflect.get(service, "ctx");
4647
+ if (Context.is(ctx)) provideInvocationAccessor(ctx);
4648
+ return Object.freeze({
4649
+ service,
4650
+ serviceKey,
4651
+ namespace
4652
+ });
4653
+ }
4654
+ /** Cordis Service base that exposes its registered name through Typert Gateway. */
4655
+ var TypertRemoteService = class extends Service {
4656
+ /** Visible binding consumed by the Gateway's source-mode discovery. */
4657
+ typertRemote;
4658
+ /**
4659
+ * Register the Service and bind the same key to Typert Gateway.
4660
+ * @param ctx - owning Cordis Context.
4661
+ * @param serviceKey - exact Cordis service key and default wire namespace.
4662
+ * @param options - optional wire namespace.
4663
+ */
4664
+ constructor(ctx, serviceKey, options = {}) {
4665
+ super(ctx, serviceKey);
4666
+ this.typertRemote = bindTypertRemote(this, this.name, options);
4667
+ }
4668
+ };
4669
+ /**
4670
+ * Make `ctx.invocation` read as `undefined` outside a Remote call instead of the
4671
+ * reflect service's "cannot get property" error; a call-derived Context shadows
4672
+ * the accessor with its own property. The first Remote Service constructed in a
4673
+ * tree registers it on the root, where it outlives any one Service.
4674
+ */
4675
+ function provideInvocationAccessor(ctx) {
4676
+ if (Object.hasOwn(ctx[Context.root].reflect.props, "invocation")) return;
4677
+ ctx[Context.root].accessor("invocation", { get: () => void 0 });
4678
+ }
4679
+ function Remote(methodExportOrOptions, context) {
4680
+ if (typeof methodExportOrOptions === "string") {
4681
+ validateName("Remote export name", methodExportOrOptions);
4682
+ return remoteDecorator({ kind: "direct" }, { exportName: methodExportOrOptions });
4683
+ }
4684
+ if (typeof methodExportOrOptions === "object") return remoteDecorator({ kind: "direct" }, markerOptions(methodExportOrOptions, REMOTE_OPTION_KEYS, "Remote options require name, mode: \"stream\", or resources"));
4685
+ if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
4686
+ addMarkerInitializer(context, { kind: "direct" });
4687
+ }
4688
+ const REMOTE_OPTION_KEYS = /* @__PURE__ */ new Set([
4689
+ "name",
4690
+ "mode",
4691
+ "resources"
4692
+ ]);
4693
+ /** Validate one decorator options object against its accepted keys and select the marker fields. */
4694
+ function markerOptions(options, accepted, requirement) {
4695
+ const keys = Reflect.ownKeys(options);
4696
+ if (keys.length === 0 || keys.some((key) => typeof key !== "string" || !accepted.has(key)) || Object.hasOwn(options, "mode") && options.mode !== "stream") throw new TypeError(`typert-protocol: ${requirement}`);
4697
+ const { mode, name, resources } = options;
4698
+ if (name !== void 0) validateName("Remote export name", name);
4699
+ return {
4700
+ ...mode === void 0 ? {} : { mode },
4701
+ ...name === void 0 ? {} : { exportName: name },
4702
+ ...resources === void 0 ? {} : { resources: resourceReaders(resources) }
4703
+ };
4704
+ }
4705
+ /** Freeze declared readers into the marker record; a misdeclared reader fails at decoration. */
4706
+ function resourceReaders(resources) {
4707
+ const readers = {};
4708
+ for (const [kind, reader] of Object.entries(resources)) {
4709
+ if (typeof reader !== "function") throw new TypeError(`typert-protocol: Remote resource reader "${kind}" must be a function`);
4710
+ readers[kind] = reader;
4711
+ }
4712
+ if (Object.keys(readers).length === 0) throw new TypeError("typert-protocol: Remote resources require at least one reader");
4713
+ return Object.freeze(readers);
4714
+ }
4715
+ function remoteDecorator(invocation, options = {}) {
4716
+ return function(_method, context) {
4717
+ addMarkerInitializer(context, invocation, options);
4718
+ };
4719
+ }
4720
+ function readRemoteMethodDescriptor(prototype) {
4721
+ const property = Object.getOwnPropertyDescriptor(prototype, REMOTE_METHOD_DESCRIPTOR);
4722
+ if (property === void 0) return void 0;
4723
+ const descriptor = property.value;
4724
+ if (descriptor === null || typeof descriptor !== "object") throw new TypeError("typert-protocol: Remote method descriptor must be an object");
4725
+ const version = Reflect.get(descriptor, "version");
4726
+ if (version !== 1) throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(version)}`);
4727
+ const methods = Reflect.get(descriptor, "methods");
4728
+ if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
4729
+ return descriptor;
4730
+ }
4731
+ function addMarkerInitializer(context, invocation, options = {}) {
4732
+ if (context.private || context.static || typeof context.name !== "string") throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");
4733
+ const method = context.name;
4734
+ context.addInitializer(function() {
4735
+ const prototype = Object.getPrototypeOf(this);
4736
+ if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
4737
+ mark(prototype, method, invocation, options);
4738
+ });
4739
+ }
4740
+ function mark(prototype, method, invocation, { mode, exportName, resources }) {
4741
+ const descriptor = readRemoteMethodDescriptor(prototype);
4742
+ const marker = Object.freeze({
4743
+ method,
4744
+ ...exportName === void 0 || exportName === method ? {} : { exportName },
4745
+ ...mode === void 0 ? {} : { mode },
4746
+ invocation: Object.freeze(invocation),
4747
+ ...resources === void 0 ? {} : { resources }
4748
+ });
4749
+ const current = descriptor?.methods.find((candidate) => candidate.method === method);
4750
+ if (current !== void 0) {
4751
+ if (current.exportName === marker.exportName && current.mode === marker.mode && current.resources === marker.resources && sameInvocation(current.invocation, invocation)) return;
4752
+ throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
4753
+ }
4754
+ Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
4755
+ configurable: true,
4756
+ value: Object.freeze({
4757
+ version: 1,
4758
+ methods: Object.freeze([...descriptor?.methods ?? [], marker])
4759
+ })
4760
+ });
4761
+ }
4762
+ function sameInvocation(left, right) {
4763
+ if (left.kind === "direct") return right.kind === "direct";
4764
+ if (right.kind === "direct") return false;
4765
+ return left.context === right.context;
4766
+ }
4767
+ function validateName(subject, value) {
4768
+ if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
4769
+ }
4770
+ //#endregion
4771
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-crypto@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3/node_modules/@deepseek-ai/dsh-util-crypto/lib/index.js
4772
+ /**
4773
+ * Random v4 UUID, minted from `crypto.getRandomValues`.
4774
+ * @returns the UUID string.
4775
+ */
4776
+ function randomUUID() {
4777
+ const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
4778
+ const hex = Array.from(bytes, (byte, index) => {
4779
+ return (index === 6 ? byte & 15 | 64 : index === 8 ? byte & 63 | 128 : byte).toString(16).padStart(2, "0");
4780
+ }).join("");
4781
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
4782
+ }
4783
+ //#endregion
4784
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-brand@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3/node_modules/@deepseek-ai/dsh-brand/lib/index.js
4785
+ /**
4786
+ * Duplicate-install-safe nominal primitive helpers.
4787
+ *
4788
+ * A brand makes structurally identical strings or numbers non-interchangeable
4789
+ * at the type level: a `SessionId` cannot be passed where a `ToolCallId` is
4790
+ * expected, and an event sequence cannot be passed as a log offset. Comparison,
4791
+ * logging, and serialization retain the underlying primitive behavior.
4792
+ *
4793
+ * This package owns no concrete domain value and keeps no runtime identity or mutable
4794
+ * state, so independently installed copies produce interchangeable values.
4795
+ *
4796
+ * @module @deepseek-ai/dsh-brand
4797
+ */
4798
+ /**
4799
+ * Apply a compile-time string brand without changing the value.
4800
+ * @param value - string admitted by the domain that owns the target brand.
4801
+ * @returns the same string with the requested compile-time brand.
4802
+ */
4803
+ function brandString(value) {
4804
+ return value;
4805
+ }
4806
+ //#endregion
4807
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.10.0-alpha.3/node_modules/@deepseek-ai/cosmokit/lib/index.js
4808
+ /** Return true when a value is `null` or `undefined`. */
4809
+ function isNullable(value) {
4810
+ return value === null || value === void 0;
4811
+ }
4812
+ /** Return true for non-array object values. */
4813
+ function isPlainObject(data) {
4814
+ return data && typeof data === "object" && !Array.isArray(data);
4815
+ }
4816
+ /** Filter object entries and return a new object. */
4817
+ function filterKeys(object, filter) {
4818
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
4819
+ }
4820
+ /** Map object values while preserving the original key set. */
4821
+ function mapValues(object, transform) {
4822
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
4823
+ }
4824
+ /** Pick selected keys from an object, optionally including `undefined` values. */
4825
+ function pick(source, keys, forced) {
4826
+ if (!keys) return { ...source };
4827
+ const result = {};
4828
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
4829
+ return result;
4830
+ }
4831
+ /** Shared config references used by schema validators and plugin runtimes. */
4832
+ const write = Symbol.for("cosmokit.volatile.write");
4833
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
4834
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
4835
+ if (value === null || typeof value !== "object") return value;
4836
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
4837
+ ancestors.add(value);
4838
+ try {
4839
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
4840
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
4841
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
4842
+ } finally {
4843
+ ancestors.delete(value);
4844
+ }
4845
+ }
4846
+ /**
4847
+ * Create a detached reference containing an immutable copy of the supplied data.
4848
+ * @param value - validated config data; class instances and functions are unsupported.
4849
+ * @returns a reference whose value is updated only by its owning runtime.
4850
+ */
4851
+ function createVolatile(value) {
4852
+ let current = snapshot(value);
4853
+ return Object.freeze({
4854
+ get: () => current,
4855
+ [write]: (value) => {
4856
+ current = value;
4857
+ }
4858
+ });
4859
+ }
4860
+ /**
4861
+ * Identify references across ESM/CJS copies of the shared library.
4862
+ * @param value - a parsed config value.
4863
+ * @returns whether the value implements the shared reference protocol.
4864
+ */
4865
+ function isVolatile(value) {
4866
+ return typeof value === "object" && value !== null && write in value;
4867
+ }
4868
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
4869
+ function is(type, value) {
4870
+ if (arguments.length === 1) return (value) => is(type, value);
4871
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
4486
4872
  }
4487
4873
  function isArrayBufferLike(value) {
4488
4874
  return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
@@ -4672,7 +5058,7 @@ var Time;
4672
5058
  Time.template = template;
4673
5059
  })(Time || (Time = {}));
4674
5060
  //#endregion
4675
- //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.19.0/node_modules/@deepseek-ai/schemastery/lib/index.mjs
5061
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.20.0-alpha.3/node_modules/@deepseek-ai/schemastery/lib/index.mjs
4676
5062
  const kSchema = Symbol.for("schemastery");
4677
5063
  const kValidationError = Symbol.for("ValidationError");
4678
5064
  globalThis.__schemastery_index__ ??= 0;
@@ -5305,41 +5691,11 @@ defineMethod("transform", [
5305
5691
  "preserve"
5306
5692
  ], ({ inner }, isInner) => inner.toString(isInner));
5307
5693
  //#endregion
5308
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
5694
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
5309
5695
  /** Largest delay Node schedules without clamping it to one millisecond. */
5310
5696
  const MAX_TIMER_DELAY_MS = 2147483647;
5311
5697
  //#endregion
5312
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-error@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-error/lib/index.js
5313
- /**
5314
- * Harness error base with a stable machine-routable code and chained cause.
5315
- * Package errors extend it so tool results and replay can retain failure class.
5316
- * @module @deepseek-ai/dsh-error
5317
- */
5318
- /**
5319
- * Base class for all harness errors. Carries a `code` (stable, programmatic —
5320
- * e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the
5321
- * human-readable `message`, and supports `cause` chaining via the standard
5322
- * `ErrorOptions`. `name` defaults to the subclass constructor name.
5323
- */
5324
- var HarnessError = class extends Error {
5325
- /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
5326
- code;
5327
- constructor(message, code, options) {
5328
- super(message, options);
5329
- this.code = code;
5330
- this.name = new.target.name;
5331
- }
5332
- };
5333
- //#endregion
5334
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-error@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0_/node_modules/@deepseek-ai/dsh-llm/lib/index.js
5335
- /**
5336
- * Detach and deep-freeze a message whose identity already exists.
5337
- * @param message - complete message, including its stable identity.
5338
- * @returns an immutable snapshot that preserves the identity.
5339
- */
5340
- function freezeMessage(message) {
5341
- return deepFreeze(structuredClone(message));
5342
- }
5698
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3_@deepseek-ai+dsh-e_04155935fd2dad839d5ea0a7da583551/node_modules/@deepseek-ai/dsh-llm/lib/index.js
5343
5699
  /**
5344
5700
  * LLM failure codes and helpers over the shared Harness error base. The base
5345
5701
  * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
@@ -5358,6 +5714,7 @@ const LLM_FAILURE_CODES = {
5358
5714
  ACCOUNT_TOKEN_INVALID: {},
5359
5715
  AUTH: {},
5360
5716
  CLIENT_UPGRADE_REQUIRED: {},
5717
+ CONTENT_REFUSED: {},
5361
5718
  CONTEXT_WINDOW_EXCEEDED: {},
5362
5719
  DISCOVERY_FAILED: {},
5363
5720
  DISCOVERY_UNSUPPORTED: {},
@@ -5381,6 +5738,7 @@ const LLM_FAILURE_CODES = {
5381
5738
  INVALID_REPLAY_STATE: {},
5382
5739
  INVALID_REQUEST: {},
5383
5740
  INVALID_RESPONSE: {},
5741
+ INVALID_TOOL_ARGUMENTS: { retryChoice: true },
5384
5742
  MALFORMED_RESPONSE: { retryChoice: true },
5385
5743
  MISSING_CREDENTIAL: {},
5386
5744
  MODEL_SWITCH_COMPACTION_FAILED: {},
@@ -5421,19 +5779,56 @@ new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` + Str
5421
5779
  new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?` + String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?` + String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`, "i");
5422
5780
  new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}` + String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}` + String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`, "i");
5423
5781
  /**
5424
- * Provider-owned request-retry policy configuration and resolution.
5425
- *
5426
- * Adapters expose one resolved policy per registered provider route; the
5427
- * optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
5428
- *
5429
- * @module @deepseek-ai/dsh-llm/retry-policy
5782
+ * Detach and deep-freeze a message whose identity already exists.
5783
+ * @param message - complete message, including its stable identity.
5784
+ * @returns an immutable snapshot that preserves the identity.
5430
5785
  */
5431
- const DEFAULT_MAX_RETRIES = 5;
5432
- const DEFAULT_INITIAL_DELAY_MS = 500;
5786
+ function freezeMessage(message) {
5787
+ return deepFreeze(structuredClone(message));
5788
+ }
5789
+ /**
5790
+ * Create one identified message and freeze it before publication.
5791
+ * @param input - complete role, content, and source for a new message.
5792
+ * @returns an immutable message with a fresh stable identity.
5793
+ */
5794
+ function createMessage(input) {
5795
+ return deepFreeze(structuredClone({
5796
+ ...input,
5797
+ id: brandString(randomUUID())
5798
+ }));
5799
+ }
5800
+ /**
5801
+ * Create and freeze one identified tool-result message.
5802
+ * @param input - call identity, raw result blocks, and outcome.
5803
+ * @returns an immutable tool-role message that answers the tool call.
5804
+ */
5805
+ function createToolResultMessage(input) {
5806
+ return createMessage({
5807
+ role: "tool",
5808
+ source: {
5809
+ kind: "tool",
5810
+ callId: input.callId
5811
+ },
5812
+ toolCallId: input.callId,
5813
+ content: input.content,
5814
+ isError: input.isError
5815
+ });
5816
+ }
5817
+ /**
5818
+ * Provider-owned request-retry policy configuration and resolution.
5819
+ *
5820
+ * Adapters expose one resolved policy per registered provider route; the
5821
+ * optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
5822
+ *
5823
+ * @module @deepseek-ai/dsh-llm/retry-policy
5824
+ */
5825
+ const DEFAULT_MAX_RETRIES = 5;
5826
+ const DEFAULT_INITIAL_DELAY_MS = 500;
5433
5827
  const DEFAULT_MAX_DELAY_MS = 1e4;
5434
5828
  const DEFAULT_JITTER_RATIO = .1;
5435
5829
  const DEFAULT_RETRYABLE_CODES = Object.freeze([
5436
5830
  EMPTY_RESPONSE_CODE,
5831
+ "INVALID_TOOL_ARGUMENTS",
5437
5832
  "RATE_LIMIT",
5438
5833
  "SERVER",
5439
5834
  "TIMEOUT",
@@ -5614,10 +6009,11 @@ function failureSnapshot(value) {
5614
6009
  }
5615
6010
  /** Read an SDK error message without letting an accessor replace the primary failure. */
5616
6011
  function errorMessage(error) {
6012
+ let message;
5617
6013
  try {
5618
- const message = error.message;
5619
- if (typeof message === "string" && message.length > 0) return message;
6014
+ message = error.message;
5620
6015
  } catch (_sdkMessageGetter) {}
6016
+ if (typeof message === "string" && message.length > 0) return message;
5621
6017
  return "LLM adapter failed";
5622
6018
  }
5623
6019
  /** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */
@@ -6227,7 +6623,7 @@ var LlmError = class LlmError extends HarnessError {
6227
6623
  * @param provider - registered provider route.
6228
6624
  * @param model - exact model id.
6229
6625
  * @param image - normalized image reference.
6230
- * @returns dimensions and byte target used by the adapter's request serializer.
6626
+ * @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions.
6231
6627
  */
6232
6628
  imageRequestTarget(provider, model, image) {
6233
6629
  return this.registration(provider).adapter.imageRequestTarget(provider, model, image);
@@ -6274,6 +6670,18 @@ var LlmError = class LlmError extends HarnessError {
6274
6670
  });
6275
6671
  }
6276
6672
  /**
6673
+ * Report whether a registered provider advertises a model in its current
6674
+ * catalog. Catalog-driven entry points use it to accept only listed models.
6675
+ * @param provider - provider route to inspect.
6676
+ * @param model - provider-owned model id.
6677
+ * @returns false when the provider is unregistered or its catalog omits the model.
6678
+ * @throws the provider's catalog failure, unchanged.
6679
+ */
6680
+ async isModelInCatalog(provider, model) {
6681
+ if (!this.adapters.has(provider)) return false;
6682
+ return (await this.listModels(provider)).some((entry) => entry.id === model);
6683
+ }
6684
+ /**
6277
6685
  * Resolve and validate all metadata from the adapter that owns one exact
6278
6686
  * route. The result is detached from adapter-owned objects; catalog
6279
6687
  * membership remains advisory and does not control request routing.
@@ -6600,12 +7008,22 @@ function detachDirectoryEntry(entry) {
6600
7008
  };
6601
7009
  }
6602
7010
  //#endregion
6603
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.3_c6df380a2007cdef080fa53578fb6f5f/node_modules/@deepseek-ai/dsh-tools/lib/shared-DGx6D7zk.js
6604
- /** The selected provider is missing or unloaded; another provider must not take its calls. */
6605
- var ToolExecutorUnavailableError = class extends HarnessError {
7011
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.3-alpha.4_ca12df44b3bbe3a755034ba57f11ee40/node_modules/@deepseek-ai/dsh-tools/lib/shared-DzeEFgIh.js
7012
+ /** Composable tool registries and the batches `ctx.tools.execute()` runs. @module */
7013
+ /** A drained batch failed internally; only the included results are committed. */
7014
+ var ToolBatchExecutionError = class extends Error {
7015
+ partial;
7016
+ constructor(cause, partial) {
7017
+ super("Tool batch execution failed", { cause });
7018
+ this.partial = partial;
7019
+ this.name = "ToolBatchExecutionError";
7020
+ }
7021
+ };
7022
+ /** The selected root registry is missing or unloaded; another registry must not take its calls. */
7023
+ var ToolRegistryUnavailableError = class extends HarnessError {
6606
7024
  constructor() {
6607
- super("The selected tool executor is unavailable. Load an executor in this composition before running the agent.", "TOOL_EXECUTOR_UNAVAILABLE");
6608
- this.name = "ToolExecutorUnavailableError";
7025
+ super("The selected tool registry is unavailable. Load a native or PTC tool registry in this composition before running the agent.", "TOOL_REGISTRY_UNAVAILABLE");
7026
+ this.name = "ToolRegistryUnavailableError";
6609
7027
  }
6610
7028
  };
6611
7029
  /**
@@ -7121,276 +7539,1256 @@ function checkValue(schema, value, path) {
7121
7539
  function validateJsonSchemaValue(schema, value, path = "value") {
7122
7540
  return checkValue(schema, value, path);
7123
7541
  }
7124
- /** Tool definitions and invocation data shared by registries and executors. @module */
7542
+ /**
7543
+ * Error identities the registry records on failed tool results. The values are
7544
+ * persisted contract; the entry does not re-export them, and consumers compare
7545
+ * the recorded strings.
7546
+ * @module
7547
+ */
7548
+ /** Error name the registry records when approval does not grant a call. */
7549
+ const APPROVAL_ERROR_NAME = "ApprovalError";
7550
+ /** Approval code for a call the user rejected. */
7551
+ const APPROVAL_REJECTED = "APPROVAL_REJECTED";
7552
+ /** Approval code for an approval request cancelled without a caller cancellation. */
7553
+ const APPROVAL_CANCELLED = "APPROVAL_CANCELLED";
7554
+ /** Approval code for a call that needs approval when no approval service, Agent, or channel can answer it. */
7555
+ const APPROVAL_UNAVAILABLE = "APPROVAL_UNAVAILABLE";
7556
+ /** Code of `EnvironmentUnsupportedError`. */
7557
+ const ENVIRONMENT_UNSUPPORTED = "ENVIRONMENT_UNSUPPORTED";
7558
+ /** Tool definitions and invocation data shared by tool registries. @module */
7125
7559
  /** Reserved model-facing program transport name. */
7126
7560
  const RUN_CODE_NAME = "run_code";
7127
- /** Failure to determine a tool's step-time availability. */
7128
- var ToolActivationError = class extends HarnessError {
7561
+ /**
7562
+ * A tool name resolves to more than one candidate in the scope that decides it,
7563
+ * or a registry inclusion reaches the registry that is being queried.
7564
+ */
7565
+ var ToolCompositionError = class extends HarnessError {
7129
7566
  /**
7130
- * Preserve a condition failure without treating it as normal unavailability.
7131
- * @param name - tool whose condition rejected.
7132
- * @param cause - underlying condition failure.
7567
+ * @param message - names the ambiguous tool or the inclusion cycle.
7133
7568
  */
7134
- constructor(name, cause) {
7135
- super(`cannot resolve availability of tool "${name}"`, "TOOL_ACTIVATION_FAILED", { cause });
7136
- this.name = "ToolActivationError";
7569
+ constructor(message) {
7570
+ super(message, "INVALID_TOOL_COMPOSITION");
7571
+ this.name = "ToolCompositionError";
7137
7572
  }
7138
7573
  };
7139
- //#endregion
7140
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-scope/lib/index.js
7574
+ /** A call targets a non-local environment that its tool does not support. */
7575
+ var EnvironmentUnsupportedError = class extends HarnessError {
7576
+ toolName;
7577
+ environment;
7578
+ /**
7579
+ * @param toolName - called tool.
7580
+ * @param environment - environment the call targets.
7581
+ */
7582
+ constructor(toolName, environment) {
7583
+ super(`tool "${toolName}" runs only in the local environment, but this call targets environment "${environment}"; switch back to the local environment or use a tool that supports environments`, ENVIRONMENT_UNSUPPORTED);
7584
+ this.toolName = toolName;
7585
+ this.environment = environment;
7586
+ this.name = "EnvironmentUnsupportedError";
7587
+ }
7588
+ };
7589
+ /** Canonical error code for cancellation after a tool body was invoked. */
7590
+ const TOOL_ABORTED = "ABORTED";
7591
+ /** Canonical error code for cancellation before a tool body was invoked. */
7592
+ const TOOL_ABORTED_BEFORE_DISPATCH = "ABORTED_BEFORE_DISPATCH";
7141
7593
  /**
7142
- * Shared insertion-ordered storage and effect ownership for scope-aware registries.
7143
- *
7144
- * @module @deepseek-ai/dsh-scope
7594
+ * Thrown (internally) when a call names no definition its caller may execute.
7595
+ * Extends {@link HarnessError} (`code: 'UNKNOWN_TOOL'`) so an unknown-tool
7596
+ * failure is as routable as a tool-thrown one — retry/sandbox/replay code can
7597
+ * distinguish it from a tool body's own error.
7145
7598
  */
7599
+ var ToolNotFoundError = class extends HarnessError {
7600
+ /**
7601
+ * @param toolName - the name the caller asked for.
7602
+ * @param callable - the entries the caller can call directly, which the message
7603
+ * lists; given when the name is a tool the caller can reach only from those
7604
+ * entries, such as a program binding, and omitted otherwise. An empty list
7605
+ * adds nothing to the message.
7606
+ */
7607
+ constructor(toolName, callable = []) {
7608
+ super(callable.length === 0 ? `unknown tool "${toolName}"` : `unknown tool "${toolName}"; tools you can call directly: ${callable.join(", ")}`, "UNKNOWN_TOOL");
7609
+ this.name = "ToolNotFoundError";
7610
+ }
7611
+ };
7612
+ /** Thrown when a tool body or post-policy value violates its declared output. */
7613
+ var ToolOutputError = class extends HarnessError {
7614
+ /** Schema/value violations in validation order. */
7615
+ violations;
7616
+ constructor(toolName, violations) {
7617
+ super(`tool "${toolName}" returned invalid output: ${violations.join("; ")}`, "INVALID_TOOL_OUTPUT");
7618
+ this.name = "ToolOutputError";
7619
+ this.violations = violations;
7620
+ }
7621
+ };
7622
+ /** Flat registrations and live inclusions shared by registry implementations. @module */
7623
+ /** Several different definitions that one place offers under one name. */
7624
+ var AmbiguousCandidate = class {
7625
+ definitions;
7626
+ /** @param definitions - the conflicting definitions in the order the place offers them. */
7627
+ constructor(definitions) {
7628
+ this.definitions = definitions;
7629
+ }
7630
+ };
7146
7631
  /**
7147
- * Insertion-ordered named entries with caller-owned duplicate diagnostics.
7148
- *
7149
- * Values are borrowed. Iterators are live within one nonempty table
7150
- * generation; draining the table detaches them from later insertions. Each
7151
- * successful insertion returns an idempotent undo for that exact entry.
7632
+ * Add one definition to a place's candidate for its name; the same definition
7633
+ * reached twice stays one candidate, and different definitions conflict.
7634
+ * @param existing - the candidate collected so far, if any.
7635
+ * @param definition - a definition the place offers under the same name.
7636
+ * @returns the merged candidate.
7152
7637
  */
7153
- var NamedEntries = class {
7154
- duplicateError;
7155
- data = /* @__PURE__ */ new Map();
7156
- constructor(duplicateError) {
7157
- this.duplicateError = duplicateError;
7638
+ function mergeToolCandidate(existing, definition) {
7639
+ if (existing === void 0 || existing === definition) return definition;
7640
+ const definitions = existing instanceof AmbiguousCandidate ? existing.definitions : [existing];
7641
+ return definitions.includes(definition) ? existing : new AmbiguousCandidate([...definitions, definition]);
7642
+ }
7643
+ /**
7644
+ * Validate one definition before a registry retains it.
7645
+ * @param definition - definition supplied to `register()`.
7646
+ * @throws TypeError when the output declaration or timeout is invalid.
7647
+ * @throws Error when the definition uses the reserved `run_code` name.
7648
+ */
7649
+ function assertToolDefinition(definition) {
7650
+ const name = definition.name;
7651
+ const output = definition.output;
7652
+ 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? }`);
7653
+ assertSupportedJsonSchema(output.schema);
7654
+ const timeoutMs = definition.timeoutMs;
7655
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new TypeError(`tool "${name}" timeoutMs must be a positive finite number`);
7656
+ if (name === "run_code") throw new Error(`tool name "${RUN_CODE_NAME}" is reserved for the PTC program entry and cannot be registered or shadowed`);
7657
+ }
7658
+ /**
7659
+ * Collect one place's candidates: its own registrations, then the entries of
7660
+ * each included registry for the viewing scope. The same definition reached
7661
+ * twice stays one candidate; different definitions under one name conflict.
7662
+ * @param own - definitions this place offers itself; a repeated name merges like an included one.
7663
+ * @param sources - registries included in this place.
7664
+ * @param scope - viewing scope passed to every included registry.
7665
+ * @returns candidates by name in first-seen order.
7666
+ */
7667
+ function collectToolCandidates(own, sources, scope) {
7668
+ const candidates = /* @__PURE__ */ new Map();
7669
+ const add = (definition) => {
7670
+ candidates.set(definition.name, mergeToolCandidate(candidates.get(definition.name), definition));
7671
+ };
7672
+ for (const definition of own) add(definition);
7673
+ for (const source of sources) for (const definition of source.getAll(scope)) add(definition);
7674
+ return candidates;
7675
+ }
7676
+ /**
7677
+ * Find one name among a place's registration and its included registries.
7678
+ * @param own - the place's own registration with the name, if any.
7679
+ * @param sources - registries included in the place.
7680
+ * @param name - tool name to find.
7681
+ * @param scope - viewing scope passed to every included registry.
7682
+ * @returns the definition, the conflicting definitions when several differ, or undefined.
7683
+ */
7684
+ function findToolCandidate(own, sources, name, scope) {
7685
+ let found = own;
7686
+ for (const source of sources) {
7687
+ const definition = source.get(name, scope);
7688
+ if (definition !== void 0) found = mergeToolCandidate(found, definition);
7158
7689
  }
7159
- /**
7160
- * Insert one unique name.
7161
- * @param name - name unique within this table.
7162
- * @param value - borrowed value to retain.
7163
- * @returns an idempotent undo that removes only this insertion.
7164
- */
7165
- insert(name, value) {
7166
- const data = this.data;
7167
- if (data.has(name)) throw this.duplicateError(name);
7168
- data.set(name, value);
7169
- let active = true;
7170
- return () => {
7171
- if (!active) return;
7172
- active = false;
7173
- data.delete(name);
7174
- if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
7690
+ return found;
7691
+ }
7692
+ /**
7693
+ * Resolve one deciding candidate.
7694
+ * @param name - tool name being resolved.
7695
+ * @param candidate - the deciding place's candidate, if any.
7696
+ * @returns the definition, or undefined when no place offers the name.
7697
+ * @throws ToolCompositionError when the deciding place offers several definitions.
7698
+ */
7699
+ function resolveToolCandidate(name, candidate) {
7700
+ if (candidate instanceof AmbiguousCandidate) throw ambiguousTool(name, candidate);
7701
+ return candidate;
7702
+ }
7703
+ /**
7704
+ * Resolve every visible candidate.
7705
+ * @param candidates - deciding candidates by name.
7706
+ * @returns definitions in candidate order.
7707
+ * @throws ToolCompositionError when any visible name is ambiguous.
7708
+ */
7709
+ function resolveToolCandidates(candidates) {
7710
+ const definitions = [];
7711
+ for (const [name, candidate] of candidates) {
7712
+ if (candidate instanceof AmbiguousCandidate) throw ambiguousTool(name, candidate);
7713
+ definitions.push(candidate);
7714
+ }
7715
+ return definitions;
7716
+ }
7717
+ /**
7718
+ * List every definition of the candidates, keeping each conflict's definitions
7719
+ * so a registry that includes this list decides the name in its own place.
7720
+ * @param candidates - candidates by name.
7721
+ * @returns definitions in candidate order.
7722
+ */
7723
+ function listToolCandidates(candidates) {
7724
+ return [...candidates.values()].flatMap((candidate) => candidate instanceof AmbiguousCandidate ? candidate.definitions : [candidate]);
7725
+ }
7726
+ /**
7727
+ * Resolve a registry listing to one definition per name.
7728
+ * @param definitions - a registry's `getAll()` result.
7729
+ * @returns definitions in first-seen order.
7730
+ * @throws ToolCompositionError when the listing offers several definitions under one name.
7731
+ */
7732
+ function resolveToolList(definitions) {
7733
+ return resolveToolCandidates(collectToolCandidates(definitions, [], void 0));
7734
+ }
7735
+ /**
7736
+ * Build the failure for a name with several definitions in the place that
7737
+ * decides it. The message quotes the first line of each definition's
7738
+ * description so a developer can find the plugins that register them.
7739
+ */
7740
+ function ambiguousTool(name, candidate) {
7741
+ return new ToolCompositionError(`tool "${name}" has several definitions in the scope that decides it (described as ${candidate.definitions.map((definition) => JSON.stringify(summaryLine(definition.description))).join(", ")}); register or include one definition per name`);
7742
+ }
7743
+ /** The first line of a description, shortened for a diagnostic. */
7744
+ function summaryLine(description) {
7745
+ const line = description.split("\n", 1).join("");
7746
+ return line.length > 80 ? `${line.slice(0, 79)}…` : line;
7747
+ }
7748
+ /**
7749
+ * Execute raw calls with ordered policy and results around overlapping tool bodies.
7750
+ * Abort drains started calls and synthesizes results for skipped calls. Internal
7751
+ * failures drain before rejecting with the already committed results and context.
7752
+ * Concurrency-safe calls run at most `input.maxParallelToolCalls` at once, or
7753
+ * {@link DEFAULT_MAX_PARALLEL_TOOL_CALLS} without an override.
7754
+ * @param input - raw calls, optional concurrency override, and optional Session owner.
7755
+ * @param pipeline - invocation stages that resolve each call's definition.
7756
+ * @returns model-ordered outcomes after every started body has settled.
7757
+ * @throws RangeError when the explicit concurrency override is not a positive integer.
7758
+ */
7759
+ async function executeToolBatch(input, pipeline) {
7760
+ const { calls: toolCalls, signal, agent, toolStep, maxParallelToolCalls } = input;
7761
+ if (maxParallelToolCalls !== void 0 && (!Number.isInteger(maxParallelToolCalls) || maxParallelToolCalls < 1)) throw new RangeError("maxParallelToolCalls must be a positive integer");
7762
+ const settlement = new BatchSettlement(input);
7763
+ try {
7764
+ const planned = toolCalls.map((block) => ({
7765
+ block,
7766
+ exec: {
7767
+ callId: block.id,
7768
+ name: block.name,
7769
+ arguments: parseArguments(block.arguments),
7770
+ ...agent === void 0 ? {} : { agent },
7771
+ ...toolStep === void 0 ? {} : { toolStep },
7772
+ signal
7773
+ }
7774
+ }));
7775
+ let next = 0;
7776
+ let concluded = false;
7777
+ while (next < planned.length) {
7778
+ const first = planned[next];
7779
+ const mode = pipeline.executionMode(first.exec).kind;
7780
+ const group = mode === "parallel" ? planned.slice(next) : [first];
7781
+ const outcome = await runGroup(pipeline, settlement, maxParallelToolCalls ?? 10, group, mode, signal);
7782
+ next += outcome.consumed;
7783
+ concluded ||= outcome.concluded;
7784
+ if (outcome.aborted) {
7785
+ for (const call of planned.slice(next)) settlement.skip(call.block);
7786
+ return settlement.result(concluded);
7787
+ }
7788
+ }
7789
+ return settlement.result(concluded);
7790
+ } catch (error) {
7791
+ throw new ToolBatchExecutionError(error, settlement.result());
7792
+ }
7793
+ }
7794
+ /** Parse model arguments, preserving invalid JSON as text and mapping empty input to `{}`. */
7795
+ function parseArguments(raw) {
7796
+ try {
7797
+ return raw ? JSON.parse(raw) : {};
7798
+ } catch (_error) {
7799
+ return raw;
7800
+ }
7801
+ }
7802
+ /**
7803
+ * Run one exclusive barrier or parallel pool. Later calls are reclassified
7804
+ * before start; an exclusive reclassification waits for the current pool to
7805
+ * drain and remains for the caller's next barrier. Results and contexts commit
7806
+ * in model order. Abort stops starts, drains and commits started calls, accepts
7807
+ * their contexts into the owning batch, records results for skipped calls, and
7808
+ * returns an aborted outcome. Scheduler failure drains dispatches and rejects
7809
+ * for the owning step to record recovery results.
7810
+ */
7811
+ async function runGroup(pipeline, settlement, maxParallelToolCalls, group, mode, signal) {
7812
+ const slots = group.map(() => void 0);
7813
+ const callSeqs = group.map(() => void 0);
7814
+ let nextToStart = 0;
7815
+ let committed = 0;
7816
+ let started = 0;
7817
+ let aborted = signal.aborted;
7818
+ let concluded = false;
7819
+ let schedulerFailure;
7820
+ const throwSchedulerFailure = () => {
7821
+ if (schedulerFailure !== void 0) throw schedulerFailure.error;
7822
+ };
7823
+ const commitReady = async () => {
7824
+ while (committed < group.length) {
7825
+ const slot = slots[committed];
7826
+ if (slot === void 0) break;
7827
+ const call = group[committed];
7828
+ const result = await pipeline.complete(slot.exec, slot);
7829
+ settlement.commit(call.block, result, callSeqs[committed]);
7830
+ concluded ||= result.concludesTurn === true;
7831
+ committed++;
7832
+ }
7833
+ };
7834
+ const inFlight = /* @__PURE__ */ new Map();
7835
+ const startCall = async (index) => {
7836
+ const call = group[index];
7837
+ callSeqs[index] = settlement.start(call.block);
7838
+ started++;
7839
+ const prepared = await pipeline.prepare(call.exec);
7840
+ throwSchedulerFailure();
7841
+ switch (prepared.kind) {
7842
+ case "dispatch": {
7843
+ const promise = pipeline.dispatch(prepared.exec).then((outcome) => {
7844
+ slots[index] = {
7845
+ ...outcome,
7846
+ exec: prepared.exec
7847
+ };
7848
+ return index;
7849
+ }, (error) => {
7850
+ schedulerFailure ??= { error };
7851
+ return index;
7852
+ });
7853
+ inFlight.set(index, promise);
7854
+ break;
7855
+ }
7856
+ case "post-result":
7857
+ case "final-result":
7858
+ slots[index] = prepared;
7859
+ break;
7860
+ /* v8 ignore next -- closed-union exhaustiveness guard */
7861
+ default: assertNever(prepared, "tool-call scheduler prepare result");
7862
+ }
7863
+ };
7864
+ const fillPool = async () => {
7865
+ while (!aborted && nextToStart < group.length && inFlight.size < maxParallelToolCalls) {
7866
+ const nextCall = group[nextToStart];
7867
+ if (nextToStart > 0 && mode === "parallel" && pipeline.executionMode(nextCall.exec).kind !== "parallel") break;
7868
+ await startCall(nextToStart);
7869
+ nextToStart++;
7870
+ throwSchedulerFailure();
7871
+ await commitReady();
7872
+ throwSchedulerFailure();
7873
+ if (signal.aborted) aborted = true;
7874
+ }
7875
+ };
7876
+ try {
7877
+ await fillPool();
7878
+ while (inFlight.size > 0) {
7879
+ const settledIndex = await Promise.race(inFlight.values());
7880
+ inFlight.delete(settledIndex);
7881
+ throwSchedulerFailure();
7882
+ await commitReady();
7883
+ throwSchedulerFailure();
7884
+ if (signal.aborted) aborted = true;
7885
+ await fillPool();
7886
+ }
7887
+ } catch (error) {
7888
+ schedulerFailure ??= { error };
7889
+ await Promise.allSettled(inFlight.values());
7890
+ throw schedulerFailure.error;
7891
+ }
7892
+ if (aborted) {
7893
+ for (const call of group.slice(started)) settlement.skip(call.block);
7894
+ return {
7895
+ consumed: group.length,
7896
+ aborted: true,
7897
+ concluded
7175
7898
  };
7176
7899
  }
7900
+ /* v8 ignore next -- unreachable: a non-aborted group commits every started call */
7901
+ if (committed !== started) throw new Error("tool-call scheduler: uncommitted settled calls");
7902
+ return {
7903
+ consumed: started,
7904
+ aborted: false,
7905
+ concluded
7906
+ };
7907
+ }
7908
+ /** Collect committed results and optionally append their durable Session events. */
7909
+ var BatchSettlement = class {
7910
+ input;
7911
+ results = [];
7912
+ contexts = [];
7913
+ constructor(input) {
7914
+ this.input = input;
7915
+ }
7916
+ start(block) {
7917
+ if (this.input.log === void 0) return void 0;
7918
+ const { agent, log: { turn, step } } = this.input;
7919
+ return agent.session.append("tool/call", {
7920
+ turn,
7921
+ step,
7922
+ callId: block.id,
7923
+ name: block.name,
7924
+ arguments: block.arguments
7925
+ }).seq;
7926
+ }
7927
+ commit(block, result, callSeq) {
7928
+ if (this.input.log !== void 0) {
7929
+ const { agent, log: { turn, step } } = this.input;
7930
+ agent.session.append("tool/result", {
7931
+ turn,
7932
+ step,
7933
+ message: createToolResultMessage({
7934
+ callId: block.id,
7935
+ content: result.content,
7936
+ isError: result.isError
7937
+ }),
7938
+ ...result.error?.info ? { error: result.error.info } : {},
7939
+ ...result.meta !== void 0 ? { meta: result.meta } : {}
7940
+ }, {
7941
+ surfaceOp: "append",
7942
+ sourceEventSeqs: [callSeq]
7943
+ });
7944
+ }
7945
+ this.results.push({
7946
+ callId: block.id,
7947
+ result
7948
+ });
7949
+ this.contexts.push(...result.additionalContexts ?? []);
7950
+ }
7951
+ skip(block) {
7952
+ this.commit(block, {
7953
+ content: [{
7954
+ type: "text",
7955
+ text: "Error: tool call aborted before dispatch"
7956
+ }],
7957
+ isError: true,
7958
+ error: {
7959
+ message: "tool call aborted before dispatch",
7960
+ info: {
7961
+ name: "AbortError",
7962
+ code: TOOL_ABORTED_BEFORE_DISPATCH
7963
+ }
7964
+ }
7965
+ }, this.start(block));
7966
+ }
7967
+ result(concluded = this.results.some(({ result }) => result.concludesTurn === true)) {
7968
+ return {
7969
+ results: this.results,
7970
+ additionalContexts: this.contexts,
7971
+ concluded
7972
+ };
7973
+ }
7974
+ };
7975
+ /**
7976
+ * Shared invocation stages for batch and program schedulers. Schedulers order
7977
+ * prepare and complete calls while dispatch may overlap. Use executeToolBatch
7978
+ * for complete calls, including a single-call batch.
7979
+ */
7980
+ var ToolExecutionPipeline = class {
7981
+ ctx;
7982
+ source;
7983
+ tools;
7177
7984
  /**
7178
- * Read one named value.
7179
- * @param name - name to resolve.
7180
- * @returns the retained value, or `undefined` when absent.
7985
+ * @param ctx - registry context owning policy events and approval lookup.
7986
+ * @param source - registry lookup and refusals for every call this pipeline runs.
7181
7987
  */
7182
- get(name) {
7183
- return this.data.get(name);
7988
+ constructor(ctx, source) {
7989
+ this.ctx = ctx;
7990
+ this.source = source;
7991
+ this.tools = ctx.tools;
7992
+ }
7993
+ resolveExecution(exec) {
7994
+ return this.source.get(exec.name, exec.agent, exec.toolStep);
7184
7995
  }
7185
7996
  /**
7186
- * Test one name for membership.
7187
- * @param name - name to test.
7188
- * @returns whether the table contains that name.
7997
+ * Run one source lookup or refusal for a call being prepared or dispatched.
7998
+ * A composition failure, such as two definitions that appear under the
7999
+ * call's name during a step, is logged once with its message, and the call
8000
+ * fails with a message the model can act on.
8001
+ * @param call - name, call id, and Agent of the call the lookup serves.
8002
+ * @param lookup - source lookup or refusal.
8003
+ * @returns the lookup result.
8004
+ * @throws ToolCompositionError with the model-facing message when the lookup meets a composition failure.
7189
8005
  */
7190
- has(name) {
7191
- return this.data.has(name);
8006
+ lookup(call, lookup) {
8007
+ try {
8008
+ return lookup();
8009
+ } catch (error) {
8010
+ if (!(error instanceof ToolCompositionError)) throw error;
8011
+ const caller = call.agent === void 0 ? "" : ` from Agent ${call.agent.id}`;
8012
+ this.ctx.logger.warn(`tool "${call.name}" (call ${call.callId}${caller}) cannot run: ${error.message}`);
8013
+ throw new ToolCompositionError(`tool "${call.name}" cannot run because it is misconfigured in this environment; do not retry it; use another tool or tell the user`);
8014
+ }
7192
8015
  }
7193
8016
  /**
7194
- * Iterate live names in insertion order.
7195
- * @returns the native live key iterator.
8017
+ * The definition prepare captured for one call, while the source still offers exactly it; checked as dispatch starts.
8018
+ * @throws ToolNotFoundError when prepare captured none or the source now resolves another definition or none.
8019
+ * @throws ToolCompositionError when the lookup meets a composition failure.
7196
8020
  */
7197
- keys() {
7198
- return this.data.keys();
8021
+ capturedDefinition(exec) {
8022
+ const definition = this.dispatchedDefinition(exec);
8023
+ if (this.lookup(exec, () => this.resolveExecution(exec)) !== definition) throw new ToolNotFoundError(exec.name);
8024
+ return definition;
7199
8025
  }
7200
8026
  /**
7201
- * Iterate live entries in insertion order.
7202
- * @returns the native live entry iterator.
8027
+ * The definition whose output contract a dispatched call's result follows. A
8028
+ * call that started keeps it even if its source withdraws the tool meanwhile.
8029
+ * @throws ToolNotFoundError when prepare captured no definition.
7203
8030
  */
7204
- entries() {
7205
- return this.data.entries();
7206
- }
8031
+ dispatchedDefinition(exec) {
8032
+ const definition = exec.definition;
8033
+ if (definition === void 0) throw new ToolNotFoundError(exec.name);
8034
+ return definition;
8035
+ }
8036
+ /** Context deferred by a running tool body, keyed by its scheduler-owned execution. */
8037
+ deferredContexts = /* @__PURE__ */ new WeakMap();
8038
+ /** Executions whose tool body declared the current turn complete. */
8039
+ concludingExecutions = /* @__PURE__ */ new WeakSet();
8040
+ /** Original caller cancellation, kept outside the wrapper-mutable execution object. */
8041
+ cancellationStates = /* @__PURE__ */ new WeakMap();
8042
+ /** Definition-owned final content transform snapshotted before policy begins. */
8043
+ contentFinalizers = /* @__PURE__ */ new WeakMap();
8044
+ /** Execution-prepared content installed before post-execute policy. */
8045
+ contentProjectors = /* @__PURE__ */ new WeakMap();
7207
8046
  /**
7208
- * Iterate live values in insertion order.
7209
- * @returns the native live value iterator.
8047
+ * Classify a pending call through the caller's visible tool definition. Only
8048
+ * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or
8049
+ * throwing classifiers are exclusive, and so is a call whose lookup throws,
8050
+ * which preparation then fails alone.
8051
+ * @param exec - call name, parsed arguments, and optional agent scope.
8052
+ * @returns the fail-closed scheduling mode.
7210
8053
  */
7211
- values() {
7212
- return this.data.values();
8054
+ executionMode(exec) {
8055
+ try {
8056
+ const tool = this.resolveExecution(exec);
8057
+ if (!tool?.isConcurrencySafe) return { kind: "exclusive" };
8058
+ return tool.isConcurrencySafe(exec.arguments) === true ? { kind: "parallel" } : { kind: "exclusive" };
8059
+ } catch {
8060
+ return { kind: "exclusive" };
8061
+ }
8062
+ }
8063
+ createExecution(exec) {
8064
+ const deferredContexts = [];
8065
+ const token = createExecutionToken();
8066
+ const callId = exec.callId;
8067
+ const rootCallId = exec.rootCallId ?? callId;
8068
+ const name = exec.name;
8069
+ const agent = exec.agent;
8070
+ const parent = exec.parent;
8071
+ const signal = exec.signal;
8072
+ let visible;
8073
+ let refusal;
8074
+ try {
8075
+ const call = {
8076
+ name,
8077
+ callId,
8078
+ ...agent !== void 0 ? { agent } : {}
8079
+ };
8080
+ visible = this.lookup(call, () => this.source.get(name, agent, exec.toolStep));
8081
+ const rejection = this.lookup(call, () => this.source.reject?.(exec));
8082
+ if (rejection !== void 0) refusal = { error: rejection };
8083
+ } catch (error) {
8084
+ refusal = { error };
8085
+ }
8086
+ if (refusal !== void 0) visible = void 0;
8087
+ let capturedFinalizer = visible?.finalizeContent?.bind(visible);
8088
+ const capturedProjector = visible?.projectContent?.bind(visible);
8089
+ let args;
8090
+ try {
8091
+ const detached = snapshotJsonValue(exec.arguments);
8092
+ if (detached === void 0) throw new TypeError("tool execution arguments must be losslessly JSON-serializable");
8093
+ args = { value: deepFreeze(detached) };
8094
+ } catch (error) {
8095
+ args = { error };
8096
+ }
8097
+ let environment;
8098
+ if (visible !== void 0 && "value" in args) try {
8099
+ environment = this.resolveCallEnvironment({
8100
+ callId,
8101
+ rootCallId,
8102
+ name,
8103
+ signal,
8104
+ arguments: args.value,
8105
+ ...agent !== void 0 ? { agent } : {},
8106
+ ...exec.toolStep !== void 0 ? { toolStep: exec.toolStep } : {},
8107
+ ...parent !== void 0 ? { parent } : {}
8108
+ }, visible);
8109
+ } catch (error) {
8110
+ refusal = { error };
8111
+ visible = void 0;
8112
+ capturedFinalizer = void 0;
8113
+ }
8114
+ const concludingExecutions = this.concludingExecutions;
8115
+ const base = {
8116
+ token,
8117
+ callId,
8118
+ rootCallId,
8119
+ name,
8120
+ signal,
8121
+ ...agent !== void 0 ? { agent } : {},
8122
+ ...exec.toolStep !== void 0 ? { toolStep: exec.toolStep } : {},
8123
+ ...visible !== void 0 ? { definition: visible } : {},
8124
+ ...parent !== void 0 ? { parent } : {},
8125
+ ...exec.schema !== void 0 ? { schema: exec.schema } : {},
8126
+ ...environment !== void 0 ? { environment } : {},
8127
+ deferContext(context) {
8128
+ deferredContexts.push(context);
8129
+ },
8130
+ concludeTurn() {
8131
+ concludingExecutions.add(this);
8132
+ }
8133
+ };
8134
+ if ("error" in args) {
8135
+ const execution = {
8136
+ ...base,
8137
+ arguments: void 0
8138
+ };
8139
+ this.contentFinalizers.set(execution, capturedFinalizer);
8140
+ return {
8141
+ kind: "final-result",
8142
+ exec: execution,
8143
+ result: toolErrorResult(args.error)
8144
+ };
8145
+ }
8146
+ const execution = {
8147
+ ...base,
8148
+ arguments: args.value
8149
+ };
8150
+ this.deferredContexts.set(execution, deferredContexts);
8151
+ this.contentFinalizers.set(execution, capturedFinalizer);
8152
+ this.cancellationStates.set(execution, {
8153
+ callerSignal: signal,
8154
+ bodyInvoked: false
8155
+ });
8156
+ if (refusal !== void 0) return {
8157
+ kind: "final-result",
8158
+ exec: execution,
8159
+ result: signal.aborted ? toolAbortedBeforeDispatchResult() : toolErrorResult(refusal.error)
8160
+ };
8161
+ this.contentProjectors.set(execution, capturedProjector);
8162
+ return {
8163
+ kind: "ready",
8164
+ exec: execution
8165
+ };
7213
8166
  }
7214
8167
  /**
7215
- * Test whether this table has no entries.
7216
- * @returns whether the table is empty.
8168
+ * The target one call runs in: none for an `'explicit'` or `'independent'`
8169
+ * tool; otherwise a program call inherits the target its enclosing execution
8170
+ * was prepared with, and a root call asks its definition. The definition must
8171
+ * support it.
8172
+ * @param exec - the call with its snapshotted arguments.
8173
+ * @param definition - the definition the call resolved.
8174
+ * @returns the target, or undefined for the local environment.
8175
+ * @throws EnvironmentUnsupportedError when the definition does not support the environment.
7217
8176
  */
7218
- isEmpty() {
7219
- return this.data.size === 0;
8177
+ resolveCallEnvironment(exec, definition) {
8178
+ if (definition.environment === "explicit" || definition.environment === "independent") return void 0;
8179
+ const environment = exec.parent === void 0 ? definition.resolveEnvironment?.(exec.arguments, exec) : exec.parent.environment;
8180
+ if (environment !== void 0 && definition.environment !== "bound") throw new EnvironmentUnsupportedError(definition.name, environment.id);
8181
+ return environment;
7220
8182
  }
7221
- };
7222
- /**
7223
- * Insertion-ordered anonymous entries with independent registration identity.
7224
- *
7225
- * Equal values remain separate registrations. Values are borrowed, and
7226
- * iterators are live within one nonempty table generation; draining the table
7227
- * detaches them from later appends.
7228
- */
7229
- var AnonymousEntries = class {
7230
- data = /* @__PURE__ */ new Map();
7231
8183
  /**
7232
- * Append one independently owned value.
7233
- * @param value - borrowed value to retain.
7234
- * @returns an idempotent undo for this exact append.
8184
+ * Snapshot input, assign its correlation token, settle a call the source
8185
+ * refuses, and run ordered pre-execute policy and guards for the others.
8186
+ * A refused call reaches no policy, approval, guard, or execution wrapper.
8187
+ * Cancellation skips a body that has not started and takes precedence over
8188
+ * a refusal.
8189
+ * @param input - the caller-supplied execution input.
8190
+ * @returns the prepared execution plus the next scheduler stage.
7235
8191
  */
7236
- append(value) {
7237
- const data = this.data;
7238
- const key = Symbol();
7239
- data.set(key, value);
7240
- let active = true;
7241
- return () => {
7242
- if (!active) return;
7243
- active = false;
7244
- data.delete(key);
7245
- if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
8192
+ async prepare(input) {
8193
+ const created = this.createExecution(input);
8194
+ if (created.kind !== "ready") return created;
8195
+ const exec = created.exec;
8196
+ if (this.callerCancelled(exec)) return {
8197
+ kind: "final-result",
8198
+ exec,
8199
+ result: toolAbortedBeforeDispatchResult()
7246
8200
  };
8201
+ try {
8202
+ const carrier = scopeTarget(this.tools, exec.agent);
8203
+ const gate = await this.ctx.waterfall(carrier, "tools/pre-execute", exec, () => Promise.resolve({ kind: "allow" }));
8204
+ const askResolution = gate.kind === "ask" ? await this.serviceAsk(exec, gate) : {
8205
+ decision: gate,
8206
+ approvalCancelled: false
8207
+ };
8208
+ const { decision } = askResolution;
8209
+ if (this.callerCancelled(exec) && askResolution.approvalCancelled) return {
8210
+ kind: "post-result",
8211
+ exec,
8212
+ result: toolAbortedBeforeDispatchResult()
8213
+ };
8214
+ if (decision.kind === "cancel") return {
8215
+ kind: "post-result",
8216
+ exec,
8217
+ result: toolAbortedBeforeDispatchResult()
8218
+ };
8219
+ const denial = decision.kind === "allow" ? this.tools.checkGuards(exec) : decision;
8220
+ if (denial !== void 0) {
8221
+ const { reason: denialReason, info: denialInfo } = denial;
8222
+ return {
8223
+ kind: "post-result",
8224
+ exec,
8225
+ result: this.materializeFinalResult({
8226
+ content: [{
8227
+ type: "text",
8228
+ text: `Error: ${denialReason}`
8229
+ }],
8230
+ isError: true,
8231
+ error: {
8232
+ message: denialReason,
8233
+ ...denialInfo === void 0 ? {} : { info: denialInfo }
8234
+ }
8235
+ })
8236
+ };
8237
+ }
8238
+ if (this.callerCancelled(exec)) return {
8239
+ kind: "post-result",
8240
+ exec,
8241
+ result: toolAbortedBeforeDispatchResult()
8242
+ };
8243
+ return {
8244
+ kind: "dispatch",
8245
+ exec
8246
+ };
8247
+ } catch (error) {
8248
+ return {
8249
+ kind: "final-result",
8250
+ exec,
8251
+ result: toolErrorResult(error)
8252
+ };
8253
+ }
8254
+ }
8255
+ /** Whether the original caller signal is currently aborted. */
8256
+ callerCancelled(exec) {
8257
+ const state = this.cancellationStates.get(exec);
8258
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
8259
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
8260
+ return state.callerSignal.aborted;
8261
+ }
8262
+ /** Canonical cancellation outcome selected by whether the tool body started. */
8263
+ cancellationResult(exec, prior) {
8264
+ const state = this.cancellationStates.get(exec);
8265
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
8266
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
8267
+ return state.bodyInvoked ? toolAbortedResult(prior) : toolAbortedBeforeDispatchResult(prior);
7247
8268
  }
7248
8269
  /**
7249
- * Iterate live values in insertion order.
7250
- * @returns the native live value iterator.
8270
+ * Dispatch the registered body with the original caller signal fused back
8271
+ * into any around-wrapper replacement. Cancellation never abandons the body:
8272
+ * a started promise reaches quiescence before its outcome becomes `ABORTED`.
8273
+ * After cancellation, a thrown signal reason or an `Error` named
8274
+ * `AbortError` without `HarnessError` identity keeps its message, or the
8275
+ * canonical abort message for a messageless reason object, and gains the
8276
+ * `ABORTED` identity, whichever operation inside the body aborted; a
8277
+ * thrown `HarnessError` and any other failure stay unchanged.
7251
8278
  */
7252
- values() {
7253
- return this.data.values();
8279
+ async dispatchToolBody(exec) {
8280
+ const state = this.cancellationStates.get(exec);
8281
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
8282
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
8283
+ const wrapperSignal = exec.signal;
8284
+ const fused = fuseToolSignals(state.callerSignal, wrapperSignal);
8285
+ const signal = fused.signal;
8286
+ if (isAborted(signal)) {
8287
+ fused.dispose();
8288
+ return toolAbortedBeforeDispatchResult();
8289
+ }
8290
+ exec.signal = signal;
8291
+ try {
8292
+ const tool = this.capturedDefinition(exec);
8293
+ state.bodyInvoked = true;
8294
+ const returned = await tool.execute(exec.arguments, exec);
8295
+ const result = this.createSuccessResult(exec, tool, returned);
8296
+ return isAborted(signal) ? toolAbortedResult(result) : result;
8297
+ } catch (error) {
8298
+ return isAborted(signal) && isUnclassifiedCancellation(error, signal) ? cancellationErrorResult(error, true) : toolErrorResult(error);
8299
+ } finally {
8300
+ fused.dispose();
8301
+ exec.signal = wrapperSignal;
8302
+ }
7254
8303
  }
7255
8304
  /**
7256
- * Test whether this table has no entries.
7257
- * @returns whether the table is empty.
8305
+ * Run around-dispatch and the tool body. Tool and unknown-tool failures still
8306
+ * receive post-execute; pipeline failures are already final. Started bodies
8307
+ * drain on cancellation before a successful outcome becomes `ABORTED`. After
8308
+ * caller cancellation, a wrapper that throws the caller signal's reason or an
8309
+ * `Error` named `AbortError` without `HarnessError` identity keeps its message,
8310
+ * or the canonical abort message for a messageless reason object, and gains
8311
+ * `ABORTED`, or `ABORTED_BEFORE_DISPATCH` when the body never started; a
8312
+ * wrapper's `HarnessError` and other failures stay unchanged.
8313
+ * @param exec - the execution returned by this pipeline's prepare stage.
8314
+ * @returns whether the result still needs post-execute.
7258
8315
  */
7259
- isEmpty() {
7260
- return this.data.size === 0;
8316
+ async dispatch(exec) {
8317
+ try {
8318
+ const mutableExec = exec;
8319
+ const carrier = scopeTarget(this.tools, exec.agent);
8320
+ const result = await this.ctx.waterfall(carrier, "tools/execute", mutableExec, () => this.dispatchToolBody(mutableExec));
8321
+ const normalized = this.normalizeDispatchResult(exec, result);
8322
+ const deferredContexts = this.deferredContexts.get(exec);
8323
+ /* v8 ignore next -- dispatch only receives executions minted by this registry's prepare stage */
8324
+ if (deferredContexts === void 0) throw new Error("tool registry scheduler invariant violated: unprepared execution");
8325
+ const resultWithDeferredContexts = deferredContexts.length === 0 ? normalized : this.markCanonical(exec, {
8326
+ ...normalized,
8327
+ additionalContexts: [...deferredContexts, ...normalized.additionalContexts ?? []]
8328
+ });
8329
+ return {
8330
+ kind: "post-result",
8331
+ result: this.callerCancelled(exec) && !resultWithDeferredContexts.isError ? this.cancellationResult(exec, resultWithDeferredContexts) : resultWithDeferredContexts
8332
+ };
8333
+ } catch (error) {
8334
+ return {
8335
+ kind: "final-result",
8336
+ result: this.wrapperFailureResult(exec, error)
8337
+ };
8338
+ }
7261
8339
  }
7262
- };
7263
- /**
7264
- * Own the global and exact-scope layers for one registry.
7265
- *
7266
- * Reads never create scoped layers. Registrations derive both visibility and
7267
- * effect ownership from the supplied Cordis context, collect undo before
7268
- * notification, and reclaim only a completely empty aggregate layer.
7269
- */
7270
- var ScopedLayers = class {
7271
- createLayer;
7272
- onChange;
7273
- /** The eagerly constructed context-global layer. */
7274
- global;
7275
- scoped = /* @__PURE__ */ new Map();
7276
- constructor(createLayer, onChange) {
7277
- this.createLayer = createLayer;
7278
- this.onChange = onChange;
7279
- this.global = createLayer(void 0);
8340
+ /** Classify a failure thrown around dispatch; see {@link dispatch}. */
8341
+ wrapperFailureResult(exec, error) {
8342
+ const state = this.cancellationStates.get(exec);
8343
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
8344
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
8345
+ if (!isAborted(state.callerSignal) || !isUnclassifiedCancellation(error, state.callerSignal)) return toolErrorResult(error);
8346
+ return cancellationErrorResult(error, state.bodyInvoked);
7280
8347
  }
7281
8348
  /**
7282
- * Read an existing exact-scope overlay. Deliberately chain-blind: callers
7283
- * addressing one scope's OWN contributions (its restrictions, its guards)
7284
- * must not silently pick up an ancestor's — use {@link chainLayers} where
7285
- * inheritance is the point.
7286
- * @param scope - exact scope key; `undefined` denotes no overlay.
7287
- * @returns the existing scoped layer, or `undefined` without creating one.
8349
+ * Run post-execute when required, apply definition-owned content finalization,
8350
+ * and publish the lossless, frozen result. Policy and finalization failures
8351
+ * become error results. Cancellation replaces a successful outcome before
8352
+ * final materialization; tool-owned errors remain intact.
8353
+ * @param exec - the execution returned by this pipeline's prepare stage.
8354
+ * @param outcome - the preparation or dispatch result awaiting completion.
8355
+ * @returns the same materialized result delivered to final observers.
7288
8356
  */
7289
- peek(scope) {
7290
- if (scope === void 0) return void 0;
7291
- return this.scoped.get(scope);
8357
+ async complete(exec, outcome) {
8358
+ switch (outcome.kind) {
8359
+ case "final-result": return this.finish(exec, outcome.result);
8360
+ case "post-result": break;
8361
+ /* v8 ignore next -- closed-union exhaustiveness guard */
8362
+ default: return assertNever(outcome, "scheduled tool outcome");
8363
+ }
8364
+ const { result } = outcome;
8365
+ try {
8366
+ const project = this.contentProjectors.get(exec);
8367
+ this.contentProjectors.delete(exec);
8368
+ const content = project?.(exec, result);
8369
+ const projected = content === void 0 ? result : this.markCanonical(exec, this.materializeFinalResult({
8370
+ ...result,
8371
+ content
8372
+ }));
8373
+ const postResult = await this.postExecute(exec, projected);
8374
+ return this.finish(exec, this.callerCancelled(exec) && !postResult.isError ? this.cancellationResult(exec, postResult) : postResult);
8375
+ } catch (error) {
8376
+ return this.finish(exec, toolErrorResult(error));
8377
+ }
7292
8378
  }
7293
- /**
7294
- * Existing overlays along the scope's parent chain ({@link scopeChainOf}),
7295
- * farthest ancestor first and the exact scope last, so a caller layering
7296
- * them in order gives the nearest scope the final word.
7297
- * @param scope - viewing scope, or `undefined` for no overlays.
7298
- * @returns the existing layers, nearest last; absent overlays are skipped.
8379
+ /**
8380
+ * Materialize the candidate, apply definition-owned content finalization,
8381
+ * then materialize and notify the authoritative result.
8382
+ * @param exec - the prepared execution.
8383
+ * @param result - final result.
8384
+ * @returns the materialized final result.
8385
+ * @internal
7299
8386
  */
7300
- chainLayers(scope) {
7301
- const layers = [];
7302
- for (const key of scopeChainOf(scope).reverse()) {
7303
- const layer = this.scoped.get(key);
7304
- if (layer !== void 0) layers.push(layer);
8387
+ finish(exec, result) {
8388
+ let materializedResult;
8389
+ try {
8390
+ materializedResult = this.materializeFinalResult(result);
8391
+ } catch (error) {
8392
+ materializedResult = this.materializeFinalResult(toolErrorResult(error));
8393
+ }
8394
+ let finalResult;
8395
+ try {
8396
+ finalResult = this.materializeFinalResult(this.applyFinalContent(exec, materializedResult));
8397
+ } catch (error) {
8398
+ finalResult = this.materializeFinalResult(toolErrorResult(error));
8399
+ }
8400
+ this.notifyResult(exec, finalResult);
8401
+ return finalResult;
8402
+ }
8403
+ /** Apply the snapshotted tool-owned content transform without exposing other result fields. */
8404
+ applyFinalContent(exec, result) {
8405
+ const finalizeContent = this.contentFinalizers.get(exec);
8406
+ if (finalizeContent === void 0) return result;
8407
+ const content = finalizeContent(exec, result);
8408
+ return content === void 0 ? result : {
8409
+ ...result,
8410
+ content
8411
+ };
8412
+ }
8413
+ /** Notify observers without exposing a mutation or error channel into the outcome. */
8414
+ notifyResult(exec, result) {
8415
+ Object.freeze(exec);
8416
+ const { name: toolName, callId } = exec;
8417
+ const reportFailure = (error) => {
8418
+ this.ctx.logger.warn(`tool "${toolName}" (${callId}): tools/result observer failed: ${errorMessage$1(error)}`);
8419
+ };
8420
+ const callbacks = this.ctx.events.dispatch("emit", [
8421
+ scopeTarget(this.tools, exec.agent),
8422
+ "tools/result",
8423
+ exec,
8424
+ result
8425
+ ]);
8426
+ for (const callback of callbacks) try {
8427
+ const returned = callback(exec, result);
8428
+ Promise.resolve(returned).catch(reportFailure);
8429
+ } catch (error) {
8430
+ reportFailure(error);
7305
8431
  }
7306
- return layers;
7307
8432
  }
7308
8433
  /**
7309
- * Materialize global named entries followed by scope-chain shadows,
7310
- * farthest ancestor first, so the nearest scope's entry wins a name.
7311
- * @param scope - viewing scope, or `undefined` for the global view.
7312
- * @param pick - select the named table from a layer.
7313
- * @returns an insertion-ordered effective map.
8434
+ * Resolve an `ask` decision to allow/deny through the approval seam. The
8435
+ * seam is consumed opportunistically with `ctx.get('approval')` — a
8436
+ * deployment that composes no ApprovalService keeps the historical degrade
8437
+ * to deny, and an unmount mid-session degrades the same way on the next ask.
8438
+ * An agent-less execution also degrades: without an agent there is no
8439
+ * session to audit to and no UI to route to. Otherwise the outcome maps
8440
+ * one-to-one — `allowed-once` proceeds; the three non-grants deny with
8441
+ * distinct reasons so the model can tell a human "no" from an absent
8442
+ * approval channel. Every denial carries `ApprovalError` with
8443
+ * `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`.
7314
8444
  */
7315
- merge(scope, pick) {
7316
- const merged = new Map(pick(this.global).entries());
7317
- for (const layer of this.chainLayers(scope)) for (const [name, value] of pick(layer).entries()) merged.set(name, value);
7318
- return merged;
8445
+ async serviceAsk(exec, ask) {
8446
+ const approval = this.ctx.get("approval");
8447
+ if (approval === void 0) return {
8448
+ decision: approvalDenial(ask.reason ?? `tool "${exec.name}" requires approval (not yet supported)`, APPROVAL_UNAVAILABLE),
8449
+ approvalCancelled: false
8450
+ };
8451
+ if (exec.agent === void 0) return {
8452
+ decision: approvalDenial(`tool "${exec.name}" requires approval, but the call has no agent to route it through`, APPROVAL_UNAVAILABLE),
8453
+ approvalCancelled: false
8454
+ };
8455
+ const outcome = await approval.request({
8456
+ agent: exec.agent,
8457
+ toolName: exec.name,
8458
+ callId: exec.callId,
8459
+ ...ask.reason !== void 0 ? { reason: ask.reason } : {},
8460
+ ...ask.displayReason !== void 0 ? { displayReason: ask.displayReason } : {},
8461
+ signal: exec.signal
8462
+ });
8463
+ switch (outcome) {
8464
+ case "allowed-once": return {
8465
+ decision: { kind: "allow" },
8466
+ approvalCancelled: false
8467
+ };
8468
+ case "rejected": return {
8469
+ decision: approvalDenial(`the user rejected tool "${exec.name}"`, APPROVAL_REJECTED),
8470
+ approvalCancelled: false
8471
+ };
8472
+ case "cancelled": return {
8473
+ decision: approvalDenial(`approval for tool "${exec.name}" was cancelled`, APPROVAL_CANCELLED),
8474
+ approvalCancelled: true
8475
+ };
8476
+ case "unavailable": return {
8477
+ decision: approvalDenial(`tool "${exec.name}" requires approval, but no approval channel is available`, APPROVAL_UNAVAILABLE),
8478
+ approvalCancelled: false
8479
+ };
8480
+ default: return assertNever(outcome, "ApprovalOutcome");
8481
+ }
7319
8482
  }
7320
8483
  /**
7321
- * Attach one synchronous layer mutation to its registration context.
7322
- * @param ctx - context that determines both scope visibility and effect ownership.
7323
- * @param action - atomic mutation returning its synchronous undo.
7324
- * @param options - Cordis effect label and optional change notification.
7325
- * @returns the exact disposer returned by `ctx.effect()`.
8484
+ * Run the `tools/post-execute` waterfall over a dispatched `result` and apply
8485
+ * its {@link PostToolDecision}: `accept` keeps the call successful (replacing
8486
+ * `content` when given), `block` turns it into an `isError` whose content is
8487
+ * the corrective `feedback`. Either decision may attach `additionalContexts`,
8488
+ * which are ferried on the returned result for the loop's active-batch FIFO.
8489
+ * Context deferred by the tool body survives an accepted result but is
8490
+ * discarded when the outer call is blocked; a block exposes only context the
8491
+ * blocking decision explicitly supplied.
8492
+ * Runs inside `execute`'s outer try/catch (a throwing listener → isError).
7326
8493
  */
7327
- effect(ctx, action, options) {
7328
- const scope = scopeOf(ctx);
7329
- const notify = options.notify ?? true;
7330
- return ctx.effect(function* () {
7331
- let layer;
7332
- let created = false;
7333
- if (scope === void 0) layer = this.global;
7334
- else {
7335
- const existing = this.scoped.get(scope);
7336
- if (existing === void 0) {
7337
- layer = this.createLayer(scope);
7338
- this.scoped.set(scope, layer);
7339
- created = true;
7340
- } else layer = existing;
7341
- }
7342
- let undo;
8494
+ async postExecute(exec, result) {
8495
+ const decision = await this.ctx.waterfall(scopeTarget(this.tools, exec.agent), "tools/post-execute", exec, result, () => Promise.resolve({ kind: "accept" }));
8496
+ const decisionContexts = decision.additionalContexts ?? [];
8497
+ if (decision.kind === "block") {
8498
+ const message = failureMessageFromContent(decision.feedback);
8499
+ return this.markCanonical(exec, {
8500
+ content: decision.feedback,
8501
+ isError: true,
8502
+ error: {
8503
+ message,
8504
+ ...decision.info === void 0 ? {} : { info: decision.info }
8505
+ },
8506
+ ...decisionContexts.length > 0 ? { additionalContexts: decisionContexts } : {}
8507
+ });
8508
+ }
8509
+ if (Object.hasOwn(decision, "content") && Object.hasOwn(decision, "value")) throw new TypeError("tools/post-execute accept decision cannot replace both value and content");
8510
+ const additionalContexts = [...result.additionalContexts ?? [], ...decisionContexts];
8511
+ if (Object.hasOwn(decision, "value")) {
8512
+ if (result.isError) throw new TypeError("tools/post-execute cannot replace the value of a failed result");
8513
+ const replaced = this.createSuccessResult(exec, this.dispatchedDefinition(exec), decision.value);
8514
+ return this.markCanonical(exec, {
8515
+ ...replaced,
8516
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
8517
+ });
8518
+ }
8519
+ return this.markCanonical(exec, {
8520
+ ...result,
8521
+ ...decision.content !== void 0 ? { content: decision.content } : {},
8522
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
8523
+ });
8524
+ }
8525
+ /** Registry-normalized results and the exact dispatch that validated each value. */
8526
+ canonicalResults = /* @__PURE__ */ new WeakMap();
8527
+ /** Mark one registry-normalized result as canonical only for its owning dispatch. */
8528
+ markCanonical(exec, result) {
8529
+ this.canonicalResults.set(result, exec.token);
8530
+ return result;
8531
+ }
8532
+ /** Snapshot, validate, render, and optionally project one successful body value. */
8533
+ createSuccessResult(exec, tool, candidate) {
8534
+ const detached = snapshotToolValue(tool.name, candidate);
8535
+ const violations = validateJsonSchemaValue(tool.output.schema, detached, "value");
8536
+ if (violations.length > 0) throw new ToolOutputError(tool.name, violations);
8537
+ const value = deepFreeze(detached);
8538
+ let rendered;
8539
+ try {
8540
+ rendered = tool.output.render(exec.arguments, value);
8541
+ } catch (error) {
8542
+ throw projectionError(tool.name, "render", error);
8543
+ }
8544
+ const content = snapshotProjection(tool.name, "render", rendered);
8545
+ let meta;
8546
+ if (tool.output.presentationMeta !== void 0) {
8547
+ let projected;
7343
8548
  try {
7344
- undo = action(layer);
8549
+ projected = tool.output.presentationMeta(exec.arguments, value);
7345
8550
  } catch (error) {
7346
- if (scope !== void 0 && created && layer.isEmpty()) this.scoped.delete(scope);
7347
- throw error;
8551
+ throw projectionError(tool.name, "presentationMeta", error);
7348
8552
  }
7349
- yield () => {
7350
- undo();
7351
- if (scope !== void 0 && layer.isEmpty()) this.scoped.delete(scope);
7352
- if (notify) this.onChange();
7353
- };
7354
- if (notify) this.onChange();
7355
- }.bind(this), options.label);
8553
+ meta = snapshotProjection(tool.name, "presentationMeta", projected);
8554
+ }
8555
+ const concludesTurn = this.concludingExecutions.has(exec);
8556
+ return this.markCanonical(exec, this.materializeFinalResult({
8557
+ isError: false,
8558
+ value,
8559
+ content,
8560
+ ...meta !== void 0 ? { meta } : {},
8561
+ ...concludesTurn ? { concludesTurn: true } : {}
8562
+ }));
8563
+ }
8564
+ /** Normalize an around-dispatch wrapper's authored result through the owning output contract. */
8565
+ normalizeDispatchResult(exec, result) {
8566
+ if (this.canonicalResults.get(result) === exec.token) return result;
8567
+ if (result.isError) return this.markCanonical(exec, {
8568
+ isError: true,
8569
+ error: result.error,
8570
+ content: result.content,
8571
+ ...result.meta !== void 0 ? { meta: result.meta } : {},
8572
+ ...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
8573
+ });
8574
+ const normalized = this.createSuccessResult(exec, this.dispatchedDefinition(exec), result.value);
8575
+ return this.markCanonical(exec, {
8576
+ ...normalized,
8577
+ ...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
8578
+ });
8579
+ }
8580
+ /** Materialize the authoritative commit outcome once, immediately before `tools/result`. */
8581
+ materializeFinalResult(result) {
8582
+ const presentation = {
8583
+ content: result.content,
8584
+ ...result.meta !== void 0 ? { meta: result.meta } : {},
8585
+ ...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
8586
+ };
8587
+ if (result.isError) return materializePresentation({
8588
+ isError: true,
8589
+ error: result.error,
8590
+ ...presentation
8591
+ });
8592
+ return deepFreeze({
8593
+ ...materializePresentation({
8594
+ isError: false,
8595
+ ...presentation,
8596
+ ...result.concludesTurn === true ? { concludesTurn: true } : {}
8597
+ }),
8598
+ value: result.value
8599
+ });
7356
8600
  }
7357
8601
  };
8602
+ /** Convert one projector exception into the canonical invalid-output failure. */
8603
+ function projectionError(toolName, projector, error) {
8604
+ return new ToolOutputError(toolName, [`output.${projector} failed: ${errorMessage$1(error)}`]);
8605
+ }
8606
+ /** Snapshot one projector result before later durable-result materialization. */
8607
+ function snapshotProjection(toolName, projector, candidate) {
8608
+ try {
8609
+ const detached = snapshotJsonValue(candidate);
8610
+ if (detached === void 0) throw new ToolOutputError(toolName, [`output.${projector} returned non-lossless JSON`]);
8611
+ return detached;
8612
+ } catch (error) {
8613
+ if (error instanceof ToolOutputError) throw error;
8614
+ throw projectionError(toolName, projector, error);
8615
+ }
8616
+ }
8617
+ /** Snapshot one body or policy value into the canonical invalid-output failure class. */
8618
+ function snapshotToolValue(toolName, candidate) {
8619
+ try {
8620
+ const detached = snapshotJsonValue(candidate);
8621
+ if (detached === void 0) throw new ToolOutputError(toolName, ["value is not lossless JSON"]);
8622
+ return detached;
8623
+ } catch (error) {
8624
+ if (error instanceof ToolOutputError) throw error;
8625
+ throw new ToolOutputError(toolName, [`value snapshot failed: ${errorMessage$1(error)}`]);
8626
+ }
8627
+ }
8628
+ /** Derive one failure message from policy feedback without changing its rendered blocks. */
8629
+ function failureMessageFromContent(content) {
8630
+ const text = content.map((block) => block.type === "text" ? block.text : `[${block.type} content]`).join("\n");
8631
+ return text.length > 0 ? text : "tool result blocked by post-execute policy";
8632
+ }
8633
+ /** Snapshot and freeze one durable tool-result projection or reject lossy data. */
8634
+ function materializePresentation(candidate) {
8635
+ const detached = snapshotJsonValue(candidate);
8636
+ if (detached === void 0) throw new TypeError("tool result must be losslessly JSON-serializable");
8637
+ return deepFreeze(detached);
8638
+ }
8639
+ /** Structured `{ name, code }` for a thrown HarnessError, else undefined. */
8640
+ function errorInfo(error) {
8641
+ try {
8642
+ return error instanceof HarnessError ? {
8643
+ name: error.name,
8644
+ code: error.code
8645
+ } : void 0;
8646
+ } catch {
8647
+ return;
8648
+ }
8649
+ }
8650
+ /** Materialize a non-granting approval outcome as a denial with routable `ApprovalError` identity. */
8651
+ function approvalDenial(reason, code) {
8652
+ return {
8653
+ kind: "deny",
8654
+ reason,
8655
+ info: {
8656
+ name: APPROVAL_ERROR_NAME,
8657
+ code
8658
+ }
8659
+ };
8660
+ }
8661
+ /** Whether a value thrown after cancellation is that cancellation and carries no identity of its own. */
8662
+ function isUnclassifiedCancellation(error, signal) {
8663
+ if (errorInfo(error) !== void 0) return false;
8664
+ try {
8665
+ return error === signal.reason || error instanceof Error && error.name === "AbortError";
8666
+ } catch {
8667
+ return false;
8668
+ }
8669
+ }
7358
8670
  /**
7359
- * Scoped-context primitive: mint a Cordis context that tags registrations with
7360
- * an opaque identity and build routing-only event carriers for that identity.
7361
- *
7362
- * @module @deepseek-ai/dsh-scope
7363
- */
7364
- /** Context tag written by {@link createScope}. */
7365
- const kScope = Symbol("dsh.scope");
7366
- /**
7367
- * The enclosing scope of each key. One relation powers both directions of
7368
- * scope nesting: registration views inherit DOWN the chain (a child scope
7369
- * sees its ancestors' layers — {@link ScopedLayers}), and event admission
7370
- * extends UP it (a listener tagged with an ancestor receives events dispatched
7371
- * to a descendant key — {@link scopeTarget}).
7372
- */
7373
- const scopeParents = /* @__PURE__ */ new WeakMap();
7374
- /**
7375
- * The chain from a key to its root ancestor.
7376
- * @param key - the starting key, or `undefined` for the empty chain.
7377
- * @returns keys nearest-first: `[key, parent, grandparent, …]`.
8671
+ * Result for a recognized cancellation: the thrown message, or the canonical
8672
+ * abort message when the thrown value is an object without a string `message`,
8673
+ * such as an `AgentCancelCause` signal reason.
7378
8674
  */
7379
- function scopeChainOf(key) {
7380
- const chain = [];
7381
- for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) chain.push(cursor);
7382
- return chain;
8675
+ function cancellationErrorResult(error, bodyInvoked) {
8676
+ if (isMessagelessObject(error)) return bodyInvoked ? toolAbortedResult() : toolAbortedBeforeDispatchResult();
8677
+ return toolErrorResult(error, {
8678
+ name: "AbortError",
8679
+ code: bodyInvoked ? TOOL_ABORTED : TOOL_ABORTED_BEFORE_DISPATCH
8680
+ });
8681
+ }
8682
+ /** Whether a thrown value is a non-Error object without a string `message`; its own `toString` is not consulted. */
8683
+ function isMessagelessObject(error) {
8684
+ try {
8685
+ return typeof error === "object" && error !== null && !(error instanceof Error) && !("message" in error && typeof error.message === "string");
8686
+ } catch {
8687
+ return false;
8688
+ }
8689
+ }
8690
+ /** Mint a same-process correlation token whose identity is its value. */
8691
+ function createExecutionToken() {
8692
+ return Symbol("dsh.tool.execution");
8693
+ }
8694
+ function toolErrorResult(error, info = errorInfo(error)) {
8695
+ const message = errorMessage$1(error);
8696
+ return {
8697
+ content: [{
8698
+ type: "text",
8699
+ text: `Error: ${message}`
8700
+ }],
8701
+ isError: true,
8702
+ error: {
8703
+ message,
8704
+ ...info ? { info } : {}
8705
+ }
8706
+ };
8707
+ }
8708
+ /** Read live abort state across an await without treating it as synchronously immutable. */
8709
+ function isAborted(signal) {
8710
+ return signal.aborted;
7383
8711
  }
7384
8712
  /**
7385
- * Read the nearest scope tag inherited by a context.
7386
- * @param ctx - context to inspect.
7387
- * @returns its scope key, or `undefined` for an unscoped context.
8713
+ * Fuse caller and wrapper cancellation without nesting `AbortSignal.any`.
8714
+ * Keeping the relay dispatch-scoped also removes listeners when work settles.
7388
8715
  */
7389
- function scopeOf(ctx) {
7390
- return ctx[kScope];
8716
+ function fuseToolSignals(caller, wrapper) {
8717
+ if (caller === wrapper) return {
8718
+ signal: caller,
8719
+ dispose() {}
8720
+ };
8721
+ const controller = new AbortController();
8722
+ let listening = false;
8723
+ const dispose = () => {
8724
+ if (!listening) return;
8725
+ listening = false;
8726
+ caller.removeEventListener("abort", abortFromCaller);
8727
+ wrapper.removeEventListener("abort", abortFromWrapper);
8728
+ };
8729
+ const abortFrom = (source) => {
8730
+ const reason = source.reason;
8731
+ controller.abort(reason);
8732
+ dispose();
8733
+ };
8734
+ const abortFromCaller = () => {
8735
+ abortFrom(caller);
8736
+ };
8737
+ const abortFromWrapper = () => {
8738
+ abortFrom(wrapper);
8739
+ };
8740
+ if (wrapper.aborted) abortFromWrapper();
8741
+ else if (caller.aborted) abortFromCaller();
8742
+ else {
8743
+ listening = true;
8744
+ caller.addEventListener("abort", abortFromCaller, { once: true });
8745
+ wrapper.addEventListener("abort", abortFromWrapper, { once: true });
8746
+ }
8747
+ return {
8748
+ signal: controller.signal,
8749
+ dispose
8750
+ };
8751
+ }
8752
+ /** Canonical result when cancellation supersedes success after body invocation. */
8753
+ function toolAbortedResult(prior) {
8754
+ const additionalContexts = prior?.additionalContexts ?? [];
8755
+ return {
8756
+ content: [{
8757
+ type: "text",
8758
+ text: "Error: tool call aborted"
8759
+ }],
8760
+ isError: true,
8761
+ error: {
8762
+ message: "tool call aborted",
8763
+ info: {
8764
+ name: "AbortError",
8765
+ code: TOOL_ABORTED
8766
+ }
8767
+ },
8768
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
8769
+ };
8770
+ }
8771
+ /** Canonical result when cancellation prevents tool body invocation. */
8772
+ function toolAbortedBeforeDispatchResult(prior) {
8773
+ const additionalContexts = prior?.additionalContexts ?? [];
8774
+ return {
8775
+ content: [{
8776
+ type: "text",
8777
+ text: "Error: tool call aborted before dispatch"
8778
+ }],
8779
+ isError: true,
8780
+ error: {
8781
+ message: "tool call aborted before dispatch",
8782
+ info: {
8783
+ name: "AbortError",
8784
+ code: TOOL_ABORTED_BEFORE_DISPATCH
8785
+ }
8786
+ },
8787
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
8788
+ };
7391
8789
  }
7392
8790
  //#endregion
7393
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.3_c6df380a2007cdef080fa53578fb6f5f/node_modules/@deepseek-ai/dsh-tools/lib/index.js
8791
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.3-alpha.4_ca12df44b3bbe3a755034ba57f11ee40/node_modules/@deepseek-ai/dsh-tools/lib/index.js
7394
8792
  /** Unified JSON-value schema DSL, inference, compilation, and tool definition helpers. @module dsh-tools/schema */
7395
8793
  const ANNOTATION_KEYS = [
7396
8794
  "description",
@@ -7712,6 +9110,8 @@ function defineTool(options) {
7712
9110
  },
7713
9111
  ...options.deferLoading === true ? { deferLoading: options.deferLoading } : {},
7714
9112
  ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
9113
+ ...options.guidance !== void 0 ? { guidance: options.guidance } : {},
9114
+ ...options.environment !== void 0 ? { environment: options.environment } : {},
7715
9115
  async execute(args, exec) {
7716
9116
  const violations = validate(args);
7717
9117
  if (violations.length > 0) throw new ToolArgsError(violations);
@@ -7751,23 +9151,36 @@ function projectToolSchema(definition, detachParameters) {
7751
9151
  ...deferLoading === true ? { deferLoading } : {}
7752
9152
  };
7753
9153
  }
7754
- /** Tool definitions and scoped dispatch to plugin-owned executors. @module */
7755
- /** One scope's complete tool-registry contribution. */
9154
+ /** Scoped tool contributions routed to the selected root registry, which answers lookups and dispatch. @module */
9155
+ /** One scope's complete tool contribution. */
7756
9156
  var ToolLayer = class {
7757
9157
  tools;
9158
+ includes = new AnonymousEntries();
7758
9159
  restrictions = new AnonymousEntries();
7759
9160
  constructor(scope) {
7760
9161
  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`));
7761
9162
  }
7762
- /** Whether every contribution table in this aggregate layer is empty. */
9163
+ /** Whether every contribution table in this layer is empty. */
7763
9164
  isEmpty() {
7764
- return this.tools.isEmpty() && this.restrictions.isEmpty();
9165
+ return this.tools.isEmpty() && this.includes.isEmpty() && this.restrictions.isEmpty();
7765
9166
  }
7766
- /** Whether every compiled restriction in this layer admits a global tool name. */
9167
+ /** Whether every compiled restriction in this layer admits an inherited tool name. */
7767
9168
  admits(name) {
7768
9169
  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;
7769
9170
  return true;
7770
9171
  }
9172
+ /** Registrations, then included entries, as the viewing scope resolves them. */
9173
+ candidates(scope) {
9174
+ return collectToolCandidates(this.tools.values(), this.includes.values(), scope);
9175
+ }
9176
+ /** The registration or included entry with one name, as the viewing scope resolves it. */
9177
+ candidate(name, scope) {
9178
+ return findToolCandidate(this.tools.get(name), this.includes.values(), name, scope);
9179
+ }
9180
+ /** Every name this layer can offer: registrations plus each inclusion's unscoped entries. */
9181
+ names() {
9182
+ return [...this.tools.keys(), ...[...this.includes.values()].flatMap((source) => source.getAll().map((tool) => tool.name))];
9183
+ }
7771
9184
  };
7772
9185
  var GuardLayer = class {
7773
9186
  guards = new AnonymousEntries();
@@ -7778,51 +9191,148 @@ var GuardLayer = class {
7778
9191
  (class extends Service {
7779
9192
  static inject = ["systemPrompt"];
7780
9193
  static Config = Schema.object({
7781
- mode: Schema.never().description("Removed. Mount a native or PTC tool executor instead."),
7782
- maxParallelSubCalls: Schema.never().description("Moved to the PTC tool executor configuration.")
9194
+ mode: Schema.never().description("Removed. Mount a native or PTC root tool registry instead."),
9195
+ maxParallelSubCalls: Schema.never().description("Moved to the PTC tool registry configuration.")
7783
9196
  });
7784
- layers = new ScopedLayers((scope) => new ToolLayer(scope), () => {
9197
+ /** Emit `tools/change` from this service's own context, which outlives a caller that unloads. */
9198
+ notifyChange = () => {
7785
9199
  this.ctx.emit("tools/change");
7786
- });
7787
- scoped = /* @__PURE__ */ new WeakMap();
7788
- root;
9200
+ };
9201
+ layers = new ScopedLayers((scope) => new ToolLayer(scope), this.notifyChange);
9202
+ /** Root selections by scope key; ended scopes release theirs, while an unloaded selection stays recorded. */
9203
+ roots = /* @__PURE__ */ new WeakMap();
9204
+ /** The `roots` key of the unscoped selection, which serves every scope without its own. */
9205
+ unscoped = {};
9206
+ /** Environment registries by scope key, keyed like `roots`. */
9207
+ environments = /* @__PURE__ */ new WeakMap();
7789
9208
  guards = new ScopedLayers(() => new GuardLayer(), () => {});
9209
+ viewing = false;
9210
+ /** Whether `ctx.tools` is calling into a root, which must not read `ctx.tools`. */
9211
+ callingRoot = false;
9212
+ /** Roots that already include the registrations, which serve every scope that selects them. */
9213
+ includedRoots = /* @__PURE__ */ new WeakSet();
9214
+ /** Registered tools with guidance by section name; their registrations render the shared section. */
9215
+ guidanceTools = /* @__PURE__ */ new Map();
9216
+ /** The registrations each scope sees, which every selected root includes. */
9217
+ registrations = {
9218
+ get: (name, scope) => this.registered(name, scope),
9219
+ getAll: (scope) => listToolCandidates(this.visible(scope))
9220
+ };
7790
9221
  constructor(ctx) {
7791
9222
  super(ctx, "tools");
7792
- ctx.systemPrompt.tools(({ scope, toolSet }) => {
7793
- const description = this.selectExecutor(scope).describe(this.definitions(scope, toolSet));
9223
+ ctx.systemPrompt.tools(({ scope, toolStep }) => {
9224
+ const declared = toolStep !== void 0 && toolStep.agent === scope ? toolStep.declarations : this.getAll(scope);
7794
9225
  return {
7795
- ...description,
7796
- knownNames: description.knownNames ?? [...this.view(scope).knownNames]
9226
+ schemas: declared.map((definition) => projectToolSchema(definition, false)),
9227
+ knownNames: [.../* @__PURE__ */ new Set([...declared.map((definition) => definition.name), ...this.names(scope).known])]
9228
+ };
9229
+ });
9230
+ }
9231
+ /**
9232
+ * Register in the calling scope. The tool reaches the root the scope
9233
+ * selects and the roots its descendant scopes select: a native root offers
9234
+ * it as an entry, a PTC root binds it in programs. Nearer scopes shadow
9235
+ * farther ones; duplicates within one scope, a name an inclusion in the
9236
+ * scope already offers, and the reserved `run_code` name fail. A tool's
9237
+ * `guidance` registers its system prompt section in the same effect; the
9238
+ * section renders while the viewing scope's registrations resolve the tool.
9239
+ * @param tool - tool schema, execution, and optional finalization, presentation, or guidance.
9240
+ * @returns the exact disposer that unregisters the tool and its guidance.
9241
+ * @throws ToolCompositionError when the scope's inclusions already offer another definition with the name.
9242
+ */
9243
+ register(tool) {
9244
+ assertToolDefinition(tool);
9245
+ this.read(() => {
9246
+ const offered = findToolCandidate(void 0, this.ownLayer()?.includes.values() ?? [], tool.name, void 0);
9247
+ if (offered !== void 0) resolveToolCandidate(tool.name, mergeToolCandidate(offered, tool));
9248
+ });
9249
+ const guidance = tool.guidance;
9250
+ if (guidance === void 0) return this.layers.effect(this.ctx, (layer) => layer.tools.insert(tool.name, tool), { label: "tools.register()" });
9251
+ const section = guidance.section ?? `tool:${tool.name}`;
9252
+ return this.ctx.effect(function* () {
9253
+ yield this.layers.effect(this.ctx, (layer) => layer.tools.insert(tool.name, tool), { label: "tools.register()" });
9254
+ const tools = this.guidanceTools.get(section) ?? [];
9255
+ this.guidanceTools.set(section, tools);
9256
+ tools.push(tool);
9257
+ yield () => {
9258
+ tools.splice(tools.indexOf(tool), 1);
9259
+ if (tools.length === 0) this.guidanceTools.delete(section);
7797
9260
  };
9261
+ yield this.ctx.systemPrompt.section({
9262
+ name: section,
9263
+ order: this.ctx.systemPrompt.getSectionOrder(guidance.order),
9264
+ interpolate: false,
9265
+ ...guidance.retirement === void 0 ? {} : { retirement: guidance.retirement },
9266
+ text: (context) => this.guidanceText(tools, guidance, context)
9267
+ });
9268
+ }.bind(this), "tools.register()");
9269
+ }
9270
+ /**
9271
+ * Render a guidance section for the viewing scope.
9272
+ * @param tools - the tools that share the section.
9273
+ * @param guidance - guidance of the registration the system prompt renders.
9274
+ * @param context - the assembly context, whose scope views the tools.
9275
+ * @returns the section text, or empty text when the scope's registrations resolve none of the tools.
9276
+ * @throws ToolCompositionError when the deciding scope offers several definitions under one of the names.
9277
+ */
9278
+ guidanceText(tools, guidance, context) {
9279
+ const available = new Set(tools.filter((tool) => this.registered(tool.name, context.scope) === tool).map((tool) => tool.name));
9280
+ if (available.size === 0) return "";
9281
+ return typeof guidance.text === "string" ? guidance.text : guidance.text([...available].sort());
9282
+ }
9283
+ /**
9284
+ * Include another registry's entries in the calling scope; they reach roots
9285
+ * as registrations do. Each query reads the source for the viewing scope.
9286
+ * Descendant scopes inherit the entries, so their restrictions apply; the
9287
+ * including scope's own restrictions do not.
9288
+ * @param registry - source that keeps ownership of its definitions.
9289
+ * @returns the exact disposer that removes this inclusion.
9290
+ * @throws ToolCompositionError when the scope already offers another definition under one of the source's names,
9291
+ * when the source itself offers several definitions under one of them, or when the source includes this service.
9292
+ */
9293
+ include(registry) {
9294
+ this.read(() => {
9295
+ const layer = this.ownLayer();
9296
+ const sources = [...layer?.includes.values() ?? [], registry];
9297
+ for (const name of new Set(registry.getAll().map((definition) => definition.name))) resolveToolCandidate(name, findToolCandidate(layer?.tools.get(name), sources, name, void 0));
7798
9298
  });
9299
+ return this.layers.effect(this.ctx, (layer) => layer.includes.append(registry), { label: "tools.include()" });
9300
+ }
9301
+ /**
9302
+ * The calling scope's existing layer; the global layer for an unscoped context.
9303
+ * Conflicts are checked against every name a contribution can offer, before it
9304
+ * publishes, so a conflicting plugin fails at load. Later changes inside an
9305
+ * included registry fail the queries that reach them.
9306
+ */
9307
+ ownLayer() {
9308
+ const scope = scopeOf(this.ctx);
9309
+ return scope === void 0 ? this.layers.global : this.layers.peek(scope);
9310
+ }
9311
+ /**
9312
+ * Run one read of contributions, rejecting a read that re-enters through an inclusion.
9313
+ * @param read - lookup over this service's layers and their inclusions.
9314
+ * @returns the lookup result.
9315
+ * @throws ToolCompositionError when an included registry reads this service again.
9316
+ */
9317
+ read(read) {
9318
+ if (this.viewing) throw inclusionCycle();
9319
+ this.viewing = true;
9320
+ try {
9321
+ return read();
9322
+ } finally {
9323
+ this.viewing = false;
9324
+ }
7799
9325
  }
7800
9326
  /**
7801
- * Register globally or in the calling agent scope. Scoped tools shadow
7802
- * globals; duplicates within one layer and the reserved `run_code` name fail.
7803
- * @param definition - tool schema, execution, and optional finalization/presentation callbacks.
7804
- * @param options - optional step-time activation condition.
7805
- * @returns the exact disposer that unregisters the tool.
7806
- */
7807
- register(definition, options = {}) {
7808
- const name = definition.name;
7809
- const output = definition.output;
7810
- 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? }`);
7811
- assertSupportedJsonSchema(output.schema);
7812
- const timeoutMs = definition.timeoutMs;
7813
- if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new TypeError(`tool "${name}" timeoutMs must be a positive finite number`);
7814
- if (name === "run_code") throw new Error(`tool name "${RUN_CODE_NAME}" is reserved for the PTC mode presentation transport and cannot be registered or shadowed`);
7815
- return this.layers.effect(this.ctx, (layer) => layer.tools.insert(name, {
7816
- definition,
7817
- when: options.when
7818
- }), { label: "tools.register()" });
7819
- }
7820
- /**
7821
- * Restrict global tools for the calling agent scope. Empty filters, unknown
7822
- * names, scope-local names, and reserved transport names fail. Restrictions
7823
- * intersect; scoped registrations remain visible.
7824
- * @param filter - global-tool mask: `allow` (keep only) and/or `deny` (remove).
9327
+ * Restrict inherited tools for the calling scope. Restrictions intersect;
9328
+ * the scope's own registrations and inclusions stay visible. `allow` names
9329
+ * must be ones an inherited registration or inclusion can offer; an
9330
+ * inclusion contributes its unscoped entries, so a tool a provider adds to
9331
+ * Agents later can be allowed in advance. `deny` accepts any name, so a
9332
+ * scope can deny a tool before anything offers it.
9333
+ * @param filter - inherited-tool mask: `allow` (keep only) and/or `deny` (remove).
7825
9334
  * @returns the exact disposer that lifts this restriction.
9335
+ * @throws Error when the context is unscoped, the filter is empty, a name is `run_code`, or an `allow` name is not inherited.
7826
9336
  */
7827
9337
  restrict(filter) {
7828
9338
  const scope = scopeOf(this.ctx);
@@ -7834,186 +9344,265 @@ var GuardLayer = class {
7834
9344
  ...allow !== void 0 ? { allow: new Set(allow) } : {},
7835
9345
  ...deny !== void 0 ? { deny: new Set(deny) } : {}
7836
9346
  };
7837
- if ([...allow ?? [], ...deny ?? []].includes("run_code")) throw new Error(`tools.restrict() cannot name reserved PTC mode presentation transport "${RUN_CODE_NAME}"; restrict end-capability tools instead`);
7838
- const known = this.view(scope).restrictableNames;
7839
- const unknown = [...allow ?? [], ...deny ?? []].filter((name) => !known.has(name));
7840
- 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)"}`);
9347
+ if ([...allow ?? [], ...deny ?? []].includes("run_code")) throw new Error(`tools.restrict() cannot name reserved PTC program entry "${RUN_CODE_NAME}"; restrict the tools programs call instead`);
9348
+ const known = this.names(scope).restrictable;
9349
+ const unknown = (allow ?? []).filter((name) => !known.has(name));
9350
+ if (unknown.length > 0) throw new Error(`tools.restrict() names unknown inherited tool${unknown.length > 1 ? "s" : ""} ${unknown.map((n) => `"${n}"`).join(", ")}; known inherited tools: ${[...known].sort().join(", ") || "(none)"}`);
7841
9351
  return this.layers.effect(this.ctx, (layer) => layer.restrictions.append(compiled), { label: "tools.restrict()" });
7842
9352
  }
7843
9353
  /**
7844
- * Resolve visible tools and pre-restriction names. Restrictions across the
7845
- * scope chain intersect over inherited global and ancestor tools; the viewing
7846
- * scope's own registrations remain exempt. Nearer registrations shadow
7847
- * farther ones. Pre-restriction names support restriction and prompt-order validation.
7848
- * @param scope - the viewing scope (the agent), or undefined for the global view.
7849
- * @returns the complete derived view for that scope.
7850
- */
7851
- view(scope) {
7852
- const layers = this.layers.chainLayers(scope);
7853
- const own = this.layers.peek(scope);
7854
- const inherited = new Map(this.layers.global.tools.entries());
7855
- for (const layer of layers) {
7856
- if (layer === own) continue;
7857
- for (const [name, registration] of layer.tools.entries()) inherited.set(name, registration);
7858
- }
7859
- const visible = /* @__PURE__ */ new Map();
7860
- const registrations = /* @__PURE__ */ new Map();
7861
- const knownNames = /* @__PURE__ */ new Set();
7862
- const restrictableNames = /* @__PURE__ */ new Set();
7863
- for (const [name, registration] of inherited) {
7864
- knownNames.add(name);
7865
- restrictableNames.add(name);
7866
- if (layers.every((layer) => layer.admits(name))) {
7867
- visible.set(name, registration.definition);
7868
- registrations.set(name, registration);
9354
+ * Resolve the deciding candidates a scope sees. Restrictions across the scope
9355
+ * chain intersect over inherited tools; the viewing scope's own contributions
9356
+ * remain exempt. The nearest place offering a name decides it.
9357
+ * @param scope - the viewing scope, or undefined for the unscoped view.
9358
+ * @returns visible candidates by name.
9359
+ */
9360
+ visible(scope) {
9361
+ return this.read(() => {
9362
+ const layers = this.layers.chainLayers(scope);
9363
+ const own = this.layers.peek(scope);
9364
+ const inherited = this.layers.global.candidates(scope);
9365
+ for (const layer of layers) {
9366
+ if (layer === own) continue;
9367
+ for (const [name, candidate] of layer.candidates(scope)) inherited.set(name, candidate);
7869
9368
  }
7870
- }
7871
- if (own !== void 0) for (const [name, registration] of own.tools.entries()) {
7872
- knownNames.add(name);
7873
- visible.set(name, registration.definition);
7874
- registrations.set(name, registration);
7875
- }
7876
- return {
7877
- visible,
7878
- registrations,
7879
- knownNames,
7880
- restrictableNames
7881
- };
9369
+ const visible = /* @__PURE__ */ new Map();
9370
+ for (const [name, candidate] of inherited) if (layers.every((layer) => layer.admits(name))) visible.set(name, candidate);
9371
+ for (const [name, candidate] of own?.candidates(scope) ?? []) visible.set(name, candidate);
9372
+ return visible;
9373
+ });
7882
9374
  }
7883
9375
  /**
7884
- * Look up a tool as one scope sees it (scoped
7885
- * shadows global; a restricted-away global reads as absent). Presenters pass
7886
- * the calling agent so the rendered card matches the definition that
7887
- * actually executed.
7888
- * @param name - the tool name as registered.
7889
- * @param scope - the viewing scope (the agent); omitted = the global view.
7890
- * @param toolSet - step admission; omit only to inspect registered definitions.
7891
- * @returns the definition the scope resolves, or undefined when none is visible.
7892
- */
7893
- get(name, scope, toolSet) {
7894
- return toolSet === void 0 ? this.view(scope).visible.get(name) : toolSet.view(scope).get(name);
7895
- }
7896
- /**
7897
- * Resolve the definition a call may execute. With a step's admitted set, the
7898
- * set decides; without one, conditional registrations are unavailable.
7899
- * @param name - the tool name as registered.
7900
- * @param scope - the calling agent; omitted = the global view.
7901
- * @param toolSet - step admission, or omitted for a call outside a model step.
7902
- * @returns the executable definition, or undefined when the call must fail as `UNKNOWN_TOOL`.
7903
- */
7904
- executable(name, scope, toolSet) {
7905
- if (toolSet !== void 0) return toolSet.view(scope).get(name);
7906
- const view = this.view(scope);
7907
- return view.registrations.get(name)?.when === void 0 ? view.visible.get(name) : void 0;
7908
- }
7909
- /**
7910
- * Resolve conditions once for this step without changing shared registrations.
7911
- * Cancellation or a rejected condition publishes no partial selection. Removed
7912
- * registrations cannot be restored by a late condition result.
7913
- * @param context - preparing agent, captured model selection, and cancellation.
7914
- * @returns the complete selection; the caller disposes it after its tool batch settles.
7915
- */
7916
- async resolve(context) {
7917
- const { agent, signal } = context;
7918
- signal.throwIfAborted();
7919
- const view = this.view(agent);
7920
- const admitted = /* @__PURE__ */ new Map();
7921
- for (const [name, definition] of view.visible) {
7922
- const registration = view.registrations.get(name);
7923
- let enabled;
7924
- try {
7925
- enabled = registration?.when === void 0 || await registration.when(context);
7926
- } catch (cause) {
7927
- signal.throwIfAborted();
7928
- throw new ToolActivationError(name, cause);
7929
- }
7930
- signal.throwIfAborted();
7931
- if (enabled) admitted.set(name, definition);
7932
- }
7933
- let closed = false;
7934
- return Object.freeze({
7935
- dispose: () => {
7936
- closed = true;
7937
- },
7938
- view: (scope) => {
7939
- const visible = /* @__PURE__ */ new Map();
7940
- if (closed || scope !== agent) return visible;
7941
- const current = this.view(agent);
7942
- for (const [name, definition] of admitted) if (current.visible.get(name) === definition && current.registrations.get(name) === view.registrations.get(name)) visible.set(name, definition);
7943
- return visible;
7944
- }
9376
+ * Collect the names a scope's contributions can offer before restrictions,
9377
+ * including every entry its inclusions offer to any Agent.
9378
+ * @param scope - the viewing scope, or undefined for the unscoped view.
9379
+ * @returns known and restrictable names.
9380
+ */
9381
+ names(scope) {
9382
+ return this.read(() => {
9383
+ const layers = this.layers.chainLayers(scope);
9384
+ const own = this.layers.peek(scope);
9385
+ const inheritedLayers = [this.layers.global, ...layers.filter((layer) => layer !== own)];
9386
+ const restrictable = new Set(inheritedLayers.flatMap((layer) => layer.names()));
9387
+ return {
9388
+ restrictable,
9389
+ known: /* @__PURE__ */ new Set([...restrictable, ...own?.names() ?? []])
9390
+ };
7945
9391
  });
7946
9392
  }
7947
9393
  /**
7948
- * Read the visible capability definitions for descriptions and program bindings.
7949
- * @param scope - viewing Agent or preset; omitted selects the global view.
7950
- * @param toolSet - step admission; omit only to inspect registered definitions.
7951
- * @returns definitions after scoped shadowing and restrictions, limited to the step's admission when given.
9394
+ * Resolve one registration as a scope sees it: nearer contributions shadow
9395
+ * farther ones, and a restricted inherited tool reads as absent.
9396
+ * @param name - the tool name as registered or included.
9397
+ * @param scope - the viewing scope (the agent); omitted selects the unscoped view.
9398
+ * @returns the registration the scope resolves, or undefined when none is visible.
9399
+ * @throws ToolCompositionError when the deciding scope offers several definitions.
9400
+ */
9401
+ registered(name, scope) {
9402
+ return resolveToolCandidate(name, this.read(() => {
9403
+ const layers = this.layers.chainLayers(scope);
9404
+ const own = this.layers.peek(scope);
9405
+ const owned = own?.candidate(name, scope);
9406
+ if (owned !== void 0) return owned;
9407
+ if (!layers.every((layer) => layer.admits(name))) return void 0;
9408
+ for (const layer of layers.toReversed()) {
9409
+ if (layer === own) continue;
9410
+ const inherited = layer.candidate(name, scope);
9411
+ if (inherited !== void 0) return inherited;
9412
+ }
9413
+ return this.layers.global.candidate(name, scope);
9414
+ }));
9415
+ }
9416
+ /**
9417
+ * Resolve one entry of the root a scope selects: a native root resolves the
9418
+ * scope's registrations, a PTC root only its program entry.
9419
+ * @param name - entry name.
9420
+ * @param scope - the viewing scope (the agent); omitted reads the root the unscoped context selects.
9421
+ * @returns the root's entry, or undefined when the root has none with that name.
9422
+ * @throws ToolRegistryUnavailableError when the scope's selected root is missing or unloaded.
9423
+ * @throws ToolCompositionError when the deciding scope offers several definitions, or when the root
9424
+ * or an included registry reads `ctx.tools`.
9425
+ */
9426
+ get(name, scope) {
9427
+ return this.callRoot(() => this.selectRoot(scope).get(name, scope));
9428
+ }
9429
+ /**
9430
+ * List the entries of the root a scope selects, which its model steps
9431
+ * declare: a native root lists the scope's registrations after shadowing and
9432
+ * restrictions, a PTC root only its program entry.
9433
+ * @param scope - the viewing scope (the agent); omitted reads the root the unscoped context selects.
9434
+ * @returns the root's entries.
9435
+ * @throws ToolRegistryUnavailableError when the scope's selected root is missing or unloaded.
9436
+ * @throws ToolCompositionError when a visible name has several definitions in its deciding scope, or
9437
+ * when the root or an included registry reads `ctx.tools`.
7952
9438
  */
7953
- definitions(scope, toolSet) {
7954
- return toolSet === void 0 ? [...this.view(scope).visible.values()] : [...toolSet.view(scope).values()];
9439
+ getAll(scope) {
9440
+ return this.callRoot(() => resolveToolList(this.selectRoot(scope).getAll(scope)));
7955
9441
  }
7956
9442
  /**
7957
- * Project visible definitions onto the allowlisted model-facing schema fields,
7958
- * excluding execution and presentation callbacks.
7959
- * @param scope - the viewing scope (the agent); omitted = the global view.
7960
- * @param toolSet - step admission, or omitted for registered-definition inspection.
7961
- * @returns one deep-cloned schema per visible tool.
9443
+ * Run one call into a root registry. A root receives the registrations from
9444
+ * `setRoot()`, so a root that reads `ctx.tools` during the call would read
9445
+ * itself; that read fails instead of recursing. A read that arrives while the
9446
+ * registrations are being read comes from an included registry and fails as
9447
+ * an inclusion cycle.
9448
+ * @param call - lookup or inclusion on a root registry.
9449
+ * @returns the call's result.
9450
+ * @throws ToolCompositionError when the root or an included registry reads `ctx.tools` during the call.
7962
9451
  */
7963
- schemas(scope, toolSet) {
7964
- return this.definitions(scope, toolSet).map((definition) => projectToolSchema(definition, true));
9452
+ callRoot(call) {
9453
+ if (this.viewing) throw inclusionCycle();
9454
+ if (this.callingRoot) throw new ToolCompositionError("a root tool registry must not include or read ctx.tools; ctx.tools.setRoot() gives the root the registrations each scope sees");
9455
+ this.callingRoot = true;
9456
+ try {
9457
+ return call();
9458
+ } finally {
9459
+ this.callingRoot = false;
9460
+ }
7965
9461
  }
7966
9462
  /**
7967
- * Provide the executor for the calling scope; an unscoped contribution is the deployment default.
7968
- * Rendering any executor-owned section requires the viewing scope's selection to remain available.
7969
- * @param executor - initialized provider owned by the contributing plugin.
9463
+ * Select the root registry for the calling scope; an unscoped call selects
9464
+ * the root for every scope without its own. Agents use the nearest selected root. The
9465
+ * root includes the registrations each viewing scope sees, and keeps them
9466
+ * after unloading so accepted batches settle their calls; selecting the
9467
+ * same registry again does not include them twice. A root must not include
9468
+ * or read `ctx.tools`: such a read fails with `ToolCompositionError` when
9469
+ * the root is selected or, for a root that reads it later, in the lookup or
9470
+ * batch that reaches it. Register tools through `ctx.tools`: a tool
9471
+ * registered directly in a root skips the scope's conflict check, so another
9472
+ * definition registered under its name through `ctx.tools` is accepted and
9473
+ * the next `ctx.tools.getAll()` throws. Selecting or unloading a root emits
9474
+ * `tools/change`; every observer runs, and an observer that throws fails the
9475
+ * selection, which restores the scope's earlier selection, or none, and
9476
+ * emits `tools/change` again.
9477
+ * @param registry - initialized root owned by the contributing plugin.
7970
9478
  * @returns the effect disposer. Unloading leaves the selection unavailable until it is replaced.
9479
+ * @throws Error when the calling scope already has a live root.
9480
+ * @throws ToolCompositionError when the root's own entries conflict with the registrations, or when the root reads `ctx.tools`.
9481
+ * @throws an `AggregateError` whose `errors` holds the observer failures when a `tools/change` observer fails the selection.
7971
9482
  */
7972
- setExecutor(executor) {
9483
+ setRoot(registry) {
7973
9484
  const scope = scopeOf(this.ctx);
7974
- if ((scope === void 0 ? this.root : this.scoped.get(scope))?.executor !== void 0) throw new Error("Only one tool executor may be registered in each scope");
7975
- const record = { executor };
9485
+ const key = scope ?? this.unscoped;
9486
+ const existing = this.roots.get(key);
9487
+ if (existing?.registry !== void 0) throw new Error("Only one root tool registry may be installed in each scope");
9488
+ const record = { registry };
9489
+ const select = (selection) => {
9490
+ if (selection === void 0) this.roots.delete(key);
9491
+ else this.roots.set(key, selection);
9492
+ };
7976
9493
  return this.ctx.effect(function* () {
7977
- for (const section of executor.sections ?? []) yield this.ctx.systemPrompt.section({
7978
- name: section.name,
7979
- order: section.order,
7980
- ...section.interpolate === void 0 ? {} : { interpolate: section.interpolate },
7981
- text: ({ scope, toolSet }) => {
7982
- if (this.selectExecutor(scope) !== executor) return "";
7983
- return typeof section.text === "function" ? section.text(this.definitions(scope, toolSet)) : section.text;
9494
+ const undo = this.callRoot(() => {
9495
+ const removeInclusion = this.includedRoots.has(registry) ? void 0 : registry.include(this.registrations);
9496
+ try {
9497
+ resolveToolList(registry.getAll(scope));
9498
+ } catch (error) {
9499
+ removeInclusion?.();
9500
+ throw error;
7984
9501
  }
9502
+ return removeInclusion;
7985
9503
  });
7986
- if (scope === void 0) this.root = record;
7987
- else this.scoped.set(scope, record);
9504
+ select(record);
9505
+ let committed = false;
7988
9506
  yield () => {
7989
- record.executor = void 0;
9507
+ if (committed) record.registry = void 0;
9508
+ else {
9509
+ select(existing);
9510
+ undo?.();
9511
+ }
9512
+ this.notifyChange();
7990
9513
  };
7991
- }.bind(this), "tools.setExecutor()");
9514
+ this.notifyChange();
9515
+ committed = true;
9516
+ this.includedRoots.add(registry);
9517
+ }.bind(this), "tools.setRoot()");
7992
9518
  }
7993
9519
  /**
7994
- * Resolve the nearest scoped provider, or the deployment default.
7995
- * @param scope - Agent or preset scope; omitted selects only the root contribution.
7996
- * @returns the selected executor; throws when it is missing or unloaded.
9520
+ * Resolve the nearest root selected along the scope chain, ending with the unscoped selection.
9521
+ * @param scope - Agent or preset scope; omitted reads only the unscoped selection.
9522
+ * @returns the selected root; throws when it is missing or unloaded.
7997
9523
  */
7998
- selectExecutor(scope) {
7999
- let record;
8000
- for (const key of scopeChainOf(scope)) {
8001
- record = this.scoped.get(key);
8002
- if (record !== void 0) break;
8003
- }
8004
- record ??= this.root;
8005
- const executor = record?.executor;
8006
- if (executor === void 0) throw new ToolExecutorUnavailableError();
8007
- return executor;
9524
+ selectBaseRoot(scope) {
9525
+ const record = [...scopeChainOf(scope), this.unscoped].map((key) => this.roots.get(key)).find((found) => found !== void 0);
9526
+ if (record?.registry === void 0) throw new ToolRegistryUnavailableError();
9527
+ return record.registry;
9528
+ }
9529
+ /**
9530
+ * The registry that answers a scope's lookups: the nearest environment
9531
+ * registry, which reads the scope's root, else the root itself.
9532
+ * @param scope - Agent or preset scope; omitted reads only the unscoped selections.
9533
+ * @throws ToolRegistryUnavailableError when the scope's root is missing or unloaded.
9534
+ */
9535
+ selectRoot(scope) {
9536
+ const root = this.selectBaseRoot(scope);
9537
+ return [...scopeChainOf(scope), this.unscoped].map((key) => this.environments.get(key)).find((found) => found !== void 0) ?? root;
9538
+ }
9539
+ /**
9540
+ * Select the environment registry for the calling scope and the scopes
9541
+ * below it without their own. `ctx.tools` includes the root each viewing
9542
+ * scope selects in it, resolved at every query, so it stays above any root
9543
+ * the scope selects, including one that loads later or reloads; lookups,
9544
+ * declarations, and calls then go through it. It offers the root's entries
9545
+ * in execution environments, such as copies with `resolveEnvironment` whose
9546
+ * `origin` names the root's definition, and must not read `ctx.tools`.
9547
+ * Selecting or removing it emits `tools/change`.
9548
+ * @param registry - the environment registry; its `include()` receives, once, a view of the root each scope selects.
9549
+ * @returns the effect disposer that removes the registry and its inclusion.
9550
+ * @throws Error when the calling scope already has an environment registry.
9551
+ * @throws ToolCompositionError when the registry reads `ctx.tools` or offers conflicting entries for the calling scope's root.
9552
+ */
9553
+ setEnvironments(registry) {
9554
+ const scope = scopeOf(this.ctx);
9555
+ const key = scope ?? this.unscoped;
9556
+ if (this.environments.has(key)) throw new Error("Only one tool environment registry may be set in each scope");
9557
+ return this.ctx.effect(function* () {
9558
+ const removeInclusion = this.callRoot(() => registry.include({
9559
+ get: (name, viewer) => this.selectBaseRoot(viewer).get(name, viewer),
9560
+ getAll: (viewer) => this.selectBaseRoot(viewer).getAll(viewer)
9561
+ }));
9562
+ this.environments.set(key, registry);
9563
+ yield () => {
9564
+ this.environments.delete(key);
9565
+ removeInclusion();
9566
+ this.notifyChange();
9567
+ };
9568
+ if ([...scopeChainOf(scope), this.unscoped].map((found) => this.roots.get(found)).find((found) => found !== void 0)?.registry !== void 0) this.callRoot(() => resolveToolList(registry.getAll(scope)));
9569
+ this.notifyChange();
9570
+ }.bind(this), "tools.setEnvironments()");
8008
9571
  }
8009
9572
  /**
8010
- * Delegate a raw call batch to its Agent's provider or the deployment default.
8011
- * Select at dispatch; accepted batches settle through that provider even if it unloads.
8012
- * @param input - original calls, optional owning Agent, and optional logging step.
8013
- * @returns the selected executor's settled batch; unavailable selections reject.
9573
+ * Execute a complete batch of calls to the entries of the root the Agent
9574
+ * selects, or the unscoped context's root for a standalone call. Each call runs the entry the root
9575
+ * resolves for the Agent; with a model step, only the exact entry the step
9576
+ * declared, and any other call fails as `UNKNOWN_TOOL`. A call naming a
9577
+ * tool the Agent can reach only from the root's entries, such as a program
9578
+ * binding, fails as `UNKNOWN_TOOL` before `tools/pre-execute`, approval,
9579
+ * guards, and execution wrappers, and its message names the entries the
9580
+ * Agent can call directly. An accepted batch settles through the root it
9581
+ * started with even if that root unloads. With log, root call/result events are committed to
9582
+ * the Agent's Session; without log, they are omitted. One outcome is
9583
+ * returned per input call in input order, including skipped calls on abort,
9584
+ * and the batch never settles while started work is still running.
9585
+ * Internal failures reject with ToolBatchExecutionError after draining,
9586
+ * preserving committed outcomes and context; callers must stop dependent
9587
+ * work and repair missing log results.
9588
+ * @param input - original calls, cancellation, optional concurrency override, Agent, model step, and logging step.
9589
+ * @returns settled results, deferred context, and whether a success concludes the turn.
9590
+ * @throws ToolRegistryUnavailableError when the Agent's selected root is missing or unloaded.
8014
9591
  */
8015
9592
  async execute(input) {
8016
- return this.selectExecutor(input.agent).execute(input);
9593
+ const root = this.selectRoot(input.agent);
9594
+ return executeToolBatch(input, new ToolExecutionPipeline(this.ctx, {
9595
+ get: (name, scope, toolStep) => {
9596
+ const entry = this.callRoot(() => root.get(name, scope));
9597
+ return entry !== void 0 && (toolStep?.declares(entry) ?? true) ? entry : void 0;
9598
+ },
9599
+ reject: (exec) => {
9600
+ if (this.callRoot(() => root.get(exec.name, exec.agent)) !== void 0) return void 0;
9601
+ if (this.registered(exec.name, exec.agent) === void 0) return void 0;
9602
+ const callable = exec.toolStep === void 0 ? this.callRoot(() => root.getAll(exec.agent)) : exec.toolStep.declarations.filter((entry) => this.callRoot(() => root.get(entry.name, exec.agent)) === entry);
9603
+ return new ToolNotFoundError(exec.name, [...new Set(callable.map((entry) => entry.name))]);
9604
+ }
9605
+ }));
8017
9606
  }
8018
9607
  /**
8019
9608
  * Register a monotonic denial in the calling scope.
@@ -8035,6 +9624,10 @@ var GuardLayer = class {
8035
9624
  }
8036
9625
  }
8037
9626
  });
9627
+ /** The failure of a read that re-enters `ctx.tools` through an included registry. */
9628
+ function inclusionCycle() {
9629
+ return new ToolCompositionError("tool registry inclusion cycle reaches ctx.tools");
9630
+ }
8038
9631
  //#endregion
8039
9632
  //#region src/host/tools.ts
8040
9633
  /**
@@ -8769,22 +10362,10 @@ function readWebServer(ctx) {
8769
10362
  }
8770
10363
  }
8771
10364
  /**
8772
- * Resolve the host's authenticated entry URL for `url` across SDK cohorts:
8773
- * legacy hosts expose `connection.authenticatedUrl(url)`, while peer-auth
8774
- * hosts collect entry URLs via `ctx.emit(webServer, 'webserver/entry-url', url, entries)`.
10365
+ * Resolve the host's authenticated entry URL for `url` via the official
10366
+ * `webserver/entry-url` event (`ctx.emit(webServer, 'webserver/entry-url', url, entries)`).
8775
10367
  */
8776
10368
  function resolveAuthenticatedUrl(ctx, url) {
8777
- let connection;
8778
- if (typeof ctx.get === "function") try {
8779
- connection = ctx.get("connection");
8780
- } catch {
8781
- connection = void 0;
8782
- }
8783
- if (connection !== void 0 && typeof connection.authenticatedUrl === "function") try {
8784
- return connection.authenticatedUrl(url);
8785
- } catch {
8786
- return;
8787
- }
8788
10369
  const webServer = readWebServer(ctx);
8789
10370
  if (webServer === void 0 || typeof ctx.emit !== "function") return void 0;
8790
10371
  const entries = [];