@linxin666/dsh-remote-bridge 0.4.21 → 0.4.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +12 -13
- package/README.zh.md +13 -14
- package/lib/client.js +195 -39
- package/lib/client.js.map +1 -1
- package/lib/index.js +2550 -715
- package/lib/types/client/PairEntry.d.ts +1 -1
- package/lib/types/client/PairPanel.d.ts +2 -2
- package/lib/types/client/RemoteConnectionExtension.d.ts +12 -0
- package/lib/types/client/UiPresentRow.d.ts +1 -1
- package/lib/types/client/index.d.ts +2 -1
- package/lib/types/core/usage.d.ts +42 -0
- package/lib/types/host/dsh-home.d.ts +13 -3
- package/package.json +24 -23
- package/src/client/PairEntry.tsx +1 -1
- package/src/client/PairPanel.tsx +3 -3
- package/src/client/RemoteConnectionExtension.tsx +161 -0
- package/src/client/UiPresentRow.tsx +1 -1
- package/src/client/index.ts +22 -2
- package/src/client/panel.module.css +51 -0
- package/src/core/connection.ts +29 -8
- package/src/core/usage.ts +173 -7
- package/src/core/wire.ts +1 -1
- package/src/host/dsh-home.ts +35 -12
- package/src/host/routes.ts +1 -4
- package/src/host/ui-tools.ts +1 -0
- package/src/index.ts +28 -10
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
|
|
4849
|
-
|
|
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(
|
|
4952
|
-
headers
|
|
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: "
|
|
5403
|
-
method: "
|
|
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
|
|
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 ?
|
|
5959
|
-
...
|
|
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("
|
|
7252
|
+
const catalog = await this.#unary("models", "catalog");
|
|
7089
7253
|
if (!catalog.ok) return catalog;
|
|
7090
|
-
if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, "
|
|
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, "
|
|
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("
|
|
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("
|
|
7374
|
+
const catalog = await this.#unary("models", "catalog");
|
|
7211
7375
|
if (!catalog.ok) return catalog;
|
|
7212
|
-
if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, "
|
|
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
|
|
10616
|
-
* environment
|
|
10617
|
-
*
|
|
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
|
-
|
|
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,189 +12079,335 @@ function makePairTokenRoute(deps) {
|
|
|
11913
12079
|
};
|
|
11914
12080
|
}
|
|
11915
12081
|
//#endregion
|
|
11916
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-
|
|
11917
|
-
/** The one Remote failure class shared by owners, the Gateway, and consumers. */
|
|
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
|
|
11918
12083
|
/**
|
|
11919
|
-
*
|
|
11920
|
-
*
|
|
11921
|
-
*
|
|
11922
|
-
* `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
|
|
11923
|
-
* Discrimination is always by `code`, never by instanceof.
|
|
12084
|
+
* Shared insertion-ordered storage and effect ownership for scope-aware registries.
|
|
12085
|
+
*
|
|
12086
|
+
* @module @deepseek-ai/dsh-scope
|
|
11924
12087
|
*/
|
|
11925
|
-
|
|
11926
|
-
|
|
11927
|
-
|
|
11928
|
-
|
|
11929
|
-
|
|
12088
|
+
/**
|
|
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.
|
|
12094
|
+
*/
|
|
12095
|
+
var NamedEntries = class {
|
|
12096
|
+
duplicateError;
|
|
12097
|
+
data = /* @__PURE__ */ new Map();
|
|
12098
|
+
constructor(duplicateError) {
|
|
12099
|
+
this.duplicateError = duplicateError;
|
|
12100
|
+
}
|
|
11930
12101
|
/**
|
|
11931
|
-
*
|
|
11932
|
-
* @param
|
|
11933
|
-
* @param
|
|
11934
|
-
* @
|
|
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.
|
|
11935
12106
|
*/
|
|
11936
|
-
|
|
11937
|
-
|
|
11938
|
-
|
|
11939
|
-
|
|
11940
|
-
|
|
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
|
+
};
|
|
12118
|
+
}
|
|
12119
|
+
/**
|
|
12120
|
+
* Read one named value.
|
|
12121
|
+
* @param name - name to resolve.
|
|
12122
|
+
* @returns the retained value, or `undefined` when absent.
|
|
12123
|
+
*/
|
|
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;
|
|
11941
12162
|
}
|
|
11942
12163
|
};
|
|
11943
12164
|
/**
|
|
11944
|
-
*
|
|
11945
|
-
*
|
|
11946
|
-
*
|
|
11947
|
-
*
|
|
11948
|
-
|
|
11949
|
-
const TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
|
|
11950
|
-
/**
|
|
11951
|
-
* Test one generated Remote name against the Connection endpoint grammar.
|
|
11952
|
-
* @param value - namespace, method, lookup, or Context segment.
|
|
11953
|
-
* @returns whether the value can cross the shared RPC carrier unchanged.
|
|
11954
|
-
*/
|
|
11955
|
-
function isTypertRemoteSegment(value) {
|
|
11956
|
-
return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
|
|
11957
|
-
}
|
|
11958
|
-
const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
|
|
11959
|
-
/**
|
|
11960
|
-
* Bind one visible Service field to a Cordis key and Remote namespace. A
|
|
11961
|
-
* service that owns a Cordis Context also gives its tree `ctx.invocation`,
|
|
11962
|
-
* `undefined` outside a Remote call, so no `TypertRemoteService` is needed for
|
|
11963
|
-
* a Host composition to read it.
|
|
11964
|
-
* @param service - owning Service instance, normally `this`.
|
|
11965
|
-
* @param serviceKey - exact Cordis service key.
|
|
11966
|
-
* @param options - optional wire namespace.
|
|
11967
|
-
* @returns a frozen, inspectable binding with no compiler-injected metadata.
|
|
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.
|
|
11968
12170
|
*/
|
|
11969
|
-
|
|
11970
|
-
|
|
11971
|
-
const namespace = options.namespace ?? serviceKey;
|
|
11972
|
-
validateName("namespace", namespace);
|
|
11973
|
-
const ctx = Reflect.get(service, "ctx");
|
|
11974
|
-
if (Context.is(ctx)) provideInvocationAccessor(ctx);
|
|
11975
|
-
return Object.freeze({
|
|
11976
|
-
service,
|
|
11977
|
-
serviceKey,
|
|
11978
|
-
namespace
|
|
11979
|
-
});
|
|
11980
|
-
}
|
|
11981
|
-
/** Cordis Service base that exposes its registered name through Typert Gateway. */
|
|
11982
|
-
var TypertRemoteService = class extends Service {
|
|
11983
|
-
/** Visible binding consumed by the Gateway's source-mode discovery. */
|
|
11984
|
-
typertRemote;
|
|
12171
|
+
var AnonymousEntries = class {
|
|
12172
|
+
data = /* @__PURE__ */ new Map();
|
|
11985
12173
|
/**
|
|
11986
|
-
*
|
|
11987
|
-
* @param
|
|
11988
|
-
* @
|
|
11989
|
-
* @param options - optional wire namespace.
|
|
12174
|
+
* Append one independently owned value.
|
|
12175
|
+
* @param value - borrowed value to retain.
|
|
12176
|
+
* @returns an idempotent undo for this exact append.
|
|
11990
12177
|
*/
|
|
11991
|
-
|
|
11992
|
-
|
|
11993
|
-
|
|
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
|
+
};
|
|
12189
|
+
}
|
|
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;
|
|
11994
12203
|
}
|
|
11995
12204
|
};
|
|
11996
12205
|
/**
|
|
11997
|
-
*
|
|
11998
|
-
*
|
|
11999
|
-
*
|
|
12000
|
-
*
|
|
12001
|
-
|
|
12002
|
-
|
|
12003
|
-
|
|
12004
|
-
|
|
12005
|
-
|
|
12006
|
-
|
|
12007
|
-
|
|
12008
|
-
|
|
12009
|
-
|
|
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);
|
|
12010
12222
|
}
|
|
12011
|
-
|
|
12012
|
-
|
|
12013
|
-
|
|
12014
|
-
}
|
|
12015
|
-
|
|
12016
|
-
|
|
12017
|
-
|
|
12018
|
-
|
|
12019
|
-
|
|
12020
|
-
|
|
12021
|
-
|
|
12022
|
-
const keys = Reflect.ownKeys(options);
|
|
12023
|
-
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}`);
|
|
12024
|
-
const { mode, name, resources } = options;
|
|
12025
|
-
if (name !== void 0) validateName("Remote export name", name);
|
|
12026
|
-
return {
|
|
12027
|
-
...mode === void 0 ? {} : { mode },
|
|
12028
|
-
...name === void 0 ? {} : { exportName: name },
|
|
12029
|
-
...resources === void 0 ? {} : { resources: resourceReaders(resources) }
|
|
12030
|
-
};
|
|
12031
|
-
}
|
|
12032
|
-
/** Freeze declared readers into the marker record; a misdeclared reader fails at decoration. */
|
|
12033
|
-
function resourceReaders(resources) {
|
|
12034
|
-
const readers = {};
|
|
12035
|
-
for (const [kind, reader] of Object.entries(resources)) {
|
|
12036
|
-
if (typeof reader !== "function") throw new TypeError(`typert-protocol: Remote resource reader "${kind}" must be a function`);
|
|
12037
|
-
readers[kind] = reader;
|
|
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);
|
|
12038
12234
|
}
|
|
12039
|
-
|
|
12040
|
-
|
|
12041
|
-
|
|
12042
|
-
|
|
12043
|
-
|
|
12044
|
-
|
|
12045
|
-
|
|
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;
|
|
12046
12327
|
}
|
|
12047
|
-
|
|
12048
|
-
|
|
12049
|
-
|
|
12050
|
-
|
|
12051
|
-
|
|
12052
|
-
|
|
12053
|
-
|
|
12054
|
-
const methods = Reflect.get(descriptor, "methods");
|
|
12055
|
-
if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
|
|
12056
|
-
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];
|
|
12057
12335
|
}
|
|
12058
|
-
|
|
12059
|
-
|
|
12060
|
-
|
|
12061
|
-
|
|
12062
|
-
|
|
12063
|
-
|
|
12064
|
-
|
|
12065
|
-
|
|
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;
|
|
12066
12359
|
}
|
|
12067
|
-
|
|
12068
|
-
|
|
12069
|
-
|
|
12070
|
-
|
|
12071
|
-
|
|
12072
|
-
|
|
12073
|
-
|
|
12074
|
-
|
|
12075
|
-
|
|
12076
|
-
|
|
12077
|
-
|
|
12078
|
-
|
|
12079
|
-
|
|
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>";
|
|
12080
12398
|
}
|
|
12081
|
-
Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
|
|
12082
|
-
configurable: true,
|
|
12083
|
-
value: Object.freeze({
|
|
12084
|
-
version: 1,
|
|
12085
|
-
methods: Object.freeze([...descriptor?.methods ?? [], marker])
|
|
12086
|
-
})
|
|
12087
|
-
});
|
|
12088
|
-
}
|
|
12089
|
-
function sameInvocation(left, right) {
|
|
12090
|
-
if (left.kind === "direct") return right.kind === "direct";
|
|
12091
|
-
if (right.kind === "direct") return false;
|
|
12092
|
-
return left.context === right.context;
|
|
12093
12399
|
}
|
|
12094
|
-
|
|
12095
|
-
|
|
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>";
|
|
12096
12408
|
}
|
|
12097
12409
|
//#endregion
|
|
12098
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.
|
|
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
|
|
12099
12411
|
/**
|
|
12100
12412
|
* Lazily scanned view of one JSON object's top-level fields, built from text
|
|
12101
12413
|
* that may still be streaming or from an already parsed object. Nothing is
|
|
@@ -12739,13 +13051,14 @@ function hasIntrinsicConstructor$1(prototype, name) {
|
|
|
12739
13051
|
return false;
|
|
12740
13052
|
}
|
|
12741
13053
|
}
|
|
12742
|
-
/** Whether a candidate is
|
|
13054
|
+
/** Whether a candidate is this or another realm's intrinsic `Object.prototype`. */
|
|
12743
13055
|
function isIntrinsicObjectPrototype$1(value) {
|
|
12744
|
-
return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, "Object");
|
|
13056
|
+
return value === Object.prototype || Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, "Object");
|
|
12745
13057
|
}
|
|
12746
13058
|
/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
|
|
12747
13059
|
function hasPlainArrayPrototype$1(value) {
|
|
12748
13060
|
const prototype = Object.getPrototypeOf(value);
|
|
13061
|
+
if (prototype === Array.prototype) return true;
|
|
12749
13062
|
if (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, "Array")) return false;
|
|
12750
13063
|
const objectPrototype = Object.getPrototypeOf(prototype);
|
|
12751
13064
|
return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);
|
|
@@ -12914,25 +13227,244 @@ function deepFreeze(value) {
|
|
|
12914
13227
|
return value;
|
|
12915
13228
|
}
|
|
12916
13229
|
//#endregion
|
|
12917
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+
|
|
12918
|
-
/**
|
|
12919
|
-
|
|
12920
|
-
|
|
12921
|
-
|
|
12922
|
-
|
|
12923
|
-
|
|
12924
|
-
|
|
12925
|
-
|
|
12926
|
-
|
|
12927
|
-
|
|
12928
|
-
|
|
12929
|
-
|
|
12930
|
-
/**
|
|
12931
|
-
|
|
12932
|
-
|
|
12933
|
-
}
|
|
12934
|
-
|
|
12935
|
-
|
|
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
|
|
13450
|
+
/** Return true when a value is `null` or `undefined`. */
|
|
13451
|
+
function isNullable(value) {
|
|
13452
|
+
return value === null || value === void 0;
|
|
13453
|
+
}
|
|
13454
|
+
/** Return true for non-array object values. */
|
|
13455
|
+
function isPlainObject(data) {
|
|
13456
|
+
return data && typeof data === "object" && !Array.isArray(data);
|
|
13457
|
+
}
|
|
13458
|
+
/** Filter object entries and return a new object. */
|
|
13459
|
+
function filterKeys(object, filter) {
|
|
13460
|
+
return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
|
|
13461
|
+
}
|
|
13462
|
+
/** Map object values while preserving the original key set. */
|
|
13463
|
+
function mapValues(object, transform) {
|
|
13464
|
+
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
|
|
13465
|
+
}
|
|
13466
|
+
/** Pick selected keys from an object, optionally including `undefined` values. */
|
|
13467
|
+
function pick(source, keys, forced) {
|
|
12936
13468
|
if (!keys) return { ...source };
|
|
12937
13469
|
const result = {};
|
|
12938
13470
|
for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
|
|
@@ -13168,7 +13700,7 @@ var Time;
|
|
|
13168
13700
|
Time.template = template;
|
|
13169
13701
|
})(Time || (Time = {}));
|
|
13170
13702
|
//#endregion
|
|
13171
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.
|
|
13703
|
+
//#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.20.0-alpha.3/node_modules/@deepseek-ai/schemastery/lib/index.mjs
|
|
13172
13704
|
const kSchema = Symbol.for("schemastery");
|
|
13173
13705
|
const kValidationError = Symbol.for("ValidationError");
|
|
13174
13706
|
globalThis.__schemastery_index__ ??= 0;
|
|
@@ -13801,41 +14333,11 @@ defineMethod("transform", [
|
|
|
13801
14333
|
"preserve"
|
|
13802
14334
|
], ({ inner }, isInner) => inner.toString(isInner));
|
|
13803
14335
|
//#endregion
|
|
13804
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.
|
|
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
|
|
13805
14337
|
/** Largest delay Node schedules without clamping it to one millisecond. */
|
|
13806
14338
|
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
13807
14339
|
//#endregion
|
|
13808
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-
|
|
13809
|
-
/**
|
|
13810
|
-
* Harness error base with a stable machine-routable code and chained cause.
|
|
13811
|
-
* Package errors extend it so tool results and replay can retain failure class.
|
|
13812
|
-
* @module @deepseek-ai/dsh-error
|
|
13813
|
-
*/
|
|
13814
|
-
/**
|
|
13815
|
-
* Base class for all harness errors. Carries a `code` (stable, programmatic —
|
|
13816
|
-
* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the
|
|
13817
|
-
* human-readable `message`, and supports `cause` chaining via the standard
|
|
13818
|
-
* `ErrorOptions`. `name` defaults to the subclass constructor name.
|
|
13819
|
-
*/
|
|
13820
|
-
var HarnessError = class extends Error {
|
|
13821
|
-
/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
|
|
13822
|
-
code;
|
|
13823
|
-
constructor(message, code, options) {
|
|
13824
|
-
super(message, options);
|
|
13825
|
-
this.code = code;
|
|
13826
|
-
this.name = new.target.name;
|
|
13827
|
-
}
|
|
13828
|
-
};
|
|
13829
|
-
//#endregion
|
|
13830
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-error@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0_/node_modules/@deepseek-ai/dsh-llm/lib/index.js
|
|
13831
|
-
/**
|
|
13832
|
-
* Detach and deep-freeze a message whose identity already exists.
|
|
13833
|
-
* @param message - complete message, including its stable identity.
|
|
13834
|
-
* @returns an immutable snapshot that preserves the identity.
|
|
13835
|
-
*/
|
|
13836
|
-
function freezeMessage(message) {
|
|
13837
|
-
return deepFreeze(structuredClone(message));
|
|
13838
|
-
}
|
|
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
|
|
13839
14341
|
/**
|
|
13840
14342
|
* LLM failure codes and helpers over the shared Harness error base. The base
|
|
13841
14343
|
* class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
|
|
@@ -13854,6 +14356,7 @@ const LLM_FAILURE_CODES = {
|
|
|
13854
14356
|
ACCOUNT_TOKEN_INVALID: {},
|
|
13855
14357
|
AUTH: {},
|
|
13856
14358
|
CLIENT_UPGRADE_REQUIRED: {},
|
|
14359
|
+
CONTENT_REFUSED: {},
|
|
13857
14360
|
CONTEXT_WINDOW_EXCEEDED: {},
|
|
13858
14361
|
DISCOVERY_FAILED: {},
|
|
13859
14362
|
DISCOVERY_UNSUPPORTED: {},
|
|
@@ -13877,6 +14380,7 @@ const LLM_FAILURE_CODES = {
|
|
|
13877
14380
|
INVALID_REPLAY_STATE: {},
|
|
13878
14381
|
INVALID_REQUEST: {},
|
|
13879
14382
|
INVALID_RESPONSE: {},
|
|
14383
|
+
INVALID_TOOL_ARGUMENTS: { retryChoice: true },
|
|
13880
14384
|
MALFORMED_RESPONSE: { retryChoice: true },
|
|
13881
14385
|
MISSING_CREDENTIAL: {},
|
|
13882
14386
|
MODEL_SWITCH_COMPACTION_FAILED: {},
|
|
@@ -13917,6 +14421,42 @@ new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` + Str
|
|
|
13917
14421
|
new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?` + String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?` + String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`, "i");
|
|
13918
14422
|
new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}` + String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}` + String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`, "i");
|
|
13919
14423
|
/**
|
|
14424
|
+
* Detach and deep-freeze a message whose identity already exists.
|
|
14425
|
+
* @param message - complete message, including its stable identity.
|
|
14426
|
+
* @returns an immutable snapshot that preserves the identity.
|
|
14427
|
+
*/
|
|
14428
|
+
function freezeMessage(message) {
|
|
14429
|
+
return deepFreeze(structuredClone(message));
|
|
14430
|
+
}
|
|
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
|
+
/**
|
|
13920
14460
|
* Provider-owned request-retry policy configuration and resolution.
|
|
13921
14461
|
*
|
|
13922
14462
|
* Adapters expose one resolved policy per registered provider route; the
|
|
@@ -13930,6 +14470,7 @@ const DEFAULT_MAX_DELAY_MS = 1e4;
|
|
|
13930
14470
|
const DEFAULT_JITTER_RATIO = .1;
|
|
13931
14471
|
const DEFAULT_RETRYABLE_CODES = Object.freeze([
|
|
13932
14472
|
EMPTY_RESPONSE_CODE,
|
|
14473
|
+
"INVALID_TOOL_ARGUMENTS",
|
|
13933
14474
|
"RATE_LIMIT",
|
|
13934
14475
|
"SERVER",
|
|
13935
14476
|
"TIMEOUT",
|
|
@@ -14110,10 +14651,11 @@ function failureSnapshot(value) {
|
|
|
14110
14651
|
}
|
|
14111
14652
|
/** Read an SDK error message without letting an accessor replace the primary failure. */
|
|
14112
14653
|
function errorMessage(error) {
|
|
14654
|
+
let message;
|
|
14113
14655
|
try {
|
|
14114
|
-
|
|
14115
|
-
if (typeof message === "string" && message.length > 0) return message;
|
|
14656
|
+
message = error.message;
|
|
14116
14657
|
} catch (_sdkMessageGetter) {}
|
|
14658
|
+
if (typeof message === "string" && message.length > 0) return message;
|
|
14117
14659
|
return "LLM adapter failed";
|
|
14118
14660
|
}
|
|
14119
14661
|
/** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */
|
|
@@ -14723,7 +15265,7 @@ var LlmError = class LlmError extends HarnessError {
|
|
|
14723
15265
|
* @param provider - registered provider route.
|
|
14724
15266
|
* @param model - exact model id.
|
|
14725
15267
|
* @param image - normalized image reference.
|
|
14726
|
-
* @returns dimensions and byte
|
|
15268
|
+
* @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions.
|
|
14727
15269
|
*/
|
|
14728
15270
|
imageRequestTarget(provider, model, image) {
|
|
14729
15271
|
return this.registration(provider).adapter.imageRequestTarget(provider, model, image);
|
|
@@ -14770,8 +15312,20 @@ var LlmError = class LlmError extends HarnessError {
|
|
|
14770
15312
|
});
|
|
14771
15313
|
}
|
|
14772
15314
|
/**
|
|
14773
|
-
*
|
|
14774
|
-
*
|
|
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
|
+
/**
|
|
15327
|
+
* Resolve and validate all metadata from the adapter that owns one exact
|
|
15328
|
+
* route. The result is detached from adapter-owned objects; catalog
|
|
14775
15329
|
* membership remains advisory and does not control request routing.
|
|
14776
15330
|
* @param provider - registered provider route to inspect.
|
|
14777
15331
|
* @param model - exact model id passed to the adapter.
|
|
@@ -15096,12 +15650,22 @@ function detachDirectoryEntry(entry) {
|
|
|
15096
15650
|
};
|
|
15097
15651
|
}
|
|
15098
15652
|
//#endregion
|
|
15099
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.
|
|
15100
|
-
/**
|
|
15101
|
-
|
|
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 {
|
|
15102
15666
|
constructor() {
|
|
15103
|
-
super("The selected tool
|
|
15104
|
-
this.name = "
|
|
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";
|
|
15105
15669
|
}
|
|
15106
15670
|
};
|
|
15107
15671
|
/**
|
|
@@ -15617,276 +16181,1256 @@ function checkValue(schema, value, path) {
|
|
|
15617
16181
|
function validateJsonSchemaValue(schema, value, path = "value") {
|
|
15618
16182
|
return checkValue(schema, value, path);
|
|
15619
16183
|
}
|
|
15620
|
-
/**
|
|
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 */
|
|
15621
16201
|
/** Reserved model-facing program transport name. */
|
|
15622
16202
|
const RUN_CODE_NAME = "run_code";
|
|
15623
|
-
/**
|
|
15624
|
-
|
|
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 {
|
|
15625
16208
|
/**
|
|
15626
|
-
*
|
|
15627
|
-
* @param name - tool whose condition rejected.
|
|
15628
|
-
* @param cause - underlying condition failure.
|
|
16209
|
+
* @param message - names the ambiguous tool or the inclusion cycle.
|
|
15629
16210
|
*/
|
|
15630
|
-
constructor(
|
|
15631
|
-
super(
|
|
15632
|
-
this.name = "
|
|
16211
|
+
constructor(message) {
|
|
16212
|
+
super(message, "INVALID_TOOL_COMPOSITION");
|
|
16213
|
+
this.name = "ToolCompositionError";
|
|
15633
16214
|
}
|
|
15634
16215
|
};
|
|
15635
|
-
|
|
15636
|
-
|
|
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";
|
|
15637
16235
|
/**
|
|
15638
|
-
*
|
|
15639
|
-
*
|
|
15640
|
-
*
|
|
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.
|
|
15641
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
|
+
};
|
|
15642
16273
|
/**
|
|
15643
|
-
*
|
|
15644
|
-
*
|
|
15645
|
-
*
|
|
15646
|
-
*
|
|
15647
|
-
*
|
|
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.
|
|
15648
16325
|
*/
|
|
15649
|
-
|
|
15650
|
-
|
|
15651
|
-
|
|
15652
|
-
|
|
15653
|
-
|
|
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);
|
|
15654
16331
|
}
|
|
15655
|
-
|
|
15656
|
-
|
|
15657
|
-
|
|
15658
|
-
|
|
15659
|
-
|
|
15660
|
-
|
|
15661
|
-
|
|
15662
|
-
|
|
15663
|
-
|
|
15664
|
-
|
|
15665
|
-
|
|
15666
|
-
|
|
15667
|
-
|
|
15668
|
-
|
|
15669
|
-
|
|
15670
|
-
|
|
15671
|
-
|
|
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.
|
|
16340
|
+
*/
|
|
16341
|
+
function resolveToolCandidate(name, candidate) {
|
|
16342
|
+
if (candidate instanceof AmbiguousCandidate) throw ambiguousTool(name, candidate);
|
|
16343
|
+
return candidate;
|
|
16344
|
+
}
|
|
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);
|
|
15672
16356
|
}
|
|
15673
|
-
|
|
15674
|
-
|
|
15675
|
-
|
|
15676
|
-
|
|
15677
|
-
|
|
15678
|
-
|
|
15679
|
-
|
|
16357
|
+
return definitions;
|
|
16358
|
+
}
|
|
16359
|
+
/**
|
|
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.
|
|
16364
|
+
*/
|
|
16365
|
+
function listToolCandidates(candidates) {
|
|
16366
|
+
return [...candidates.values()].flatMap((candidate) => candidate instanceof AmbiguousCandidate ? candidate.definitions : [candidate]);
|
|
16367
|
+
}
|
|
16368
|
+
/**
|
|
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.
|
|
16373
|
+
*/
|
|
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());
|
|
15680
16434
|
}
|
|
15681
|
-
|
|
15682
|
-
|
|
15683
|
-
|
|
15684
|
-
|
|
15685
|
-
|
|
15686
|
-
|
|
15687
|
-
return
|
|
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;
|
|
15688
16533
|
}
|
|
15689
|
-
|
|
15690
|
-
|
|
15691
|
-
|
|
15692
|
-
|
|
15693
|
-
|
|
15694
|
-
|
|
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
|
+
};
|
|
15695
16541
|
}
|
|
15696
|
-
|
|
15697
|
-
|
|
15698
|
-
|
|
15699
|
-
|
|
15700
|
-
|
|
15701
|
-
|
|
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;
|
|
15702
16557
|
}
|
|
15703
|
-
|
|
15704
|
-
|
|
15705
|
-
|
|
15706
|
-
|
|
15707
|
-
|
|
15708
|
-
|
|
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 ?? []);
|
|
15709
16592
|
}
|
|
15710
|
-
|
|
15711
|
-
|
|
15712
|
-
|
|
15713
|
-
|
|
15714
|
-
|
|
15715
|
-
|
|
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));
|
|
16608
|
+
}
|
|
16609
|
+
result(concluded = this.results.some(({ result }) => result.concludesTurn === true)) {
|
|
16610
|
+
return {
|
|
16611
|
+
results: this.results,
|
|
16612
|
+
additionalContexts: this.contexts,
|
|
16613
|
+
concluded
|
|
16614
|
+
};
|
|
15716
16615
|
}
|
|
15717
16616
|
};
|
|
15718
16617
|
/**
|
|
15719
|
-
*
|
|
15720
|
-
*
|
|
15721
|
-
*
|
|
15722
|
-
* iterators are live within one nonempty table generation; draining the table
|
|
15723
|
-
* 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.
|
|
15724
16621
|
*/
|
|
15725
|
-
var
|
|
15726
|
-
|
|
16622
|
+
var ToolExecutionPipeline = class {
|
|
16623
|
+
ctx;
|
|
16624
|
+
source;
|
|
16625
|
+
tools;
|
|
15727
16626
|
/**
|
|
15728
|
-
*
|
|
15729
|
-
* @param
|
|
15730
|
-
* @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.
|
|
15731
16629
|
*/
|
|
15732
|
-
|
|
15733
|
-
|
|
15734
|
-
|
|
15735
|
-
|
|
15736
|
-
|
|
15737
|
-
|
|
15738
|
-
|
|
15739
|
-
active = false;
|
|
15740
|
-
data.delete(key);
|
|
15741
|
-
if (data.size === 0 && this.data === data) this.data = /* @__PURE__ */ new Map();
|
|
15742
|
-
};
|
|
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);
|
|
15743
16637
|
}
|
|
15744
16638
|
/**
|
|
15745
|
-
*
|
|
15746
|
-
*
|
|
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.
|
|
15747
16647
|
*/
|
|
15748
|
-
|
|
15749
|
-
|
|
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
|
+
};
|
|
15750
16808
|
}
|
|
15751
16809
|
/**
|
|
15752
|
-
*
|
|
15753
|
-
*
|
|
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
|
+
}
|
|
16896
|
+
}
|
|
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
|
+
}
|
|
16945
|
+
}
|
|
16946
|
+
/**
|
|
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.
|
|
15754
16957
|
*/
|
|
15755
|
-
|
|
15756
|
-
|
|
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
|
+
}
|
|
15757
16981
|
}
|
|
15758
|
-
}
|
|
15759
|
-
|
|
15760
|
-
|
|
15761
|
-
|
|
15762
|
-
|
|
15763
|
-
|
|
15764
|
-
|
|
15765
|
-
*/
|
|
15766
|
-
var ScopedLayers = class {
|
|
15767
|
-
createLayer;
|
|
15768
|
-
onChange;
|
|
15769
|
-
/** The eagerly constructed context-global layer. */
|
|
15770
|
-
global;
|
|
15771
|
-
scoped = /* @__PURE__ */ new Map();
|
|
15772
|
-
constructor(createLayer, onChange) {
|
|
15773
|
-
this.createLayer = createLayer;
|
|
15774
|
-
this.onChange = onChange;
|
|
15775
|
-
this.global = createLayer(void 0);
|
|
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);
|
|
15776
16989
|
}
|
|
15777
16990
|
/**
|
|
15778
|
-
*
|
|
15779
|
-
*
|
|
15780
|
-
*
|
|
15781
|
-
*
|
|
15782
|
-
* @param
|
|
15783
|
-
* @
|
|
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.
|
|
15784
16998
|
*/
|
|
15785
|
-
|
|
15786
|
-
|
|
15787
|
-
|
|
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));
|
|
17019
|
+
}
|
|
15788
17020
|
}
|
|
15789
17021
|
/**
|
|
15790
|
-
*
|
|
15791
|
-
*
|
|
15792
|
-
*
|
|
15793
|
-
* @param
|
|
15794
|
-
* @returns the
|
|
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
|
|
15795
17028
|
*/
|
|
15796
|
-
|
|
15797
|
-
|
|
15798
|
-
|
|
15799
|
-
|
|
15800
|
-
|
|
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
|
+
};
|
|
17054
|
+
}
|
|
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
|
+
});
|
|
15801
17150
|
}
|
|
15802
|
-
|
|
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
|
+
});
|
|
15803
17166
|
}
|
|
15804
|
-
/**
|
|
15805
|
-
|
|
15806
|
-
|
|
15807
|
-
|
|
15808
|
-
|
|
15809
|
-
|
|
15810
|
-
*/
|
|
15811
|
-
merge(scope, pick) {
|
|
15812
|
-
const merged = new Map(pick(this.global).entries());
|
|
15813
|
-
for (const layer of this.chainLayers(scope)) for (const [name, value] of pick(layer).entries()) merged.set(name, value);
|
|
15814
|
-
return merged;
|
|
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;
|
|
15815
17173
|
}
|
|
15816
|
-
/**
|
|
15817
|
-
|
|
15818
|
-
|
|
15819
|
-
|
|
15820
|
-
|
|
15821
|
-
|
|
15822
|
-
|
|
15823
|
-
|
|
15824
|
-
|
|
15825
|
-
|
|
15826
|
-
|
|
15827
|
-
|
|
15828
|
-
|
|
15829
|
-
|
|
15830
|
-
|
|
15831
|
-
|
|
15832
|
-
if (existing === void 0) {
|
|
15833
|
-
layer = this.createLayer(scope);
|
|
15834
|
-
this.scoped.set(scope, layer);
|
|
15835
|
-
created = true;
|
|
15836
|
-
} else layer = existing;
|
|
15837
|
-
}
|
|
15838
|
-
let undo;
|
|
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;
|
|
15839
17190
|
try {
|
|
15840
|
-
|
|
17191
|
+
projected = tool.output.presentationMeta(exec.arguments, value);
|
|
15841
17192
|
} catch (error) {
|
|
15842
|
-
|
|
15843
|
-
throw error;
|
|
17193
|
+
throw projectionError(tool.name, "presentationMeta", error);
|
|
15844
17194
|
}
|
|
15845
|
-
|
|
15846
|
-
|
|
15847
|
-
|
|
15848
|
-
|
|
15849
|
-
|
|
15850
|
-
|
|
15851
|
-
|
|
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
|
+
});
|
|
15852
17242
|
}
|
|
15853
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
|
+
}
|
|
15854
17312
|
/**
|
|
15855
|
-
*
|
|
15856
|
-
*
|
|
15857
|
-
*
|
|
15858
|
-
* @module @deepseek-ai/dsh-scope
|
|
15859
|
-
*/
|
|
15860
|
-
/** Context tag written by {@link createScope}. */
|
|
15861
|
-
const kScope = Symbol("dsh.scope");
|
|
15862
|
-
/**
|
|
15863
|
-
* The enclosing scope of each key. One relation powers both directions of
|
|
15864
|
-
* scope nesting: registration views inherit DOWN the chain (a child scope
|
|
15865
|
-
* sees its ancestors' layers — {@link ScopedLayers}), and event admission
|
|
15866
|
-
* extends UP it (a listener tagged with an ancestor receives events dispatched
|
|
15867
|
-
* to a descendant key — {@link scopeTarget}).
|
|
15868
|
-
*/
|
|
15869
|
-
const scopeParents = /* @__PURE__ */ new WeakMap();
|
|
15870
|
-
/**
|
|
15871
|
-
* The chain from a key to its root ancestor.
|
|
15872
|
-
* @param key - the starting key, or `undefined` for the empty chain.
|
|
15873
|
-
* @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.
|
|
15874
17316
|
*/
|
|
15875
|
-
function
|
|
15876
|
-
|
|
15877
|
-
|
|
15878
|
-
|
|
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;
|
|
15879
17353
|
}
|
|
15880
17354
|
/**
|
|
15881
|
-
*
|
|
15882
|
-
*
|
|
15883
|
-
* @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.
|
|
15884
17357
|
*/
|
|
15885
|
-
function
|
|
15886
|
-
return
|
|
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
|
+
};
|
|
15887
17431
|
}
|
|
15888
17432
|
//#endregion
|
|
15889
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.
|
|
17433
|
+
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.3-alpha.4_ca12df44b3bbe3a755034ba57f11ee40/node_modules/@deepseek-ai/dsh-tools/lib/index.js
|
|
15890
17434
|
/** Unified JSON-value schema DSL, inference, compilation, and tool definition helpers. @module dsh-tools/schema */
|
|
15891
17435
|
const ANNOTATION_KEYS = [
|
|
15892
17436
|
"description",
|
|
@@ -16208,6 +17752,8 @@ function defineTool(options) {
|
|
|
16208
17752
|
},
|
|
16209
17753
|
...options.deferLoading === true ? { deferLoading: options.deferLoading } : {},
|
|
16210
17754
|
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
17755
|
+
...options.guidance !== void 0 ? { guidance: options.guidance } : {},
|
|
17756
|
+
...options.environment !== void 0 ? { environment: options.environment } : {},
|
|
16211
17757
|
async execute(args, exec) {
|
|
16212
17758
|
const violations = validate(args);
|
|
16213
17759
|
if (violations.length > 0) throw new ToolArgsError(violations);
|
|
@@ -16247,23 +17793,36 @@ function projectToolSchema(definition, detachParameters) {
|
|
|
16247
17793
|
...deferLoading === true ? { deferLoading } : {}
|
|
16248
17794
|
};
|
|
16249
17795
|
}
|
|
16250
|
-
/**
|
|
16251
|
-
/** One scope's complete tool
|
|
17796
|
+
/** Scoped tool contributions routed to the selected root registry, which answers lookups and dispatch. @module */
|
|
17797
|
+
/** One scope's complete tool contribution. */
|
|
16252
17798
|
var ToolLayer = class {
|
|
16253
17799
|
tools;
|
|
17800
|
+
includes = new AnonymousEntries();
|
|
16254
17801
|
restrictions = new AnonymousEntries();
|
|
16255
17802
|
constructor(scope) {
|
|
16256
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`));
|
|
16257
17804
|
}
|
|
16258
|
-
/** Whether every contribution table in this
|
|
17805
|
+
/** Whether every contribution table in this layer is empty. */
|
|
16259
17806
|
isEmpty() {
|
|
16260
|
-
return this.tools.isEmpty() && this.restrictions.isEmpty();
|
|
17807
|
+
return this.tools.isEmpty() && this.includes.isEmpty() && this.restrictions.isEmpty();
|
|
16261
17808
|
}
|
|
16262
|
-
/** Whether every compiled restriction in this layer admits
|
|
17809
|
+
/** Whether every compiled restriction in this layer admits an inherited tool name. */
|
|
16263
17810
|
admits(name) {
|
|
16264
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;
|
|
16265
17812
|
return true;
|
|
16266
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
|
+
}
|
|
16267
17826
|
};
|
|
16268
17827
|
var GuardLayer = class {
|
|
16269
17828
|
guards = new AnonymousEntries();
|
|
@@ -16274,51 +17833,148 @@ var GuardLayer = class {
|
|
|
16274
17833
|
(class extends Service {
|
|
16275
17834
|
static inject = ["systemPrompt"];
|
|
16276
17835
|
static Config = Schema.object({
|
|
16277
|
-
mode: Schema.never().description("Removed. Mount a native or PTC tool
|
|
16278
|
-
maxParallelSubCalls: Schema.never().description("Moved to the PTC tool
|
|
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.")
|
|
16279
17838
|
});
|
|
16280
|
-
|
|
17839
|
+
/** Emit `tools/change` from this service's own context, which outlives a caller that unloads. */
|
|
17840
|
+
notifyChange = () => {
|
|
16281
17841
|
this.ctx.emit("tools/change");
|
|
16282
|
-
}
|
|
16283
|
-
|
|
16284
|
-
|
|
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();
|
|
16285
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
|
+
};
|
|
16286
17863
|
constructor(ctx) {
|
|
16287
17864
|
super(ctx, "tools");
|
|
16288
|
-
ctx.systemPrompt.tools(({ scope,
|
|
16289
|
-
const
|
|
17865
|
+
ctx.systemPrompt.tools(({ scope, toolStep }) => {
|
|
17866
|
+
const declared = toolStep !== void 0 && toolStep.agent === scope ? toolStep.declarations : this.getAll(scope);
|
|
16290
17867
|
return {
|
|
16291
|
-
|
|
16292
|
-
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);
|
|
16293
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));
|
|
16294
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
|
+
}
|
|
16295
17967
|
}
|
|
16296
17968
|
/**
|
|
16297
|
-
*
|
|
16298
|
-
*
|
|
16299
|
-
*
|
|
16300
|
-
*
|
|
16301
|
-
*
|
|
16302
|
-
|
|
16303
|
-
|
|
16304
|
-
const name = definition.name;
|
|
16305
|
-
const output = definition.output;
|
|
16306
|
-
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? }`);
|
|
16307
|
-
assertSupportedJsonSchema(output.schema);
|
|
16308
|
-
const timeoutMs = definition.timeoutMs;
|
|
16309
|
-
if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new TypeError(`tool "${name}" timeoutMs must be a positive finite number`);
|
|
16310
|
-
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`);
|
|
16311
|
-
return this.layers.effect(this.ctx, (layer) => layer.tools.insert(name, {
|
|
16312
|
-
definition,
|
|
16313
|
-
when: options.when
|
|
16314
|
-
}), { label: "tools.register()" });
|
|
16315
|
-
}
|
|
16316
|
-
/**
|
|
16317
|
-
* Restrict global tools for the calling agent scope. Empty filters, unknown
|
|
16318
|
-
* names, scope-local names, and reserved transport names fail. Restrictions
|
|
16319
|
-
* intersect; scoped registrations remain visible.
|
|
16320
|
-
* @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).
|
|
16321
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.
|
|
16322
17978
|
*/
|
|
16323
17979
|
restrict(filter) {
|
|
16324
17980
|
const scope = scopeOf(this.ctx);
|
|
@@ -16330,186 +17986,265 @@ var GuardLayer = class {
|
|
|
16330
17986
|
...allow !== void 0 ? { allow: new Set(allow) } : {},
|
|
16331
17987
|
...deny !== void 0 ? { deny: new Set(deny) } : {}
|
|
16332
17988
|
};
|
|
16333
|
-
if ([...allow ?? [], ...deny ?? []].includes("run_code")) throw new Error(`tools.restrict() cannot name reserved PTC
|
|
16334
|
-
const known = this.
|
|
16335
|
-
const unknown =
|
|
16336
|
-
if (unknown.length > 0) throw new Error(`tools.restrict() names unknown
|
|
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)"}`);
|
|
16337
17993
|
return this.layers.effect(this.ctx, (layer) => layer.restrictions.append(compiled), { label: "tools.restrict()" });
|
|
16338
17994
|
}
|
|
16339
17995
|
/**
|
|
16340
|
-
* Resolve
|
|
16341
|
-
*
|
|
16342
|
-
*
|
|
16343
|
-
*
|
|
16344
|
-
* @
|
|
16345
|
-
|
|
16346
|
-
|
|
16347
|
-
|
|
16348
|
-
|
|
16349
|
-
|
|
16350
|
-
|
|
16351
|
-
|
|
16352
|
-
|
|
16353
|
-
|
|
16354
|
-
}
|
|
16355
|
-
const visible = /* @__PURE__ */ new Map();
|
|
16356
|
-
const registrations = /* @__PURE__ */ new Map();
|
|
16357
|
-
const knownNames = /* @__PURE__ */ new Set();
|
|
16358
|
-
const restrictableNames = /* @__PURE__ */ new Set();
|
|
16359
|
-
for (const [name, registration] of inherited) {
|
|
16360
|
-
knownNames.add(name);
|
|
16361
|
-
restrictableNames.add(name);
|
|
16362
|
-
if (layers.every((layer) => layer.admits(name))) {
|
|
16363
|
-
visible.set(name, registration.definition);
|
|
16364
|
-
registrations.set(name, registration);
|
|
16365
|
-
}
|
|
16366
|
-
}
|
|
16367
|
-
if (own !== void 0) for (const [name, registration] of own.tools.entries()) {
|
|
16368
|
-
knownNames.add(name);
|
|
16369
|
-
visible.set(name, registration.definition);
|
|
16370
|
-
registrations.set(name, registration);
|
|
16371
|
-
}
|
|
16372
|
-
return {
|
|
16373
|
-
visible,
|
|
16374
|
-
registrations,
|
|
16375
|
-
knownNames,
|
|
16376
|
-
restrictableNames
|
|
16377
|
-
};
|
|
16378
|
-
}
|
|
16379
|
-
/**
|
|
16380
|
-
* Look up a tool as one scope sees it (scoped
|
|
16381
|
-
* shadows global; a restricted-away global reads as absent). Presenters pass
|
|
16382
|
-
* the calling agent so the rendered card matches the definition that
|
|
16383
|
-
* actually executed.
|
|
16384
|
-
* @param name - the tool name as registered.
|
|
16385
|
-
* @param scope - the viewing scope (the agent); omitted = the global view.
|
|
16386
|
-
* @param toolSet - step admission; omit only to inspect registered definitions.
|
|
16387
|
-
* @returns the definition the scope resolves, or undefined when none is visible.
|
|
16388
|
-
*/
|
|
16389
|
-
get(name, scope, toolSet) {
|
|
16390
|
-
return toolSet === void 0 ? this.view(scope).visible.get(name) : toolSet.view(scope).get(name);
|
|
16391
|
-
}
|
|
16392
|
-
/**
|
|
16393
|
-
* Resolve the definition a call may execute. With a step's admitted set, the
|
|
16394
|
-
* set decides; without one, conditional registrations are unavailable.
|
|
16395
|
-
* @param name - the tool name as registered.
|
|
16396
|
-
* @param scope - the calling agent; omitted = the global view.
|
|
16397
|
-
* @param toolSet - step admission, or omitted for a call outside a model step.
|
|
16398
|
-
* @returns the executable definition, or undefined when the call must fail as `UNKNOWN_TOOL`.
|
|
16399
|
-
*/
|
|
16400
|
-
executable(name, scope, toolSet) {
|
|
16401
|
-
if (toolSet !== void 0) return toolSet.view(scope).get(name);
|
|
16402
|
-
const view = this.view(scope);
|
|
16403
|
-
return view.registrations.get(name)?.when === void 0 ? view.visible.get(name) : void 0;
|
|
16404
|
-
}
|
|
16405
|
-
/**
|
|
16406
|
-
* Resolve conditions once for this step without changing shared registrations.
|
|
16407
|
-
* Cancellation or a rejected condition publishes no partial selection. Removed
|
|
16408
|
-
* registrations cannot be restored by a late condition result.
|
|
16409
|
-
* @param context - preparing agent, captured model selection, and cancellation.
|
|
16410
|
-
* @returns the complete selection; the caller disposes it after its tool batch settles.
|
|
16411
|
-
*/
|
|
16412
|
-
async resolve(context) {
|
|
16413
|
-
const { agent, signal } = context;
|
|
16414
|
-
signal.throwIfAborted();
|
|
16415
|
-
const view = this.view(agent);
|
|
16416
|
-
const admitted = /* @__PURE__ */ new Map();
|
|
16417
|
-
for (const [name, definition] of view.visible) {
|
|
16418
|
-
const registration = view.registrations.get(name);
|
|
16419
|
-
let enabled;
|
|
16420
|
-
try {
|
|
16421
|
-
enabled = registration?.when === void 0 || await registration.when(context);
|
|
16422
|
-
} catch (cause) {
|
|
16423
|
-
signal.throwIfAborted();
|
|
16424
|
-
throw new ToolActivationError(name, cause);
|
|
16425
|
-
}
|
|
16426
|
-
signal.throwIfAborted();
|
|
16427
|
-
if (enabled) admitted.set(name, definition);
|
|
16428
|
-
}
|
|
16429
|
-
let closed = false;
|
|
16430
|
-
return Object.freeze({
|
|
16431
|
-
dispose: () => {
|
|
16432
|
-
closed = true;
|
|
16433
|
-
},
|
|
16434
|
-
view: (scope) => {
|
|
16435
|
-
const visible = /* @__PURE__ */ new Map();
|
|
16436
|
-
if (closed || scope !== agent) return visible;
|
|
16437
|
-
const current = this.view(agent);
|
|
16438
|
-
for (const [name, definition] of admitted) if (current.visible.get(name) === definition && current.registrations.get(name) === view.registrations.get(name)) visible.set(name, definition);
|
|
16439
|
-
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);
|
|
16440
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;
|
|
16441
18015
|
});
|
|
16442
18016
|
}
|
|
16443
18017
|
/**
|
|
16444
|
-
*
|
|
16445
|
-
*
|
|
16446
|
-
* @param
|
|
16447
|
-
* @returns
|
|
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.
|
|
16448
18022
|
*/
|
|
16449
|
-
|
|
16450
|
-
return
|
|
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
|
+
});
|
|
16451
18034
|
}
|
|
16452
18035
|
/**
|
|
16453
|
-
*
|
|
16454
|
-
*
|
|
16455
|
-
* @param
|
|
16456
|
-
* @param
|
|
16457
|
-
* @returns
|
|
16458
|
-
|
|
16459
|
-
|
|
16460
|
-
|
|
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
|
+
}));
|
|
16461
18057
|
}
|
|
16462
18058
|
/**
|
|
16463
|
-
*
|
|
16464
|
-
*
|
|
16465
|
-
* @param
|
|
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.
|
|
16466
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.
|
|
16467
18124
|
*/
|
|
16468
|
-
|
|
18125
|
+
setRoot(registry) {
|
|
16469
18126
|
const scope = scopeOf(this.ctx);
|
|
16470
|
-
|
|
16471
|
-
const
|
|
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
|
+
};
|
|
16472
18135
|
return this.ctx.effect(function* () {
|
|
16473
|
-
|
|
16474
|
-
|
|
16475
|
-
|
|
16476
|
-
|
|
16477
|
-
|
|
16478
|
-
|
|
16479
|
-
|
|
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;
|
|
16480
18143
|
}
|
|
18144
|
+
return removeInclusion;
|
|
16481
18145
|
});
|
|
16482
|
-
|
|
16483
|
-
|
|
18146
|
+
select(record);
|
|
18147
|
+
let committed = false;
|
|
16484
18148
|
yield () => {
|
|
16485
|
-
record.
|
|
18149
|
+
if (committed) record.registry = void 0;
|
|
18150
|
+
else {
|
|
18151
|
+
select(existing);
|
|
18152
|
+
undo?.();
|
|
18153
|
+
}
|
|
18154
|
+
this.notifyChange();
|
|
16486
18155
|
};
|
|
16487
|
-
|
|
16488
|
-
|
|
16489
|
-
|
|
16490
|
-
|
|
16491
|
-
|
|
16492
|
-
|
|
16493
|
-
|
|
16494
|
-
|
|
16495
|
-
|
|
16496
|
-
|
|
16497
|
-
|
|
16498
|
-
|
|
16499
|
-
|
|
16500
|
-
record
|
|
16501
|
-
|
|
16502
|
-
|
|
16503
|
-
|
|
16504
|
-
|
|
16505
|
-
|
|
16506
|
-
*
|
|
16507
|
-
|
|
16508
|
-
|
|
16509
|
-
|
|
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.
|
|
16510
18233
|
*/
|
|
16511
18234
|
async execute(input) {
|
|
16512
|
-
|
|
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
|
+
}));
|
|
16513
18248
|
}
|
|
16514
18249
|
/**
|
|
16515
18250
|
* Register a monotonic denial in the calling scope.
|
|
@@ -16531,6 +18266,10 @@ var GuardLayer = class {
|
|
|
16531
18266
|
}
|
|
16532
18267
|
}
|
|
16533
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
|
+
}
|
|
16534
18273
|
//#endregion
|
|
16535
18274
|
//#region src/host/ui-tools.ts
|
|
16536
18275
|
/**
|
|
@@ -16609,6 +18348,7 @@ function presentationOf(args, value) {
|
|
|
16609
18348
|
function createUiPresentTool(host) {
|
|
16610
18349
|
return defineTool({
|
|
16611
18350
|
name: "ui_present",
|
|
18351
|
+
environment: "independent",
|
|
16612
18352
|
description: UI_PRESENT_DESCRIPTION,
|
|
16613
18353
|
parameters: {
|
|
16614
18354
|
html: {
|
|
@@ -28433,7 +30173,7 @@ var require_negotiator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
28433
30173
|
Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
|
|
28434
30174
|
}));
|
|
28435
30175
|
//#endregion
|
|
28436
|
-
//#region ../../node_modules/.pnpm/@deepseek-ai+dsh-host-webserver@0.2.
|
|
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
|
|
28437
30177
|
var lib_exports = /* @__PURE__ */ __exportAll({
|
|
28438
30178
|
WebServer: () => WebServer,
|
|
28439
30179
|
bindUrlHost: () => bindUrlHost,
|
|
@@ -28542,6 +30282,8 @@ function renderIndexInjections(html, rows) {
|
|
|
28542
30282
|
* Route handlers retain direct response ownership; a route or the fallback may
|
|
28543
30283
|
* instead give a resource, which maps a Fetch `Request` to a `Response` and
|
|
28544
30284
|
* also answers in-process reads.
|
|
30285
|
+
* WebServer events use the instance as their subject: ordinary listeners follow
|
|
30286
|
+
* its webServer isolation, while explicitly global listeners receive every instance.
|
|
28545
30287
|
*/
|
|
28546
30288
|
const DEFAULT_COMPRESSION = "none";
|
|
28547
30289
|
const DEFAULT_COMPRESSION_LEVEL = 1;
|
|
@@ -28728,7 +30470,8 @@ async function writeResponse(res, response, head, signal) {
|
|
|
28728
30470
|
* initialization, and the boot process reports the failed fiber. Route
|
|
28729
30471
|
* registration order does not affect requests because configured named routes
|
|
28730
30472
|
* must be distinct, and a request no named route matches is answered 404
|
|
28731
|
-
* until the fallback owner registers.
|
|
30473
|
+
* until the fallback owner registers. HTTP and upgrade admission refusals
|
|
30474
|
+
* carry `Cache-Control: no-store`.
|
|
28732
30475
|
*/
|
|
28733
30476
|
var WebServer = class extends Service {
|
|
28734
30477
|
config;
|
|
@@ -28834,12 +30577,12 @@ var WebServer = class extends Service {
|
|
|
28834
30577
|
* composition). One owner only — a second registration throws, because two
|
|
28835
30578
|
* fallbacks cannot compose.
|
|
28836
30579
|
* @param fallback - a handler owning the full response lifecycle of
|
|
28837
|
-
* unmatched requests, or `
|
|
30580
|
+
* unmatched requests, or an object declaring `handler` or `resource` and auth.
|
|
28838
30581
|
* @returns the disposer releasing the seat.
|
|
28839
30582
|
*/
|
|
28840
30583
|
registerFallback(fallback) {
|
|
28841
30584
|
if (this.fallback !== void 0) throw new Error("webserver: fallback already registered");
|
|
28842
|
-
this.fallback = fallback;
|
|
30585
|
+
this.fallback = typeof fallback === "function" ? { handler: fallback } : fallback;
|
|
28843
30586
|
return () => {
|
|
28844
30587
|
this.fallback = void 0;
|
|
28845
30588
|
};
|
|
@@ -28850,6 +30593,7 @@ var WebServer = class extends Service {
|
|
|
28850
30593
|
* path picks the responder by the HTTP match order — exact, longest prefix,
|
|
28851
30594
|
* then the fallback — and only a resource answers. This method checks no
|
|
28852
30595
|
* cookie, Host, or Origin: the caller admits the reader before reading.
|
|
30596
|
+
* A resolved deny policy returns 403 even for an explicitly admitted Peer.
|
|
28853
30597
|
* @param request - the read; its URL path selects the responder.
|
|
28854
30598
|
* @param peer - the Peer the read speaks for, passed to the resource.
|
|
28855
30599
|
* @returns the resource's response, without a body for HEAD as over HTTP;
|
|
@@ -28864,8 +30608,16 @@ var WebServer = class extends Service {
|
|
|
28864
30608
|
status: 405,
|
|
28865
30609
|
headers: { allow: RESOURCE_METHODS }
|
|
28866
30610
|
});
|
|
28867
|
-
const
|
|
28868
|
-
|
|
30611
|
+
const url = new URL(request.url);
|
|
30612
|
+
const responder = this.responderFor(url.pathname);
|
|
30613
|
+
if (responder === void 0 || !("resource" in responder)) return new Response(null, { status: 404 });
|
|
30614
|
+
if (this.authPolicy(responder.auth, {
|
|
30615
|
+
headers: request.headers,
|
|
30616
|
+
method: request.method,
|
|
30617
|
+
url,
|
|
30618
|
+
transport: "http",
|
|
30619
|
+
signal: request.signal
|
|
30620
|
+
}) === "deny") return new Response(null, { status: 403 });
|
|
28869
30621
|
const response = await responder.resource(request, peer);
|
|
28870
30622
|
if (request.method === "GET") return response;
|
|
28871
30623
|
await response.body?.cancel();
|
|
@@ -28901,13 +30653,45 @@ var WebServer = class extends Service {
|
|
|
28901
30653
|
res.end();
|
|
28902
30654
|
return;
|
|
28903
30655
|
}
|
|
28904
|
-
|
|
28905
|
-
|
|
28906
|
-
|
|
30656
|
+
const abort = new AbortController();
|
|
30657
|
+
const cleanup = () => {
|
|
30658
|
+
res.off("close", onClose);
|
|
30659
|
+
res.off("finish", cleanup);
|
|
30660
|
+
};
|
|
30661
|
+
const onClose = () => {
|
|
30662
|
+
abort.abort();
|
|
30663
|
+
cleanup();
|
|
30664
|
+
};
|
|
30665
|
+
res.once("close", onClose);
|
|
30666
|
+
res.once("finish", cleanup);
|
|
30667
|
+
try {
|
|
30668
|
+
const request = {
|
|
30669
|
+
headers: req.headers,
|
|
30670
|
+
method: req.method,
|
|
30671
|
+
url: target,
|
|
30672
|
+
transport: "http",
|
|
30673
|
+
signal: abort.signal,
|
|
30674
|
+
socket: req.socket
|
|
30675
|
+
};
|
|
30676
|
+
const admission = this.authorize(request, responder.auth);
|
|
30677
|
+
if (abort.signal.aborted || request.socket?.destroyed) return;
|
|
30678
|
+
if (admission.kind === "deny") {
|
|
30679
|
+
res.writeHead(admission.status, { "Cache-Control": "no-store" });
|
|
30680
|
+
res.end(admission.status === 401 ? "unauthorized" : admission.status === 503 ? "authentication unavailable" : "forbidden");
|
|
30681
|
+
return;
|
|
30682
|
+
}
|
|
30683
|
+
if ("resource" in responder) await this.serveResource(req, res, target, responder.resource, abort.signal, admission.peer);
|
|
30684
|
+
else await responder.handler(req, res, admission.peer);
|
|
30685
|
+
} finally {
|
|
30686
|
+
if (res.writableEnded || abort.signal.aborted) cleanup();
|
|
30687
|
+
}
|
|
28907
30688
|
};
|
|
28908
30689
|
const listener = (req, res) => {
|
|
28909
30690
|
const next = () => {
|
|
28910
|
-
|
|
30691
|
+
const dispatch = async () => {
|
|
30692
|
+
await this.ctx.waterfall(this, "webserver/request", req, res, () => handle(req, res));
|
|
30693
|
+
};
|
|
30694
|
+
dispatch().catch((err) => {
|
|
28911
30695
|
this.ctx.logger.warn(err instanceof Error ? err : new Error(String(err)));
|
|
28912
30696
|
if (res.headersSent) {
|
|
28913
30697
|
res.destroy();
|
|
@@ -28953,9 +30737,11 @@ var WebServer = class extends Service {
|
|
|
28953
30737
|
this.upgradedSockets.delete(socket);
|
|
28954
30738
|
});
|
|
28955
30739
|
let route;
|
|
30740
|
+
let target;
|
|
28956
30741
|
try {
|
|
28957
30742
|
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
28958
|
-
|
|
30743
|
+
target = new URL(req.url ?? "/", "http://x");
|
|
30744
|
+
route = this.upgrades.get(target.pathname);
|
|
28959
30745
|
} catch (error) {
|
|
28960
30746
|
this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error)));
|
|
28961
30747
|
socket.destroy();
|
|
@@ -28966,8 +30752,36 @@ var WebServer = class extends Service {
|
|
|
28966
30752
|
return;
|
|
28967
30753
|
}
|
|
28968
30754
|
this.upgradedSockets.add(socket);
|
|
30755
|
+
const abort = new AbortController();
|
|
30756
|
+
socket.once("close", () => {
|
|
30757
|
+
abort.abort();
|
|
30758
|
+
});
|
|
28969
30759
|
try {
|
|
28970
|
-
|
|
30760
|
+
const admission = this.authorize({
|
|
30761
|
+
headers: req.headers,
|
|
30762
|
+
method: req.method,
|
|
30763
|
+
url: target,
|
|
30764
|
+
transport: "upgrade",
|
|
30765
|
+
signal: abort.signal,
|
|
30766
|
+
socket
|
|
30767
|
+
}, route.auth);
|
|
30768
|
+
if (abort.signal.aborted || socket.destroyed) return;
|
|
30769
|
+
if (admission.kind === "deny") {
|
|
30770
|
+
const reason = {
|
|
30771
|
+
401: "Unauthorized",
|
|
30772
|
+
403: "Forbidden",
|
|
30773
|
+
503: "Service Unavailable"
|
|
30774
|
+
}[admission.status];
|
|
30775
|
+
const body = reason.toLowerCase();
|
|
30776
|
+
socket.end(`HTTP/1.1 ${String(admission.status)} ${reason}\r\nConnection: close\r\nCache-Control: no-store\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${String(Buffer.byteLength(body))}\r\n\r\n${body}`);
|
|
30777
|
+
return;
|
|
30778
|
+
}
|
|
30779
|
+
const dispatch = async () => {
|
|
30780
|
+
await this.ctx.waterfall(this, "webserver/upgrade", req, socket, head, admission.peer, async () => {
|
|
30781
|
+
if (!socket.destroyed) await route.handler(req, socket, head, admission.peer);
|
|
30782
|
+
});
|
|
30783
|
+
};
|
|
30784
|
+
dispatch().catch((error) => {
|
|
28971
30785
|
this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error)));
|
|
28972
30786
|
socket.destroy();
|
|
28973
30787
|
});
|
|
@@ -29011,6 +30825,31 @@ var WebServer = class extends Service {
|
|
|
29011
30825
|
responderFor(pathname) {
|
|
29012
30826
|
return this.match(pathname) ?? this.fallback;
|
|
29013
30827
|
}
|
|
30828
|
+
authPolicy(auth, request) {
|
|
30829
|
+
return typeof auth === "function" ? auth(request) : auth ?? "required";
|
|
30830
|
+
}
|
|
30831
|
+
authorize(request, auth) {
|
|
30832
|
+
const policy = this.authPolicy(auth, request);
|
|
30833
|
+
if (policy === "deny") return {
|
|
30834
|
+
kind: "deny",
|
|
30835
|
+
status: 403
|
|
30836
|
+
};
|
|
30837
|
+
const admission = this.ctx.bail(this, "webserver/authorize", request, policy) ?? (policy === "anonymous" ? { kind: "allow" } : {
|
|
30838
|
+
kind: "deny",
|
|
30839
|
+
status: 503
|
|
30840
|
+
});
|
|
30841
|
+
if (admission.kind === "allow") {
|
|
30842
|
+
if (policy === "required" && admission.peer === void 0) return {
|
|
30843
|
+
kind: "deny",
|
|
30844
|
+
status: 503
|
|
30845
|
+
};
|
|
30846
|
+
if (admission.peer?.signal.aborted) return {
|
|
30847
|
+
kind: "deny",
|
|
30848
|
+
status: 401
|
|
30849
|
+
};
|
|
30850
|
+
}
|
|
30851
|
+
return admission;
|
|
30852
|
+
}
|
|
29014
30853
|
/** Longest-prefix-wins over the prefix table after an exact-table miss. */
|
|
29015
30854
|
match(pathname) {
|
|
29016
30855
|
const exact = this.exact.get(pathname);
|
|
@@ -29025,13 +30864,13 @@ var WebServer = class extends Service {
|
|
|
29025
30864
|
/**
|
|
29026
30865
|
* Answer one HTTP exchange from a resource. Only GET and HEAD reach it;
|
|
29027
30866
|
* any other method receives 405 and its request body is never read. The
|
|
29028
|
-
* request becomes a Fetch `Request`
|
|
30867
|
+
* request becomes a Fetch `Request` whose URL is the request
|
|
29029
30868
|
* target resolved against a placeholder origin, as the match reads it; the
|
|
29030
30869
|
* client's authority stays only in the `host` header. The connection
|
|
29031
30870
|
* closing before this method ends the response aborts the request signal
|
|
29032
30871
|
* and cancels the response body.
|
|
29033
30872
|
*/
|
|
29034
|
-
async serveResource(req, res, target, resource) {
|
|
30873
|
+
async serveResource(req, res, target, resource, signal, peer) {
|
|
29035
30874
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
29036
30875
|
res.writeHead(405, { allow: RESOURCE_METHODS });
|
|
29037
30876
|
res.end();
|
|
@@ -29039,25 +30878,12 @@ var WebServer = class extends Service {
|
|
|
29039
30878
|
}
|
|
29040
30879
|
const headers = new Headers();
|
|
29041
30880
|
for (const [name, value] of Object.entries(req.headers)) for (const item of typeof value === "string" ? [value] : value ?? []) headers.append(name, item);
|
|
29042
|
-
|
|
29043
|
-
|
|
29044
|
-
|
|
29045
|
-
|
|
29046
|
-
};
|
|
29047
|
-
res.
|
|
29048
|
-
try {
|
|
29049
|
-
await writeResponse(res, await resource(new Request(target, {
|
|
29050
|
-
method: req.method,
|
|
29051
|
-
headers,
|
|
29052
|
-
signal: abort.signal
|
|
29053
|
-
})), req.method === "HEAD", abort.signal);
|
|
29054
|
-
if (!abort.signal.aborted) {
|
|
29055
|
-
ended = true;
|
|
29056
|
-
res.end();
|
|
29057
|
-
}
|
|
29058
|
-
} finally {
|
|
29059
|
-
res.off("close", onClose);
|
|
29060
|
-
}
|
|
30881
|
+
await writeResponse(res, await resource(new Request(target, {
|
|
30882
|
+
method: req.method,
|
|
30883
|
+
headers,
|
|
30884
|
+
signal
|
|
30885
|
+
}), peer), req.method === "HEAD", signal);
|
|
30886
|
+
if (!signal.aborted) res.end();
|
|
29061
30887
|
}
|
|
29062
30888
|
/**
|
|
29063
30889
|
* Run an index.html body through the registered taps in registration order
|
|
@@ -29080,7 +30906,7 @@ var WebServer = class extends Service {
|
|
|
29080
30906
|
*/
|
|
29081
30907
|
collectIndexInjections(peer) {
|
|
29082
30908
|
const table = [];
|
|
29083
|
-
this.ctx.emit("webserver/index-inject", table, peer);
|
|
30909
|
+
this.ctx.emit(this, "webserver/index-inject", table, peer);
|
|
29084
30910
|
return table;
|
|
29085
30911
|
}
|
|
29086
30912
|
/**
|
|
@@ -34041,17 +35867,17 @@ function sessionRoster(ctx, peer, log) {
|
|
|
34041
35867
|
* @returns 路由 face。
|
|
34042
35868
|
*/
|
|
34043
35869
|
function sessionRoute(ctx, peer, log) {
|
|
34044
|
-
const invoke = async (method, args) => await ctx.typertGateway.invoke({
|
|
34045
|
-
namespace
|
|
35870
|
+
const invoke = async (namespace, method, args) => await ctx.typertGateway.invoke({
|
|
35871
|
+
namespace,
|
|
34046
35872
|
method,
|
|
34047
|
-
args: wireArgs(
|
|
35873
|
+
args: wireArgs(namespace, method, args),
|
|
34048
35874
|
peer
|
|
34049
35875
|
});
|
|
34050
35876
|
return { current: async (sessionId) => {
|
|
34051
35877
|
try {
|
|
34052
|
-
const folded = modelSelectionOf(await invoke("projections", { sessionId }));
|
|
35878
|
+
const folded = modelSelectionOf(await invoke("session", "projections", { sessionId }));
|
|
34053
35879
|
const selected = folded.next ?? folded.lastUsed;
|
|
34054
|
-
const fallback = selected === void 0 ? selectionOf(catalogDefaultOf(await invoke("
|
|
35880
|
+
const fallback = selected === void 0 ? selectionOf(catalogDefaultOf(await invoke("models", "catalog", {}))) : void 0;
|
|
34055
35881
|
const answer = selected ?? fallback;
|
|
34056
35882
|
return answer === void 0 ? void 0 : {
|
|
34057
35883
|
provider: answer.provider,
|
|
@@ -34063,7 +35889,7 @@ function sessionRoute(ctx, peer, log) {
|
|
|
34063
35889
|
}
|
|
34064
35890
|
} };
|
|
34065
35891
|
}
|
|
34066
|
-
/** `
|
|
35892
|
+
/** `models/catalog` 里的 `default` 一格。 */
|
|
34067
35893
|
function catalogDefaultOf(value) {
|
|
34068
35894
|
return typeof value === "object" && value !== null ? value.default : void 0;
|
|
34069
35895
|
}
|
|
@@ -34080,13 +35906,22 @@ function catalogDefaultOf(value) {
|
|
|
34080
35906
|
* @param log - 读不到名册时的落点。
|
|
34081
35907
|
* @returns 这些 face 此刻的样子。
|
|
34082
35908
|
*/
|
|
35909
|
+
function optionalService(ctx, name) {
|
|
35910
|
+
try {
|
|
35911
|
+
return ctx.get(name, false) ?? ctx.get(name);
|
|
35912
|
+
} catch {
|
|
35913
|
+
return;
|
|
35914
|
+
}
|
|
35915
|
+
}
|
|
34083
35916
|
function usageFaces(ctx, peer, log) {
|
|
34084
35917
|
return {
|
|
34085
|
-
sessions: ctx
|
|
35918
|
+
sessions: optionalService(ctx, "sessions"),
|
|
34086
35919
|
roster: sessionRoster(ctx, peer, log),
|
|
34087
|
-
credentials: ctx
|
|
34088
|
-
settings: ctx
|
|
34089
|
-
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")
|
|
34090
35925
|
};
|
|
34091
35926
|
}
|
|
34092
35927
|
/**
|