@linxin666/dsh-remote-bridge 0.4.22 → 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
@@ -4646,6 +4646,8 @@ const USAGE_METHODS = /* @__PURE__ */ new Set([METHOD_USAGE_SESSION, METHOD_USAG
4646
4646
  const DEEPSEEK_BALANCE_URL = `https://api.deepseek.com/user/balance`;
4647
4647
  /** 官方余额适配认的 provider 路由 id,与 dsh-usage 的 deepseek adapter 同一份名单。 */
4648
4648
  const DEEPSEEK_ROUTES = /* @__PURE__ */ new Set(["deepseek", "deepseek-official"]);
4649
+ /** 官方 App 托管账户的路由 id(走 `ctx.deepseekAccount.getBalance`)。 */
4650
+ const DEEPSEEK_ACCOUNT_ROUTE = "deepseek-account";
4649
4651
  /** pi-ai 凭据记录的 scope:一条记录以 `<scope>/<id>` 寻址。 */
4650
4652
  const PI_AI_CREDENTIAL_SCOPE = "llm-pi-ai";
4651
4653
  /** pi-ai 适配器的设置命名空间。 */
@@ -4836,21 +4838,23 @@ var UsageService = class {
4836
4838
  * @returns 余额,或者为什么读不到。
4837
4839
  */
4838
4840
  async balance(provider) {
4841
+ const faces = this.#faces();
4842
+ if (provider === DEEPSEEK_ACCOUNT_ROUTE) return await this.#accountBalance(provider, faces.deepseekAccount);
4839
4843
  if (!DEEPSEEK_ROUTES.has(provider)) return {
4840
4844
  provider,
4841
4845
  unsupported: "not-deepseek-route"
4842
4846
  };
4843
- const faces = this.#faces();
4844
4847
  if (!officialRoute(provider, faces.settings)) return {
4845
4848
  provider,
4846
4849
  unsupported: "not-deepseek-route"
4847
4850
  };
4848
- const credential = await this.#credentialOf(provider, faces);
4849
- if (credential === void 0) return {
4851
+ const authorized = await this.#deepseekAuthOf(provider, faces);
4852
+ const credential = authorized === void 0 ? await this.#credentialOf(provider, faces) : void 0;
4853
+ if (authorized === void 0 && credential === void 0) return {
4850
4854
  provider,
4851
4855
  unsupported: "no-credential"
4852
4856
  };
4853
- const cacheKey = `${provider}\u0000${fingerprint(credential)}`;
4857
+ const cacheKey = `${provider}\u0000${authorized !== void 0 ? `${authorized.endpoint}\u0000${headerAuthFingerprint(authorized.headers)}` : fingerprint(credential)}`;
4854
4858
  const cached = this.#cache.get(cacheKey);
4855
4859
  if (cached !== void 0 && this.#options.now() - cached.at < this.#ttl()) return cached.answer;
4856
4860
  const running = this.#inFlight.get(cacheKey);
@@ -4860,7 +4864,7 @@ var UsageService = class {
4860
4864
  this.#inFlight.delete(cacheKey);
4861
4865
  return answer;
4862
4866
  };
4863
- const probe = this.#probe(provider, credential).then(settle, (error) => settle({
4867
+ const probe = (authorized !== void 0 ? this.#probeAuthorized(provider, authorized.endpoint, authorized.headers) : this.#probe(provider, credential)).then(settle, (error) => settle({
4864
4868
  provider,
4865
4869
  unsupported: "probe-failed",
4866
4870
  reason: failureText(error)
@@ -4939,6 +4943,86 @@ var UsageService = class {
4939
4943
  this.#options.log(`the credential reference "${name}" of route "${provider}" could not be resolved: ${failureText(error)}`);
4940
4944
  }
4941
4945
  }
4946
+ /** 优先向官方 `ctx.deepseekAuth` 申请余额请求头,仅接受指向官方 origin 的 api-key 授权。 */
4947
+ async #deepseekAuthOf(provider, faces) {
4948
+ const auth = faces.deepseekAuth;
4949
+ if (auth === void 0 || typeof auth.authorize !== "function") return void 0;
4950
+ try {
4951
+ const authorization = await auth.authorize({
4952
+ consumer: "dsh-remote-bridge",
4953
+ accepts: ["api-key"],
4954
+ billing: "api-key",
4955
+ route: provider,
4956
+ destination: { path: "/user/balance" }
4957
+ }, AbortSignal.timeout(this.#timeout()));
4958
+ if (authorization === void 0 || authorization.kind !== "api-key") return void 0;
4959
+ if (originOf$1(authorization.endpoint) !== "https://api.deepseek.com") return void 0;
4960
+ return {
4961
+ endpoint: authorization.endpoint,
4962
+ headers: { ...authorization.headers }
4963
+ };
4964
+ } catch (error) {
4965
+ this.#options.log(`deepseekAuth could not authorize route "${provider}": ${failureText(error)}`);
4966
+ return;
4967
+ }
4968
+ }
4969
+ /** 通过官方 `ctx.deepseekAccount` 查询 App 托管账户余额,带缓存与并发合并。 */
4970
+ async #accountBalance(provider, account) {
4971
+ if (account === void 0 || typeof account.getState !== "function" || typeof account.getBalance !== "function") return {
4972
+ provider,
4973
+ unsupported: "not-deepseek-route"
4974
+ };
4975
+ const cacheKey = `${provider}\u0000account`;
4976
+ const cached = this.#cache.get(cacheKey);
4977
+ if (cached !== void 0 && this.#options.now() - cached.at < this.#ttl()) return cached.answer;
4978
+ const running = this.#inFlight.get(cacheKey);
4979
+ if (running !== void 0) return await running;
4980
+ const settle = (answer) => {
4981
+ this.#remember(cacheKey, answer);
4982
+ this.#inFlight.delete(cacheKey);
4983
+ return answer;
4984
+ };
4985
+ const probe = (async () => {
4986
+ try {
4987
+ if ((await account.getState()).status !== "credential-stored") return {
4988
+ provider,
4989
+ unsupported: "no-credential"
4990
+ };
4991
+ const offsetMin = (/* @__PURE__ */ new Date()).getTimezoneOffset();
4992
+ const outcome = await account.getBalance({
4993
+ version: "0.2.3",
4994
+ locale: "zh-CN",
4995
+ timezoneOffsetSeconds: offsetMin === 0 ? 0 : -offsetMin * 60
4996
+ });
4997
+ if (outcome === null) return {
4998
+ provider,
4999
+ unsupported: "no-credential"
5000
+ };
5001
+ if (outcome.status === "failed") return {
5002
+ provider,
5003
+ unsupported: "probe-failed",
5004
+ reason: "account balance query failed"
5005
+ };
5006
+ return {
5007
+ provider,
5008
+ ...parseAccountWallets(outcome.value, outcome.bonusWallets),
5009
+ updatedAt: this.#options.now()
5010
+ };
5011
+ } catch (error) {
5012
+ return {
5013
+ provider,
5014
+ unsupported: "probe-failed",
5015
+ reason: failureText(error)
5016
+ };
5017
+ }
5018
+ })().then(settle, (error) => settle({
5019
+ provider,
5020
+ unsupported: "probe-failed",
5021
+ reason: failureText(error)
5022
+ }));
5023
+ this.#inFlight.set(cacheKey, probe);
5024
+ return await probe;
5025
+ }
4942
5026
  /**
4943
5027
  * 对官方余额端点做一次探测。
4944
5028
  *
@@ -4946,10 +5030,13 @@ var UsageService = class {
4946
5030
  * 「这次没读到」,任何一条都不会拿上一轮的旧值顶上。
4947
5031
  */
4948
5032
  async #probe(provider, credential) {
5033
+ return await this.#probeAuthorized(provider, DEEPSEEK_BALANCE_URL, { authorization: `Bearer ${credential}` });
5034
+ }
5035
+ async #probeAuthorized(provider, endpoint, headers) {
4949
5036
  const call = this.#options.fetch ?? defaultFetch;
4950
5037
  try {
4951
- const response = await call(DEEPSEEK_BALANCE_URL, {
4952
- headers: { authorization: `Bearer ${credential}` },
5038
+ const response = await call(endpoint, {
5039
+ headers,
4953
5040
  signal: AbortSignal.timeout(this.#timeout())
4954
5041
  });
4955
5042
  if (!response.ok) return {
@@ -5299,6 +5386,58 @@ function amount(value) {
5299
5386
  const parsed = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
5300
5387
  return Number.isFinite(parsed) ? parsed : void 0;
5301
5388
  }
5389
+ /** 合并官方 `ctx.deepseekAccount.getBalance` 返回的充值与赠金钱包,优先 CNY,次选 USD。 */
5390
+ function parseAccountWallets(value, bonusWallets) {
5391
+ const sum = (list, target) => {
5392
+ let found = false;
5393
+ let total = 0;
5394
+ for (const wallet of list) {
5395
+ if (wallet.currency.toUpperCase() !== target) continue;
5396
+ const num = amount(wallet.balance);
5397
+ if (num === void 0) continue;
5398
+ found = true;
5399
+ total += num;
5400
+ }
5401
+ return {
5402
+ found,
5403
+ total
5404
+ };
5405
+ };
5406
+ const cnyTopped = sum(value, "CNY");
5407
+ const cnyBonus = sum(bonusWallets, "CNY");
5408
+ if (cnyTopped.found || cnyBonus.found) {
5409
+ const toppedUp = Number(cnyTopped.total.toFixed(2));
5410
+ const granted = Number(cnyBonus.total.toFixed(2));
5411
+ return {
5412
+ currency: "CNY",
5413
+ toppedUp,
5414
+ granted,
5415
+ total: Number((toppedUp + granted).toFixed(2))
5416
+ };
5417
+ }
5418
+ const usdTopped = sum(value, "USD");
5419
+ const usdBonus = sum(bonusWallets, "USD");
5420
+ if (usdTopped.found || usdBonus.found) {
5421
+ const toppedUp = Number(usdTopped.total.toFixed(2));
5422
+ const granted = Number(usdBonus.total.toFixed(2));
5423
+ return {
5424
+ currency: "USD",
5425
+ toppedUp,
5426
+ granted,
5427
+ total: Number((toppedUp + granted).toFixed(2))
5428
+ };
5429
+ }
5430
+ return {
5431
+ currency: "CNY",
5432
+ toppedUp: 0,
5433
+ granted: 0,
5434
+ total: 0
5435
+ };
5436
+ }
5437
+ /** 根据授权请求头计算凭据指纹,键名小写排序确保稳定。 */
5438
+ function headerAuthFingerprint(headers) {
5439
+ return fingerprint(Object.entries(headers).map(([key, value]) => `${key.toLowerCase()}:${value}`).sort().join("\n"));
5440
+ }
5302
5441
  /**
5303
5442
  * 凭据的指纹(FNV-1a)。
5304
5443
  *
@@ -5399,8 +5538,8 @@ const WIRE_TABLE = [
5399
5538
  wire: "request"
5400
5539
  },
5401
5540
  {
5402
- namespace: "session",
5403
- method: "modelCatalog",
5541
+ namespace: "models",
5542
+ method: "catalog",
5404
5543
  wire: "none"
5405
5544
  },
5406
5545
  {
@@ -5943,6 +6082,30 @@ function effortIdsOf(groups, provider, model) {
5943
6082
  * @param efforts - the host's preference table.
5944
6083
  * @returns the rows to publish, with the remembered levels injected.
5945
6084
  */
6085
+ /**
6086
+ * Providers whose own routes still accept `off` in requests but hide it from
6087
+ * picker choices unless the model declares `off` as its default effort (DSH #9860).
6088
+ */
6089
+ const OFF_HIDDEN_PROVIDERS = /* @__PURE__ */ new Set(["deepseek-account", "deepseek-official"]);
6090
+ /** Hide `off` from DeepSeek picker rows unless it is the model's declared default effort. */
6091
+ function filterPickerReasoning(provider, row) {
6092
+ if (!OFF_HIDDEN_PROVIDERS.has(provider)) return row;
6093
+ const reasoning = row.reasoning;
6094
+ if (!isRecord(reasoning) || !Array.isArray(reasoning.efforts)) return row;
6095
+ const defaultEffort = optionalText(reasoning.defaultEffort);
6096
+ const filtered = reasoning.efforts.filter((effort) => {
6097
+ const id = isRecord(effort) ? optionalText(effort.id) : void 0;
6098
+ return id !== "off" || id === defaultEffort;
6099
+ });
6100
+ if (filtered.length === reasoning.efforts.length) return row;
6101
+ return {
6102
+ ...row,
6103
+ reasoning: {
6104
+ ...reasoning,
6105
+ efforts: filtered
6106
+ }
6107
+ };
6108
+ }
5946
6109
  function withPreferredEfforts(groups, efforts) {
5947
6110
  if (!Array.isArray(groups)) return [];
5948
6111
  return groups.map((group) => {
@@ -5953,10 +6116,11 @@ function withPreferredEfforts(groups, efforts) {
5953
6116
  ...group,
5954
6117
  models: group.models.map((row) => {
5955
6118
  if (!isRecord(row)) return row;
5956
- const model = optionalText(row.id);
6119
+ const visible = filterPickerReasoning(provider, row);
6120
+ const model = optionalText(visible.id);
5957
6121
  const preferred = model === void 0 ? void 0 : efforts.effortOf(provider, model);
5958
- return preferred === void 0 ? row : {
5959
- ...row,
6122
+ return preferred === void 0 ? visible : {
6123
+ ...visible,
5960
6124
  preferredEffort: preferred
5961
6125
  };
5962
6126
  })
@@ -7085,9 +7249,9 @@ var BridgeConnection = class {
7085
7249
  async #sessionModels(payload) {
7086
7250
  const sessionId = stringArg(payload, "sessionId");
7087
7251
  if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.models requires sessionId");
7088
- const catalog = await this.#unary("session", "modelCatalog");
7252
+ const catalog = await this.#unary("models", "catalog");
7089
7253
  if (!catalog.ok) return catalog;
7090
- if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, "session/modelCatalog returned no catalog");
7254
+ if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, "models/catalog returned no catalog");
7091
7255
  const folded = await this.#sessionCurrent(sessionId, catalog.value);
7092
7256
  if (!folded.ok) return folded;
7093
7257
  await this.#options.modelEfforts.load();
@@ -7113,7 +7277,7 @@ var BridgeConnection = class {
7113
7277
  */
7114
7278
  async #sessionCurrent(sessionId, catalog) {
7115
7279
  const fallback = selectionOf(catalog.default);
7116
- if (fallback === void 0) return refusal(CODE_INTERNAL, "session/modelCatalog returned no default model");
7280
+ if (fallback === void 0) return refusal(CODE_INTERNAL, "models/catalog returned no default model");
7117
7281
  const projections = await this.#unary("session", "projections", { sessionId });
7118
7282
  if (!projections.ok) return projections;
7119
7283
  const folded = modelSelectionOf(projections.value);
@@ -7179,7 +7343,7 @@ var BridgeConnection = class {
7179
7343
  async #rememberedEffort(provider, model) {
7180
7344
  const remembered = this.#options.modelEfforts.effortOf(provider, model);
7181
7345
  if (remembered === void 0) return void 0;
7182
- const catalog = await this.#unary("session", "modelCatalog");
7346
+ const catalog = await this.#unary("models", "catalog");
7183
7347
  if (!catalog.ok || !isRecord(catalog.value)) return remembered;
7184
7348
  const offered = effortIdsOf(catalog.value.groups, provider, model);
7185
7349
  if (offered === void 0) return void 0;
@@ -7207,9 +7371,9 @@ var BridgeConnection = class {
7207
7371
  const effort = stringArg(payload, "effort");
7208
7372
  if (sessionId === void 0 || provider === void 0 || model === void 0 || effort === void 0) return refusal(CODE_INVALID_ARGS, "session.setEffort requires sessionId, provider, model and effort");
7209
7373
  await this.#options.modelEfforts.load();
7210
- const catalog = await this.#unary("session", "modelCatalog");
7374
+ const catalog = await this.#unary("models", "catalog");
7211
7375
  if (!catalog.ok) return catalog;
7212
- if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, "session/modelCatalog returned no catalog");
7376
+ if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, "models/catalog returned no catalog");
7213
7377
  const offered = effortIdsOf(catalog.value.groups, provider, model);
7214
7378
  if (offered === void 0) return refusal(CODE_INVALID_ARGS, `session.setEffort: this host publishes no model ${provider}/${model}`);
7215
7379
  if (!offered.includes(effort)) return refusal(CODE_INVALID_ARGS, `session.setEffort: ${effort} is not a reasoning effort of ${provider}/${model}`);
@@ -10612,9 +10776,9 @@ var SessionPermissions = class {
10612
10776
  //#endregion
10613
10777
  //#region src/host/dsh-home.ts
10614
10778
  /**
10615
- * DSH_HOME resolution shared by the plugin family's Host halves: the
10616
- * environment override wins, the platform home fallback follows. Mirrors
10617
- * what dsh-pet and dsh-liangshen each used to implement locally.
10779
+ * DSH_HOME and DSH_AGENTS_HOME resolution shared by the plugin family's Host
10780
+ * halves: environment overrides win (blank values treated as unset), then the
10781
+ * platform home fallbacks follow — mirroring `@deepseek-ai/dsh-home-paths`.
10618
10782
  */
10619
10783
  /** Expand a leading ~ (or ~user) in a path, platform-style. */
10620
10784
  function expandHome(path, home = homedir()) {
@@ -10623,6 +10787,16 @@ function expandHome(path, home = homedir()) {
10623
10787
  if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
10624
10788
  return path;
10625
10789
  }
10790
+ function resolveUserRoot(envValue, defaultDirName, home) {
10791
+ const isPosix = home.startsWith("/");
10792
+ const j = isPosix ? join$1 : join;
10793
+ const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
10794
+ if (envValue !== void 0 && envValue.trim() !== "") {
10795
+ const expanded = expandHome(envValue.trim(), home);
10796
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
10797
+ }
10798
+ return j(home, defaultDirName);
10799
+ }
10626
10800
  /**
10627
10801
  * Resolve the DSH home directory.
10628
10802
  * @param env - process environment to read DSH_HOME from.
@@ -10630,15 +10804,7 @@ function expandHome(path, home = homedir()) {
10630
10804
  * @returns the absolute DSH home path.
10631
10805
  */
10632
10806
  function resolveDshHome(env = process.env, home = homedir()) {
10633
- const isPosix = home.startsWith("/");
10634
- const j = isPosix ? join$1 : join;
10635
- const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
10636
- const raw = env.DSH_HOME;
10637
- if (raw !== void 0 && raw.trim() !== "") {
10638
- const expanded = expandHome(raw.trim(), home);
10639
- return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
10640
- }
10641
- return j(home, ".dsh");
10807
+ return resolveUserRoot(env.DSH_HOME, ".dsh", home);
10642
10808
  }
10643
10809
  /** Resolve the DSH home directory from the live environment. */
10644
10810
  function dshHome() {
@@ -11913,212 +12079,335 @@ function makePairTokenRoute(deps) {
11913
12079
  };
11914
12080
  }
11915
12081
  //#endregion
11916
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-error@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1/node_modules/@deepseek-ai/dsh-error/lib/index.js
12082
+ //#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
11917
12083
  /**
11918
- * Harness error base with a stable machine-routable code and chained cause.
11919
- * Package errors extend it so tool results and replay can retain failure class.
11920
- * @module @deepseek-ai/dsh-error
12084
+ * Shared insertion-ordered storage and effect ownership for scope-aware registries.
12085
+ *
12086
+ * @module @deepseek-ai/dsh-scope
11921
12087
  */
11922
12088
  /**
11923
- * Base class for all harness errors. Carries a `code` (stable, programmatic —
11924
- * e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the
11925
- * human-readable `message`, and supports `cause` chaining via the standard
11926
- * `ErrorOptions`. `name` defaults to the subclass constructor name.
12089
+ * Insertion-ordered named entries with caller-owned duplicate diagnostics.
12090
+ *
12091
+ * Values are borrowed. Iterators are live within one nonempty table
12092
+ * generation; draining the table detaches them from later insertions. Each
12093
+ * successful insertion returns an idempotent undo for that exact entry.
11927
12094
  */
11928
- var HarnessError = class extends Error {
11929
- /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
11930
- code;
11931
- constructor(message, code, options) {
11932
- super(message, options);
11933
- this.code = code;
11934
- this.name = new.target.name;
12095
+ var NamedEntries = class {
12096
+ duplicateError;
12097
+ data = /* @__PURE__ */ new Map();
12098
+ constructor(duplicateError) {
12099
+ this.duplicateError = duplicateError;
11935
12100
  }
11936
- };
11937
- //#endregion
11938
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1_@deeps_6153b0a06151bba505d5f32876686bf8/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
11939
- /** The one Remote failure class shared by owners, the Gateway, and consumers. */
11940
- /**
11941
- * One Remote call failure: a `HarnessError` carrying its stable code and typed
11942
- * details. Owners throw it at the failure point; the Host Gateway encodes it
11943
- * onto the wire unchanged; the Client face rebuilds an instance for the
11944
- * `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
11945
- * A tool body that throws it records `name: 'RemoteError'` and its Remote code
11946
- * on `tool/result`. Discrimination is always by `code`, never by instanceof.
11947
- */
11948
- var RemoteError = class extends HarnessError {
11949
- code;
11950
- details;
11951
- /** Structural marker: cross-realm/bundle identification never uses instanceof. */
11952
- isDSHRemoteError = true;
11953
12101
  /**
11954
- * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
11955
- * @param message - human diagnostic carried across the wire.
11956
- * @param details - structured payload typed by the code.
11957
- * @param options - standard Error options (`cause` survives in-process only).
12102
+ * Insert one unique name.
12103
+ * @param name - name unique within this table.
12104
+ * @param value - borrowed value to retain.
12105
+ * @returns an idempotent undo that removes only this insertion.
11958
12106
  */
11959
- constructor(code, message, details, options) {
11960
- super(message, code, options);
11961
- this.code = code;
11962
- this.details = details;
11963
- this.name = "RemoteError";
12107
+ insert(name, value) {
12108
+ const data = this.data;
12109
+ if (data.has(name)) throw this.duplicateError(name);
12110
+ data.set(name, value);
12111
+ let active = true;
12112
+ return () => {
12113
+ if (!active) return;
12114
+ active = false;
12115
+ data.delete(name);
12116
+ if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
12117
+ };
11964
12118
  }
11965
- };
11966
- /**
11967
- * Remote decorators and explicit Gateway bindings backed by versioned
11968
- * descriptors carried on decorated class prototypes. Strict reflection
11969
- * remains a Typert compiler responsibility.
11970
- * @module @deepseek-ai/dsh-typert-protocol
11971
- */
11972
- const TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
11973
- /**
11974
- * Test one generated Remote name against the Connection endpoint grammar.
11975
- * @param value - namespace, method, lookup, or Context segment.
11976
- * @returns whether the value can cross the shared RPC carrier unchanged.
11977
- */
11978
- function isTypertRemoteSegment(value) {
11979
- return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
11980
- }
11981
- const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
11982
- /**
11983
- * Bind one visible Service field to a Cordis key and Remote namespace. A
11984
- * service that owns a Cordis Context also gives its tree `ctx.invocation`,
11985
- * `undefined` outside a Remote call, so no `TypertRemoteService` is needed for
11986
- * a Host composition to read it.
11987
- * @param service - owning Service instance, normally `this`.
11988
- * @param serviceKey - exact Cordis service key.
11989
- * @param options - optional wire namespace.
11990
- * @returns a frozen, inspectable binding with no compiler-injected metadata.
11991
- */
11992
- function bindTypertRemote(service, serviceKey, options = {}) {
11993
- validateName("service key", serviceKey);
11994
- const namespace = options.namespace ?? serviceKey;
11995
- validateName("namespace", namespace);
11996
- const ctx = Reflect.get(service, "ctx");
11997
- if (Context.is(ctx)) provideInvocationAccessor(ctx);
11998
- return Object.freeze({
11999
- service,
12000
- serviceKey,
12001
- namespace
12002
- });
12003
- }
12004
- /** Cordis Service base that exposes its registered name through Typert Gateway. */
12005
- var TypertRemoteService = class extends Service {
12006
- /** Visible binding consumed by the Gateway's source-mode discovery. */
12007
- typertRemote;
12008
12119
  /**
12009
- * Register the Service and bind the same key to Typert Gateway.
12010
- * @param ctx - owning Cordis Context.
12011
- * @param serviceKey - exact Cordis service key and default wire namespace.
12012
- * @param options - optional wire namespace.
12120
+ * Read one named value.
12121
+ * @param name - name to resolve.
12122
+ * @returns the retained value, or `undefined` when absent.
12013
12123
  */
12014
- constructor(ctx, serviceKey, options = {}) {
12015
- super(ctx, serviceKey);
12016
- this.typertRemote = bindTypertRemote(this, this.name, options);
12124
+ get(name) {
12125
+ return this.data.get(name);
12126
+ }
12127
+ /**
12128
+ * Test one name for membership.
12129
+ * @param name - name to test.
12130
+ * @returns whether the table contains that name.
12131
+ */
12132
+ has(name) {
12133
+ return this.data.has(name);
12134
+ }
12135
+ /**
12136
+ * Iterate live names in insertion order.
12137
+ * @returns the native live key iterator.
12138
+ */
12139
+ keys() {
12140
+ return this.data.keys();
12141
+ }
12142
+ /**
12143
+ * Iterate live entries in insertion order.
12144
+ * @returns the native live entry iterator.
12145
+ */
12146
+ entries() {
12147
+ return this.data.entries();
12148
+ }
12149
+ /**
12150
+ * Iterate live values in insertion order.
12151
+ * @returns the native live value iterator.
12152
+ */
12153
+ values() {
12154
+ return this.data.values();
12155
+ }
12156
+ /**
12157
+ * Test whether this table has no entries.
12158
+ * @returns whether the table is empty.
12159
+ */
12160
+ isEmpty() {
12161
+ return this.data.size === 0;
12017
12162
  }
12018
12163
  };
12019
12164
  /**
12020
- * Make `ctx.invocation` read as `undefined` outside a Remote call instead of the
12021
- * reflect service's "cannot get property" error; a call-derived Context shadows
12022
- * the accessor with its own property. The first Remote Service constructed in a
12023
- * tree registers it on the root, where it outlives any one Service.
12165
+ * Insertion-ordered anonymous entries with independent registration identity.
12166
+ *
12167
+ * Equal values remain separate registrations. Values are borrowed, and
12168
+ * iterators are live within one nonempty table generation; draining the table
12169
+ * detaches them from later appends.
12024
12170
  */
12025
- function provideInvocationAccessor(ctx) {
12026
- if (Object.hasOwn(ctx[Context.root].reflect.props, "invocation")) return;
12027
- ctx[Context.root].accessor("invocation", { get: () => void 0 });
12028
- }
12029
- function Remote(methodExportOrOptions, context) {
12030
- if (typeof methodExportOrOptions === "string") {
12031
- validateName("Remote export name", methodExportOrOptions);
12032
- return remoteDecorator({ kind: "direct" }, { exportName: methodExportOrOptions });
12033
- }
12034
- if (typeof methodExportOrOptions === "object") return remoteDecorator({ kind: "direct" }, markerOptions(methodExportOrOptions, REMOTE_OPTION_KEYS, "Remote options require name, mode: \"stream\", or resources"));
12035
- if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
12036
- addMarkerInitializer(context, { kind: "direct" });
12037
- }
12038
- const REMOTE_OPTION_KEYS = /* @__PURE__ */ new Set([
12039
- "name",
12040
- "mode",
12041
- "resources"
12042
- ]);
12043
- /** Validate one decorator options object against its accepted keys and select the marker fields. */
12044
- function markerOptions(options, accepted, requirement) {
12045
- const keys = Reflect.ownKeys(options);
12046
- 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}`);
12047
- const { mode, name, resources } = options;
12048
- if (name !== void 0) validateName("Remote export name", name);
12049
- return {
12050
- ...mode === void 0 ? {} : { mode },
12051
- ...name === void 0 ? {} : { exportName: name },
12052
- ...resources === void 0 ? {} : { resources: resourceReaders(resources) }
12053
- };
12054
- }
12055
- /** Freeze declared readers into the marker record; a misdeclared reader fails at decoration. */
12056
- function resourceReaders(resources) {
12057
- const readers = {};
12058
- for (const [kind, reader] of Object.entries(resources)) {
12059
- if (typeof reader !== "function") throw new TypeError(`typert-protocol: Remote resource reader "${kind}" must be a function`);
12060
- readers[kind] = reader;
12171
+ var AnonymousEntries = class {
12172
+ data = /* @__PURE__ */ new Map();
12173
+ /**
12174
+ * Append one independently owned value.
12175
+ * @param value - borrowed value to retain.
12176
+ * @returns an idempotent undo for this exact append.
12177
+ */
12178
+ append(value) {
12179
+ const data = this.data;
12180
+ const key = Symbol();
12181
+ data.set(key, value);
12182
+ let active = true;
12183
+ return () => {
12184
+ if (!active) return;
12185
+ active = false;
12186
+ data.delete(key);
12187
+ if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
12188
+ };
12061
12189
  }
12062
- if (Object.keys(readers).length === 0) throw new TypeError("typert-protocol: Remote resources require at least one reader");
12063
- return Object.freeze(readers);
12064
- }
12065
- function remoteDecorator(invocation, options = {}) {
12066
- return function(_method, context) {
12067
- addMarkerInitializer(context, invocation, options);
12068
- };
12190
+ /**
12191
+ * Iterate live values in insertion order.
12192
+ * @returns the native live value iterator.
12193
+ */
12194
+ values() {
12195
+ return this.data.values();
12196
+ }
12197
+ /**
12198
+ * Test whether this table has no entries.
12199
+ * @returns whether the table is empty.
12200
+ */
12201
+ isEmpty() {
12202
+ return this.data.size === 0;
12203
+ }
12204
+ };
12205
+ /**
12206
+ * Own the global and exact-scope layers for one registry.
12207
+ *
12208
+ * Reads never create scoped layers. Registrations derive both visibility and
12209
+ * effect ownership from the supplied Cordis context, collect undo before
12210
+ * notification, and reclaim only a completely empty aggregate layer.
12211
+ */
12212
+ var ScopedLayers = class {
12213
+ createLayer;
12214
+ onChange;
12215
+ /** The eagerly constructed context-global layer. */
12216
+ global;
12217
+ scoped = /* @__PURE__ */ new Map();
12218
+ constructor(createLayer, onChange) {
12219
+ this.createLayer = createLayer;
12220
+ this.onChange = onChange;
12221
+ this.global = createLayer(void 0);
12222
+ }
12223
+ /**
12224
+ * Read an existing exact-scope overlay. Deliberately chain-blind: callers
12225
+ * addressing one scope's OWN contributions (its restrictions, its guards)
12226
+ * must not silently pick up an ancestor's — use {@link chainLayers} where
12227
+ * inheritance is the point.
12228
+ * @param scope - exact scope key; `undefined` denotes no overlay.
12229
+ * @returns the existing scoped layer, or `undefined` without creating one.
12230
+ */
12231
+ peek(scope) {
12232
+ if (scope === void 0) return void 0;
12233
+ return this.scoped.get(scope);
12234
+ }
12235
+ /**
12236
+ * Existing overlays along the scope's parent chain ({@link scopeChainOf}),
12237
+ * farthest ancestor first and the exact scope last, so a caller layering
12238
+ * them in order gives the nearest scope the final word.
12239
+ * @param scope - viewing scope, or `undefined` for no overlays.
12240
+ * @returns the existing layers, nearest last; absent overlays are skipped.
12241
+ */
12242
+ chainLayers(scope) {
12243
+ const layers = [];
12244
+ for (const key of scopeChainOf(scope).reverse()) {
12245
+ const layer = this.scoped.get(key);
12246
+ if (layer !== void 0) layers.push(layer);
12247
+ }
12248
+ return layers;
12249
+ }
12250
+ /**
12251
+ * Materialize global named entries followed by scope-chain shadows,
12252
+ * farthest ancestor first, so the nearest scope's entry wins a name.
12253
+ * @param scope - viewing scope, or `undefined` for the global view.
12254
+ * @param pick - select the named table from a layer.
12255
+ * @returns an insertion-ordered effective map.
12256
+ */
12257
+ merge(scope, pick) {
12258
+ const merged = new Map(pick(this.global).entries());
12259
+ for (const layer of this.chainLayers(scope)) for (const [name, value] of pick(layer).entries()) merged.set(name, value);
12260
+ return merged;
12261
+ }
12262
+ /**
12263
+ * Attach one synchronous layer mutation to its registration context.
12264
+ * @param ctx - context that determines both scope visibility and effect ownership.
12265
+ * @param action - atomic mutation returning its synchronous undo.
12266
+ * @param options - Cordis effect label and optional change notification.
12267
+ * @returns the exact disposer returned by `ctx.effect()`.
12268
+ */
12269
+ effect(ctx, action, options) {
12270
+ const scope = scopeOf(ctx);
12271
+ const notify = options.notify ?? true;
12272
+ return ctx.effect(function* () {
12273
+ let layer;
12274
+ let created = false;
12275
+ if (scope === void 0) layer = this.global;
12276
+ else {
12277
+ const existing = this.scoped.get(scope);
12278
+ if (existing === void 0) {
12279
+ layer = this.createLayer(scope);
12280
+ this.scoped.set(scope, layer);
12281
+ created = true;
12282
+ } else layer = existing;
12283
+ }
12284
+ let undo;
12285
+ try {
12286
+ undo = action(layer);
12287
+ } catch (error) {
12288
+ if (scope !== void 0 && created && layer.isEmpty()) this.scoped.delete(scope);
12289
+ throw error;
12290
+ }
12291
+ yield () => {
12292
+ undo();
12293
+ if (scope !== void 0 && layer.isEmpty()) this.scoped.delete(scope);
12294
+ if (notify) this.onChange();
12295
+ };
12296
+ if (notify) this.onChange();
12297
+ }.bind(this), options.label);
12298
+ }
12299
+ };
12300
+ /**
12301
+ * Scoped-context primitive: mint a Cordis context that tags registrations with
12302
+ * an opaque identity and build routing-only event carriers for that identity.
12303
+ *
12304
+ * @module @deepseek-ai/dsh-scope
12305
+ */
12306
+ /** Context tag written by {@link createScope}. */
12307
+ const kScope = Symbol("dsh.scope");
12308
+ /** The key associated with each carrier. Presence distinguishes an unkeyed carrier from a non-carrier. */
12309
+ const carrierKeys = /* @__PURE__ */ new WeakMap();
12310
+ /**
12311
+ * The enclosing scope of each key. One relation powers both directions of
12312
+ * scope nesting: registration views inherit DOWN the chain (a child scope
12313
+ * sees its ancestors' layers — {@link ScopedLayers}), and event admission
12314
+ * extends UP it (a listener tagged with an ancestor receives events dispatched
12315
+ * to a descendant key — {@link scopeTarget}).
12316
+ */
12317
+ const scopeParents = /* @__PURE__ */ new WeakMap();
12318
+ /**
12319
+ * The chain from a key to its root ancestor.
12320
+ * @param key - the starting key, or `undefined` for the empty chain.
12321
+ * @returns keys nearest-first: `[key, parent, grandparent, …]`.
12322
+ */
12323
+ function scopeChainOf(key) {
12324
+ const chain = [];
12325
+ for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) chain.push(cursor);
12326
+ return chain;
12069
12327
  }
12070
- function readRemoteMethodDescriptor(prototype) {
12071
- const property = Object.getOwnPropertyDescriptor(prototype, REMOTE_METHOD_DESCRIPTOR);
12072
- if (property === void 0) return void 0;
12073
- const descriptor = property.value;
12074
- if (descriptor === null || typeof descriptor !== "object") throw new TypeError("typert-protocol: Remote method descriptor must be an object");
12075
- const version = Reflect.get(descriptor, "version");
12076
- if (version !== 1) throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(version)}`);
12077
- const methods = Reflect.get(descriptor, "methods");
12078
- if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
12079
- return descriptor;
12328
+ /**
12329
+ * Read the nearest scope tag inherited by a context.
12330
+ * @param ctx - context to inspect.
12331
+ * @returns its scope key, or `undefined` for an unscoped context.
12332
+ */
12333
+ function scopeOf(ctx) {
12334
+ return ctx[kScope];
12080
12335
  }
12081
- function addMarkerInitializer(context, invocation, options = {}) {
12082
- 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");
12083
- const method = context.name;
12084
- context.addInitializer(function() {
12085
- const prototype = Object.getPrototypeOf(this);
12086
- if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
12087
- mark(prototype, method, invocation, options);
12088
- });
12336
+ /**
12337
+ * Build an opaque receiver that preserves the base filter, admits untagged
12338
+ * listeners globally, and admits tagged listeners for a matching key or any
12339
+ * of its ancestors ({@link bindScopeParent}): a listener owned by an enclosing
12340
+ * scope receives every descendant scope's events, which is what lets one
12341
+ * standing composition observe each of the agents composed under it. A tag
12342
+ * BELOW the dispatch key stays excluded — events flow up the chain, never
12343
+ * down.
12344
+ * @param base - subject or service whose existing Cordis filter is preserved.
12345
+ * @param key - routed scope identity, or `undefined` for an unscoped subject.
12346
+ * @returns a carrier whose subject remains available only through event arguments.
12347
+ */
12348
+ function scopeTarget(base, key) {
12349
+ const baseFilter = base[Context.filter];
12350
+ const carrier = { [Context.filter](ctx) {
12351
+ if (baseFilter !== void 0 && !baseFilter.call(base, ctx)) return false;
12352
+ const tag = scopeOf(ctx);
12353
+ if (tag === void 0) return true;
12354
+ for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) if (cursor === tag) return true;
12355
+ return false;
12356
+ } };
12357
+ carrierKeys.set(carrier, key);
12358
+ return carrier;
12089
12359
  }
12090
- function mark(prototype, method, invocation, { mode, exportName, resources }) {
12091
- const descriptor = readRemoteMethodDescriptor(prototype);
12092
- const marker = Object.freeze({
12093
- method,
12094
- ...exportName === void 0 || exportName === method ? {} : { exportName },
12095
- ...mode === void 0 ? {} : { mode },
12096
- invocation: Object.freeze(invocation),
12097
- ...resources === void 0 ? {} : { resources }
12098
- });
12099
- const current = descriptor?.methods.find((candidate) => candidate.method === method);
12100
- if (current !== void 0) {
12101
- if (current.exportName === marker.exportName && current.mode === marker.mode && current.resources === marker.resources && sameInvocation(current.invocation, invocation)) return;
12102
- throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
12360
+ //#endregion
12361
+ //#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
12362
+ /**
12363
+ * Harness error base with a stable machine-routable code and chained cause.
12364
+ * Package errors extend it so tool results and replay can retain failure class.
12365
+ * @module @deepseek-ai/dsh-error
12366
+ */
12367
+ /**
12368
+ * Base class for all harness errors. Carries a `code` (stable, programmatic —
12369
+ * e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the
12370
+ * human-readable `message`, and supports `cause` chaining via the standard
12371
+ * `ErrorOptions`. `name` defaults to the subclass constructor name.
12372
+ */
12373
+ var HarnessError = class extends Error {
12374
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
12375
+ code;
12376
+ constructor(message, code, options) {
12377
+ super(message, options);
12378
+ this.code = code;
12379
+ this.name = new.target.name;
12380
+ }
12381
+ };
12382
+ /**
12383
+ * Render one thrown value as readable text for a log line, tool result, or UI
12384
+ * message. An `Error` contributes its `message`, and another object with a
12385
+ * string `message` contributes that message; every other value is rendered as
12386
+ * JSON when it survives `JSON.stringify`, so a cancelled operation's reason
12387
+ * object reads as its fields instead of `[object Object]`.
12388
+ * @param error - thrown value, `AbortSignal.reason`, or rejected promise value.
12389
+ * @returns readable text, total even for hostile values that trap property reads or coercion.
12390
+ */
12391
+ function errorMessage$1(error) {
12392
+ try {
12393
+ if (error instanceof Error) return error.message;
12394
+ if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
12395
+ return renderValue(error);
12396
+ } catch {
12397
+ return "<unprintable thrown value>";
12103
12398
  }
12104
- Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
12105
- configurable: true,
12106
- value: Object.freeze({
12107
- version: 1,
12108
- methods: Object.freeze([...descriptor?.methods ?? [], marker])
12109
- })
12110
- });
12111
- }
12112
- function sameInvocation(left, right) {
12113
- if (left.kind === "direct") return right.kind === "direct";
12114
- if (right.kind === "direct") return false;
12115
- return left.context === right.context;
12116
- }
12117
- function validateName(subject, value) {
12118
- if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
12399
+ }
12400
+ /** JSON text for a structured thrown value; primitives keep their default coercion and objects without JSON text get a fixed label. */
12401
+ function renderValue(value) {
12402
+ if (typeof value !== "object" || value === null) return String(value);
12403
+ let json;
12404
+ try {
12405
+ json = JSON.stringify(value);
12406
+ } catch (_unrepresentable) {}
12407
+ return typeof json === "string" ? json : "<unrepresentable thrown value>";
12119
12408
  }
12120
12409
  //#endregion
12121
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
12410
+ //#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
12122
12411
  /**
12123
12412
  * Lazily scanned view of one JSON object's top-level fields, built from text
12124
12413
  * that may still be streaming or from an already parsed object. Nothing is
@@ -12762,13 +13051,14 @@ function hasIntrinsicConstructor$1(prototype, name) {
12762
13051
  return false;
12763
13052
  }
12764
13053
  }
12765
- /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
13054
+ /** Whether a candidate is this or another realm's intrinsic `Object.prototype`. */
12766
13055
  function isIntrinsicObjectPrototype$1(value) {
12767
- return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, "Object");
13056
+ return value === Object.prototype || Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, "Object");
12768
13057
  }
12769
13058
  /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
12770
13059
  function hasPlainArrayPrototype$1(value) {
12771
13060
  const prototype = Object.getPrototypeOf(value);
13061
+ if (prototype === Array.prototype) return true;
12772
13062
  if (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, "Array")) return false;
12773
13063
  const objectPrototype = Object.getPrototypeOf(prototype);
12774
13064
  return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);
@@ -12937,7 +13227,226 @@ function deepFreeze(value) {
12937
13227
  return value;
12938
13228
  }
12939
13229
  //#endregion
12940
- //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.10.0-alpha.1/node_modules/@deepseek-ai/cosmokit/lib/index.js
13230
+ //#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
13231
+ /** The one Remote failure class shared by owners, the Gateway, and consumers. */
13232
+ /**
13233
+ * One Remote call failure: a `HarnessError` carrying its stable code and typed
13234
+ * details. Owners throw it at the failure point; the Host Gateway encodes it
13235
+ * onto the wire unchanged; the Client face rebuilds an instance for the
13236
+ * `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
13237
+ * A tool body that throws it records `name: 'RemoteError'` and its Remote code
13238
+ * on `tool/result`. Discrimination is always by `code`, never by instanceof.
13239
+ */
13240
+ var RemoteError = class extends HarnessError {
13241
+ code;
13242
+ details;
13243
+ /** Structural marker: cross-realm/bundle identification never uses instanceof. */
13244
+ isDSHRemoteError = true;
13245
+ /**
13246
+ * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
13247
+ * @param message - human diagnostic carried across the wire.
13248
+ * @param details - structured payload typed by the code.
13249
+ * @param options - standard Error options (`cause` survives in-process only).
13250
+ */
13251
+ constructor(code, message, details, options) {
13252
+ super(message, code, options);
13253
+ this.code = code;
13254
+ this.details = details;
13255
+ this.name = "RemoteError";
13256
+ }
13257
+ };
13258
+ /**
13259
+ * Remote decorators and explicit Gateway bindings backed by versioned
13260
+ * descriptors carried on decorated class prototypes. Strict reflection
13261
+ * remains a Typert compiler responsibility.
13262
+ * @module @deepseek-ai/dsh-typert-protocol
13263
+ */
13264
+ const TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
13265
+ /**
13266
+ * Test one generated Remote name against the Connection endpoint grammar.
13267
+ * @param value - namespace, method, lookup, or Context segment.
13268
+ * @returns whether the value can cross the shared RPC carrier unchanged.
13269
+ */
13270
+ function isTypertRemoteSegment(value) {
13271
+ return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
13272
+ }
13273
+ const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
13274
+ /**
13275
+ * Bind one visible Service field to a Cordis key and Remote namespace. A
13276
+ * service that owns a Cordis Context also gives its tree `ctx.invocation`,
13277
+ * `undefined` outside a Remote call, so no `TypertRemoteService` is needed for
13278
+ * a Host composition to read it.
13279
+ * @param service - owning Service instance, normally `this`.
13280
+ * @param serviceKey - exact Cordis service key.
13281
+ * @param options - optional wire namespace.
13282
+ * @returns a frozen, inspectable binding with no compiler-injected metadata.
13283
+ */
13284
+ function bindTypertRemote(service, serviceKey, options = {}) {
13285
+ validateName("service key", serviceKey);
13286
+ const namespace = options.namespace ?? serviceKey;
13287
+ validateName("namespace", namespace);
13288
+ const ctx = Reflect.get(service, "ctx");
13289
+ if (Context.is(ctx)) provideInvocationAccessor(ctx);
13290
+ return Object.freeze({
13291
+ service,
13292
+ serviceKey,
13293
+ namespace
13294
+ });
13295
+ }
13296
+ /** Cordis Service base that exposes its registered name through Typert Gateway. */
13297
+ var TypertRemoteService = class extends Service {
13298
+ /** Visible binding consumed by the Gateway's source-mode discovery. */
13299
+ typertRemote;
13300
+ /**
13301
+ * Register the Service and bind the same key to Typert Gateway.
13302
+ * @param ctx - owning Cordis Context.
13303
+ * @param serviceKey - exact Cordis service key and default wire namespace.
13304
+ * @param options - optional wire namespace.
13305
+ */
13306
+ constructor(ctx, serviceKey, options = {}) {
13307
+ super(ctx, serviceKey);
13308
+ this.typertRemote = bindTypertRemote(this, this.name, options);
13309
+ }
13310
+ };
13311
+ /**
13312
+ * Make `ctx.invocation` read as `undefined` outside a Remote call instead of the
13313
+ * reflect service's "cannot get property" error; a call-derived Context shadows
13314
+ * the accessor with its own property. The first Remote Service constructed in a
13315
+ * tree registers it on the root, where it outlives any one Service.
13316
+ */
13317
+ function provideInvocationAccessor(ctx) {
13318
+ if (Object.hasOwn(ctx[Context.root].reflect.props, "invocation")) return;
13319
+ ctx[Context.root].accessor("invocation", { get: () => void 0 });
13320
+ }
13321
+ function Remote(methodExportOrOptions, context) {
13322
+ if (typeof methodExportOrOptions === "string") {
13323
+ validateName("Remote export name", methodExportOrOptions);
13324
+ return remoteDecorator({ kind: "direct" }, { exportName: methodExportOrOptions });
13325
+ }
13326
+ if (typeof methodExportOrOptions === "object") return remoteDecorator({ kind: "direct" }, markerOptions(methodExportOrOptions, REMOTE_OPTION_KEYS, "Remote options require name, mode: \"stream\", or resources"));
13327
+ if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
13328
+ addMarkerInitializer(context, { kind: "direct" });
13329
+ }
13330
+ const REMOTE_OPTION_KEYS = /* @__PURE__ */ new Set([
13331
+ "name",
13332
+ "mode",
13333
+ "resources"
13334
+ ]);
13335
+ /** Validate one decorator options object against its accepted keys and select the marker fields. */
13336
+ function markerOptions(options, accepted, requirement) {
13337
+ const keys = Reflect.ownKeys(options);
13338
+ 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}`);
13339
+ const { mode, name, resources } = options;
13340
+ if (name !== void 0) validateName("Remote export name", name);
13341
+ return {
13342
+ ...mode === void 0 ? {} : { mode },
13343
+ ...name === void 0 ? {} : { exportName: name },
13344
+ ...resources === void 0 ? {} : { resources: resourceReaders(resources) }
13345
+ };
13346
+ }
13347
+ /** Freeze declared readers into the marker record; a misdeclared reader fails at decoration. */
13348
+ function resourceReaders(resources) {
13349
+ const readers = {};
13350
+ for (const [kind, reader] of Object.entries(resources)) {
13351
+ if (typeof reader !== "function") throw new TypeError(`typert-protocol: Remote resource reader "${kind}" must be a function`);
13352
+ readers[kind] = reader;
13353
+ }
13354
+ if (Object.keys(readers).length === 0) throw new TypeError("typert-protocol: Remote resources require at least one reader");
13355
+ return Object.freeze(readers);
13356
+ }
13357
+ function remoteDecorator(invocation, options = {}) {
13358
+ return function(_method, context) {
13359
+ addMarkerInitializer(context, invocation, options);
13360
+ };
13361
+ }
13362
+ function readRemoteMethodDescriptor(prototype) {
13363
+ const property = Object.getOwnPropertyDescriptor(prototype, REMOTE_METHOD_DESCRIPTOR);
13364
+ if (property === void 0) return void 0;
13365
+ const descriptor = property.value;
13366
+ if (descriptor === null || typeof descriptor !== "object") throw new TypeError("typert-protocol: Remote method descriptor must be an object");
13367
+ const version = Reflect.get(descriptor, "version");
13368
+ if (version !== 1) throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(version)}`);
13369
+ const methods = Reflect.get(descriptor, "methods");
13370
+ if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
13371
+ return descriptor;
13372
+ }
13373
+ function addMarkerInitializer(context, invocation, options = {}) {
13374
+ 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");
13375
+ const method = context.name;
13376
+ context.addInitializer(function() {
13377
+ const prototype = Object.getPrototypeOf(this);
13378
+ if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
13379
+ mark(prototype, method, invocation, options);
13380
+ });
13381
+ }
13382
+ function mark(prototype, method, invocation, { mode, exportName, resources }) {
13383
+ const descriptor = readRemoteMethodDescriptor(prototype);
13384
+ const marker = Object.freeze({
13385
+ method,
13386
+ ...exportName === void 0 || exportName === method ? {} : { exportName },
13387
+ ...mode === void 0 ? {} : { mode },
13388
+ invocation: Object.freeze(invocation),
13389
+ ...resources === void 0 ? {} : { resources }
13390
+ });
13391
+ const current = descriptor?.methods.find((candidate) => candidate.method === method);
13392
+ if (current !== void 0) {
13393
+ if (current.exportName === marker.exportName && current.mode === marker.mode && current.resources === marker.resources && sameInvocation(current.invocation, invocation)) return;
13394
+ throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
13395
+ }
13396
+ Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
13397
+ configurable: true,
13398
+ value: Object.freeze({
13399
+ version: 1,
13400
+ methods: Object.freeze([...descriptor?.methods ?? [], marker])
13401
+ })
13402
+ });
13403
+ }
13404
+ function sameInvocation(left, right) {
13405
+ if (left.kind === "direct") return right.kind === "direct";
13406
+ if (right.kind === "direct") return false;
13407
+ return left.context === right.context;
13408
+ }
13409
+ function validateName(subject, value) {
13410
+ if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
13411
+ }
13412
+ //#endregion
13413
+ //#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
13414
+ /**
13415
+ * Random v4 UUID, minted from `crypto.getRandomValues`.
13416
+ * @returns the UUID string.
13417
+ */
13418
+ function randomUUID() {
13419
+ const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
13420
+ const hex = Array.from(bytes, (byte, index) => {
13421
+ return (index === 6 ? byte & 15 | 64 : index === 8 ? byte & 63 | 128 : byte).toString(16).padStart(2, "0");
13422
+ }).join("");
13423
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
13424
+ }
13425
+ //#endregion
13426
+ //#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
13427
+ /**
13428
+ * Duplicate-install-safe nominal primitive helpers.
13429
+ *
13430
+ * A brand makes structurally identical strings or numbers non-interchangeable
13431
+ * at the type level: a `SessionId` cannot be passed where a `ToolCallId` is
13432
+ * expected, and an event sequence cannot be passed as a log offset. Comparison,
13433
+ * logging, and serialization retain the underlying primitive behavior.
13434
+ *
13435
+ * This package owns no concrete domain value and keeps no runtime identity or mutable
13436
+ * state, so independently installed copies produce interchangeable values.
13437
+ *
13438
+ * @module @deepseek-ai/dsh-brand
13439
+ */
13440
+ /**
13441
+ * Apply a compile-time string brand without changing the value.
13442
+ * @param value - string admitted by the domain that owns the target brand.
13443
+ * @returns the same string with the requested compile-time brand.
13444
+ */
13445
+ function brandString(value) {
13446
+ return value;
13447
+ }
13448
+ //#endregion
13449
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.10.0-alpha.3/node_modules/@deepseek-ai/cosmokit/lib/index.js
12941
13450
  /** Return true when a value is `null` or `undefined`. */
12942
13451
  function isNullable(value) {
12943
13452
  return value === null || value === void 0;
@@ -13191,7 +13700,7 @@ var Time;
13191
13700
  Time.template = template;
13192
13701
  })(Time || (Time = {}));
13193
13702
  //#endregion
13194
- //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.20.0-alpha.1/node_modules/@deepseek-ai/schemastery/lib/index.mjs
13703
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.20.0-alpha.3/node_modules/@deepseek-ai/schemastery/lib/index.mjs
13195
13704
  const kSchema = Symbol.for("schemastery");
13196
13705
  const kValidationError = Symbol.for("ValidationError");
13197
13706
  globalThis.__schemastery_index__ ??= 0;
@@ -13824,11 +14333,11 @@ defineMethod("transform", [
13824
14333
  "preserve"
13825
14334
  ], ({ inner }, isInner) => inner.toString(isInner));
13826
14335
  //#endregion
13827
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
14336
+ //#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
13828
14337
  /** Largest delay Node schedules without clamping it to one millisecond. */
13829
14338
  const MAX_TIMER_DELAY_MS = 2147483647;
13830
14339
  //#endregion
13831
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1_@deepseek-ai+dsh-e_3734babba1c9d85ae3e99b1bc6b8c6ed/node_modules/@deepseek-ai/dsh-llm/lib/index.js
14340
+ //#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
13832
14341
  /**
13833
14342
  * LLM failure codes and helpers over the shared Harness error base. The base
13834
14343
  * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
@@ -13871,6 +14380,7 @@ const LLM_FAILURE_CODES = {
13871
14380
  INVALID_REPLAY_STATE: {},
13872
14381
  INVALID_REQUEST: {},
13873
14382
  INVALID_RESPONSE: {},
14383
+ INVALID_TOOL_ARGUMENTS: { retryChoice: true },
13874
14384
  MALFORMED_RESPONSE: { retryChoice: true },
13875
14385
  MISSING_CREDENTIAL: {},
13876
14386
  MODEL_SWITCH_COMPACTION_FAILED: {},
@@ -13919,6 +14429,34 @@ function freezeMessage(message) {
13919
14429
  return deepFreeze(structuredClone(message));
13920
14430
  }
13921
14431
  /**
14432
+ * Create one identified message and freeze it before publication.
14433
+ * @param input - complete role, content, and source for a new message.
14434
+ * @returns an immutable message with a fresh stable identity.
14435
+ */
14436
+ function createMessage(input) {
14437
+ return deepFreeze(structuredClone({
14438
+ ...input,
14439
+ id: brandString(randomUUID())
14440
+ }));
14441
+ }
14442
+ /**
14443
+ * Create and freeze one identified tool-result message.
14444
+ * @param input - call identity, raw result blocks, and outcome.
14445
+ * @returns an immutable tool-role message that answers the tool call.
14446
+ */
14447
+ function createToolResultMessage(input) {
14448
+ return createMessage({
14449
+ role: "tool",
14450
+ source: {
14451
+ kind: "tool",
14452
+ callId: input.callId
14453
+ },
14454
+ toolCallId: input.callId,
14455
+ content: input.content,
14456
+ isError: input.isError
14457
+ });
14458
+ }
14459
+ /**
13922
14460
  * Provider-owned request-retry policy configuration and resolution.
13923
14461
  *
13924
14462
  * Adapters expose one resolved policy per registered provider route; the
@@ -13932,6 +14470,7 @@ const DEFAULT_MAX_DELAY_MS = 1e4;
13932
14470
  const DEFAULT_JITTER_RATIO = .1;
13933
14471
  const DEFAULT_RETRYABLE_CODES = Object.freeze([
13934
14472
  EMPTY_RESPONSE_CODE,
14473
+ "INVALID_TOOL_ARGUMENTS",
13935
14474
  "RATE_LIMIT",
13936
14475
  "SERVER",
13937
14476
  "TIMEOUT",
@@ -14773,6 +15312,18 @@ var LlmError = class LlmError extends HarnessError {
14773
15312
  });
14774
15313
  }
14775
15314
  /**
15315
+ * Report whether a registered provider advertises a model in its current
15316
+ * catalog. Catalog-driven entry points use it to accept only listed models.
15317
+ * @param provider - provider route to inspect.
15318
+ * @param model - provider-owned model id.
15319
+ * @returns false when the provider is unregistered or its catalog omits the model.
15320
+ * @throws the provider's catalog failure, unchanged.
15321
+ */
15322
+ async isModelInCatalog(provider, model) {
15323
+ if (!this.adapters.has(provider)) return false;
15324
+ return (await this.listModels(provider)).some((entry) => entry.id === model);
15325
+ }
15326
+ /**
14776
15327
  * Resolve and validate all metadata from the adapter that owns one exact
14777
15328
  * route. The result is detached from adapter-owned objects; catalog
14778
15329
  * membership remains advisory and does not control request routing.
@@ -15099,12 +15650,22 @@ function detachDirectoryEntry(entry) {
15099
15650
  };
15100
15651
  }
15101
15652
  //#endregion
15102
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.3-alpha.2_fe5258332cf8d58c43bca084c938026e/node_modules/@deepseek-ai/dsh-tools/lib/shared-DGx6D7zk.js
15103
- /** The selected provider is missing or unloaded; another provider must not take its calls. */
15104
- var ToolExecutorUnavailableError = class extends HarnessError {
15653
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.3-alpha.4_ca12df44b3bbe3a755034ba57f11ee40/node_modules/@deepseek-ai/dsh-tools/lib/shared-DzeEFgIh.js
15654
+ /** Composable tool registries and the batches `ctx.tools.execute()` runs. @module */
15655
+ /** A drained batch failed internally; only the included results are committed. */
15656
+ var ToolBatchExecutionError = class extends Error {
15657
+ partial;
15658
+ constructor(cause, partial) {
15659
+ super("Tool batch execution failed", { cause });
15660
+ this.partial = partial;
15661
+ this.name = "ToolBatchExecutionError";
15662
+ }
15663
+ };
15664
+ /** The selected root registry is missing or unloaded; another registry must not take its calls. */
15665
+ var ToolRegistryUnavailableError = class extends HarnessError {
15105
15666
  constructor() {
15106
- super("The selected tool executor is unavailable. Load an executor in this composition before running the agent.", "TOOL_EXECUTOR_UNAVAILABLE");
15107
- this.name = "ToolExecutorUnavailableError";
15667
+ super("The selected tool registry is unavailable. Load a native or PTC tool registry in this composition before running the agent.", "TOOL_REGISTRY_UNAVAILABLE");
15668
+ this.name = "ToolRegistryUnavailableError";
15108
15669
  }
15109
15670
  };
15110
15671
  /**
@@ -15610,286 +16171,1266 @@ function checkValue(schema, value, path) {
15610
16171
  return rootResult ?? losslessValueViolation(path);
15611
16172
  }
15612
16173
  /**
15613
- * Validate a candidate value against an asserted raw schema. The function is
15614
- * total for arbitrary values and returns path-qualified violations.
15615
- * @param schema - a schema accepted by {@link assertSupportedJsonSchema}.
15616
- * @param value - the candidate JSON value.
15617
- * @param path - root label used in diagnostics.
15618
- * @returns All violations in walk order; empty means valid.
16174
+ * Validate a candidate value against an asserted raw schema. The function is
16175
+ * total for arbitrary values and returns path-qualified violations.
16176
+ * @param schema - a schema accepted by {@link assertSupportedJsonSchema}.
16177
+ * @param value - the candidate JSON value.
16178
+ * @param path - root label used in diagnostics.
16179
+ * @returns All violations in walk order; empty means valid.
16180
+ */
16181
+ function validateJsonSchemaValue(schema, value, path = "value") {
16182
+ return checkValue(schema, value, path);
16183
+ }
16184
+ /**
16185
+ * Error identities the registry records on failed tool results. The values are
16186
+ * persisted contract; the entry does not re-export them, and consumers compare
16187
+ * the recorded strings.
16188
+ * @module
16189
+ */
16190
+ /** Error name the registry records when approval does not grant a call. */
16191
+ const APPROVAL_ERROR_NAME = "ApprovalError";
16192
+ /** Approval code for a call the user rejected. */
16193
+ const APPROVAL_REJECTED = "APPROVAL_REJECTED";
16194
+ /** Approval code for an approval request cancelled without a caller cancellation. */
16195
+ const APPROVAL_CANCELLED = "APPROVAL_CANCELLED";
16196
+ /** Approval code for a call that needs approval when no approval service, Agent, or channel can answer it. */
16197
+ const APPROVAL_UNAVAILABLE = "APPROVAL_UNAVAILABLE";
16198
+ /** Code of `EnvironmentUnsupportedError`. */
16199
+ const ENVIRONMENT_UNSUPPORTED = "ENVIRONMENT_UNSUPPORTED";
16200
+ /** Tool definitions and invocation data shared by tool registries. @module */
16201
+ /** Reserved model-facing program transport name. */
16202
+ const RUN_CODE_NAME = "run_code";
16203
+ /**
16204
+ * A tool name resolves to more than one candidate in the scope that decides it,
16205
+ * or a registry inclusion reaches the registry that is being queried.
16206
+ */
16207
+ var ToolCompositionError = class extends HarnessError {
16208
+ /**
16209
+ * @param message - names the ambiguous tool or the inclusion cycle.
16210
+ */
16211
+ constructor(message) {
16212
+ super(message, "INVALID_TOOL_COMPOSITION");
16213
+ this.name = "ToolCompositionError";
16214
+ }
16215
+ };
16216
+ /** A call targets a non-local environment that its tool does not support. */
16217
+ var EnvironmentUnsupportedError = class extends HarnessError {
16218
+ toolName;
16219
+ environment;
16220
+ /**
16221
+ * @param toolName - called tool.
16222
+ * @param environment - environment the call targets.
16223
+ */
16224
+ constructor(toolName, environment) {
16225
+ 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);
16226
+ this.toolName = toolName;
16227
+ this.environment = environment;
16228
+ this.name = "EnvironmentUnsupportedError";
16229
+ }
16230
+ };
16231
+ /** Canonical error code for cancellation after a tool body was invoked. */
16232
+ const TOOL_ABORTED = "ABORTED";
16233
+ /** Canonical error code for cancellation before a tool body was invoked. */
16234
+ const TOOL_ABORTED_BEFORE_DISPATCH = "ABORTED_BEFORE_DISPATCH";
16235
+ /**
16236
+ * Thrown (internally) when a call names no definition its caller may execute.
16237
+ * Extends {@link HarnessError} (`code: 'UNKNOWN_TOOL'`) so an unknown-tool
16238
+ * failure is as routable as a tool-thrown one — retry/sandbox/replay code can
16239
+ * distinguish it from a tool body's own error.
16240
+ */
16241
+ var ToolNotFoundError = class extends HarnessError {
16242
+ /**
16243
+ * @param toolName - the name the caller asked for.
16244
+ * @param callable - the entries the caller can call directly, which the message
16245
+ * lists; given when the name is a tool the caller can reach only from those
16246
+ * entries, such as a program binding, and omitted otherwise. An empty list
16247
+ * adds nothing to the message.
16248
+ */
16249
+ constructor(toolName, callable = []) {
16250
+ super(callable.length === 0 ? `unknown tool "${toolName}"` : `unknown tool "${toolName}"; tools you can call directly: ${callable.join(", ")}`, "UNKNOWN_TOOL");
16251
+ this.name = "ToolNotFoundError";
16252
+ }
16253
+ };
16254
+ /** Thrown when a tool body or post-policy value violates its declared output. */
16255
+ var ToolOutputError = class extends HarnessError {
16256
+ /** Schema/value violations in validation order. */
16257
+ violations;
16258
+ constructor(toolName, violations) {
16259
+ super(`tool "${toolName}" returned invalid output: ${violations.join("; ")}`, "INVALID_TOOL_OUTPUT");
16260
+ this.name = "ToolOutputError";
16261
+ this.violations = violations;
16262
+ }
16263
+ };
16264
+ /** Flat registrations and live inclusions shared by registry implementations. @module */
16265
+ /** Several different definitions that one place offers under one name. */
16266
+ var AmbiguousCandidate = class {
16267
+ definitions;
16268
+ /** @param definitions - the conflicting definitions in the order the place offers them. */
16269
+ constructor(definitions) {
16270
+ this.definitions = definitions;
16271
+ }
16272
+ };
16273
+ /**
16274
+ * Add one definition to a place's candidate for its name; the same definition
16275
+ * reached twice stays one candidate, and different definitions conflict.
16276
+ * @param existing - the candidate collected so far, if any.
16277
+ * @param definition - a definition the place offers under the same name.
16278
+ * @returns the merged candidate.
16279
+ */
16280
+ function mergeToolCandidate(existing, definition) {
16281
+ if (existing === void 0 || existing === definition) return definition;
16282
+ const definitions = existing instanceof AmbiguousCandidate ? existing.definitions : [existing];
16283
+ return definitions.includes(definition) ? existing : new AmbiguousCandidate([...definitions, definition]);
16284
+ }
16285
+ /**
16286
+ * Validate one definition before a registry retains it.
16287
+ * @param definition - definition supplied to `register()`.
16288
+ * @throws TypeError when the output declaration or timeout is invalid.
16289
+ * @throws Error when the definition uses the reserved `run_code` name.
16290
+ */
16291
+ function assertToolDefinition(definition) {
16292
+ const name = definition.name;
16293
+ const output = definition.output;
16294
+ 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? }`);
16295
+ assertSupportedJsonSchema(output.schema);
16296
+ const timeoutMs = definition.timeoutMs;
16297
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new TypeError(`tool "${name}" timeoutMs must be a positive finite number`);
16298
+ 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`);
16299
+ }
16300
+ /**
16301
+ * Collect one place's candidates: its own registrations, then the entries of
16302
+ * each included registry for the viewing scope. The same definition reached
16303
+ * twice stays one candidate; different definitions under one name conflict.
16304
+ * @param own - definitions this place offers itself; a repeated name merges like an included one.
16305
+ * @param sources - registries included in this place.
16306
+ * @param scope - viewing scope passed to every included registry.
16307
+ * @returns candidates by name in first-seen order.
16308
+ */
16309
+ function collectToolCandidates(own, sources, scope) {
16310
+ const candidates = /* @__PURE__ */ new Map();
16311
+ const add = (definition) => {
16312
+ candidates.set(definition.name, mergeToolCandidate(candidates.get(definition.name), definition));
16313
+ };
16314
+ for (const definition of own) add(definition);
16315
+ for (const source of sources) for (const definition of source.getAll(scope)) add(definition);
16316
+ return candidates;
16317
+ }
16318
+ /**
16319
+ * Find one name among a place's registration and its included registries.
16320
+ * @param own - the place's own registration with the name, if any.
16321
+ * @param sources - registries included in the place.
16322
+ * @param name - tool name to find.
16323
+ * @param scope - viewing scope passed to every included registry.
16324
+ * @returns the definition, the conflicting definitions when several differ, or undefined.
16325
+ */
16326
+ function findToolCandidate(own, sources, name, scope) {
16327
+ let found = own;
16328
+ for (const source of sources) {
16329
+ const definition = source.get(name, scope);
16330
+ if (definition !== void 0) found = mergeToolCandidate(found, definition);
16331
+ }
16332
+ return found;
16333
+ }
16334
+ /**
16335
+ * Resolve one deciding candidate.
16336
+ * @param name - tool name being resolved.
16337
+ * @param candidate - the deciding place's candidate, if any.
16338
+ * @returns the definition, or undefined when no place offers the name.
16339
+ * @throws ToolCompositionError when the deciding place offers several definitions.
15619
16340
  */
15620
- function validateJsonSchemaValue(schema, value, path = "value") {
15621
- return checkValue(schema, value, path);
16341
+ function resolveToolCandidate(name, candidate) {
16342
+ if (candidate instanceof AmbiguousCandidate) throw ambiguousTool(name, candidate);
16343
+ return candidate;
15622
16344
  }
15623
- /** Tool definitions and invocation data shared by registries and executors. @module */
15624
- /** Reserved model-facing program transport name. */
15625
- const RUN_CODE_NAME = "run_code";
15626
- /** Failure to determine a tool's step-time availability. */
15627
- var ToolActivationError = class extends HarnessError {
15628
- /**
15629
- * Preserve a condition failure without treating it as normal unavailability.
15630
- * @param name - tool whose condition rejected.
15631
- * @param cause - underlying condition failure.
15632
- */
15633
- constructor(name, cause) {
15634
- super(`cannot resolve availability of tool "${name}"`, "TOOL_ACTIVATION_FAILED", { cause });
15635
- this.name = "ToolActivationError";
16345
+ /**
16346
+ * Resolve every visible candidate.
16347
+ * @param candidates - deciding candidates by name.
16348
+ * @returns definitions in candidate order.
16349
+ * @throws ToolCompositionError when any visible name is ambiguous.
16350
+ */
16351
+ function resolveToolCandidates(candidates) {
16352
+ const definitions = [];
16353
+ for (const [name, candidate] of candidates) {
16354
+ if (candidate instanceof AmbiguousCandidate) throw ambiguousTool(name, candidate);
16355
+ definitions.push(candidate);
15636
16356
  }
15637
- };
15638
- //#endregion
15639
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1/node_modules/@deepseek-ai/dsh-scope/lib/index.js
16357
+ return definitions;
16358
+ }
15640
16359
  /**
15641
- * Shared insertion-ordered storage and effect ownership for scope-aware registries.
15642
- *
15643
- * @module @deepseek-ai/dsh-scope
16360
+ * List every definition of the candidates, keeping each conflict's definitions
16361
+ * so a registry that includes this list decides the name in its own place.
16362
+ * @param candidates - candidates by name.
16363
+ * @returns definitions in candidate order.
15644
16364
  */
16365
+ function listToolCandidates(candidates) {
16366
+ return [...candidates.values()].flatMap((candidate) => candidate instanceof AmbiguousCandidate ? candidate.definitions : [candidate]);
16367
+ }
15645
16368
  /**
15646
- * Insertion-ordered named entries with caller-owned duplicate diagnostics.
15647
- *
15648
- * Values are borrowed. Iterators are live within one nonempty table
15649
- * generation; draining the table detaches them from later insertions. Each
15650
- * successful insertion returns an idempotent undo for that exact entry.
16369
+ * Resolve a registry listing to one definition per name.
16370
+ * @param definitions - a registry's `getAll()` result.
16371
+ * @returns definitions in first-seen order.
16372
+ * @throws ToolCompositionError when the listing offers several definitions under one name.
15651
16373
  */
15652
- var NamedEntries = class {
15653
- duplicateError;
15654
- data = /* @__PURE__ */ new Map();
15655
- constructor(duplicateError) {
15656
- this.duplicateError = duplicateError;
15657
- }
15658
- /**
15659
- * Insert one unique name.
15660
- * @param name - name unique within this table.
15661
- * @param value - borrowed value to retain.
15662
- * @returns an idempotent undo that removes only this insertion.
15663
- */
15664
- insert(name, value) {
15665
- const data = this.data;
15666
- if (data.has(name)) throw this.duplicateError(name);
15667
- data.set(name, value);
15668
- let active = true;
15669
- return () => {
15670
- if (!active) return;
15671
- active = false;
15672
- data.delete(name);
15673
- if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
15674
- };
16374
+ function resolveToolList(definitions) {
16375
+ return resolveToolCandidates(collectToolCandidates(definitions, [], void 0));
16376
+ }
16377
+ /**
16378
+ * Build the failure for a name with several definitions in the place that
16379
+ * decides it. The message quotes the first line of each definition's
16380
+ * description so a developer can find the plugins that register them.
16381
+ */
16382
+ function ambiguousTool(name, candidate) {
16383
+ 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`);
16384
+ }
16385
+ /** The first line of a description, shortened for a diagnostic. */
16386
+ function summaryLine(description) {
16387
+ const line = description.split("\n", 1).join("");
16388
+ return line.length > 80 ? `${line.slice(0, 79)}…` : line;
16389
+ }
16390
+ /**
16391
+ * Execute raw calls with ordered policy and results around overlapping tool bodies.
16392
+ * Abort drains started calls and synthesizes results for skipped calls. Internal
16393
+ * failures drain before rejecting with the already committed results and context.
16394
+ * Concurrency-safe calls run at most `input.maxParallelToolCalls` at once, or
16395
+ * {@link DEFAULT_MAX_PARALLEL_TOOL_CALLS} without an override.
16396
+ * @param input - raw calls, optional concurrency override, and optional Session owner.
16397
+ * @param pipeline - invocation stages that resolve each call's definition.
16398
+ * @returns model-ordered outcomes after every started body has settled.
16399
+ * @throws RangeError when the explicit concurrency override is not a positive integer.
16400
+ */
16401
+ async function executeToolBatch(input, pipeline) {
16402
+ const { calls: toolCalls, signal, agent, toolStep, maxParallelToolCalls } = input;
16403
+ if (maxParallelToolCalls !== void 0 && (!Number.isInteger(maxParallelToolCalls) || maxParallelToolCalls < 1)) throw new RangeError("maxParallelToolCalls must be a positive integer");
16404
+ const settlement = new BatchSettlement(input);
16405
+ try {
16406
+ const planned = toolCalls.map((block) => ({
16407
+ block,
16408
+ exec: {
16409
+ callId: block.id,
16410
+ name: block.name,
16411
+ arguments: parseArguments(block.arguments),
16412
+ ...agent === void 0 ? {} : { agent },
16413
+ ...toolStep === void 0 ? {} : { toolStep },
16414
+ signal
16415
+ }
16416
+ }));
16417
+ let next = 0;
16418
+ let concluded = false;
16419
+ while (next < planned.length) {
16420
+ const first = planned[next];
16421
+ const mode = pipeline.executionMode(first.exec).kind;
16422
+ const group = mode === "parallel" ? planned.slice(next) : [first];
16423
+ const outcome = await runGroup(pipeline, settlement, maxParallelToolCalls ?? 10, group, mode, signal);
16424
+ next += outcome.consumed;
16425
+ concluded ||= outcome.concluded;
16426
+ if (outcome.aborted) {
16427
+ for (const call of planned.slice(next)) settlement.skip(call.block);
16428
+ return settlement.result(concluded);
16429
+ }
16430
+ }
16431
+ return settlement.result(concluded);
16432
+ } catch (error) {
16433
+ throw new ToolBatchExecutionError(error, settlement.result());
15675
16434
  }
15676
- /**
15677
- * Read one named value.
15678
- * @param name - name to resolve.
15679
- * @returns the retained value, or `undefined` when absent.
15680
- */
15681
- get(name) {
15682
- return this.data.get(name);
16435
+ }
16436
+ /** Parse model arguments, preserving invalid JSON as text and mapping empty input to `{}`. */
16437
+ function parseArguments(raw) {
16438
+ try {
16439
+ return raw ? JSON.parse(raw) : {};
16440
+ } catch (_error) {
16441
+ return raw;
16442
+ }
16443
+ }
16444
+ /**
16445
+ * Run one exclusive barrier or parallel pool. Later calls are reclassified
16446
+ * before start; an exclusive reclassification waits for the current pool to
16447
+ * drain and remains for the caller's next barrier. Results and contexts commit
16448
+ * in model order. Abort stops starts, drains and commits started calls, accepts
16449
+ * their contexts into the owning batch, records results for skipped calls, and
16450
+ * returns an aborted outcome. Scheduler failure drains dispatches and rejects
16451
+ * for the owning step to record recovery results.
16452
+ */
16453
+ async function runGroup(pipeline, settlement, maxParallelToolCalls, group, mode, signal) {
16454
+ const slots = group.map(() => void 0);
16455
+ const callSeqs = group.map(() => void 0);
16456
+ let nextToStart = 0;
16457
+ let committed = 0;
16458
+ let started = 0;
16459
+ let aborted = signal.aborted;
16460
+ let concluded = false;
16461
+ let schedulerFailure;
16462
+ const throwSchedulerFailure = () => {
16463
+ if (schedulerFailure !== void 0) throw schedulerFailure.error;
16464
+ };
16465
+ const commitReady = async () => {
16466
+ while (committed < group.length) {
16467
+ const slot = slots[committed];
16468
+ if (slot === void 0) break;
16469
+ const call = group[committed];
16470
+ const result = await pipeline.complete(slot.exec, slot);
16471
+ settlement.commit(call.block, result, callSeqs[committed]);
16472
+ concluded ||= result.concludesTurn === true;
16473
+ committed++;
16474
+ }
16475
+ };
16476
+ const inFlight = /* @__PURE__ */ new Map();
16477
+ const startCall = async (index) => {
16478
+ const call = group[index];
16479
+ callSeqs[index] = settlement.start(call.block);
16480
+ started++;
16481
+ const prepared = await pipeline.prepare(call.exec);
16482
+ throwSchedulerFailure();
16483
+ switch (prepared.kind) {
16484
+ case "dispatch": {
16485
+ const promise = pipeline.dispatch(prepared.exec).then((outcome) => {
16486
+ slots[index] = {
16487
+ ...outcome,
16488
+ exec: prepared.exec
16489
+ };
16490
+ return index;
16491
+ }, (error) => {
16492
+ schedulerFailure ??= { error };
16493
+ return index;
16494
+ });
16495
+ inFlight.set(index, promise);
16496
+ break;
16497
+ }
16498
+ case "post-result":
16499
+ case "final-result":
16500
+ slots[index] = prepared;
16501
+ break;
16502
+ /* v8 ignore next -- closed-union exhaustiveness guard */
16503
+ default: assertNever$1(prepared, "tool-call scheduler prepare result");
16504
+ }
16505
+ };
16506
+ const fillPool = async () => {
16507
+ while (!aborted && nextToStart < group.length && inFlight.size < maxParallelToolCalls) {
16508
+ const nextCall = group[nextToStart];
16509
+ if (nextToStart > 0 && mode === "parallel" && pipeline.executionMode(nextCall.exec).kind !== "parallel") break;
16510
+ await startCall(nextToStart);
16511
+ nextToStart++;
16512
+ throwSchedulerFailure();
16513
+ await commitReady();
16514
+ throwSchedulerFailure();
16515
+ if (signal.aborted) aborted = true;
16516
+ }
16517
+ };
16518
+ try {
16519
+ await fillPool();
16520
+ while (inFlight.size > 0) {
16521
+ const settledIndex = await Promise.race(inFlight.values());
16522
+ inFlight.delete(settledIndex);
16523
+ throwSchedulerFailure();
16524
+ await commitReady();
16525
+ throwSchedulerFailure();
16526
+ if (signal.aborted) aborted = true;
16527
+ await fillPool();
16528
+ }
16529
+ } catch (error) {
16530
+ schedulerFailure ??= { error };
16531
+ await Promise.allSettled(inFlight.values());
16532
+ throw schedulerFailure.error;
15683
16533
  }
15684
- /**
15685
- * Test one name for membership.
15686
- * @param name - name to test.
15687
- * @returns whether the table contains that name.
15688
- */
15689
- has(name) {
15690
- return this.data.has(name);
16534
+ if (aborted) {
16535
+ for (const call of group.slice(started)) settlement.skip(call.block);
16536
+ return {
16537
+ consumed: group.length,
16538
+ aborted: true,
16539
+ concluded
16540
+ };
15691
16541
  }
15692
- /**
15693
- * Iterate live names in insertion order.
15694
- * @returns the native live key iterator.
15695
- */
15696
- keys() {
15697
- return this.data.keys();
16542
+ /* v8 ignore next -- unreachable: a non-aborted group commits every started call */
16543
+ if (committed !== started) throw new Error("tool-call scheduler: uncommitted settled calls");
16544
+ return {
16545
+ consumed: started,
16546
+ aborted: false,
16547
+ concluded
16548
+ };
16549
+ }
16550
+ /** Collect committed results and optionally append their durable Session events. */
16551
+ var BatchSettlement = class {
16552
+ input;
16553
+ results = [];
16554
+ contexts = [];
16555
+ constructor(input) {
16556
+ this.input = input;
15698
16557
  }
15699
- /**
15700
- * Iterate live entries in insertion order.
15701
- * @returns the native live entry iterator.
15702
- */
15703
- entries() {
15704
- return this.data.entries();
16558
+ start(block) {
16559
+ if (this.input.log === void 0) return void 0;
16560
+ const { agent, log: { turn, step } } = this.input;
16561
+ return agent.session.append("tool/call", {
16562
+ turn,
16563
+ step,
16564
+ callId: block.id,
16565
+ name: block.name,
16566
+ arguments: block.arguments
16567
+ }).seq;
16568
+ }
16569
+ commit(block, result, callSeq) {
16570
+ if (this.input.log !== void 0) {
16571
+ const { agent, log: { turn, step } } = this.input;
16572
+ agent.session.append("tool/result", {
16573
+ turn,
16574
+ step,
16575
+ message: createToolResultMessage({
16576
+ callId: block.id,
16577
+ content: result.content,
16578
+ isError: result.isError
16579
+ }),
16580
+ ...result.error?.info ? { error: result.error.info } : {},
16581
+ ...result.meta !== void 0 ? { meta: result.meta } : {}
16582
+ }, {
16583
+ surfaceOp: "append",
16584
+ sourceEventSeqs: [callSeq]
16585
+ });
16586
+ }
16587
+ this.results.push({
16588
+ callId: block.id,
16589
+ result
16590
+ });
16591
+ this.contexts.push(...result.additionalContexts ?? []);
15705
16592
  }
15706
- /**
15707
- * Iterate live values in insertion order.
15708
- * @returns the native live value iterator.
15709
- */
15710
- values() {
15711
- return this.data.values();
16593
+ skip(block) {
16594
+ this.commit(block, {
16595
+ content: [{
16596
+ type: "text",
16597
+ text: "Error: tool call aborted before dispatch"
16598
+ }],
16599
+ isError: true,
16600
+ error: {
16601
+ message: "tool call aborted before dispatch",
16602
+ info: {
16603
+ name: "AbortError",
16604
+ code: TOOL_ABORTED_BEFORE_DISPATCH
16605
+ }
16606
+ }
16607
+ }, this.start(block));
15712
16608
  }
15713
- /**
15714
- * Test whether this table has no entries.
15715
- * @returns whether the table is empty.
15716
- */
15717
- isEmpty() {
15718
- return this.data.size === 0;
16609
+ result(concluded = this.results.some(({ result }) => result.concludesTurn === true)) {
16610
+ return {
16611
+ results: this.results,
16612
+ additionalContexts: this.contexts,
16613
+ concluded
16614
+ };
15719
16615
  }
15720
16616
  };
15721
16617
  /**
15722
- * Insertion-ordered anonymous entries with independent registration identity.
15723
- *
15724
- * Equal values remain separate registrations. Values are borrowed, and
15725
- * iterators are live within one nonempty table generation; draining the table
15726
- * detaches them from later appends.
16618
+ * Shared invocation stages for batch and program schedulers. Schedulers order
16619
+ * prepare and complete calls while dispatch may overlap. Use executeToolBatch
16620
+ * for complete calls, including a single-call batch.
15727
16621
  */
15728
- var AnonymousEntries = class {
15729
- data = /* @__PURE__ */ new Map();
16622
+ var ToolExecutionPipeline = class {
16623
+ ctx;
16624
+ source;
16625
+ tools;
15730
16626
  /**
15731
- * Append one independently owned value.
15732
- * @param value - borrowed value to retain.
15733
- * @returns an idempotent undo for this exact append.
16627
+ * @param ctx - registry context owning policy events and approval lookup.
16628
+ * @param source - registry lookup and refusals for every call this pipeline runs.
15734
16629
  */
15735
- append(value) {
15736
- const data = this.data;
15737
- const key = Symbol();
15738
- data.set(key, value);
15739
- let active = true;
15740
- return () => {
15741
- if (!active) return;
15742
- active = false;
15743
- data.delete(key);
15744
- if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
15745
- };
16630
+ constructor(ctx, source) {
16631
+ this.ctx = ctx;
16632
+ this.source = source;
16633
+ this.tools = ctx.tools;
16634
+ }
16635
+ resolveExecution(exec) {
16636
+ return this.source.get(exec.name, exec.agent, exec.toolStep);
15746
16637
  }
15747
16638
  /**
15748
- * Iterate live values in insertion order.
15749
- * @returns the native live value iterator.
16639
+ * Run one source lookup or refusal for a call being prepared or dispatched.
16640
+ * A composition failure, such as two definitions that appear under the
16641
+ * call's name during a step, is logged once with its message, and the call
16642
+ * fails with a message the model can act on.
16643
+ * @param call - name, call id, and Agent of the call the lookup serves.
16644
+ * @param lookup - source lookup or refusal.
16645
+ * @returns the lookup result.
16646
+ * @throws ToolCompositionError with the model-facing message when the lookup meets a composition failure.
15750
16647
  */
15751
- values() {
15752
- return this.data.values();
16648
+ lookup(call, lookup) {
16649
+ try {
16650
+ return lookup();
16651
+ } catch (error) {
16652
+ if (!(error instanceof ToolCompositionError)) throw error;
16653
+ const caller = call.agent === void 0 ? "" : ` from Agent ${call.agent.id}`;
16654
+ this.ctx.logger.warn(`tool "${call.name}" (call ${call.callId}${caller}) cannot run: ${error.message}`);
16655
+ 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`);
16656
+ }
16657
+ }
16658
+ /**
16659
+ * The definition prepare captured for one call, while the source still offers exactly it; checked as dispatch starts.
16660
+ * @throws ToolNotFoundError when prepare captured none or the source now resolves another definition or none.
16661
+ * @throws ToolCompositionError when the lookup meets a composition failure.
16662
+ */
16663
+ capturedDefinition(exec) {
16664
+ const definition = this.dispatchedDefinition(exec);
16665
+ if (this.lookup(exec, () => this.resolveExecution(exec)) !== definition) throw new ToolNotFoundError(exec.name);
16666
+ return definition;
16667
+ }
16668
+ /**
16669
+ * The definition whose output contract a dispatched call's result follows. A
16670
+ * call that started keeps it even if its source withdraws the tool meanwhile.
16671
+ * @throws ToolNotFoundError when prepare captured no definition.
16672
+ */
16673
+ dispatchedDefinition(exec) {
16674
+ const definition = exec.definition;
16675
+ if (definition === void 0) throw new ToolNotFoundError(exec.name);
16676
+ return definition;
16677
+ }
16678
+ /** Context deferred by a running tool body, keyed by its scheduler-owned execution. */
16679
+ deferredContexts = /* @__PURE__ */ new WeakMap();
16680
+ /** Executions whose tool body declared the current turn complete. */
16681
+ concludingExecutions = /* @__PURE__ */ new WeakSet();
16682
+ /** Original caller cancellation, kept outside the wrapper-mutable execution object. */
16683
+ cancellationStates = /* @__PURE__ */ new WeakMap();
16684
+ /** Definition-owned final content transform snapshotted before policy begins. */
16685
+ contentFinalizers = /* @__PURE__ */ new WeakMap();
16686
+ /** Execution-prepared content installed before post-execute policy. */
16687
+ contentProjectors = /* @__PURE__ */ new WeakMap();
16688
+ /**
16689
+ * Classify a pending call through the caller's visible tool definition. Only
16690
+ * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or
16691
+ * throwing classifiers are exclusive, and so is a call whose lookup throws,
16692
+ * which preparation then fails alone.
16693
+ * @param exec - call name, parsed arguments, and optional agent scope.
16694
+ * @returns the fail-closed scheduling mode.
16695
+ */
16696
+ executionMode(exec) {
16697
+ try {
16698
+ const tool = this.resolveExecution(exec);
16699
+ if (!tool?.isConcurrencySafe) return { kind: "exclusive" };
16700
+ return tool.isConcurrencySafe(exec.arguments) === true ? { kind: "parallel" } : { kind: "exclusive" };
16701
+ } catch {
16702
+ return { kind: "exclusive" };
16703
+ }
16704
+ }
16705
+ createExecution(exec) {
16706
+ const deferredContexts = [];
16707
+ const token = createExecutionToken();
16708
+ const callId = exec.callId;
16709
+ const rootCallId = exec.rootCallId ?? callId;
16710
+ const name = exec.name;
16711
+ const agent = exec.agent;
16712
+ const parent = exec.parent;
16713
+ const signal = exec.signal;
16714
+ let visible;
16715
+ let refusal;
16716
+ try {
16717
+ const call = {
16718
+ name,
16719
+ callId,
16720
+ ...agent !== void 0 ? { agent } : {}
16721
+ };
16722
+ visible = this.lookup(call, () => this.source.get(name, agent, exec.toolStep));
16723
+ const rejection = this.lookup(call, () => this.source.reject?.(exec));
16724
+ if (rejection !== void 0) refusal = { error: rejection };
16725
+ } catch (error) {
16726
+ refusal = { error };
16727
+ }
16728
+ if (refusal !== void 0) visible = void 0;
16729
+ let capturedFinalizer = visible?.finalizeContent?.bind(visible);
16730
+ const capturedProjector = visible?.projectContent?.bind(visible);
16731
+ let args;
16732
+ try {
16733
+ const detached = snapshotJsonValue(exec.arguments);
16734
+ if (detached === void 0) throw new TypeError("tool execution arguments must be losslessly JSON-serializable");
16735
+ args = { value: deepFreeze(detached) };
16736
+ } catch (error) {
16737
+ args = { error };
16738
+ }
16739
+ let environment;
16740
+ if (visible !== void 0 && "value" in args) try {
16741
+ environment = this.resolveCallEnvironment({
16742
+ callId,
16743
+ rootCallId,
16744
+ name,
16745
+ signal,
16746
+ arguments: args.value,
16747
+ ...agent !== void 0 ? { agent } : {},
16748
+ ...exec.toolStep !== void 0 ? { toolStep: exec.toolStep } : {},
16749
+ ...parent !== void 0 ? { parent } : {}
16750
+ }, visible);
16751
+ } catch (error) {
16752
+ refusal = { error };
16753
+ visible = void 0;
16754
+ capturedFinalizer = void 0;
16755
+ }
16756
+ const concludingExecutions = this.concludingExecutions;
16757
+ const base = {
16758
+ token,
16759
+ callId,
16760
+ rootCallId,
16761
+ name,
16762
+ signal,
16763
+ ...agent !== void 0 ? { agent } : {},
16764
+ ...exec.toolStep !== void 0 ? { toolStep: exec.toolStep } : {},
16765
+ ...visible !== void 0 ? { definition: visible } : {},
16766
+ ...parent !== void 0 ? { parent } : {},
16767
+ ...exec.schema !== void 0 ? { schema: exec.schema } : {},
16768
+ ...environment !== void 0 ? { environment } : {},
16769
+ deferContext(context) {
16770
+ deferredContexts.push(context);
16771
+ },
16772
+ concludeTurn() {
16773
+ concludingExecutions.add(this);
16774
+ }
16775
+ };
16776
+ if ("error" in args) {
16777
+ const execution = {
16778
+ ...base,
16779
+ arguments: void 0
16780
+ };
16781
+ this.contentFinalizers.set(execution, capturedFinalizer);
16782
+ return {
16783
+ kind: "final-result",
16784
+ exec: execution,
16785
+ result: toolErrorResult(args.error)
16786
+ };
16787
+ }
16788
+ const execution = {
16789
+ ...base,
16790
+ arguments: args.value
16791
+ };
16792
+ this.deferredContexts.set(execution, deferredContexts);
16793
+ this.contentFinalizers.set(execution, capturedFinalizer);
16794
+ this.cancellationStates.set(execution, {
16795
+ callerSignal: signal,
16796
+ bodyInvoked: false
16797
+ });
16798
+ if (refusal !== void 0) return {
16799
+ kind: "final-result",
16800
+ exec: execution,
16801
+ result: signal.aborted ? toolAbortedBeforeDispatchResult() : toolErrorResult(refusal.error)
16802
+ };
16803
+ this.contentProjectors.set(execution, capturedProjector);
16804
+ return {
16805
+ kind: "ready",
16806
+ exec: execution
16807
+ };
15753
16808
  }
15754
16809
  /**
15755
- * Test whether this table has no entries.
15756
- * @returns whether the table is empty.
15757
- */
15758
- isEmpty() {
15759
- return this.data.size === 0;
16810
+ * The target one call runs in: none for an `'explicit'` or `'independent'`
16811
+ * tool; otherwise a program call inherits the target its enclosing execution
16812
+ * was prepared with, and a root call asks its definition. The definition must
16813
+ * support it.
16814
+ * @param exec - the call with its snapshotted arguments.
16815
+ * @param definition - the definition the call resolved.
16816
+ * @returns the target, or undefined for the local environment.
16817
+ * @throws EnvironmentUnsupportedError when the definition does not support the environment.
16818
+ */
16819
+ resolveCallEnvironment(exec, definition) {
16820
+ if (definition.environment === "explicit" || definition.environment === "independent") return void 0;
16821
+ const environment = exec.parent === void 0 ? definition.resolveEnvironment?.(exec.arguments, exec) : exec.parent.environment;
16822
+ if (environment !== void 0 && definition.environment !== "bound") throw new EnvironmentUnsupportedError(definition.name, environment.id);
16823
+ return environment;
16824
+ }
16825
+ /**
16826
+ * Snapshot input, assign its correlation token, settle a call the source
16827
+ * refuses, and run ordered pre-execute policy and guards for the others.
16828
+ * A refused call reaches no policy, approval, guard, or execution wrapper.
16829
+ * Cancellation skips a body that has not started and takes precedence over
16830
+ * a refusal.
16831
+ * @param input - the caller-supplied execution input.
16832
+ * @returns the prepared execution plus the next scheduler stage.
16833
+ */
16834
+ async prepare(input) {
16835
+ const created = this.createExecution(input);
16836
+ if (created.kind !== "ready") return created;
16837
+ const exec = created.exec;
16838
+ if (this.callerCancelled(exec)) return {
16839
+ kind: "final-result",
16840
+ exec,
16841
+ result: toolAbortedBeforeDispatchResult()
16842
+ };
16843
+ try {
16844
+ const carrier = scopeTarget(this.tools, exec.agent);
16845
+ const gate = await this.ctx.waterfall(carrier, "tools/pre-execute", exec, () => Promise.resolve({ kind: "allow" }));
16846
+ const askResolution = gate.kind === "ask" ? await this.serviceAsk(exec, gate) : {
16847
+ decision: gate,
16848
+ approvalCancelled: false
16849
+ };
16850
+ const { decision } = askResolution;
16851
+ if (this.callerCancelled(exec) && askResolution.approvalCancelled) return {
16852
+ kind: "post-result",
16853
+ exec,
16854
+ result: toolAbortedBeforeDispatchResult()
16855
+ };
16856
+ if (decision.kind === "cancel") return {
16857
+ kind: "post-result",
16858
+ exec,
16859
+ result: toolAbortedBeforeDispatchResult()
16860
+ };
16861
+ const denial = decision.kind === "allow" ? this.tools.checkGuards(exec) : decision;
16862
+ if (denial !== void 0) {
16863
+ const { reason: denialReason, info: denialInfo } = denial;
16864
+ return {
16865
+ kind: "post-result",
16866
+ exec,
16867
+ result: this.materializeFinalResult({
16868
+ content: [{
16869
+ type: "text",
16870
+ text: `Error: ${denialReason}`
16871
+ }],
16872
+ isError: true,
16873
+ error: {
16874
+ message: denialReason,
16875
+ ...denialInfo === void 0 ? {} : { info: denialInfo }
16876
+ }
16877
+ })
16878
+ };
16879
+ }
16880
+ if (this.callerCancelled(exec)) return {
16881
+ kind: "post-result",
16882
+ exec,
16883
+ result: toolAbortedBeforeDispatchResult()
16884
+ };
16885
+ return {
16886
+ kind: "dispatch",
16887
+ exec
16888
+ };
16889
+ } catch (error) {
16890
+ return {
16891
+ kind: "final-result",
16892
+ exec,
16893
+ result: toolErrorResult(error)
16894
+ };
16895
+ }
15760
16896
  }
15761
- };
15762
- /**
15763
- * Own the global and exact-scope layers for one registry.
15764
- *
15765
- * Reads never create scoped layers. Registrations derive both visibility and
15766
- * effect ownership from the supplied Cordis context, collect undo before
15767
- * notification, and reclaim only a completely empty aggregate layer.
15768
- */
15769
- var ScopedLayers = class {
15770
- createLayer;
15771
- onChange;
15772
- /** The eagerly constructed context-global layer. */
15773
- global;
15774
- scoped = /* @__PURE__ */ new Map();
15775
- constructor(createLayer, onChange) {
15776
- this.createLayer = createLayer;
15777
- this.onChange = onChange;
15778
- this.global = createLayer(void 0);
16897
+ /** Whether the original caller signal is currently aborted. */
16898
+ callerCancelled(exec) {
16899
+ const state = this.cancellationStates.get(exec);
16900
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
16901
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
16902
+ return state.callerSignal.aborted;
16903
+ }
16904
+ /** Canonical cancellation outcome selected by whether the tool body started. */
16905
+ cancellationResult(exec, prior) {
16906
+ const state = this.cancellationStates.get(exec);
16907
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
16908
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
16909
+ return state.bodyInvoked ? toolAbortedResult(prior) : toolAbortedBeforeDispatchResult(prior);
16910
+ }
16911
+ /**
16912
+ * Dispatch the registered body with the original caller signal fused back
16913
+ * into any around-wrapper replacement. Cancellation never abandons the body:
16914
+ * a started promise reaches quiescence before its outcome becomes `ABORTED`.
16915
+ * After cancellation, a thrown signal reason or an `Error` named
16916
+ * `AbortError` without `HarnessError` identity keeps its message, or the
16917
+ * canonical abort message for a messageless reason object, and gains the
16918
+ * `ABORTED` identity, whichever operation inside the body aborted; a
16919
+ * thrown `HarnessError` and any other failure stay unchanged.
16920
+ */
16921
+ async dispatchToolBody(exec) {
16922
+ const state = this.cancellationStates.get(exec);
16923
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
16924
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
16925
+ const wrapperSignal = exec.signal;
16926
+ const fused = fuseToolSignals(state.callerSignal, wrapperSignal);
16927
+ const signal = fused.signal;
16928
+ if (isAborted(signal)) {
16929
+ fused.dispose();
16930
+ return toolAbortedBeforeDispatchResult();
16931
+ }
16932
+ exec.signal = signal;
16933
+ try {
16934
+ const tool = this.capturedDefinition(exec);
16935
+ state.bodyInvoked = true;
16936
+ const returned = await tool.execute(exec.arguments, exec);
16937
+ const result = this.createSuccessResult(exec, tool, returned);
16938
+ return isAborted(signal) ? toolAbortedResult(result) : result;
16939
+ } catch (error) {
16940
+ return isAborted(signal) && isUnclassifiedCancellation(error, signal) ? cancellationErrorResult(error, true) : toolErrorResult(error);
16941
+ } finally {
16942
+ fused.dispose();
16943
+ exec.signal = wrapperSignal;
16944
+ }
15779
16945
  }
15780
16946
  /**
15781
- * Read an existing exact-scope overlay. Deliberately chain-blind: callers
15782
- * addressing one scope's OWN contributions (its restrictions, its guards)
15783
- * must not silently pick up an ancestor's — use {@link chainLayers} where
15784
- * inheritance is the point.
15785
- * @param scope - exact scope key; `undefined` denotes no overlay.
15786
- * @returns the existing scoped layer, or `undefined` without creating one.
16947
+ * Run around-dispatch and the tool body. Tool and unknown-tool failures still
16948
+ * receive post-execute; pipeline failures are already final. Started bodies
16949
+ * drain on cancellation before a successful outcome becomes `ABORTED`. After
16950
+ * caller cancellation, a wrapper that throws the caller signal's reason or an
16951
+ * `Error` named `AbortError` without `HarnessError` identity keeps its message,
16952
+ * or the canonical abort message for a messageless reason object, and gains
16953
+ * `ABORTED`, or `ABORTED_BEFORE_DISPATCH` when the body never started; a
16954
+ * wrapper's `HarnessError` and other failures stay unchanged.
16955
+ * @param exec - the execution returned by this pipeline's prepare stage.
16956
+ * @returns whether the result still needs post-execute.
15787
16957
  */
15788
- peek(scope) {
15789
- if (scope === void 0) return void 0;
15790
- return this.scoped.get(scope);
16958
+ async dispatch(exec) {
16959
+ try {
16960
+ const mutableExec = exec;
16961
+ const carrier = scopeTarget(this.tools, exec.agent);
16962
+ const result = await this.ctx.waterfall(carrier, "tools/execute", mutableExec, () => this.dispatchToolBody(mutableExec));
16963
+ const normalized = this.normalizeDispatchResult(exec, result);
16964
+ const deferredContexts = this.deferredContexts.get(exec);
16965
+ /* v8 ignore next -- dispatch only receives executions minted by this registry's prepare stage */
16966
+ if (deferredContexts === void 0) throw new Error("tool registry scheduler invariant violated: unprepared execution");
16967
+ const resultWithDeferredContexts = deferredContexts.length === 0 ? normalized : this.markCanonical(exec, {
16968
+ ...normalized,
16969
+ additionalContexts: [...deferredContexts, ...normalized.additionalContexts ?? []]
16970
+ });
16971
+ return {
16972
+ kind: "post-result",
16973
+ result: this.callerCancelled(exec) && !resultWithDeferredContexts.isError ? this.cancellationResult(exec, resultWithDeferredContexts) : resultWithDeferredContexts
16974
+ };
16975
+ } catch (error) {
16976
+ return {
16977
+ kind: "final-result",
16978
+ result: this.wrapperFailureResult(exec, error)
16979
+ };
16980
+ }
16981
+ }
16982
+ /** Classify a failure thrown around dispatch; see {@link dispatch}. */
16983
+ wrapperFailureResult(exec, error) {
16984
+ const state = this.cancellationStates.get(exec);
16985
+ /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
16986
+ if (state === void 0) throw new Error("tool registry scheduler invariant violated: missing cancellation state");
16987
+ if (!isAborted(state.callerSignal) || !isUnclassifiedCancellation(error, state.callerSignal)) return toolErrorResult(error);
16988
+ return cancellationErrorResult(error, state.bodyInvoked);
15791
16989
  }
15792
16990
  /**
15793
- * Existing overlays along the scope's parent chain ({@link scopeChainOf}),
15794
- * farthest ancestor first and the exact scope last, so a caller layering
15795
- * them in order gives the nearest scope the final word.
15796
- * @param scope - viewing scope, or `undefined` for no overlays.
15797
- * @returns the existing layers, nearest last; absent overlays are skipped.
16991
+ * Run post-execute when required, apply definition-owned content finalization,
16992
+ * and publish the lossless, frozen result. Policy and finalization failures
16993
+ * become error results. Cancellation replaces a successful outcome before
16994
+ * final materialization; tool-owned errors remain intact.
16995
+ * @param exec - the execution returned by this pipeline's prepare stage.
16996
+ * @param outcome - the preparation or dispatch result awaiting completion.
16997
+ * @returns the same materialized result delivered to final observers.
15798
16998
  */
15799
- chainLayers(scope) {
15800
- const layers = [];
15801
- for (const key of scopeChainOf(scope).reverse()) {
15802
- const layer = this.scoped.get(key);
15803
- if (layer !== void 0) layers.push(layer);
16999
+ async complete(exec, outcome) {
17000
+ switch (outcome.kind) {
17001
+ case "final-result": return this.finish(exec, outcome.result);
17002
+ case "post-result": break;
17003
+ /* v8 ignore next -- closed-union exhaustiveness guard */
17004
+ default: return assertNever$1(outcome, "scheduled tool outcome");
17005
+ }
17006
+ const { result } = outcome;
17007
+ try {
17008
+ const project = this.contentProjectors.get(exec);
17009
+ this.contentProjectors.delete(exec);
17010
+ const content = project?.(exec, result);
17011
+ const projected = content === void 0 ? result : this.markCanonical(exec, this.materializeFinalResult({
17012
+ ...result,
17013
+ content
17014
+ }));
17015
+ const postResult = await this.postExecute(exec, projected);
17016
+ return this.finish(exec, this.callerCancelled(exec) && !postResult.isError ? this.cancellationResult(exec, postResult) : postResult);
17017
+ } catch (error) {
17018
+ return this.finish(exec, toolErrorResult(error));
15804
17019
  }
15805
- return layers;
15806
17020
  }
15807
17021
  /**
15808
- * Materialize global named entries followed by scope-chain shadows,
15809
- * farthest ancestor first, so the nearest scope's entry wins a name.
15810
- * @param scope - viewing scope, or `undefined` for the global view.
15811
- * @param pick - select the named table from a layer.
15812
- * @returns an insertion-ordered effective map.
17022
+ * Materialize the candidate, apply definition-owned content finalization,
17023
+ * then materialize and notify the authoritative result.
17024
+ * @param exec - the prepared execution.
17025
+ * @param result - final result.
17026
+ * @returns the materialized final result.
17027
+ * @internal
15813
17028
  */
15814
- merge(scope, pick) {
15815
- const merged = new Map(pick(this.global).entries());
15816
- for (const layer of this.chainLayers(scope)) for (const [name, value] of pick(layer).entries()) merged.set(name, value);
15817
- return merged;
17029
+ finish(exec, result) {
17030
+ let materializedResult;
17031
+ try {
17032
+ materializedResult = this.materializeFinalResult(result);
17033
+ } catch (error) {
17034
+ materializedResult = this.materializeFinalResult(toolErrorResult(error));
17035
+ }
17036
+ let finalResult;
17037
+ try {
17038
+ finalResult = this.materializeFinalResult(this.applyFinalContent(exec, materializedResult));
17039
+ } catch (error) {
17040
+ finalResult = this.materializeFinalResult(toolErrorResult(error));
17041
+ }
17042
+ this.notifyResult(exec, finalResult);
17043
+ return finalResult;
17044
+ }
17045
+ /** Apply the snapshotted tool-owned content transform without exposing other result fields. */
17046
+ applyFinalContent(exec, result) {
17047
+ const finalizeContent = this.contentFinalizers.get(exec);
17048
+ if (finalizeContent === void 0) return result;
17049
+ const content = finalizeContent(exec, result);
17050
+ return content === void 0 ? result : {
17051
+ ...result,
17052
+ content
17053
+ };
15818
17054
  }
15819
- /**
15820
- * Attach one synchronous layer mutation to its registration context.
15821
- * @param ctx - context that determines both scope visibility and effect ownership.
15822
- * @param action - atomic mutation returning its synchronous undo.
15823
- * @param options - Cordis effect label and optional change notification.
15824
- * @returns the exact disposer returned by `ctx.effect()`.
15825
- */
15826
- effect(ctx, action, options) {
15827
- const scope = scopeOf(ctx);
15828
- const notify = options.notify ?? true;
15829
- return ctx.effect(function* () {
15830
- let layer;
15831
- let created = false;
15832
- if (scope === void 0) layer = this.global;
15833
- else {
15834
- const existing = this.scoped.get(scope);
15835
- if (existing === void 0) {
15836
- layer = this.createLayer(scope);
15837
- this.scoped.set(scope, layer);
15838
- created = true;
15839
- } else layer = existing;
15840
- }
15841
- let undo;
17055
+ /** Notify observers without exposing a mutation or error channel into the outcome. */
17056
+ notifyResult(exec, result) {
17057
+ Object.freeze(exec);
17058
+ const { name: toolName, callId } = exec;
17059
+ const reportFailure = (error) => {
17060
+ this.ctx.logger.warn(`tool "${toolName}" (${callId}): tools/result observer failed: ${errorMessage$1(error)}`);
17061
+ };
17062
+ const callbacks = this.ctx.events.dispatch("emit", [
17063
+ scopeTarget(this.tools, exec.agent),
17064
+ "tools/result",
17065
+ exec,
17066
+ result
17067
+ ]);
17068
+ for (const callback of callbacks) try {
17069
+ const returned = callback(exec, result);
17070
+ Promise.resolve(returned).catch(reportFailure);
17071
+ } catch (error) {
17072
+ reportFailure(error);
17073
+ }
17074
+ }
17075
+ /**
17076
+ * Resolve an `ask` decision to allow/deny through the approval seam. The
17077
+ * seam is consumed opportunistically with `ctx.get('approval')` — a
17078
+ * deployment that composes no ApprovalService keeps the historical degrade
17079
+ * to deny, and an unmount mid-session degrades the same way on the next ask.
17080
+ * An agent-less execution also degrades: without an agent there is no
17081
+ * session to audit to and no UI to route to. Otherwise the outcome maps
17082
+ * one-to-one — `allowed-once` proceeds; the three non-grants deny with
17083
+ * distinct reasons so the model can tell a human "no" from an absent
17084
+ * approval channel. Every denial carries `ApprovalError` with
17085
+ * `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`.
17086
+ */
17087
+ async serviceAsk(exec, ask) {
17088
+ const approval = this.ctx.get("approval");
17089
+ if (approval === void 0) return {
17090
+ decision: approvalDenial(ask.reason ?? `tool "${exec.name}" requires approval (not yet supported)`, APPROVAL_UNAVAILABLE),
17091
+ approvalCancelled: false
17092
+ };
17093
+ if (exec.agent === void 0) return {
17094
+ decision: approvalDenial(`tool "${exec.name}" requires approval, but the call has no agent to route it through`, APPROVAL_UNAVAILABLE),
17095
+ approvalCancelled: false
17096
+ };
17097
+ const outcome = await approval.request({
17098
+ agent: exec.agent,
17099
+ toolName: exec.name,
17100
+ callId: exec.callId,
17101
+ ...ask.reason !== void 0 ? { reason: ask.reason } : {},
17102
+ ...ask.displayReason !== void 0 ? { displayReason: ask.displayReason } : {},
17103
+ signal: exec.signal
17104
+ });
17105
+ switch (outcome) {
17106
+ case "allowed-once": return {
17107
+ decision: { kind: "allow" },
17108
+ approvalCancelled: false
17109
+ };
17110
+ case "rejected": return {
17111
+ decision: approvalDenial(`the user rejected tool "${exec.name}"`, APPROVAL_REJECTED),
17112
+ approvalCancelled: false
17113
+ };
17114
+ case "cancelled": return {
17115
+ decision: approvalDenial(`approval for tool "${exec.name}" was cancelled`, APPROVAL_CANCELLED),
17116
+ approvalCancelled: true
17117
+ };
17118
+ case "unavailable": return {
17119
+ decision: approvalDenial(`tool "${exec.name}" requires approval, but no approval channel is available`, APPROVAL_UNAVAILABLE),
17120
+ approvalCancelled: false
17121
+ };
17122
+ default: return assertNever$1(outcome, "ApprovalOutcome");
17123
+ }
17124
+ }
17125
+ /**
17126
+ * Run the `tools/post-execute` waterfall over a dispatched `result` and apply
17127
+ * its {@link PostToolDecision}: `accept` keeps the call successful (replacing
17128
+ * `content` when given), `block` turns it into an `isError` whose content is
17129
+ * the corrective `feedback`. Either decision may attach `additionalContexts`,
17130
+ * which are ferried on the returned result for the loop's active-batch FIFO.
17131
+ * Context deferred by the tool body survives an accepted result but is
17132
+ * discarded when the outer call is blocked; a block exposes only context the
17133
+ * blocking decision explicitly supplied.
17134
+ * Runs inside `execute`'s outer try/catch (a throwing listener → isError).
17135
+ */
17136
+ async postExecute(exec, result) {
17137
+ const decision = await this.ctx.waterfall(scopeTarget(this.tools, exec.agent), "tools/post-execute", exec, result, () => Promise.resolve({ kind: "accept" }));
17138
+ const decisionContexts = decision.additionalContexts ?? [];
17139
+ if (decision.kind === "block") {
17140
+ const message = failureMessageFromContent(decision.feedback);
17141
+ return this.markCanonical(exec, {
17142
+ content: decision.feedback,
17143
+ isError: true,
17144
+ error: {
17145
+ message,
17146
+ ...decision.info === void 0 ? {} : { info: decision.info }
17147
+ },
17148
+ ...decisionContexts.length > 0 ? { additionalContexts: decisionContexts } : {}
17149
+ });
17150
+ }
17151
+ if (Object.hasOwn(decision, "content") && Object.hasOwn(decision, "value")) throw new TypeError("tools/post-execute accept decision cannot replace both value and content");
17152
+ const additionalContexts = [...result.additionalContexts ?? [], ...decisionContexts];
17153
+ if (Object.hasOwn(decision, "value")) {
17154
+ if (result.isError) throw new TypeError("tools/post-execute cannot replace the value of a failed result");
17155
+ const replaced = this.createSuccessResult(exec, this.dispatchedDefinition(exec), decision.value);
17156
+ return this.markCanonical(exec, {
17157
+ ...replaced,
17158
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
17159
+ });
17160
+ }
17161
+ return this.markCanonical(exec, {
17162
+ ...result,
17163
+ ...decision.content !== void 0 ? { content: decision.content } : {},
17164
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
17165
+ });
17166
+ }
17167
+ /** Registry-normalized results and the exact dispatch that validated each value. */
17168
+ canonicalResults = /* @__PURE__ */ new WeakMap();
17169
+ /** Mark one registry-normalized result as canonical only for its owning dispatch. */
17170
+ markCanonical(exec, result) {
17171
+ this.canonicalResults.set(result, exec.token);
17172
+ return result;
17173
+ }
17174
+ /** Snapshot, validate, render, and optionally project one successful body value. */
17175
+ createSuccessResult(exec, tool, candidate) {
17176
+ const detached = snapshotToolValue(tool.name, candidate);
17177
+ const violations = validateJsonSchemaValue(tool.output.schema, detached, "value");
17178
+ if (violations.length > 0) throw new ToolOutputError(tool.name, violations);
17179
+ const value = deepFreeze(detached);
17180
+ let rendered;
17181
+ try {
17182
+ rendered = tool.output.render(exec.arguments, value);
17183
+ } catch (error) {
17184
+ throw projectionError(tool.name, "render", error);
17185
+ }
17186
+ const content = snapshotProjection(tool.name, "render", rendered);
17187
+ let meta;
17188
+ if (tool.output.presentationMeta !== void 0) {
17189
+ let projected;
15842
17190
  try {
15843
- undo = action(layer);
17191
+ projected = tool.output.presentationMeta(exec.arguments, value);
15844
17192
  } catch (error) {
15845
- if (scope !== void 0 && created && layer.isEmpty()) this.scoped.delete(scope);
15846
- throw error;
17193
+ throw projectionError(tool.name, "presentationMeta", error);
15847
17194
  }
15848
- yield () => {
15849
- undo();
15850
- if (scope !== void 0 && layer.isEmpty()) this.scoped.delete(scope);
15851
- if (notify) this.onChange();
15852
- };
15853
- if (notify) this.onChange();
15854
- }.bind(this), options.label);
17195
+ meta = snapshotProjection(tool.name, "presentationMeta", projected);
17196
+ }
17197
+ const concludesTurn = this.concludingExecutions.has(exec);
17198
+ return this.markCanonical(exec, this.materializeFinalResult({
17199
+ isError: false,
17200
+ value,
17201
+ content,
17202
+ ...meta !== void 0 ? { meta } : {},
17203
+ ...concludesTurn ? { concludesTurn: true } : {}
17204
+ }));
17205
+ }
17206
+ /** Normalize an around-dispatch wrapper's authored result through the owning output contract. */
17207
+ normalizeDispatchResult(exec, result) {
17208
+ if (this.canonicalResults.get(result) === exec.token) return result;
17209
+ if (result.isError) return this.markCanonical(exec, {
17210
+ isError: true,
17211
+ error: result.error,
17212
+ content: result.content,
17213
+ ...result.meta !== void 0 ? { meta: result.meta } : {},
17214
+ ...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
17215
+ });
17216
+ const normalized = this.createSuccessResult(exec, this.dispatchedDefinition(exec), result.value);
17217
+ return this.markCanonical(exec, {
17218
+ ...normalized,
17219
+ ...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
17220
+ });
17221
+ }
17222
+ /** Materialize the authoritative commit outcome once, immediately before `tools/result`. */
17223
+ materializeFinalResult(result) {
17224
+ const presentation = {
17225
+ content: result.content,
17226
+ ...result.meta !== void 0 ? { meta: result.meta } : {},
17227
+ ...result.additionalContexts !== void 0 ? { additionalContexts: result.additionalContexts } : {}
17228
+ };
17229
+ if (result.isError) return materializePresentation({
17230
+ isError: true,
17231
+ error: result.error,
17232
+ ...presentation
17233
+ });
17234
+ return deepFreeze({
17235
+ ...materializePresentation({
17236
+ isError: false,
17237
+ ...presentation,
17238
+ ...result.concludesTurn === true ? { concludesTurn: true } : {}
17239
+ }),
17240
+ value: result.value
17241
+ });
15855
17242
  }
15856
17243
  };
17244
+ /** Convert one projector exception into the canonical invalid-output failure. */
17245
+ function projectionError(toolName, projector, error) {
17246
+ return new ToolOutputError(toolName, [`output.${projector} failed: ${errorMessage$1(error)}`]);
17247
+ }
17248
+ /** Snapshot one projector result before later durable-result materialization. */
17249
+ function snapshotProjection(toolName, projector, candidate) {
17250
+ try {
17251
+ const detached = snapshotJsonValue(candidate);
17252
+ if (detached === void 0) throw new ToolOutputError(toolName, [`output.${projector} returned non-lossless JSON`]);
17253
+ return detached;
17254
+ } catch (error) {
17255
+ if (error instanceof ToolOutputError) throw error;
17256
+ throw projectionError(toolName, projector, error);
17257
+ }
17258
+ }
17259
+ /** Snapshot one body or policy value into the canonical invalid-output failure class. */
17260
+ function snapshotToolValue(toolName, candidate) {
17261
+ try {
17262
+ const detached = snapshotJsonValue(candidate);
17263
+ if (detached === void 0) throw new ToolOutputError(toolName, ["value is not lossless JSON"]);
17264
+ return detached;
17265
+ } catch (error) {
17266
+ if (error instanceof ToolOutputError) throw error;
17267
+ throw new ToolOutputError(toolName, [`value snapshot failed: ${errorMessage$1(error)}`]);
17268
+ }
17269
+ }
17270
+ /** Derive one failure message from policy feedback without changing its rendered blocks. */
17271
+ function failureMessageFromContent(content) {
17272
+ const text = content.map((block) => block.type === "text" ? block.text : `[${block.type} content]`).join("\n");
17273
+ return text.length > 0 ? text : "tool result blocked by post-execute policy";
17274
+ }
17275
+ /** Snapshot and freeze one durable tool-result projection or reject lossy data. */
17276
+ function materializePresentation(candidate) {
17277
+ const detached = snapshotJsonValue(candidate);
17278
+ if (detached === void 0) throw new TypeError("tool result must be losslessly JSON-serializable");
17279
+ return deepFreeze(detached);
17280
+ }
17281
+ /** Structured `{ name, code }` for a thrown HarnessError, else undefined. */
17282
+ function errorInfo(error) {
17283
+ try {
17284
+ return error instanceof HarnessError ? {
17285
+ name: error.name,
17286
+ code: error.code
17287
+ } : void 0;
17288
+ } catch {
17289
+ return;
17290
+ }
17291
+ }
17292
+ /** Materialize a non-granting approval outcome as a denial with routable `ApprovalError` identity. */
17293
+ function approvalDenial(reason, code) {
17294
+ return {
17295
+ kind: "deny",
17296
+ reason,
17297
+ info: {
17298
+ name: APPROVAL_ERROR_NAME,
17299
+ code
17300
+ }
17301
+ };
17302
+ }
17303
+ /** Whether a value thrown after cancellation is that cancellation and carries no identity of its own. */
17304
+ function isUnclassifiedCancellation(error, signal) {
17305
+ if (errorInfo(error) !== void 0) return false;
17306
+ try {
17307
+ return error === signal.reason || error instanceof Error && error.name === "AbortError";
17308
+ } catch {
17309
+ return false;
17310
+ }
17311
+ }
15857
17312
  /**
15858
- * Scoped-context primitive: mint a Cordis context that tags registrations with
15859
- * an opaque identity and build routing-only event carriers for that identity.
15860
- *
15861
- * @module @deepseek-ai/dsh-scope
15862
- */
15863
- /** Context tag written by {@link createScope}. */
15864
- const kScope = Symbol("dsh.scope");
15865
- /**
15866
- * The enclosing scope of each key. One relation powers both directions of
15867
- * scope nesting: registration views inherit DOWN the chain (a child scope
15868
- * sees its ancestors' layers — {@link ScopedLayers}), and event admission
15869
- * extends UP it (a listener tagged with an ancestor receives events dispatched
15870
- * to a descendant key — {@link scopeTarget}).
15871
- */
15872
- const scopeParents = /* @__PURE__ */ new WeakMap();
15873
- /**
15874
- * The chain from a key to its root ancestor.
15875
- * @param key - the starting key, or `undefined` for the empty chain.
15876
- * @returns keys nearest-first: `[key, parent, grandparent, …]`.
17313
+ * Result for a recognized cancellation: the thrown message, or the canonical
17314
+ * abort message when the thrown value is an object without a string `message`,
17315
+ * such as an `AgentCancelCause` signal reason.
15877
17316
  */
15878
- function scopeChainOf(key) {
15879
- const chain = [];
15880
- for (let cursor = key; cursor !== void 0; cursor = scopeParents.get(cursor)) chain.push(cursor);
15881
- return chain;
17317
+ function cancellationErrorResult(error, bodyInvoked) {
17318
+ if (isMessagelessObject(error)) return bodyInvoked ? toolAbortedResult() : toolAbortedBeforeDispatchResult();
17319
+ return toolErrorResult(error, {
17320
+ name: "AbortError",
17321
+ code: bodyInvoked ? TOOL_ABORTED : TOOL_ABORTED_BEFORE_DISPATCH
17322
+ });
17323
+ }
17324
+ /** Whether a thrown value is a non-Error object without a string `message`; its own `toString` is not consulted. */
17325
+ function isMessagelessObject(error) {
17326
+ try {
17327
+ return typeof error === "object" && error !== null && !(error instanceof Error) && !("message" in error && typeof error.message === "string");
17328
+ } catch {
17329
+ return false;
17330
+ }
17331
+ }
17332
+ /** Mint a same-process correlation token whose identity is its value. */
17333
+ function createExecutionToken() {
17334
+ return Symbol("dsh.tool.execution");
17335
+ }
17336
+ function toolErrorResult(error, info = errorInfo(error)) {
17337
+ const message = errorMessage$1(error);
17338
+ return {
17339
+ content: [{
17340
+ type: "text",
17341
+ text: `Error: ${message}`
17342
+ }],
17343
+ isError: true,
17344
+ error: {
17345
+ message,
17346
+ ...info ? { info } : {}
17347
+ }
17348
+ };
17349
+ }
17350
+ /** Read live abort state across an await without treating it as synchronously immutable. */
17351
+ function isAborted(signal) {
17352
+ return signal.aborted;
15882
17353
  }
15883
17354
  /**
15884
- * Read the nearest scope tag inherited by a context.
15885
- * @param ctx - context to inspect.
15886
- * @returns its scope key, or `undefined` for an unscoped context.
17355
+ * Fuse caller and wrapper cancellation without nesting `AbortSignal.any`.
17356
+ * Keeping the relay dispatch-scoped also removes listeners when work settles.
15887
17357
  */
15888
- function scopeOf(ctx) {
15889
- return ctx[kScope];
17358
+ function fuseToolSignals(caller, wrapper) {
17359
+ if (caller === wrapper) return {
17360
+ signal: caller,
17361
+ dispose() {}
17362
+ };
17363
+ const controller = new AbortController();
17364
+ let listening = false;
17365
+ const dispose = () => {
17366
+ if (!listening) return;
17367
+ listening = false;
17368
+ caller.removeEventListener("abort", abortFromCaller);
17369
+ wrapper.removeEventListener("abort", abortFromWrapper);
17370
+ };
17371
+ const abortFrom = (source) => {
17372
+ const reason = source.reason;
17373
+ controller.abort(reason);
17374
+ dispose();
17375
+ };
17376
+ const abortFromCaller = () => {
17377
+ abortFrom(caller);
17378
+ };
17379
+ const abortFromWrapper = () => {
17380
+ abortFrom(wrapper);
17381
+ };
17382
+ if (wrapper.aborted) abortFromWrapper();
17383
+ else if (caller.aborted) abortFromCaller();
17384
+ else {
17385
+ listening = true;
17386
+ caller.addEventListener("abort", abortFromCaller, { once: true });
17387
+ wrapper.addEventListener("abort", abortFromWrapper, { once: true });
17388
+ }
17389
+ return {
17390
+ signal: controller.signal,
17391
+ dispose
17392
+ };
17393
+ }
17394
+ /** Canonical result when cancellation supersedes success after body invocation. */
17395
+ function toolAbortedResult(prior) {
17396
+ const additionalContexts = prior?.additionalContexts ?? [];
17397
+ return {
17398
+ content: [{
17399
+ type: "text",
17400
+ text: "Error: tool call aborted"
17401
+ }],
17402
+ isError: true,
17403
+ error: {
17404
+ message: "tool call aborted",
17405
+ info: {
17406
+ name: "AbortError",
17407
+ code: TOOL_ABORTED
17408
+ }
17409
+ },
17410
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
17411
+ };
17412
+ }
17413
+ /** Canonical result when cancellation prevents tool body invocation. */
17414
+ function toolAbortedBeforeDispatchResult(prior) {
17415
+ const additionalContexts = prior?.additionalContexts ?? [];
17416
+ return {
17417
+ content: [{
17418
+ type: "text",
17419
+ text: "Error: tool call aborted before dispatch"
17420
+ }],
17421
+ isError: true,
17422
+ error: {
17423
+ message: "tool call aborted before dispatch",
17424
+ info: {
17425
+ name: "AbortError",
17426
+ code: TOOL_ABORTED_BEFORE_DISPATCH
17427
+ }
17428
+ },
17429
+ ...additionalContexts.length > 0 ? { additionalContexts } : {}
17430
+ };
15890
17431
  }
15891
17432
  //#endregion
15892
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.3-alpha.2_fe5258332cf8d58c43bca084c938026e/node_modules/@deepseek-ai/dsh-tools/lib/index.js
17433
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.3-alpha.4_ca12df44b3bbe3a755034ba57f11ee40/node_modules/@deepseek-ai/dsh-tools/lib/index.js
15893
17434
  /** Unified JSON-value schema DSL, inference, compilation, and tool definition helpers. @module dsh-tools/schema */
15894
17435
  const ANNOTATION_KEYS = [
15895
17436
  "description",
@@ -16211,6 +17752,8 @@ function defineTool(options) {
16211
17752
  },
16212
17753
  ...options.deferLoading === true ? { deferLoading: options.deferLoading } : {},
16213
17754
  ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
17755
+ ...options.guidance !== void 0 ? { guidance: options.guidance } : {},
17756
+ ...options.environment !== void 0 ? { environment: options.environment } : {},
16214
17757
  async execute(args, exec) {
16215
17758
  const violations = validate(args);
16216
17759
  if (violations.length > 0) throw new ToolArgsError(violations);
@@ -16250,23 +17793,36 @@ function projectToolSchema(definition, detachParameters) {
16250
17793
  ...deferLoading === true ? { deferLoading } : {}
16251
17794
  };
16252
17795
  }
16253
- /** Tool definitions and scoped dispatch to plugin-owned executors. @module */
16254
- /** One scope's complete tool-registry contribution. */
17796
+ /** Scoped tool contributions routed to the selected root registry, which answers lookups and dispatch. @module */
17797
+ /** One scope's complete tool contribution. */
16255
17798
  var ToolLayer = class {
16256
17799
  tools;
17800
+ includes = new AnonymousEntries();
16257
17801
  restrictions = new AnonymousEntries();
16258
17802
  constructor(scope) {
16259
17803
  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`));
16260
17804
  }
16261
- /** Whether every contribution table in this aggregate layer is empty. */
17805
+ /** Whether every contribution table in this layer is empty. */
16262
17806
  isEmpty() {
16263
- return this.tools.isEmpty() && this.restrictions.isEmpty();
17807
+ return this.tools.isEmpty() && this.includes.isEmpty() && this.restrictions.isEmpty();
16264
17808
  }
16265
- /** Whether every compiled restriction in this layer admits a global tool name. */
17809
+ /** Whether every compiled restriction in this layer admits an inherited tool name. */
16266
17810
  admits(name) {
16267
17811
  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;
16268
17812
  return true;
16269
17813
  }
17814
+ /** Registrations, then included entries, as the viewing scope resolves them. */
17815
+ candidates(scope) {
17816
+ return collectToolCandidates(this.tools.values(), this.includes.values(), scope);
17817
+ }
17818
+ /** The registration or included entry with one name, as the viewing scope resolves it. */
17819
+ candidate(name, scope) {
17820
+ return findToolCandidate(this.tools.get(name), this.includes.values(), name, scope);
17821
+ }
17822
+ /** Every name this layer can offer: registrations plus each inclusion's unscoped entries. */
17823
+ names() {
17824
+ return [...this.tools.keys(), ...[...this.includes.values()].flatMap((source) => source.getAll().map((tool) => tool.name))];
17825
+ }
16270
17826
  };
16271
17827
  var GuardLayer = class {
16272
17828
  guards = new AnonymousEntries();
@@ -16277,51 +17833,148 @@ var GuardLayer = class {
16277
17833
  (class extends Service {
16278
17834
  static inject = ["systemPrompt"];
16279
17835
  static Config = Schema.object({
16280
- mode: Schema.never().description("Removed. Mount a native or PTC tool executor instead."),
16281
- maxParallelSubCalls: Schema.never().description("Moved to the PTC tool executor configuration.")
17836
+ mode: Schema.never().description("Removed. Mount a native or PTC root tool registry instead."),
17837
+ maxParallelSubCalls: Schema.never().description("Moved to the PTC tool registry configuration.")
16282
17838
  });
16283
- layers = new ScopedLayers((scope) => new ToolLayer(scope), () => {
17839
+ /** Emit `tools/change` from this service's own context, which outlives a caller that unloads. */
17840
+ notifyChange = () => {
16284
17841
  this.ctx.emit("tools/change");
16285
- });
16286
- scoped = /* @__PURE__ */ new WeakMap();
16287
- root;
17842
+ };
17843
+ layers = new ScopedLayers((scope) => new ToolLayer(scope), this.notifyChange);
17844
+ /** Root selections by scope key; ended scopes release theirs, while an unloaded selection stays recorded. */
17845
+ roots = /* @__PURE__ */ new WeakMap();
17846
+ /** The `roots` key of the unscoped selection, which serves every scope without its own. */
17847
+ unscoped = {};
17848
+ /** Environment registries by scope key, keyed like `roots`. */
17849
+ environments = /* @__PURE__ */ new WeakMap();
16288
17850
  guards = new ScopedLayers(() => new GuardLayer(), () => {});
17851
+ viewing = false;
17852
+ /** Whether `ctx.tools` is calling into a root, which must not read `ctx.tools`. */
17853
+ callingRoot = false;
17854
+ /** Roots that already include the registrations, which serve every scope that selects them. */
17855
+ includedRoots = /* @__PURE__ */ new WeakSet();
17856
+ /** Registered tools with guidance by section name; their registrations render the shared section. */
17857
+ guidanceTools = /* @__PURE__ */ new Map();
17858
+ /** The registrations each scope sees, which every selected root includes. */
17859
+ registrations = {
17860
+ get: (name, scope) => this.registered(name, scope),
17861
+ getAll: (scope) => listToolCandidates(this.visible(scope))
17862
+ };
16289
17863
  constructor(ctx) {
16290
17864
  super(ctx, "tools");
16291
- ctx.systemPrompt.tools(({ scope, toolSet }) => {
16292
- const description = this.selectExecutor(scope).describe(this.definitions(scope, toolSet));
17865
+ ctx.systemPrompt.tools(({ scope, toolStep }) => {
17866
+ const declared = toolStep !== void 0 && toolStep.agent === scope ? toolStep.declarations : this.getAll(scope);
16293
17867
  return {
16294
- ...description,
16295
- knownNames: description.knownNames ?? [...this.view(scope).knownNames]
17868
+ schemas: declared.map((definition) => projectToolSchema(definition, false)),
17869
+ knownNames: [.../* @__PURE__ */ new Set([...declared.map((definition) => definition.name), ...this.names(scope).known])]
17870
+ };
17871
+ });
17872
+ }
17873
+ /**
17874
+ * Register in the calling scope. The tool reaches the root the scope
17875
+ * selects and the roots its descendant scopes select: a native root offers
17876
+ * it as an entry, a PTC root binds it in programs. Nearer scopes shadow
17877
+ * farther ones; duplicates within one scope, a name an inclusion in the
17878
+ * scope already offers, and the reserved `run_code` name fail. A tool's
17879
+ * `guidance` registers its system prompt section in the same effect; the
17880
+ * section renders while the viewing scope's registrations resolve the tool.
17881
+ * @param tool - tool schema, execution, and optional finalization, presentation, or guidance.
17882
+ * @returns the exact disposer that unregisters the tool and its guidance.
17883
+ * @throws ToolCompositionError when the scope's inclusions already offer another definition with the name.
17884
+ */
17885
+ register(tool) {
17886
+ assertToolDefinition(tool);
17887
+ this.read(() => {
17888
+ const offered = findToolCandidate(void 0, this.ownLayer()?.includes.values() ?? [], tool.name, void 0);
17889
+ if (offered !== void 0) resolveToolCandidate(tool.name, mergeToolCandidate(offered, tool));
17890
+ });
17891
+ const guidance = tool.guidance;
17892
+ if (guidance === void 0) return this.layers.effect(this.ctx, (layer) => layer.tools.insert(tool.name, tool), { label: "tools.register()" });
17893
+ const section = guidance.section ?? `tool:${tool.name}`;
17894
+ return this.ctx.effect(function* () {
17895
+ yield this.layers.effect(this.ctx, (layer) => layer.tools.insert(tool.name, tool), { label: "tools.register()" });
17896
+ const tools = this.guidanceTools.get(section) ?? [];
17897
+ this.guidanceTools.set(section, tools);
17898
+ tools.push(tool);
17899
+ yield () => {
17900
+ tools.splice(tools.indexOf(tool), 1);
17901
+ if (tools.length === 0) this.guidanceTools.delete(section);
16296
17902
  };
17903
+ yield this.ctx.systemPrompt.section({
17904
+ name: section,
17905
+ order: this.ctx.systemPrompt.getSectionOrder(guidance.order),
17906
+ interpolate: false,
17907
+ ...guidance.retirement === void 0 ? {} : { retirement: guidance.retirement },
17908
+ text: (context) => this.guidanceText(tools, guidance, context)
17909
+ });
17910
+ }.bind(this), "tools.register()");
17911
+ }
17912
+ /**
17913
+ * Render a guidance section for the viewing scope.
17914
+ * @param tools - the tools that share the section.
17915
+ * @param guidance - guidance of the registration the system prompt renders.
17916
+ * @param context - the assembly context, whose scope views the tools.
17917
+ * @returns the section text, or empty text when the scope's registrations resolve none of the tools.
17918
+ * @throws ToolCompositionError when the deciding scope offers several definitions under one of the names.
17919
+ */
17920
+ guidanceText(tools, guidance, context) {
17921
+ const available = new Set(tools.filter((tool) => this.registered(tool.name, context.scope) === tool).map((tool) => tool.name));
17922
+ if (available.size === 0) return "";
17923
+ return typeof guidance.text === "string" ? guidance.text : guidance.text([...available].sort());
17924
+ }
17925
+ /**
17926
+ * Include another registry's entries in the calling scope; they reach roots
17927
+ * as registrations do. Each query reads the source for the viewing scope.
17928
+ * Descendant scopes inherit the entries, so their restrictions apply; the
17929
+ * including scope's own restrictions do not.
17930
+ * @param registry - source that keeps ownership of its definitions.
17931
+ * @returns the exact disposer that removes this inclusion.
17932
+ * @throws ToolCompositionError when the scope already offers another definition under one of the source's names,
17933
+ * when the source itself offers several definitions under one of them, or when the source includes this service.
17934
+ */
17935
+ include(registry) {
17936
+ this.read(() => {
17937
+ const layer = this.ownLayer();
17938
+ const sources = [...layer?.includes.values() ?? [], registry];
17939
+ for (const name of new Set(registry.getAll().map((definition) => definition.name))) resolveToolCandidate(name, findToolCandidate(layer?.tools.get(name), sources, name, void 0));
16297
17940
  });
17941
+ return this.layers.effect(this.ctx, (layer) => layer.includes.append(registry), { label: "tools.include()" });
17942
+ }
17943
+ /**
17944
+ * The calling scope's existing layer; the global layer for an unscoped context.
17945
+ * Conflicts are checked against every name a contribution can offer, before it
17946
+ * publishes, so a conflicting plugin fails at load. Later changes inside an
17947
+ * included registry fail the queries that reach them.
17948
+ */
17949
+ ownLayer() {
17950
+ const scope = scopeOf(this.ctx);
17951
+ return scope === void 0 ? this.layers.global : this.layers.peek(scope);
17952
+ }
17953
+ /**
17954
+ * Run one read of contributions, rejecting a read that re-enters through an inclusion.
17955
+ * @param read - lookup over this service's layers and their inclusions.
17956
+ * @returns the lookup result.
17957
+ * @throws ToolCompositionError when an included registry reads this service again.
17958
+ */
17959
+ read(read) {
17960
+ if (this.viewing) throw inclusionCycle();
17961
+ this.viewing = true;
17962
+ try {
17963
+ return read();
17964
+ } finally {
17965
+ this.viewing = false;
17966
+ }
16298
17967
  }
16299
17968
  /**
16300
- * Register globally or in the calling agent scope. Scoped tools shadow
16301
- * globals; duplicates within one layer and the reserved `run_code` name fail.
16302
- * @param definition - tool schema, execution, and optional finalization/presentation callbacks.
16303
- * @param options - optional step-time activation condition.
16304
- * @returns the exact disposer that unregisters the tool.
16305
- */
16306
- register(definition, options = {}) {
16307
- const name = definition.name;
16308
- const output = definition.output;
16309
- 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? }`);
16310
- assertSupportedJsonSchema(output.schema);
16311
- const timeoutMs = definition.timeoutMs;
16312
- if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new TypeError(`tool "${name}" timeoutMs must be a positive finite number`);
16313
- 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`);
16314
- return this.layers.effect(this.ctx, (layer) => layer.tools.insert(name, {
16315
- definition,
16316
- when: options.when
16317
- }), { label: "tools.register()" });
16318
- }
16319
- /**
16320
- * Restrict global tools for the calling agent scope. Empty filters, unknown
16321
- * names, scope-local names, and reserved transport names fail. Restrictions
16322
- * intersect; scoped registrations remain visible.
16323
- * @param filter - global-tool mask: `allow` (keep only) and/or `deny` (remove).
17969
+ * Restrict inherited tools for the calling scope. Restrictions intersect;
17970
+ * the scope's own registrations and inclusions stay visible. `allow` names
17971
+ * must be ones an inherited registration or inclusion can offer; an
17972
+ * inclusion contributes its unscoped entries, so a tool a provider adds to
17973
+ * Agents later can be allowed in advance. `deny` accepts any name, so a
17974
+ * scope can deny a tool before anything offers it.
17975
+ * @param filter - inherited-tool mask: `allow` (keep only) and/or `deny` (remove).
16324
17976
  * @returns the exact disposer that lifts this restriction.
17977
+ * @throws Error when the context is unscoped, the filter is empty, a name is `run_code`, or an `allow` name is not inherited.
16325
17978
  */
16326
17979
  restrict(filter) {
16327
17980
  const scope = scopeOf(this.ctx);
@@ -16333,187 +17986,265 @@ var GuardLayer = class {
16333
17986
  ...allow !== void 0 ? { allow: new Set(allow) } : {},
16334
17987
  ...deny !== void 0 ? { deny: new Set(deny) } : {}
16335
17988
  };
16336
- 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`);
16337
- const known = this.view(scope).restrictableNames;
16338
- const unknown = [...allow ?? [], ...deny ?? []].filter((name) => !known.has(name));
16339
- 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)"}`);
17989
+ 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`);
17990
+ const known = this.names(scope).restrictable;
17991
+ const unknown = (allow ?? []).filter((name) => !known.has(name));
17992
+ 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)"}`);
16340
17993
  return this.layers.effect(this.ctx, (layer) => layer.restrictions.append(compiled), { label: "tools.restrict()" });
16341
17994
  }
16342
17995
  /**
16343
- * Resolve visible tools and pre-restriction names. Restrictions across the
16344
- * scope chain intersect over inherited global and ancestor tools; the viewing
16345
- * scope's own registrations remain exempt. Nearer registrations shadow
16346
- * farther ones. Pre-restriction names support restriction and prompt-order validation.
16347
- * @param scope - the viewing scope (the agent), or undefined for the global view.
16348
- * @returns the complete derived view for that scope.
16349
- */
16350
- view(scope) {
16351
- const layers = this.layers.chainLayers(scope);
16352
- const own = this.layers.peek(scope);
16353
- const inherited = new Map(this.layers.global.tools.entries());
16354
- for (const layer of layers) {
16355
- if (layer === own) continue;
16356
- for (const [name, registration] of layer.tools.entries()) inherited.set(name, registration);
16357
- }
16358
- const visible = /* @__PURE__ */ new Map();
16359
- const registrations = /* @__PURE__ */ new Map();
16360
- const knownNames = /* @__PURE__ */ new Set();
16361
- const restrictableNames = /* @__PURE__ */ new Set();
16362
- for (const [name, registration] of inherited) {
16363
- knownNames.add(name);
16364
- restrictableNames.add(name);
16365
- if (layers.every((layer) => layer.admits(name))) {
16366
- visible.set(name, registration.definition);
16367
- registrations.set(name, registration);
16368
- }
16369
- }
16370
- if (own !== void 0) for (const [name, registration] of own.tools.entries()) {
16371
- knownNames.add(name);
16372
- visible.set(name, registration.definition);
16373
- registrations.set(name, registration);
16374
- }
16375
- return {
16376
- visible,
16377
- registrations,
16378
- knownNames,
16379
- restrictableNames
16380
- };
16381
- }
16382
- /**
16383
- * Look up a tool as one scope sees it (scoped
16384
- * shadows global; a restricted-away global reads as absent). Presenters pass
16385
- * the calling agent so the rendered card matches the definition that
16386
- * actually executed.
16387
- * @param name - the tool name as registered.
16388
- * @param scope - the viewing scope (the agent); omitted = the global view.
16389
- * @param toolSet - step admission; omit only to inspect registered definitions.
16390
- * @returns the definition the scope resolves, or undefined when none is visible.
16391
- */
16392
- get(name, scope, toolSet) {
16393
- return toolSet === void 0 ? this.view(scope).visible.get(name) : toolSet.view(scope).get(name);
16394
- }
16395
- /**
16396
- * Resolve the definition a call may execute. With a step's admitted set, the
16397
- * set decides; without one, conditional registrations are unavailable.
16398
- * @param name - the tool name as registered.
16399
- * @param scope - the calling agent; omitted = the global view.
16400
- * @param toolSet - step admission, or omitted for a call outside a model step.
16401
- * @returns the executable definition, or undefined when the call must fail as `UNKNOWN_TOOL`.
16402
- */
16403
- executable(name, scope, toolSet) {
16404
- if (toolSet !== void 0) return toolSet.view(scope).get(name);
16405
- const view = this.view(scope);
16406
- return view.registrations.get(name)?.when === void 0 ? view.visible.get(name) : void 0;
16407
- }
16408
- /**
16409
- * Resolve conditions once for this step without changing shared registrations.
16410
- * Cancellation or a rejected condition publishes no partial selection. Removed
16411
- * registrations cannot be restored by a late condition result.
16412
- * @param context - preparing agent, captured model selection, and cancellation.
16413
- * @returns the complete selection; the caller disposes it after its tool batch settles.
16414
- */
16415
- async resolve(context) {
16416
- const { agent, signal } = context;
16417
- signal.throwIfAborted();
16418
- const view = this.view(agent);
16419
- const admitted = /* @__PURE__ */ new Map();
16420
- for (const [name, definition] of view.visible) {
16421
- const registration = view.registrations.get(name);
16422
- let enabled;
16423
- try {
16424
- enabled = registration?.when === void 0 || await registration.when(context);
16425
- } catch (cause) {
16426
- signal.throwIfAborted();
16427
- throw new ToolActivationError(name, cause);
16428
- }
16429
- signal.throwIfAborted();
16430
- if (enabled) admitted.set(name, definition);
16431
- }
16432
- let closed = false;
16433
- return Object.freeze({
16434
- dispose: () => {
16435
- closed = true;
16436
- },
16437
- view: (scope) => {
16438
- const visible = /* @__PURE__ */ new Map();
16439
- if (closed || scope !== agent) return visible;
16440
- const current = this.view(agent);
16441
- for (const [name, definition] of admitted) if (current.visible.get(name) === definition && current.registrations.get(name) === view.registrations.get(name)) visible.set(name, definition);
16442
- return visible;
17996
+ * Resolve the deciding candidates a scope sees. Restrictions across the scope
17997
+ * chain intersect over inherited tools; the viewing scope's own contributions
17998
+ * remain exempt. The nearest place offering a name decides it.
17999
+ * @param scope - the viewing scope, or undefined for the unscoped view.
18000
+ * @returns visible candidates by name.
18001
+ */
18002
+ visible(scope) {
18003
+ return this.read(() => {
18004
+ const layers = this.layers.chainLayers(scope);
18005
+ const own = this.layers.peek(scope);
18006
+ const inherited = this.layers.global.candidates(scope);
18007
+ for (const layer of layers) {
18008
+ if (layer === own) continue;
18009
+ for (const [name, candidate] of layer.candidates(scope)) inherited.set(name, candidate);
16443
18010
  }
18011
+ const visible = /* @__PURE__ */ new Map();
18012
+ for (const [name, candidate] of inherited) if (layers.every((layer) => layer.admits(name))) visible.set(name, candidate);
18013
+ for (const [name, candidate] of own?.candidates(scope) ?? []) visible.set(name, candidate);
18014
+ return visible;
16444
18015
  });
16445
18016
  }
16446
18017
  /**
16447
- * Read the visible capability definitions for descriptions and program bindings.
16448
- * @param scope - viewing Agent or preset; omitted selects the global view.
16449
- * @param toolSet - step admission; omit only to inspect registered definitions.
16450
- * @returns definitions after scoped shadowing and restrictions, limited to the step's admission when given.
18018
+ * Collect the names a scope's contributions can offer before restrictions,
18019
+ * including every entry its inclusions offer to any Agent.
18020
+ * @param scope - the viewing scope, or undefined for the unscoped view.
18021
+ * @returns known and restrictable names.
16451
18022
  */
16452
- definitions(scope, toolSet) {
16453
- return toolSet === void 0 ? [...this.view(scope).visible.values()] : [...toolSet.view(scope).values()];
18023
+ names(scope) {
18024
+ return this.read(() => {
18025
+ const layers = this.layers.chainLayers(scope);
18026
+ const own = this.layers.peek(scope);
18027
+ const inheritedLayers = [this.layers.global, ...layers.filter((layer) => layer !== own)];
18028
+ const restrictable = new Set(inheritedLayers.flatMap((layer) => layer.names()));
18029
+ return {
18030
+ restrictable,
18031
+ known: /* @__PURE__ */ new Set([...restrictable, ...own?.names() ?? []])
18032
+ };
18033
+ });
16454
18034
  }
16455
18035
  /**
16456
- * Project visible definitions onto the allowlisted model-facing schema fields,
16457
- * excluding execution and presentation callbacks.
16458
- * @param scope - the viewing scope (the agent); omitted = the global view.
16459
- * @param toolSet - step admission, or omitted for registered-definition inspection.
16460
- * @returns one deep-cloned schema per visible tool.
16461
- */
16462
- schemas(scope, toolSet) {
16463
- return this.definitions(scope, toolSet).map((definition) => projectToolSchema(definition, true));
18036
+ * Resolve one registration as a scope sees it: nearer contributions shadow
18037
+ * farther ones, and a restricted inherited tool reads as absent.
18038
+ * @param name - the tool name as registered or included.
18039
+ * @param scope - the viewing scope (the agent); omitted selects the unscoped view.
18040
+ * @returns the registration the scope resolves, or undefined when none is visible.
18041
+ * @throws ToolCompositionError when the deciding scope offers several definitions.
18042
+ */
18043
+ registered(name, scope) {
18044
+ return resolveToolCandidate(name, this.read(() => {
18045
+ const layers = this.layers.chainLayers(scope);
18046
+ const own = this.layers.peek(scope);
18047
+ const owned = own?.candidate(name, scope);
18048
+ if (owned !== void 0) return owned;
18049
+ if (!layers.every((layer) => layer.admits(name))) return void 0;
18050
+ for (const layer of layers.toReversed()) {
18051
+ if (layer === own) continue;
18052
+ const inherited = layer.candidate(name, scope);
18053
+ if (inherited !== void 0) return inherited;
18054
+ }
18055
+ return this.layers.global.candidate(name, scope);
18056
+ }));
16464
18057
  }
16465
18058
  /**
16466
- * Provide the executor for the calling scope; an unscoped contribution is the deployment default.
16467
- * Rendering any executor-owned section requires the viewing scope's selection to remain available.
16468
- * Disposal retires its sections; a replacement's same-name sections supersede those notices.
16469
- * @param executor - initialized provider owned by the contributing plugin.
18059
+ * Resolve one entry of the root a scope selects: a native root resolves the
18060
+ * scope's registrations, a PTC root only its program entry.
18061
+ * @param name - entry name.
18062
+ * @param scope - the viewing scope (the agent); omitted reads the root the unscoped context selects.
18063
+ * @returns the root's entry, or undefined when the root has none with that name.
18064
+ * @throws ToolRegistryUnavailableError when the scope's selected root is missing or unloaded.
18065
+ * @throws ToolCompositionError when the deciding scope offers several definitions, or when the root
18066
+ * or an included registry reads `ctx.tools`.
18067
+ */
18068
+ get(name, scope) {
18069
+ return this.callRoot(() => this.selectRoot(scope).get(name, scope));
18070
+ }
18071
+ /**
18072
+ * List the entries of the root a scope selects, which its model steps
18073
+ * declare: a native root lists the scope's registrations after shadowing and
18074
+ * restrictions, a PTC root only its program entry.
18075
+ * @param scope - the viewing scope (the agent); omitted reads the root the unscoped context selects.
18076
+ * @returns the root's entries.
18077
+ * @throws ToolRegistryUnavailableError when the scope's selected root is missing or unloaded.
18078
+ * @throws ToolCompositionError when a visible name has several definitions in its deciding scope, or
18079
+ * when the root or an included registry reads `ctx.tools`.
18080
+ */
18081
+ getAll(scope) {
18082
+ return this.callRoot(() => resolveToolList(this.selectRoot(scope).getAll(scope)));
18083
+ }
18084
+ /**
18085
+ * Run one call into a root registry. A root receives the registrations from
18086
+ * `setRoot()`, so a root that reads `ctx.tools` during the call would read
18087
+ * itself; that read fails instead of recursing. A read that arrives while the
18088
+ * registrations are being read comes from an included registry and fails as
18089
+ * an inclusion cycle.
18090
+ * @param call - lookup or inclusion on a root registry.
18091
+ * @returns the call's result.
18092
+ * @throws ToolCompositionError when the root or an included registry reads `ctx.tools` during the call.
18093
+ */
18094
+ callRoot(call) {
18095
+ if (this.viewing) throw inclusionCycle();
18096
+ 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");
18097
+ this.callingRoot = true;
18098
+ try {
18099
+ return call();
18100
+ } finally {
18101
+ this.callingRoot = false;
18102
+ }
18103
+ }
18104
+ /**
18105
+ * Select the root registry for the calling scope; an unscoped call selects
18106
+ * the root for every scope without its own. Agents use the nearest selected root. The
18107
+ * root includes the registrations each viewing scope sees, and keeps them
18108
+ * after unloading so accepted batches settle their calls; selecting the
18109
+ * same registry again does not include them twice. A root must not include
18110
+ * or read `ctx.tools`: such a read fails with `ToolCompositionError` when
18111
+ * the root is selected or, for a root that reads it later, in the lookup or
18112
+ * batch that reaches it. Register tools through `ctx.tools`: a tool
18113
+ * registered directly in a root skips the scope's conflict check, so another
18114
+ * definition registered under its name through `ctx.tools` is accepted and
18115
+ * the next `ctx.tools.getAll()` throws. Selecting or unloading a root emits
18116
+ * `tools/change`; every observer runs, and an observer that throws fails the
18117
+ * selection, which restores the scope's earlier selection, or none, and
18118
+ * emits `tools/change` again.
18119
+ * @param registry - initialized root owned by the contributing plugin.
16470
18120
  * @returns the effect disposer. Unloading leaves the selection unavailable until it is replaced.
18121
+ * @throws Error when the calling scope already has a live root.
18122
+ * @throws ToolCompositionError when the root's own entries conflict with the registrations, or when the root reads `ctx.tools`.
18123
+ * @throws an `AggregateError` whose `errors` holds the observer failures when a `tools/change` observer fails the selection.
16471
18124
  */
16472
- setExecutor(executor) {
18125
+ setRoot(registry) {
16473
18126
  const scope = scopeOf(this.ctx);
16474
- 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");
16475
- const record = { executor };
18127
+ const key = scope ?? this.unscoped;
18128
+ const existing = this.roots.get(key);
18129
+ if (existing?.registry !== void 0) throw new Error("Only one root tool registry may be installed in each scope");
18130
+ const record = { registry };
18131
+ const select = (selection) => {
18132
+ if (selection === void 0) this.roots.delete(key);
18133
+ else this.roots.set(key, selection);
18134
+ };
16476
18135
  return this.ctx.effect(function* () {
16477
- for (const section of executor.sections ?? []) yield this.ctx.systemPrompt.section({
16478
- name: section.name,
16479
- order: section.order,
16480
- ...section.interpolate === void 0 ? {} : { interpolate: section.interpolate },
16481
- text: ({ scope, toolSet }) => {
16482
- if (this.selectExecutor(scope) !== executor) return "";
16483
- return typeof section.text === "function" ? section.text(this.definitions(scope, toolSet)) : section.text;
18136
+ const undo = this.callRoot(() => {
18137
+ const removeInclusion = this.includedRoots.has(registry) ? void 0 : registry.include(this.registrations);
18138
+ try {
18139
+ resolveToolList(registry.getAll(scope));
18140
+ } catch (error) {
18141
+ removeInclusion?.();
18142
+ throw error;
16484
18143
  }
18144
+ return removeInclusion;
16485
18145
  });
16486
- if (scope === void 0) this.root = record;
16487
- else this.scoped.set(scope, record);
18146
+ select(record);
18147
+ let committed = false;
16488
18148
  yield () => {
16489
- record.executor = void 0;
18149
+ if (committed) record.registry = void 0;
18150
+ else {
18151
+ select(existing);
18152
+ undo?.();
18153
+ }
18154
+ this.notifyChange();
16490
18155
  };
16491
- }.bind(this), "tools.setExecutor()");
16492
- }
16493
- /**
16494
- * Resolve the nearest scoped provider, or the deployment default.
16495
- * @param scope - Agent or preset scope; omitted selects only the root contribution.
16496
- * @returns the selected executor; throws when it is missing or unloaded.
16497
- */
16498
- selectExecutor(scope) {
16499
- let record;
16500
- for (const key of scopeChainOf(scope)) {
16501
- record = this.scoped.get(key);
16502
- if (record !== void 0) break;
16503
- }
16504
- record ??= this.root;
16505
- const executor = record?.executor;
16506
- if (executor === void 0) throw new ToolExecutorUnavailableError();
16507
- return executor;
16508
- }
16509
- /**
16510
- * Delegate a raw call batch to its Agent's provider or the deployment default.
16511
- * Select at dispatch; accepted batches settle through that provider even if it unloads.
16512
- * @param input - original calls, optional owning Agent, and optional logging step.
16513
- * @returns the selected executor's settled batch; unavailable selections reject.
18156
+ this.notifyChange();
18157
+ committed = true;
18158
+ this.includedRoots.add(registry);
18159
+ }.bind(this), "tools.setRoot()");
18160
+ }
18161
+ /**
18162
+ * Resolve the nearest root selected along the scope chain, ending with the unscoped selection.
18163
+ * @param scope - Agent or preset scope; omitted reads only the unscoped selection.
18164
+ * @returns the selected root; throws when it is missing or unloaded.
18165
+ */
18166
+ selectBaseRoot(scope) {
18167
+ const record = [...scopeChainOf(scope), this.unscoped].map((key) => this.roots.get(key)).find((found) => found !== void 0);
18168
+ if (record?.registry === void 0) throw new ToolRegistryUnavailableError();
18169
+ return record.registry;
18170
+ }
18171
+ /**
18172
+ * The registry that answers a scope's lookups: the nearest environment
18173
+ * registry, which reads the scope's root, else the root itself.
18174
+ * @param scope - Agent or preset scope; omitted reads only the unscoped selections.
18175
+ * @throws ToolRegistryUnavailableError when the scope's root is missing or unloaded.
18176
+ */
18177
+ selectRoot(scope) {
18178
+ const root = this.selectBaseRoot(scope);
18179
+ return [...scopeChainOf(scope), this.unscoped].map((key) => this.environments.get(key)).find((found) => found !== void 0) ?? root;
18180
+ }
18181
+ /**
18182
+ * Select the environment registry for the calling scope and the scopes
18183
+ * below it without their own. `ctx.tools` includes the root each viewing
18184
+ * scope selects in it, resolved at every query, so it stays above any root
18185
+ * the scope selects, including one that loads later or reloads; lookups,
18186
+ * declarations, and calls then go through it. It offers the root's entries
18187
+ * in execution environments, such as copies with `resolveEnvironment` whose
18188
+ * `origin` names the root's definition, and must not read `ctx.tools`.
18189
+ * Selecting or removing it emits `tools/change`.
18190
+ * @param registry - the environment registry; its `include()` receives, once, a view of the root each scope selects.
18191
+ * @returns the effect disposer that removes the registry and its inclusion.
18192
+ * @throws Error when the calling scope already has an environment registry.
18193
+ * @throws ToolCompositionError when the registry reads `ctx.tools` or offers conflicting entries for the calling scope's root.
18194
+ */
18195
+ setEnvironments(registry) {
18196
+ const scope = scopeOf(this.ctx);
18197
+ const key = scope ?? this.unscoped;
18198
+ if (this.environments.has(key)) throw new Error("Only one tool environment registry may be set in each scope");
18199
+ return this.ctx.effect(function* () {
18200
+ const removeInclusion = this.callRoot(() => registry.include({
18201
+ get: (name, viewer) => this.selectBaseRoot(viewer).get(name, viewer),
18202
+ getAll: (viewer) => this.selectBaseRoot(viewer).getAll(viewer)
18203
+ }));
18204
+ this.environments.set(key, registry);
18205
+ yield () => {
18206
+ this.environments.delete(key);
18207
+ removeInclusion();
18208
+ this.notifyChange();
18209
+ };
18210
+ 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)));
18211
+ this.notifyChange();
18212
+ }.bind(this), "tools.setEnvironments()");
18213
+ }
18214
+ /**
18215
+ * Execute a complete batch of calls to the entries of the root the Agent
18216
+ * selects, or the unscoped context's root for a standalone call. Each call runs the entry the root
18217
+ * resolves for the Agent; with a model step, only the exact entry the step
18218
+ * declared, and any other call fails as `UNKNOWN_TOOL`. A call naming a
18219
+ * tool the Agent can reach only from the root's entries, such as a program
18220
+ * binding, fails as `UNKNOWN_TOOL` before `tools/pre-execute`, approval,
18221
+ * guards, and execution wrappers, and its message names the entries the
18222
+ * Agent can call directly. An accepted batch settles through the root it
18223
+ * started with even if that root unloads. With log, root call/result events are committed to
18224
+ * the Agent's Session; without log, they are omitted. One outcome is
18225
+ * returned per input call in input order, including skipped calls on abort,
18226
+ * and the batch never settles while started work is still running.
18227
+ * Internal failures reject with ToolBatchExecutionError after draining,
18228
+ * preserving committed outcomes and context; callers must stop dependent
18229
+ * work and repair missing log results.
18230
+ * @param input - original calls, cancellation, optional concurrency override, Agent, model step, and logging step.
18231
+ * @returns settled results, deferred context, and whether a success concludes the turn.
18232
+ * @throws ToolRegistryUnavailableError when the Agent's selected root is missing or unloaded.
16514
18233
  */
16515
18234
  async execute(input) {
16516
- return this.selectExecutor(input.agent).execute(input);
18235
+ const root = this.selectRoot(input.agent);
18236
+ return executeToolBatch(input, new ToolExecutionPipeline(this.ctx, {
18237
+ get: (name, scope, toolStep) => {
18238
+ const entry = this.callRoot(() => root.get(name, scope));
18239
+ return entry !== void 0 && (toolStep?.declares(entry) ?? true) ? entry : void 0;
18240
+ },
18241
+ reject: (exec) => {
18242
+ if (this.callRoot(() => root.get(exec.name, exec.agent)) !== void 0) return void 0;
18243
+ if (this.registered(exec.name, exec.agent) === void 0) return void 0;
18244
+ 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);
18245
+ return new ToolNotFoundError(exec.name, [...new Set(callable.map((entry) => entry.name))]);
18246
+ }
18247
+ }));
16517
18248
  }
16518
18249
  /**
16519
18250
  * Register a monotonic denial in the calling scope.
@@ -16535,6 +18266,10 @@ var GuardLayer = class {
16535
18266
  }
16536
18267
  }
16537
18268
  });
18269
+ /** The failure of a read that re-enters `ctx.tools` through an included registry. */
18270
+ function inclusionCycle() {
18271
+ return new ToolCompositionError("tool registry inclusion cycle reaches ctx.tools");
18272
+ }
16538
18273
  //#endregion
16539
18274
  //#region src/host/ui-tools.ts
16540
18275
  /**
@@ -16613,6 +18348,7 @@ function presentationOf(args, value) {
16613
18348
  function createUiPresentTool(host) {
16614
18349
  return defineTool({
16615
18350
  name: "ui_present",
18351
+ environment: "independent",
16616
18352
  description: UI_PRESENT_DESCRIPTION,
16617
18353
  parameters: {
16618
18354
  html: {
@@ -28437,7 +30173,7 @@ var require_negotiator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28437
30173
  Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
28438
30174
  }));
28439
30175
  //#endregion
28440
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-host-webserver@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1_supports-color@7.2.0/node_modules/@deepseek-ai/dsh-host-webserver/lib/index.js
30176
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-host-webserver@0.2.3-alpha.4_@deepseek-ai+cordis@4.2.0-alpha.3_supports-color@7.2.0/node_modules/@deepseek-ai/dsh-host-webserver/lib/index.js
28441
30177
  var lib_exports = /* @__PURE__ */ __exportAll({
28442
30178
  WebServer: () => WebServer,
28443
30179
  bindUrlHost: () => bindUrlHost,
@@ -34131,17 +35867,17 @@ function sessionRoster(ctx, peer, log) {
34131
35867
  * @returns 路由 face。
34132
35868
  */
34133
35869
  function sessionRoute(ctx, peer, log) {
34134
- const invoke = async (method, args) => await ctx.typertGateway.invoke({
34135
- namespace: "session",
35870
+ const invoke = async (namespace, method, args) => await ctx.typertGateway.invoke({
35871
+ namespace,
34136
35872
  method,
34137
- args: wireArgs("session", method, args),
35873
+ args: wireArgs(namespace, method, args),
34138
35874
  peer
34139
35875
  });
34140
35876
  return { current: async (sessionId) => {
34141
35877
  try {
34142
- const folded = modelSelectionOf(await invoke("projections", { sessionId }));
35878
+ const folded = modelSelectionOf(await invoke("session", "projections", { sessionId }));
34143
35879
  const selected = folded.next ?? folded.lastUsed;
34144
- const fallback = selected === void 0 ? selectionOf(catalogDefaultOf(await invoke("modelCatalog", {}))) : void 0;
35880
+ const fallback = selected === void 0 ? selectionOf(catalogDefaultOf(await invoke("models", "catalog", {}))) : void 0;
34145
35881
  const answer = selected ?? fallback;
34146
35882
  return answer === void 0 ? void 0 : {
34147
35883
  provider: answer.provider,
@@ -34153,7 +35889,7 @@ function sessionRoute(ctx, peer, log) {
34153
35889
  }
34154
35890
  } };
34155
35891
  }
34156
- /** `session/modelCatalog` 里的 `default` 一格。 */
35892
+ /** `models/catalog` 里的 `default` 一格。 */
34157
35893
  function catalogDefaultOf(value) {
34158
35894
  return typeof value === "object" && value !== null ? value.default : void 0;
34159
35895
  }
@@ -34170,13 +35906,22 @@ function catalogDefaultOf(value) {
34170
35906
  * @param log - 读不到名册时的落点。
34171
35907
  * @returns 这些 face 此刻的样子。
34172
35908
  */
35909
+ function optionalService(ctx, name) {
35910
+ try {
35911
+ return ctx.get(name, false) ?? ctx.get(name);
35912
+ } catch {
35913
+ return;
35914
+ }
35915
+ }
34173
35916
  function usageFaces(ctx, peer, log) {
34174
35917
  return {
34175
- sessions: ctx.get("sessions"),
35918
+ sessions: optionalService(ctx, "sessions"),
34176
35919
  roster: sessionRoster(ctx, peer, log),
34177
- credentials: ctx.get("credentials"),
34178
- settings: ctx.get("settings"),
34179
- route: sessionRoute(ctx, peer, log)
35920
+ credentials: optionalService(ctx, "credentials"),
35921
+ settings: optionalService(ctx, "settings"),
35922
+ route: sessionRoute(ctx, peer, log),
35923
+ deepseekAuth: optionalService(ctx, "deepseekAuth"),
35924
+ deepseekAccount: optionalService(ctx, "deepseekAccount")
34180
35925
  };
34181
35926
  }
34182
35927
  /**