tenjin-cli 0.1.0-alpha.32 → 0.1.0-alpha.33
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.md +42 -23
- package/dist/{_esm-RLLC72MS.js → _esm-BIN7VY2L.js} +2 -2
- package/dist/{alive-MROUMFH3.js → alive-GSOWKUOY.js} +4 -4
- package/dist/{auto-update-OPWMRZLS.js → auto-update-Y24UL56V.js} +5 -3
- package/dist/{chunk-2GNOFONN.js → chunk-2M2VPI2E.js} +2 -2
- package/dist/chunk-2M2VPI2E.js.map +1 -0
- package/dist/{chunk-VUGQTZ2L.js → chunk-2RWB7RKE.js} +89 -33
- package/dist/chunk-2RWB7RKE.js.map +1 -0
- package/dist/{chunk-OTWLERSW.js → chunk-36RVGZNY.js} +2 -2
- package/dist/{chunk-B7EM4GGF.js → chunk-3GNJXKIT.js} +2 -2
- package/dist/{chunk-DRDUIZIA.js → chunk-4K7TQHNP.js} +4 -4
- package/dist/{chunk-SYOS5CAC.js → chunk-4YOZGGTZ.js} +73 -2
- package/dist/chunk-4YOZGGTZ.js.map +1 -0
- package/dist/{chunk-AD226HDR.js → chunk-A5GKIG5O.js} +5 -5
- package/dist/{chunk-JEVQ5LKO.js → chunk-AGMVASXZ.js} +3 -3
- package/dist/{chunk-ADV4LDTB.js → chunk-BF4XHEQK.js} +12 -2
- package/dist/chunk-BF4XHEQK.js.map +1 -0
- package/dist/{chunk-IDTRSAHE.js → chunk-C2Q76BVM.js} +48 -49
- package/dist/chunk-C2Q76BVM.js.map +1 -0
- package/dist/{chunk-VJUVFZ2D.js → chunk-FVIGCDSV.js} +1 -1
- package/dist/chunk-FVIGCDSV.js.map +1 -0
- package/dist/{chunk-QF3LSMGS.js → chunk-GTTUCOPD.js} +2 -2
- package/dist/{chunk-3DIL66VX.js → chunk-HGGWCP7W.js} +2 -2
- package/dist/{chunk-D5TOQSO4.js → chunk-HMWYAUA6.js} +10 -6
- package/dist/{chunk-D5TOQSO4.js.map → chunk-HMWYAUA6.js.map} +1 -1
- package/dist/{chunk-445VQTVM.js → chunk-IE7P2BZE.js} +2 -2
- package/dist/{chunk-VOZA6O7K.js → chunk-ILNIZ5I2.js} +190 -96
- package/dist/chunk-ILNIZ5I2.js.map +1 -0
- package/dist/{chunk-TF5HCP33.js → chunk-INTFHMU4.js} +4 -4
- package/dist/{chunk-HREHWL32.js → chunk-J57UC3DD.js} +2 -2
- package/dist/{chunk-AV5NZMYO.js → chunk-KM7RY2ZS.js} +2 -2
- package/dist/{chunk-TAW4UFFF.js → chunk-L6JEXB3E.js} +132 -132
- package/dist/chunk-L6JEXB3E.js.map +1 -0
- package/dist/{chunk-E7LGOMH6.js → chunk-LRW6S53P.js} +4 -3
- package/dist/chunk-LRW6S53P.js.map +1 -0
- package/dist/{chunk-PKHI276N.js → chunk-LXAYUOXI.js} +18 -9
- package/dist/chunk-LXAYUOXI.js.map +1 -0
- package/dist/{chunk-WOM257PW.js → chunk-NDGZDTSJ.js} +3 -3
- package/dist/{chunk-SFASB5FL.js → chunk-P3LFTKE7.js} +3 -14
- package/dist/chunk-P3LFTKE7.js.map +1 -0
- package/dist/{chunk-YUY4SAGM.js → chunk-RVPYTUP4.js} +5 -5
- package/dist/chunk-RVPYTUP4.js.map +1 -0
- package/dist/{chunk-GAKUQHKA.js → chunk-TC2WZLSC.js} +3 -3
- package/dist/{chunk-D3ZURCG7.js → chunk-TKPF35W6.js} +2 -2
- package/dist/{chunk-I5TDIUKM.js → chunk-U3IKUGRP.js} +23 -5
- package/dist/chunk-U3IKUGRP.js.map +1 -0
- package/dist/{chunk-BI673VEJ.js → chunk-UXZONNEQ.js} +3 -3
- package/dist/{chunk-PJNENX2A.js → chunk-WFSPCCVW.js} +2 -2
- package/dist/{chunk-PJNENX2A.js.map → chunk-WFSPCCVW.js.map} +1 -1
- package/dist/{chunk-DW4YTVR3.js → chunk-WXA2BWTE.js} +6 -2
- package/dist/chunk-WXA2BWTE.js.map +1 -0
- package/dist/{chunk-JRZBBPO6.js → chunk-ZDZERB6L.js} +56 -228
- package/dist/chunk-ZDZERB6L.js.map +1 -0
- package/dist/{chunk-G75OPGAK.js → chunk-ZNNXRNFD.js} +5 -3
- package/dist/chunk-ZNNXRNFD.js.map +1 -0
- package/dist/{chunk-CISYM4EO.js → chunk-ZURZHELF.js} +2 -2
- package/dist/{cli-FB4LOA5A.js → cli-E36SPKBW.js} +44 -44
- package/dist/{cli-FB4LOA5A.js.map → cli-E36SPKBW.js.map} +1 -1
- package/dist/{codex-event-TYVES3UX.js → codex-event-ZO2GEFE6.js} +2 -2
- package/dist/{codex-host-WW4H2SKT.js → codex-host-KECJVTA2.js} +3 -3
- package/dist/{codex-install-2C623HPW.js → codex-install-HQZDGFXW.js} +90 -47
- package/dist/codex-install-HQZDGFXW.js.map +1 -0
- package/dist/{config-HOVJFEKD.js → config-HY2E4GGW.js} +8 -8
- package/dist/{doctor-NKU4V5OV.js → doctor-I6XQEKWD.js} +42 -31
- package/dist/doctor-I6XQEKWD.js.map +1 -0
- package/dist/{fund-WEBHTZGN.js → fund-2QRO7OJL.js} +16 -11
- package/dist/{fund-WEBHTZGN.js.map → fund-2QRO7OJL.js.map} +1 -1
- package/dist/{hook-command-ZA2PNKS6.js → hook-command-2UBCSZG6.js} +12 -13
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
- package/dist/hosts/claude/tenjin/hooks/register.tsx +51 -11
- package/dist/hosts/claude/tenjin/types/index.d.ts +2 -1
- package/dist/{hosts-AV5MHBAU.js → hosts-DVQJ32QC.js} +2 -2
- package/dist/index.js +16 -15
- package/dist/index.js.map +1 -1
- package/dist/{install-PT4EZS4R.js → install-ILUX5C4A.js} +24 -17
- package/dist/{install-identity-5A4OE6YC.js → install-identity-TZKGY6LQ.js} +7 -7
- package/dist/{install-wallet-SAAPKB73.js → install-wallet-5M4OTYLX.js} +13 -13
- package/dist/isows-native-Q2UDIVPT.js +9 -0
- package/dist/isows-native-Q2UDIVPT.js.map +1 -0
- package/dist/{mcp-HAWKCTPQ.js → mcp-LE4DUS22.js} +23 -24
- package/dist/{mcp-HAWKCTPQ.js.map → mcp-LE4DUS22.js.map} +1 -1
- package/dist/{package-SR2WB6MK.js → package-IJFGMWEV.js} +2 -2
- package/dist/{pay-OXC3WKYV.js → pay-WCG3IH4R.js} +13 -13
- package/dist/{payments-3KHMP2MG.js → payments-HFPPWHTV.js} +6 -6
- package/dist/{plugin-registration-N3GRIZVM.js → plugin-registration-PZFI5GZW.js} +18 -17
- package/dist/{runtime-UVNUA3AS.js → runtime-UZOKSUZX.js} +145 -27
- package/dist/runtime-UZOKSUZX.js.map +1 -0
- package/dist/{runtime-fetch-EKFRNR6Z.js → runtime-fetch-ZSSSK72Y.js} +5 -2
- package/dist/{runtime-layout-BDWZG2TQ.js → runtime-layout-WIDILZ6K.js} +2 -2
- package/dist/{send-HMKJLT34.js → send-GCVEAQKL.js} +8 -8
- package/dist/{status-RWXIIWYS.js → status-HCVAOCN7.js} +10 -10
- package/dist/{status-line-77XYZP7E.js → status-line-OPCXDHL2.js} +6 -6
- package/dist/{uninstall-D5G67UJH.js → uninstall-BAWRBXXQ.js} +19 -18
- package/dist/{uninstall-D5G67UJH.js.map → uninstall-BAWRBXXQ.js.map} +1 -1
- package/dist/{update-LRNOEGSB.js → update-CACXLQLR.js} +20 -17
- package/dist/{usdc-D6X7EIQ2.js → usdc-VG4CIOUK.js} +4 -4
- package/dist/{viemAdapter-By13KInL-RL742ETX.js → viemAdapter-By13KInL-DOFTEIJV.js} +2 -2
- package/dist/{wallet-XFYC27BR.js → wallet-QL4UUXEZ.js} +11 -11
- package/docs/agent-permissions.md +16 -12
- package/docs/troubleshooting.md +5 -5
- package/package.json +4 -4
- package/scripts/installers/install.ps1 +67 -0
- package/scripts/installers/install.sh +68 -0
- package/dist/_esm-C5CRWCYU.js +0 -3737
- package/dist/_esm-C5CRWCYU.js.map +0 -1
- package/dist/chunk-2GNOFONN.js.map +0 -1
- package/dist/chunk-ADV4LDTB.js.map +0 -1
- package/dist/chunk-DW4YTVR3.js.map +0 -1
- package/dist/chunk-E7LGOMH6.js.map +0 -1
- package/dist/chunk-G75OPGAK.js.map +0 -1
- package/dist/chunk-I5TDIUKM.js.map +0 -1
- package/dist/chunk-IDTRSAHE.js.map +0 -1
- package/dist/chunk-JRZBBPO6.js.map +0 -1
- package/dist/chunk-PKHI276N.js.map +0 -1
- package/dist/chunk-SFASB5FL.js.map +0 -1
- package/dist/chunk-SYOS5CAC.js.map +0 -1
- package/dist/chunk-TAW4UFFF.js.map +0 -1
- package/dist/chunk-VJUVFZ2D.js.map +0 -1
- package/dist/chunk-VOZA6O7K.js.map +0 -1
- package/dist/chunk-VUGQTZ2L.js.map +0 -1
- package/dist/chunk-YUY4SAGM.js.map +0 -1
- package/dist/codex-install-2C623HPW.js.map +0 -1
- package/dist/doctor-NKU4V5OV.js.map +0 -1
- package/dist/runtime-UVNUA3AS.js.map +0 -1
- /package/dist/{_esm-RLLC72MS.js.map → _esm-BIN7VY2L.js.map} +0 -0
- /package/dist/{alive-MROUMFH3.js.map → alive-GSOWKUOY.js.map} +0 -0
- /package/dist/{auto-update-OPWMRZLS.js.map → auto-update-Y24UL56V.js.map} +0 -0
- /package/dist/{chunk-OTWLERSW.js.map → chunk-36RVGZNY.js.map} +0 -0
- /package/dist/{chunk-B7EM4GGF.js.map → chunk-3GNJXKIT.js.map} +0 -0
- /package/dist/{chunk-DRDUIZIA.js.map → chunk-4K7TQHNP.js.map} +0 -0
- /package/dist/{chunk-AD226HDR.js.map → chunk-A5GKIG5O.js.map} +0 -0
- /package/dist/{chunk-JEVQ5LKO.js.map → chunk-AGMVASXZ.js.map} +0 -0
- /package/dist/{chunk-QF3LSMGS.js.map → chunk-GTTUCOPD.js.map} +0 -0
- /package/dist/{chunk-3DIL66VX.js.map → chunk-HGGWCP7W.js.map} +0 -0
- /package/dist/{chunk-445VQTVM.js.map → chunk-IE7P2BZE.js.map} +0 -0
- /package/dist/{chunk-TF5HCP33.js.map → chunk-INTFHMU4.js.map} +0 -0
- /package/dist/{chunk-HREHWL32.js.map → chunk-J57UC3DD.js.map} +0 -0
- /package/dist/{chunk-AV5NZMYO.js.map → chunk-KM7RY2ZS.js.map} +0 -0
- /package/dist/{chunk-WOM257PW.js.map → chunk-NDGZDTSJ.js.map} +0 -0
- /package/dist/{chunk-GAKUQHKA.js.map → chunk-TC2WZLSC.js.map} +0 -0
- /package/dist/{chunk-D3ZURCG7.js.map → chunk-TKPF35W6.js.map} +0 -0
- /package/dist/{chunk-BI673VEJ.js.map → chunk-UXZONNEQ.js.map} +0 -0
- /package/dist/{chunk-CISYM4EO.js.map → chunk-ZURZHELF.js.map} +0 -0
- /package/dist/{codex-event-TYVES3UX.js.map → codex-event-ZO2GEFE6.js.map} +0 -0
- /package/dist/{codex-host-WW4H2SKT.js.map → codex-host-KECJVTA2.js.map} +0 -0
- /package/dist/{config-HOVJFEKD.js.map → config-HY2E4GGW.js.map} +0 -0
- /package/dist/{hook-command-ZA2PNKS6.js.map → hook-command-2UBCSZG6.js.map} +0 -0
- /package/dist/{hosts-AV5MHBAU.js.map → hosts-DVQJ32QC.js.map} +0 -0
- /package/dist/{install-PT4EZS4R.js.map → install-ILUX5C4A.js.map} +0 -0
- /package/dist/{install-identity-5A4OE6YC.js.map → install-identity-TZKGY6LQ.js.map} +0 -0
- /package/dist/{install-wallet-SAAPKB73.js.map → install-wallet-5M4OTYLX.js.map} +0 -0
- /package/dist/{package-SR2WB6MK.js.map → package-IJFGMWEV.js.map} +0 -0
- /package/dist/{pay-OXC3WKYV.js.map → pay-WCG3IH4R.js.map} +0 -0
- /package/dist/{payments-3KHMP2MG.js.map → payments-HFPPWHTV.js.map} +0 -0
- /package/dist/{plugin-registration-N3GRIZVM.js.map → plugin-registration-PZFI5GZW.js.map} +0 -0
- /package/dist/{runtime-fetch-EKFRNR6Z.js.map → runtime-fetch-ZSSSK72Y.js.map} +0 -0
- /package/dist/{runtime-layout-BDWZG2TQ.js.map → runtime-layout-WIDILZ6K.js.map} +0 -0
- /package/dist/{send-HMKJLT34.js.map → send-GCVEAQKL.js.map} +0 -0
- /package/dist/{status-RWXIIWYS.js.map → status-HCVAOCN7.js.map} +0 -0
- /package/dist/{status-line-77XYZP7E.js.map → status-line-OPCXDHL2.js.map} +0 -0
- /package/dist/{update-LRNOEGSB.js.map → update-CACXLQLR.js.map} +0 -0
- /package/dist/{usdc-D6X7EIQ2.js.map → usdc-VG4CIOUK.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-RL742ETX.js.map → viemAdapter-By13KInL-DOFTEIJV.js.map} +0 -0
- /package/dist/{wallet-XFYC27BR.js.map → wallet-QL4UUXEZ.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
package_default
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-RVPYTUP4.js";
|
|
5
5
|
import {
|
|
6
6
|
PRODUCTION_ORIGIN
|
|
7
7
|
} from "./chunk-XQJXNMSB.js";
|
|
@@ -340,4 +340,4 @@ export {
|
|
|
340
340
|
httpRequest,
|
|
341
341
|
fetchFailureToCliError
|
|
342
342
|
};
|
|
343
|
-
//# sourceMappingURL=chunk-
|
|
343
|
+
//# sourceMappingURL=chunk-36RVGZNY.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
package_default
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-RVPYTUP4.js";
|
|
5
5
|
|
|
6
6
|
// src/router/mcp-processes.ts
|
|
7
7
|
import { execFile } from "node:child_process";
|
|
@@ -195,4 +195,4 @@ export {
|
|
|
195
195
|
readProcessSnapshot,
|
|
196
196
|
readMcpServers
|
|
197
197
|
};
|
|
198
|
-
//# sourceMappingURL=chunk-
|
|
198
|
+
//# sourceMappingURL=chunk-3GNJXKIT.js.map
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
setTenjinIdentity
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-36RVGZNY.js";
|
|
5
5
|
import {
|
|
6
6
|
isTeamModeConfig
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-KM7RY2ZS.js";
|
|
8
8
|
import {
|
|
9
9
|
hasCode
|
|
10
10
|
} from "./chunk-2I4QTOLB.js";
|
|
11
11
|
import {
|
|
12
12
|
loadRawConfig,
|
|
13
13
|
resolveSettings
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-2M2VPI2E.js";
|
|
15
15
|
import {
|
|
16
16
|
knownDeploymentOrigins
|
|
17
17
|
} from "./chunk-XQJXNMSB.js";
|
|
@@ -111,4 +111,4 @@ export {
|
|
|
111
111
|
enableCliIdentity,
|
|
112
112
|
enableDaemonIdentity
|
|
113
113
|
};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-4K7TQHNP.js.map
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
proxyVariable
|
|
4
|
+
} from "./chunk-3FMZGI7I.js";
|
|
2
5
|
import {
|
|
3
6
|
CliError
|
|
4
7
|
} from "./chunk-3UCIG4TG.js";
|
|
@@ -6,7 +9,7 @@ import {
|
|
|
6
9
|
// src/lib/runtime-fetch.ts
|
|
7
10
|
import { spawn } from "node:child_process";
|
|
8
11
|
import { createHash, randomBytes } from "node:crypto";
|
|
9
|
-
import { open, rm } from "node:fs/promises";
|
|
12
|
+
import { open, readFile, rm, stat } from "node:fs/promises";
|
|
10
13
|
import { join, posix, win32 } from "node:path";
|
|
11
14
|
var MIN_GLIBC = [2, 28];
|
|
12
15
|
var KEYS = /* @__PURE__ */ new Set([
|
|
@@ -119,6 +122,73 @@ async function download(url, o) {
|
|
|
119
122
|
throw err;
|
|
120
123
|
}
|
|
121
124
|
}
|
|
125
|
+
async function downloadViaCurl(url, o) {
|
|
126
|
+
if (!isHttps(url)) throw new CliError("UPDATE_FAILED", "Only HTTPS downloads are allowed.");
|
|
127
|
+
const proxy = proxyVariable(o.env);
|
|
128
|
+
const env = proxy === void 0 ? o.env : { ...o.env, HTTPS_PROXY: o.env[proxy] };
|
|
129
|
+
const file = join(o.dir, `dl-${randomBytes(6).toString("hex")}`);
|
|
130
|
+
const handle = await open(file, "wx", 384);
|
|
131
|
+
await handle.close();
|
|
132
|
+
try {
|
|
133
|
+
await new Promise((done, fail) => {
|
|
134
|
+
const child = spawn(
|
|
135
|
+
process.platform === "win32" ? "curl.exe" : "curl",
|
|
136
|
+
[
|
|
137
|
+
"-q",
|
|
138
|
+
"--proto",
|
|
139
|
+
"=https",
|
|
140
|
+
"--proto-redir",
|
|
141
|
+
"=https",
|
|
142
|
+
"--fail",
|
|
143
|
+
"--location",
|
|
144
|
+
"--silent",
|
|
145
|
+
"--show-error",
|
|
146
|
+
"--connect-timeout",
|
|
147
|
+
"30",
|
|
148
|
+
"--max-time",
|
|
149
|
+
String(Math.max(1, Math.ceil(o.timeoutMs / 1e3))),
|
|
150
|
+
"--max-filesize",
|
|
151
|
+
String(o.maxBytes),
|
|
152
|
+
"--output",
|
|
153
|
+
file,
|
|
154
|
+
url
|
|
155
|
+
],
|
|
156
|
+
// In Tenjin's own tmp folder: Windows looks for `curl.exe` in the
|
|
157
|
+
// working directory before PATH, and Tenjin runs from whatever folder
|
|
158
|
+
// the person is in, a cloned repository included. The output path is
|
|
159
|
+
// already absolute.
|
|
160
|
+
{ cwd: o.dir, env, stdio: "ignore", windowsHide: true, timeout: o.timeoutMs + 1e3 }
|
|
161
|
+
);
|
|
162
|
+
child.once(
|
|
163
|
+
"error",
|
|
164
|
+
() => fail(
|
|
165
|
+
new CliError(
|
|
166
|
+
"NETWORK_ERROR",
|
|
167
|
+
"Could not start curl for the proxy download. Use the shell or PowerShell installer."
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
);
|
|
171
|
+
child.once(
|
|
172
|
+
"close",
|
|
173
|
+
(code) => code === 0 ? done() : fail(
|
|
174
|
+
new CliError(
|
|
175
|
+
"NETWORK_ERROR",
|
|
176
|
+
"The download through the configured proxy failed. Check the connection and retry installation."
|
|
177
|
+
)
|
|
178
|
+
)
|
|
179
|
+
);
|
|
180
|
+
});
|
|
181
|
+
if ((await stat(file)).size > o.maxBytes)
|
|
182
|
+
throw new CliError("UPDATE_FAILED", "The Node download is too large.");
|
|
183
|
+
return {
|
|
184
|
+
file,
|
|
185
|
+
digest: createHash("sha256").update(await readFile(file)).digest()
|
|
186
|
+
};
|
|
187
|
+
} catch (error) {
|
|
188
|
+
await rm(file, { force: true });
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
122
192
|
function codeOf(err) {
|
|
123
193
|
const code = err?.code;
|
|
124
194
|
return typeof code === "string" ? code : messageOf(err);
|
|
@@ -171,6 +241,7 @@ export {
|
|
|
171
241
|
runningGlibc,
|
|
172
242
|
nodeArtifact,
|
|
173
243
|
download,
|
|
244
|
+
downloadViaCurl,
|
|
174
245
|
extract
|
|
175
246
|
};
|
|
176
|
-
//# sourceMappingURL=chunk-
|
|
247
|
+
//# sourceMappingURL=chunk-4YOZGGTZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/runtime-fetch.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { open, readFile, rm, stat } from 'node:fs/promises';\nimport { join, posix, win32 } from 'node:path';\nimport { CliError } from './errors';\nimport { proxyVariable } from './env-proxy';\n\n/**\n * WHAT THE RUNTIME DOWNLOADS, AND HOW: Node's own release archive and the npm\n * tarball of a tenjin-cli version, over https only, streamed to disk while\n * hashed, capped in size and time, and unpacked by the system's `tar` in exec\n * form. The checksums themselves are the caller's: the pin in `package.json`\n * for Node, the registry's `dist.integrity` for a tarball.\n */\n\n/** The oldest glibc Node 24's prebuilt Linux binaries run on. */\nconst MIN_GLIBC = [2, 28] as const;\n\n/** Node's release archives, by `nodeKey`. Anything else has no pinned build. */\nconst KEYS = new Set([\n 'darwin-arm64',\n 'darwin-x64',\n 'linux-x64',\n 'linux-arm64',\n 'win-x64',\n 'win-arm64',\n]);\n\nfunction glibcAtLeast(glibc: string, min: readonly [number, number]): boolean {\n const m = /^(\\d+)\\.(\\d+)/.exec(glibc);\n if (m === null) return false;\n const major = Number(m[1]);\n const minor = Number(m[2]);\n return major > min[0] || (major === min[0] && minor >= min[1]);\n}\n\n/**\n * The release-archive key for this machine, or null where Tenjin pins no Node:\n * musl (no glibc version at all), a glibc older than 2.28, and every platform\n * and architecture outside the six keys. A Rosetta x64 Node asks for\n * `darwin-x64`, which runs under Rosetta too.\n */\nexport function nodeKey(\n platform: NodeJS.Platform,\n arch: string,\n glibc: string | null | undefined,\n): string | null {\n const os = platform === 'win32' ? 'win' : platform;\n const key = `${os}-${arch}`;\n if (!KEYS.has(key)) return null;\n if (platform === 'linux' && (typeof glibc !== 'string' || !glibcAtLeast(glibc, MIN_GLIBC))) {\n return null;\n }\n return key;\n}\n\n/**\n * Why Tenjin pins no Node for this machine, or null when it pins one: the\n * platform and architecture, and on Linux the C library that rules it out.\n * Said by install and doctor so the cause is named, never a pinned key.\n */\nexport function unpinnedPlatform(\n platform: NodeJS.Platform,\n arch: string,\n glibc: string | null | undefined,\n): string | null {\n if (nodeKey(platform, arch, glibc) !== null) return null;\n const key = `${platform === 'win32' ? 'win' : platform}-${arch}`;\n if (platform !== 'linux' || !KEYS.has(key)) return key;\n return typeof glibc === 'string'\n ? `${key} with glibc ${glibc}, older than ${MIN_GLIBC.join('.')}`\n : `${key} with musl, not glibc`;\n}\n\n/** The glibc this Node runs on, or null: musl, or a report that cannot be read. */\nexport function runningGlibc(): string | null {\n try {\n const report = process.report.getReport() as { header?: { glibcVersionRuntime?: string } };\n return report.header?.glibcVersionRuntime ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface NodeArtifact {\n key: string;\n url: string;\n /** The archive's name in the release, the name `SHASUMS256.txt` lists. */\n file: string;\n /** The one archive member the runtime keeps: the `node` binary. */\n member: string;\n}\n\nexport function nodeArtifact(version: string, key: string): NodeArtifact {\n const base = `node-v${version}-${key}`;\n const windows = key.startsWith('win-');\n const file = `${base}.${windows ? 'zip' : 'tar.gz'}`;\n return {\n key,\n url: `https://nodejs.org/dist/v${version}/${file}`,\n file,\n member: windows ? `${base}/node.exe` : `${base}/bin/node`,\n };\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === 'https:';\n } catch {\n return false;\n }\n}\n\n/**\n * Stream `url` into a fresh file under `dir`, hashing as it goes. Refuses a URL\n * (or a redirect's final URL) that is not https, aborts past `maxBytes` or\n * `timeoutMs`, and unlinks the file on any failure, so a caller never finds a\n * half download. A transport failure (the fetch, or reading the body) is\n * `NETWORK_ERROR`, and the caller adds its fix; a write to disk that fails\n * (ENOSPC, EACCES) is not the network's, and says which file and why.\n */\nexport async function download(\n url: string,\n o: {\n dir: string;\n maxBytes: number;\n timeoutMs: number;\n hash: 'sha256' | 'sha512';\n fetchImpl?: typeof fetch;\n },\n): Promise<{ file: string; digest: Buffer }> {\n if (!isHttps(url)) {\n throw new CliError('UPDATE_FAILED', `refused to download ${url}: only https is allowed`);\n }\n const file = join(o.dir, `dl-${randomBytes(6).toString('hex')}`);\n const handle = await open(file, 'wx', 0o600);\n let closed = false;\n try {\n let res: Response;\n try {\n res = await (o.fetchImpl ?? fetch)(url, { signal: AbortSignal.timeout(o.timeoutMs) });\n } catch (err) {\n throw new CliError('NETWORK_ERROR', `could not download ${url}: ${messageOf(err)}`, {\n cause: err,\n });\n }\n if (res.url !== '' && !isHttps(res.url)) {\n throw new CliError('UPDATE_FAILED', `refused ${url}: it redirected to ${res.url}`);\n }\n if (!res.ok || res.body === null) {\n throw new CliError('NETWORK_ERROR', `could not download ${url}: HTTP ${res.status}`);\n }\n const tooLarge = () =>\n new CliError('UPDATE_FAILED', `the download from ${url} is larger than ${o.maxBytes} bytes`);\n if (Number(res.headers.get('content-length') ?? 0) > o.maxBytes) throw tooLarge();\n const hash = createHash(o.hash);\n let size = 0;\n try {\n for await (const chunk of res.body as AsyncIterable<Uint8Array>) {\n size += chunk.byteLength;\n if (size > o.maxBytes) throw tooLarge();\n hash.update(chunk);\n try {\n await handle.write(chunk);\n } catch (err) {\n throw new CliError('UPDATE_FAILED', `could not write ${file}: ${codeOf(err)}`, {\n cause: err,\n });\n }\n }\n } catch (err) {\n if (err instanceof CliError) throw err;\n throw new CliError('NETWORK_ERROR', `could not download ${url}: ${messageOf(err)}`, {\n cause: err,\n });\n }\n await handle.close();\n closed = true;\n return { file, digest: hash.digest() };\n } catch (err) {\n if (!closed) await handle.close().catch(() => undefined);\n await rm(file, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/** Old npm Node releases cannot use environment proxies; curl keeps the first install working there. */\nexport async function downloadViaCurl(\n url: string,\n o: {\n dir: string;\n maxBytes: number;\n timeoutMs: number;\n env: NodeJS.ProcessEnv;\n },\n): Promise<{ file: string; digest: Buffer }> {\n if (!isHttps(url)) throw new CliError('UPDATE_FAILED', 'Only HTTPS downloads are allowed.');\n const proxy = proxyVariable(o.env);\n const env = proxy === undefined ? o.env : { ...o.env, HTTPS_PROXY: o.env[proxy] };\n const file = join(o.dir, `dl-${randomBytes(6).toString('hex')}`);\n const handle = await open(file, 'wx', 0o600);\n await handle.close();\n try {\n await new Promise<void>((done, fail) => {\n const child = spawn(\n process.platform === 'win32' ? 'curl.exe' : 'curl',\n [\n '-q',\n '--proto',\n '=https',\n '--proto-redir',\n '=https',\n '--fail',\n '--location',\n '--silent',\n '--show-error',\n '--connect-timeout',\n '30',\n '--max-time',\n String(Math.max(1, Math.ceil(o.timeoutMs / 1000))),\n '--max-filesize',\n String(o.maxBytes),\n '--output',\n file,\n url,\n ],\n // In Tenjin's own tmp folder: Windows looks for `curl.exe` in the\n // working directory before PATH, and Tenjin runs from whatever folder\n // the person is in, a cloned repository included. The output path is\n // already absolute.\n { cwd: o.dir, env, stdio: 'ignore', windowsHide: true, timeout: o.timeoutMs + 1000 },\n );\n child.once('error', () =>\n fail(\n new CliError(\n 'NETWORK_ERROR',\n 'Could not start curl for the proxy download. Use the shell or PowerShell installer.',\n ),\n ),\n );\n child.once('close', (code) =>\n code === 0\n ? done()\n : fail(\n new CliError(\n 'NETWORK_ERROR',\n 'The download through the configured proxy failed. Check the connection and retry installation.',\n ),\n ),\n );\n });\n if ((await stat(file)).size > o.maxBytes)\n throw new CliError('UPDATE_FAILED', 'The Node download is too large.');\n return {\n file,\n digest: createHash('sha256')\n .update(await readFile(file))\n .digest(),\n };\n } catch (error) {\n await rm(file, { force: true });\n throw error;\n }\n}\n\n/** A file-system error's errno code (ENOSPC, EACCES), or its message when it has none. */\nfunction codeOf(err: unknown): string {\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' ? code : messageOf(err);\n}\n\nfunction messageOf(err: unknown): string {\n if (err instanceof Error) {\n return err.name === 'TimeoutError' ? 'it timed out' : err.message;\n }\n return String(err);\n}\n\n/** How `extract` runs `tar`: exec form, no shell, in `cwd`. A seam for tests. */\nexport type ExtractSpawn = (\n command: string,\n args: string[],\n o: { cwd: string },\n) => Promise<{ code: number | null; stderr: string }>;\n\nconst spawnTar: ExtractSpawn = (command, args, o) =>\n new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: o.cwd,\n shell: false,\n stdio: ['ignore', 'ignore', 'pipe'],\n windowsHide: true,\n });\n let stderr = '';\n child.stderr.setEncoding('utf8');\n child.stderr.on('data', (chunk: string) => {\n if (stderr.length < 4096) stderr += chunk;\n });\n child.on('error', reject);\n child.on('close', (code) => resolve({ code, stderr }));\n });\n\n/**\n * Unpack `archive` into `dest` with the system's `tar`: `tar -xzf` on POSIX,\n * and on Windows `System32\\tar.exe -xf`, which is bsdtar and reads a `.zip`\n * (Git's GNU tar, earlier on many PATHs, does not). `member` limits it to one\n * file, `strip` drops leading folders. A non-zero exit throws with what tar said.\n *\n * TAR RUNS IN THE ARCHIVE'S FOLDER and is given names relative to it. bsdtar\n * reads its argv in the ANSI code page, so a user folder named outside it\n * (Cyrillic on cp1252, an emoji) would reach it as `?`; the working directory\n * goes to Windows as a wide string, and the names it is given are the\n * runtime's own ASCII ones.\n */\nexport async function extract(\n archive: string,\n dest: string,\n o: { member?: string; strip?: number; platform?: NodeJS.Platform; spawnImpl?: ExtractSpawn } = {},\n): Promise<void> {\n const windows = (o.platform ?? process.platform) === 'win32';\n const command = windows\n ? win32.join(process.env.SystemRoot ?? 'C:\\\\Windows', 'System32', 'tar.exe')\n : 'tar';\n const path = windows ? win32 : posix;\n const cwd = path.dirname(archive);\n const into = path.relative(cwd, dest);\n const args = [\n windows ? '-xf' : '-xzf',\n path.basename(archive),\n '-C',\n into === '' ? '.' : into.startsWith('..') || path.isAbsolute(into) ? dest : into,\n ...(o.strip !== undefined && o.strip > 0 ? [`--strip-components=${o.strip}`] : []),\n ...(o.member !== undefined ? [o.member] : []),\n ];\n const run = await (o.spawnImpl ?? spawnTar)(command, args, { cwd });\n if (run.code !== 0) {\n const said = run.stderr.trim().slice(0, 300);\n throw new Error(`tar could not unpack ${archive} (exit ${run.code})${said ? `: ${said}` : ''}`);\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,YAAY,mBAAmB;AACxC,SAAS,MAAM,UAAU,IAAI,YAAY;AACzC,SAAS,MAAM,OAAO,aAAa;AAanC,IAAM,YAAY,CAAC,GAA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AE,QAAQ,IAAI,CAAC,sBAAsB,EAAE,KAAK,EAAE,IAAI,CAAC;AAAA,IAChF,GAAI,EAAE,WAAW,SAAY,CAAC,EAAE,MAAM,IAAI,CAAC;AAAA,EAC7C;AACA,QAAM,MAAM,OAAO,EAAE,aAAa,UAAU,SAAS,MAAM,EAAE,IAAI,CAAC;AAClE,MAAI,IAAI,SAAS,GAAG;AAClB,UAAM,OAAO,IAAI,OAAO,KAAK,EAAE,MAAM,GAAG,GAAG;AAC3C,UAAM,IAAI,MAAM,wBAAwB,OAAO,UAAU,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,KAAK,EAAE,EAAE;AAAA,EAChG;AACF;","names":[]}
|
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
} from "./chunk-XKESD27X.js";
|
|
17
17
|
import {
|
|
18
18
|
style
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-FVIGCDSV.js";
|
|
20
20
|
import {
|
|
21
21
|
CHANNEL_DEPOSIT_ATOMIC,
|
|
22
22
|
ROUTING_FEE_ATOMIC,
|
|
@@ -45,11 +45,11 @@ import {
|
|
|
45
45
|
projectRouterPath,
|
|
46
46
|
readProjectRouterFile,
|
|
47
47
|
routerSettings
|
|
48
|
-
} from "./chunk-
|
|
48
|
+
} from "./chunk-AGMVASXZ.js";
|
|
49
49
|
import {
|
|
50
50
|
isTeamShelfOrigin,
|
|
51
51
|
loadProjectConfig
|
|
52
|
-
} from "./chunk-
|
|
52
|
+
} from "./chunk-KM7RY2ZS.js";
|
|
53
53
|
import {
|
|
54
54
|
parseUsdToAtomic,
|
|
55
55
|
toMoney
|
|
@@ -83,7 +83,7 @@ import {
|
|
|
83
83
|
parseUpdateModeFlag,
|
|
84
84
|
resolveSettings,
|
|
85
85
|
retiredPaymentKeys
|
|
86
|
-
} from "./chunk-
|
|
86
|
+
} from "./chunk-2M2VPI2E.js";
|
|
87
87
|
import {
|
|
88
88
|
PRODUCTION_ORIGIN,
|
|
89
89
|
isSameDeployment
|
|
@@ -2034,4 +2034,4 @@ export {
|
|
|
2034
2034
|
persistInstallHarness,
|
|
2035
2035
|
persistGrantDeclined
|
|
2036
2036
|
};
|
|
2037
|
-
//# sourceMappingURL=chunk-
|
|
2037
|
+
//# sourceMappingURL=chunk-A5GKIG5O.js.map
|
|
@@ -5,12 +5,12 @@ import {
|
|
|
5
5
|
mainWorktreeOf,
|
|
6
6
|
ownedCandidates,
|
|
7
7
|
projectRoot
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-KM7RY2ZS.js";
|
|
9
9
|
import {
|
|
10
10
|
CONFIG_DEFAULTS,
|
|
11
11
|
loadRawConfig,
|
|
12
12
|
parseRouterLayer
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-2M2VPI2E.js";
|
|
14
14
|
import {
|
|
15
15
|
CliError
|
|
16
16
|
} from "./chunk-3UCIG4TG.js";
|
|
@@ -124,4 +124,4 @@ export {
|
|
|
124
124
|
readProjectRouterFile,
|
|
125
125
|
projectRouterPath
|
|
126
126
|
};
|
|
127
|
-
//# sourceMappingURL=chunk-
|
|
127
|
+
//# sourceMappingURL=chunk-AGMVASXZ.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
nodeBinPath,
|
|
4
4
|
readRuntimeState,
|
|
5
5
|
versionEntry
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-ZNNXRNFD.js";
|
|
7
7
|
import {
|
|
8
8
|
configPath,
|
|
9
9
|
defaultDataDir,
|
|
@@ -18,6 +18,7 @@ import { join, resolve } from "node:path";
|
|
|
18
18
|
var AUTO_UPDATE_FILE = "auto-update.json";
|
|
19
19
|
var AUTO_UPDATE_LOG = "auto-update.log";
|
|
20
20
|
var DAY_MS = 864e5;
|
|
21
|
+
var TLS_OFF = "TLS certificate checks are turned off (NODE_TLS_REJECT_UNAUTHORIZED=0); set NODE_EXTRA_CA_CERTS instead";
|
|
21
22
|
function maybeAutoUpdate(o) {
|
|
22
23
|
try {
|
|
23
24
|
const { env } = o;
|
|
@@ -36,6 +37,11 @@ function maybeAutoUpdate(o) {
|
|
|
36
37
|
const previous = readAutoUpdate(root);
|
|
37
38
|
const started = Date.parse(previous?.startedAt ?? "");
|
|
38
39
|
if (!Number.isNaN(started) && nowMs - started >= 0 && nowMs - started < DAY_MS) return;
|
|
40
|
+
if (env.NODE_TLS_REJECT_UNAUTHORIZED === "0") {
|
|
41
|
+
const at = new Date(nowMs).toISOString();
|
|
42
|
+
writeRecord(root, { startedAt: at, finishedAt: at, outcome: "skipped", reason: TLS_OFF });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
39
45
|
writeRecord(root, { ...previous, startedAt: new Date(nowMs).toISOString() });
|
|
40
46
|
const fd = openSync(join(root, AUTO_UPDATE_LOG), "w", 384);
|
|
41
47
|
try {
|
|
@@ -92,15 +98,19 @@ function autoUpdateLine(root) {
|
|
|
92
98
|
if (r.outcome === "updated") return `Auto-update: ${when} updated ${r.from} -> ${r.to}`;
|
|
93
99
|
if (r.outcome === "current") return `Auto-update: ${when} up to date (${r.to ?? r.from})`;
|
|
94
100
|
if (r.outcome === "failed") return `Auto-update: ${when} failed: ${r.reason ?? "unknown"}`;
|
|
101
|
+
if (r.outcome === "skipped" && r.reason !== void 0) {
|
|
102
|
+
return `Auto-update: ${when} skipped: ${r.reason}`;
|
|
103
|
+
}
|
|
95
104
|
return null;
|
|
96
105
|
}
|
|
97
106
|
|
|
98
107
|
export {
|
|
99
108
|
AUTO_UPDATE_FILE,
|
|
100
109
|
AUTO_UPDATE_LOG,
|
|
110
|
+
TLS_OFF,
|
|
101
111
|
maybeAutoUpdate,
|
|
102
112
|
readAutoUpdate,
|
|
103
113
|
recordAutoUpdate,
|
|
104
114
|
autoUpdateLine
|
|
105
115
|
};
|
|
106
|
-
//# sourceMappingURL=chunk-
|
|
116
|
+
//# sourceMappingURL=chunk-BF4XHEQK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/auto-update.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { closeSync, existsSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { configPath, defaultDataDir, runtimeDir } from './paths';\nimport { nodeBinPath, readRuntimeState, versionEntry } from './runtime-layout';\n\n/**\n * BACKGROUND AUTO-UPDATE, the way Claude Code's native installer does it:\n * downloaded in the background, used from the next session. At most once a\n * day, at the start of a Claude Code or Codex session, this starts\n * `tenjin update --background` DETACHED on the runtime's own Node and current\n * entry, and returns: the caller adds no latency and never waits.\n * The child is `tenjin update`'s runtime branch (the release's build\n * provenance is checked before it is downloaded and the build before the\n * switch, the previous version stays, an older one is never switched to, the\n * runtime lock is held), except that it takes only a release published at\n * least a day ago (`BACKGROUND_COOLDOWN_MS` in commands/update). So npm and PATH\n * are never involved, and a running session keeps its version until the next\n * one. Codex has no SessionStart hook, so `tenjin mcp --harness codex` starts\n * it as the server starts; its routing legs are `mcp_tool` calls into that\n * server, so the switch moves nothing the session is using, and the launcher\n * it rewrites starts the next session's server.\n *\n * `node:*`, the paths and the runtime layout only: the `alive` leg and\n * `tenjin mcp` load this, and neither may pay for zod, the config schema or\n * the runtime's writer. The config is read raw for the same reason.\n *\n * <root>/auto-update.json when the last run started, and how it ended\n * <root>/auto-update.log the last run's output, overwritten each run\n */\n\nexport const AUTO_UPDATE_FILE = 'auto-update.json';\nexport const AUTO_UPDATE_LOG = 'auto-update.log';\n\nconst DAY_MS = 86_400_000;\n\n/** Why no background update starts while Node checks no TLS certificate. */\nexport const TLS_OFF =\n 'TLS certificate checks are turned off (NODE_TLS_REJECT_UNAUTHORIZED=0); set NODE_EXTRA_CA_CERTS instead';\n\nexport interface AutoUpdateRecord {\n /** When the last background run was started (ISO). */\n startedAt?: string;\n /** When it finished (ISO); absent while it runs, or if it died. */\n finishedAt?: string;\n outcome?: 'updated' | 'current' | 'failed' | 'skipped';\n from?: string;\n to?: string;\n reason?: string;\n}\n\ntype Spawn = typeof spawn;\n\n/**\n * Start the background update if one is due. Synchronous and never throws:\n * every gate that does not hold returns without spawning, and so does any\n * error, since the session it rides on must start regardless.\n */\nexport function maybeAutoUpdate(o: {\n dataDir: string;\n env: NodeJS.ProcessEnv;\n home?: string;\n now?: () => number;\n spawnImpl?: Spawn;\n}): void {\n try {\n const { env } = o;\n // The same two doors the update nudge has (lib/update-check).\n if (env.CI !== undefined && env.CI.length > 0) return;\n if (env.TENJIN_NO_UPDATE_CHECK === '1') return;\n const home = o.home ?? homedir();\n if (resolve(o.dataDir) !== resolve(defaultDataDir(home))) return;\n if (!autoMode(o.dataDir)) return;\n\n const root = runtimeDir(o.dataDir);\n const state = readRuntimeState(root);\n if (state === null) return;\n const node = nodeBinPath(root, state.current.node);\n const entry = versionEntry(root, state.current.cli);\n if (!existsSync(node) || !existsSync(entry)) return;\n\n const nowMs = (o.now ?? Date.now)();\n const previous = readAutoUpdate(root);\n const started = Date.parse(previous?.startedAt ?? '');\n // A start in the future (a clock set back) counts as due, not as a day away.\n if (!Number.isNaN(started) && nowMs - started >= 0 && nowMs - started < DAY_MS) return;\n\n // NOT WITH TLS CERTIFICATE CHECKS TURNED OFF: the child inherits this\n // environment, and then anyone on the network path can answer for the\n // registry, the dist-tags, the attestations and the tarball alike, so no\n // check the update makes would hold. Recorded as a run, once a day, so\n // doctor names the cause and the fix.\n if (env.NODE_TLS_REJECT_UNAUTHORIZED === '0') {\n const at = new Date(nowMs).toISOString();\n writeRecord(root, { startedAt: at, finishedAt: at, outcome: 'skipped', reason: TLS_OFF });\n return;\n }\n\n // Stamped BEFORE the spawn, so a second session starting in the same\n // second finds it and stays put. The last result is kept for doctor.\n writeRecord(root, { ...previous, startedAt: new Date(nowMs).toISOString() });\n const fd = openSync(join(root, AUTO_UPDATE_LOG), 'w', 0o600);\n try {\n const child = (o.spawnImpl ?? spawn)(node, [entry, 'update', '--background'], {\n detached: true,\n stdio: ['ignore', fd, fd],\n cwd: home,\n windowsHide: true,\n // The child's own nudge would ask npm again for what it just learned.\n env: { ...env, TENJIN_NO_UPDATE_CHECK: '1' },\n });\n child.on('error', () => undefined);\n child.unref();\n } finally {\n closeSync(fd);\n }\n } catch {\n // Never the session's business.\n }\n}\n\n/**\n * `update.mode` as stored, read without the config schema: absent (the\n * default) or `auto` runs; `nudge` and `off` were typed by the person, and an\n * unparsable file is not read as consent. A missing file is the default.\n */\nfunction autoMode(dataDir: string): boolean {\n let text: string;\n try {\n text = readFileSync(configPath(dataDir), 'utf8');\n } catch {\n return true;\n }\n const raw = JSON.parse(text) as { update?: { mode?: unknown } } | null;\n const mode = raw?.update?.mode;\n return mode === undefined || mode === 'auto';\n}\n\n/** The last run's record, or null when there is none or it is unreadable. */\nexport function readAutoUpdate(root: string): AutoUpdateRecord | null {\n try {\n const raw = JSON.parse(readFileSync(join(root, AUTO_UPDATE_FILE), 'utf8')) as unknown;\n return typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? (raw as AutoUpdateRecord)\n : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Replace the record with how a run ended, keeping when it started, so no\n * field of an earlier run survives into this one. Throws; the caller decides.\n */\nexport function recordAutoUpdate(root: string, result: Omit<AutoUpdateRecord, 'startedAt'>): void {\n const startedAt = readAutoUpdate(root)?.startedAt;\n writeRecord(root, { ...(startedAt !== undefined ? { startedAt } : {}), ...result });\n}\n\nfunction writeRecord(root: string, record: AutoUpdateRecord): void {\n const path = join(root, AUTO_UPDATE_FILE);\n const tmp = `${path}.${process.pid}.tmp`;\n writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 });\n renameSync(tmp, path);\n}\n\n/** Doctor's one line about the last finished run, or null when there is none. */\nexport function autoUpdateLine(root: string): string | null {\n const r = readAutoUpdate(root);\n if (r === null || r.finishedAt === undefined) return null;\n const when = r.finishedAt.slice(0, 10);\n if (r.outcome === 'updated') return `Auto-update: ${when} updated ${r.from} -> ${r.to}`;\n if (r.outcome === 'current') return `Auto-update: ${when} up to date (${r.to ?? r.from})`;\n if (r.outcome === 'failed') return `Auto-update: ${when} failed: ${r.reason ?? 'unknown'}`;\n // A run that chose to wait (a release under a day old, TLS checks turned\n // off) says why, so the person sees what holds the update back.\n if (r.outcome === 'skipped' && r.reason !== undefined) {\n return `Auto-update: ${when} skipped: ${r.reason}`;\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,WAAW,YAAY,UAAU,cAAc,YAAY,qBAAqB;AACzF,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AA6BvB,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAE/B,IAAM,SAAS;AAGR,IAAM,UACX;AAoBK,SAAS,gBAAgB,GAMvB;AACP,MAAI;AACF,UAAM,EAAE,IAAI,IAAI;AAEhB,QAAI,IAAI,OAAO,UAAa,IAAI,GAAG,SAAS,EAAG;AAC/C,QAAI,IAAI,2BAA2B,IAAK;AACxC,UAAM,OAAO,EAAE,QAAQ,QAAQ;AAC/B,QAAI,QAAQ,EAAE,OAAO,MAAM,QAAQ,eAAe,IAAI,CAAC,EAAG;AAC1D,QAAI,CAAC,SAAS,EAAE,OAAO,EAAG;AAE1B,UAAM,OAAO,WAAW,EAAE,OAAO;AACjC,UAAM,QAAQ,iBAAiB,IAAI;AACnC,QAAI,UAAU,KAAM;AACpB,UAAM,OAAO,YAAY,MAAM,MAAM,QAAQ,IAAI;AACjD,UAAM,QAAQ,aAAa,MAAM,MAAM,QAAQ,GAAG;AAClD,QAAI,CAAC,WAAW,IAAI,KAAK,CAAC,WAAW,KAAK,EAAG;AAE7C,UAAM,SAAS,EAAE,OAAO,KAAK,KAAK;AAClC,UAAM,WAAW,eAAe,IAAI;AACpC,UAAM,UAAU,KAAK,MAAM,UAAU,aAAa,EAAE;AAEpD,QAAI,CAAC,OAAO,MAAM,OAAO,KAAK,QAAQ,WAAW,KAAK,QAAQ,UAAU,O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AChG,QAAM,YAAY,eAAe,IAAI,GAAG;AACxC,cAAY,MAAM,EAAE,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC,GAAI,GAAG,OAAO,CAAC;AACpF;AAEA,SAAS,YAAY,MAAc,QAAgC;AACjE,QAAM,OAAO,KAAK,MAAM,gBAAgB;AACxC,QAAM,MAAM,GAAG,IAAI,IAAI,QAAQ,GAAG;AAClC,gBAAc,KAAK,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,GAAM,EAAE,MAAM,IAAM,CAAC;AAC1E,aAAW,KAAK,IAAI;AACtB;AAGO,SAAS,eAAe,MAA6B;AAC1D,QAAM,IAAI,eAAe,IAAI;AAC7B,MAAI,MAAM,QAAQ,EAAE,eAAe,OAAW,QAAO;AACrD,QAAM,OAAO,EAAE,WAAW,MAAM,GAAG,EAAE;AACrC,MAAI,EAAE,YAAY,UAAW,QAAO,gBAAgB,IAAI,YAAY,EAAE,IAAI,OAAO,EAAE,EAAE;AACrF,MAAI,EAAE,YAAY,UAAW,QAAO,gBAAgB,IAAI,gBAAgB,EAAE,MAAM,EAAE,IAAI;AACtF,MAAI,EAAE,YAAY,SAAU,QAAO,gBAAgB,IAAI,YAAY,EAAE,UAAU,SAAS;AAGxF,MAAI,EAAE,YAAY,aAAa,EAAE,WAAW,QAAW;AACrD,WAAO,gBAAgB,IAAI,aAAa,EAAE,MAAM;AAAA,EAClD;AACA,SAAO;AACT;","names":[]}
|
|
@@ -14,18 +14,18 @@ var BINDING_PREFIX = "id-";
|
|
|
14
14
|
var OFFER_PREFIX = "offer-";
|
|
15
15
|
var SESSION_FILE = "session.json";
|
|
16
16
|
var REDIRECT_PREFIX = "redirect-";
|
|
17
|
-
var
|
|
18
|
-
var AUGMENT_BODY_SUFFIX = ".docs";
|
|
17
|
+
var NOTE_PREFIX = "note-";
|
|
19
18
|
var QUERY_PREFIX = "query-";
|
|
20
19
|
var CALL_FILE_RE = /^[a-f0-9]{64}\.json$/;
|
|
21
20
|
var STALE_AFTER_MS = 9e4;
|
|
22
21
|
var RECENT_MS = 1e4;
|
|
23
22
|
var EXPIRY_MS = 10 * 6e4;
|
|
24
23
|
var SESSION_ACTIVE_MS = 10 * 6e4;
|
|
25
|
-
var
|
|
24
|
+
var NOTE_REPEAT_MS = 5 * 6e4;
|
|
26
25
|
var MAX_RECORDS = 256;
|
|
27
26
|
var MAX_SESSIONS = 4096;
|
|
28
27
|
var MAX_RECORD_BYTES = 4096;
|
|
28
|
+
var OFFER_ID_RE = /^[\w.:-]{1,200}$/;
|
|
29
29
|
var digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
30
30
|
function bounded(value, limit) {
|
|
31
31
|
const chars = Array.from(value);
|
|
@@ -79,7 +79,7 @@ async function markOffered(dataDir, sessionId, toolUseId, offer, now = Date.now(
|
|
|
79
79
|
const saved = {
|
|
80
80
|
version: 1,
|
|
81
81
|
at: now,
|
|
82
|
-
...offer.offerId !== void 0 &&
|
|
82
|
+
...offer.offerId !== void 0 && OFFER_ID_RE.test(offer.offerId) ? { offerId: offer.offerId } : {},
|
|
83
83
|
...offer.label !== void 0 ? { label: sanitize(offer.label, 32) } : {},
|
|
84
84
|
.../^\d{1,78}$/.test(offer.priceAtomic) ? { priceAtomic: offer.priceAtomic } : {}
|
|
85
85
|
};
|
|
@@ -93,58 +93,57 @@ async function wasOffered(dataDir, sessionId, toolUseId, now = Date.now()) {
|
|
|
93
93
|
const stamp = await readStamp(path);
|
|
94
94
|
return stamp !== null && now - stamp.at <= EXPIRY_MS;
|
|
95
95
|
}
|
|
96
|
-
async function
|
|
97
|
-
|
|
98
|
-
const saved = {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
provider: sanitize(docs.provider, 60),
|
|
102
|
-
...docs.label !== void 0 ? { label: sanitize(docs.label, 32) } : {}
|
|
103
|
-
};
|
|
104
|
-
return await write(`${base}.json`, saved) ? `${base}${AUGMENT_BODY_SUFFIX}` : null;
|
|
96
|
+
async function markNoted(dataDir, sessionId, toolUseId, note, now = Date.now()) {
|
|
97
|
+
if (!OFFER_ID_RE.test(note.offerId) || !note.line.includes(note.offerId)) return false;
|
|
98
|
+
const saved = { version: 1, at: now, offerId: note.offerId, line: note.line };
|
|
99
|
+
if (Buffer.byteLength(JSON.stringify(saved), "utf8") > MAX_RECORD_BYTES) return false;
|
|
100
|
+
return write(notePath(dataDir, sessionId, toolUseId), saved);
|
|
105
101
|
}
|
|
106
|
-
async function
|
|
107
|
-
const
|
|
108
|
-
const row = await readJson(`${base}.json`);
|
|
102
|
+
async function noteOf(dataDir, sessionId, toolUseId, now = Date.now()) {
|
|
103
|
+
const row = await readJson(notePath(dataDir, sessionId, toolUseId));
|
|
109
104
|
const stamp = stampOf(row);
|
|
110
105
|
if (row === null || stamp === null || now - stamp.at > EXPIRY_MS) return null;
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
provider,
|
|
116
|
-
...label !== "" ? { label } : {},
|
|
117
|
-
body: `${base}${AUGMENT_BODY_SUFFIX}`
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
async function claimQuery(dataDir, sessionId, agentId, query, now = Date.now()) {
|
|
121
|
-
const key = digest(JSON.stringify([agentId ?? "", query]));
|
|
122
|
-
const path = join(sessionDir(dataDir, sessionId), `${QUERY_PREFIX}${key}.json`);
|
|
123
|
-
const stamp = { version: 1, at: now };
|
|
124
|
-
try {
|
|
125
|
-
await writeFileAtomicExclusive(path, JSON.stringify(stamp), { mode: 384, dirMode: 448 });
|
|
126
|
-
return true;
|
|
127
|
-
} catch {
|
|
106
|
+
const { offerId, line: line2 } = row;
|
|
107
|
+
if (typeof offerId !== "string" || !OFFER_ID_RE.test(offerId)) return null;
|
|
108
|
+
if (typeof line2 !== "string" || /[\p{Cc}\p{Cf}]/u.test(line2) || !line2.includes(offerId)) {
|
|
109
|
+
return null;
|
|
128
110
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
111
|
+
return { offerId, line: line2 };
|
|
112
|
+
}
|
|
113
|
+
function notePath(dataDir, sessionId, toolUseId) {
|
|
114
|
+
return join(sessionDir(dataDir, sessionId), `${NOTE_PREFIX}${digest(toolUseId)}.json`);
|
|
115
|
+
}
|
|
116
|
+
async function claimNote(dataDir, sessionId, agentId, query, now = Date.now()) {
|
|
117
|
+
return claimOnce(
|
|
118
|
+
(window) => {
|
|
119
|
+
const key = digest(JSON.stringify([agentId ?? "", query, window]));
|
|
120
|
+
return join(sessionDir(dataDir, sessionId), `${QUERY_PREFIX}${key}.json`);
|
|
121
|
+
},
|
|
122
|
+
NOTE_REPEAT_MS,
|
|
123
|
+
now
|
|
124
|
+
);
|
|
132
125
|
}
|
|
133
126
|
function redirectPath(dataDir, sessionId, agentId, target, window) {
|
|
134
127
|
const key = digest(JSON.stringify([agentId ?? "", target, window]));
|
|
135
128
|
return join(sessionDir(dataDir, sessionId), `${REDIRECT_PREFIX}${key}.json`);
|
|
136
129
|
}
|
|
137
130
|
async function claimRedirect(dataDir, sessionId, agentId, target, now = Date.now()) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
131
|
+
return claimOnce(
|
|
132
|
+
(window) => redirectPath(dataDir, sessionId, agentId, target, window),
|
|
133
|
+
EXPIRY_MS,
|
|
134
|
+
now
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
async function claimOnce(pathFor, span, now) {
|
|
138
|
+
const window = Math.floor(now / span);
|
|
139
|
+
const previous = await readStamp(pathFor(window - 1));
|
|
140
|
+
if (previous !== null && now - previous.at <= span) return false;
|
|
141
141
|
const stamp = { version: 1, at: now };
|
|
142
142
|
try {
|
|
143
|
-
await writeFileAtomicExclusive(
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
);
|
|
143
|
+
await writeFileAtomicExclusive(pathFor(window), JSON.stringify(stamp), {
|
|
144
|
+
mode: 384,
|
|
145
|
+
dirMode: 448
|
|
146
|
+
});
|
|
148
147
|
return true;
|
|
149
148
|
} catch {
|
|
150
149
|
return false;
|
|
@@ -246,7 +245,7 @@ async function pruneProgress(directory, now = Date.now()) {
|
|
|
246
245
|
}
|
|
247
246
|
}
|
|
248
247
|
function agesByMtime(name) {
|
|
249
|
-
return name.startsWith(".")
|
|
248
|
+
return name.startsWith(".");
|
|
250
249
|
}
|
|
251
250
|
async function mtimeOf(path) {
|
|
252
251
|
try {
|
|
@@ -383,9 +382,9 @@ export {
|
|
|
383
382
|
bindDecision,
|
|
384
383
|
markOffered,
|
|
385
384
|
wasOffered,
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
385
|
+
markNoted,
|
|
386
|
+
noteOf,
|
|
387
|
+
claimNote,
|
|
389
388
|
claimRedirect,
|
|
390
389
|
redirectClaimed,
|
|
391
390
|
writeProgress,
|
|
@@ -395,4 +394,4 @@ export {
|
|
|
395
394
|
pruneSessions,
|
|
396
395
|
renderProgress
|
|
397
396
|
};
|
|
398
|
-
//# sourceMappingURL=chunk-
|
|
397
|
+
//# sourceMappingURL=chunk-C2Q76BVM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/progress.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { lstat, open, opendir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic, writeFileAtomicExclusive } from '../lib/atomic-json';\n\n/**\n * The live status line's evidence: what this session is looking up right now,\n * which provider is actually being called, and what it cost.\n *\n * DISPLAY ONLY, AND STRICTLY DOWNSTREAM. Nothing here is read by the gate, the\n * decision, the spend policy or the paying leg; every write is best effort and\n * every failure is swallowed, so a full disk or a read-only data dir loses the\n * footer and changes no routing or payment outcome. That is the whole contract\n * this module has to keep. Two markers are read back by the hooks, the offer\n * mark and the redirect claims, and both only ever make a hook say less: losing\n * either routes a call exactly as a session with no record would, and a claim\n * that cannot be written denies nothing. The free-docs\n * records are the same kind: a lost note record is a search with no line\n * after it, and a lost query claim is one more line.\n *\n * KEYED TO THE SESSION, NEVER GUESSED FROM IT. A record lives under the SHA-256\n * of the harness's own `session_id`, so the renderer for one session cannot see\n * another's. The hook knows that id; the tool, which runs inside the MCP server\n * process, does not, so it resolves the session in one of exactly two ways:\n *\n * - BY BINDING. An `execute` decision leaves an `id-<hash>.json` marker in the\n * session that produced it, and the model passes that id back on the tool\n * call. Resolving through the marker is proof, not inference.\n * - BY SOLE ACTIVITY. With no id, the request belongs to the only session that\n * has been active recently, and when two have been, it belongs to neither as\n * far as this module is concerned: {@link resolveProgressSession} returns\n * null and nothing is written. A missing footer is the correct failure;\n * showing one session's lookup in another session's terminal is not.\n */\n\nconst PROGRESS_DIR = 'progress';\n/** The binding marker's prefix, so it can never be read back as a call record. */\nconst BINDING_PREFIX = 'id-';\n/** A pre-call redirect's marker, keyed by the harness's `tool_use_id`. */\nconst OFFER_PREFIX = 'offer-';\n/** The session's own liveness touch, likewise outside the call-record pattern. */\nconst SESSION_FILE = 'session.json';\n/** A pre-call redirect, one file per agent and target in the session. */\nconst REDIRECT_PREFIX = 'redirect-';\n/** A search the pre-call hook noted a free lookup on, keyed by its `tool_use_id`. */\nconst NOTE_PREFIX = 'note-';\n/** One agent's search query that was noted, one file per window, so the same\n * one is not noted twice. */\nconst QUERY_PREFIX = 'query-';\n/** Call records are named by a 64-hex digest and nothing else is read as one. */\nconst CALL_FILE_RE = /^[a-f0-9]{64}\\.json$/;\n\n/** An in-flight call older than this is shown as stale, never as running. */\nexport const STALE_AFTER_MS = 90_000;\n/**\n * How long a state stays on the footer once nothing has replaced it. The demo\n * holds each one for about ten seconds, which is what makes a decision that\n * takes a second readable at a one-second refresh; after that the line is\n * `x402 · ready` again.\n */\nexport const RECENT_MS = 10_000;\n/** Older than this and a record is ignored by the renderer and pruned on write. */\nexport const EXPIRY_MS = 10 * 60_000;\n/** How recently a session must have been touched to claim an id-less request. */\nexport const SESSION_ACTIVE_MS = 10 * 60_000;\n/** How long one agent's identical search is not given the same note again. */\nexport const NOTE_REPEAT_MS = 5 * 60_000;\n/** Above this many files a session directory is reported rather than scanned. */\nconst MAX_RECORDS = 256;\n/** A ceiling on the root scan. {@link pruneSessions} keeps it far below this:\n * a directory is one LIVE session, not one session this machine ever had. */\nconst MAX_SESSIONS = 4_096;\n/** A record larger than this is damaged or not ours; it is skipped unread. */\nconst MAX_RECORD_BYTES = 4_096;\n/** An offer id as a record keeps one: the server's opaque handle. */\nconst OFFER_ID_RE = /^[\\w.:-]{1,200}$/;\n\nexport type ProgressPhase = 'routing' | 'calling' | 'done';\n\n/** The two markers: a session's liveness touch and a decision-id binding. */\ninterface Stamp {\n version: 1;\n at: number;\n}\n\n/** What one call looks like on disk. Every string is already masked and bounded. */\ninterface SavedProgress extends Stamp {\n phase: ProgressPhase;\n /** The tool whose activity this is, as the footer names it. */\n operation: string;\n /** What the state SAYS: the outcome on `done`, and on an in-flight record the\n * stage, when it is not the tool's own `selecting service`. */\n outcome?: string;\n /** Host plus path of the provider actually called, without a scheme. */\n endpoint?: string;\n /** The service's display name as the server gave it. */\n label?: string;\n /** The call's parameters as compact JSON. */\n parameters?: string;\n /** What the provider was paid, as USD. */\n price?: string;\n}\n\n/**\n * THE NOTE RECORD, one per WebSearch the pre-call hook let run with a free\n * offer, keyed by its `tool_use_id`: the offer's id and the server's line,\n * which the after-call hook shows once the search has run. The CLI's alone:\n * the mod draws nothing on the search.\n */\ninterface SavedNote extends Stamp {\n offerId: string;\n line: string;\n}\n\n/** What a note record names: the offer and its line. */\nexport interface NotedOffer {\n offerId: string;\n line: string;\n}\n\n/**\n * THE OFFER RECORD, one per native call a hook redirected, keyed by its\n * `tool_use_id`: when it was made, the offer's id, its `label` when the\n * decision carried one, and its price in atomic USDC. Part of the state\n * contract between this CLI and the plugin's mod (`mod-state.ts`), which reads\n * it to draw the redirected row and to find the `request` call that takes the\n * offer up by its id; it never parses the reason the model read. Version 1\n * grows by optional fields only, so a reader ignores one it does not know, and\n * an older CLI's prune still reads it as a record.\n */\ninterface SavedOffer extends Stamp {\n offerId?: string;\n label?: string;\n priceAtomic?: string;\n}\n\n/** What the offer record names: the offer's id, display name and price. */\nexport interface OfferedTerms {\n offerId?: string;\n label?: string;\n priceAtomic: string;\n}\n\nexport interface ProgressStep {\n phase: ProgressPhase;\n operation?: string;\n outcome?: string;\n /** The executed provider's URL. It can differ from the hint's suggestion. */\n provider?: string;\n /** The service's display name, from its decision, shown in place of the URL. */\n label?: string;\n parameters?: unknown;\n price?: string;\n}\n\nconst digest = (value: string): string => createHash('sha256').update(value).digest('hex');\n\nfunction bounded(value: string, limit: number): string {\n const chars = Array.from(value);\n return chars.length <= limit ? value : `${chars.slice(0, limit - 1).join('')}…`;\n}\n\n/**\n * Provider text reaches a terminal here, so it is treated as hostile: control\n * characters, format characters and directional overrides are replaced before\n * anything is written, and again before anything is printed. A footer that can\n * be made to repaint the line above it is a spoofing surface, not a display.\n */\nexport function sanitize(value: string, limit: number): string {\n return bounded(\n value\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim(),\n limit,\n );\n}\n\n/**\n * The CLI's own redaction, behind a dynamic import ON PURPOSE: the rule corpus\n * and the BIP-39 wordlist are a real parse cost, the renderer runs once a\n * second, and only the write path needs them. `dist-chunks.test.ts` pins it.\n */\nasync function clean(value: string, limit: number): Promise<string> {\n const { mask } = await import('../lib/redact');\n return sanitize(mask(value), limit);\n}\n\n/** Host plus path, which is what names a provider to a person watching. */\nasync function endpointOf(value: string): Promise<string> {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return 'invalid endpoint';\n }\n if (url.username !== '' || url.password !== '') return 'invalid endpoint';\n return clean(`${url.host}${url.pathname === '/' ? '' : url.pathname}`, 110);\n}\n\nasync function parametersOf(value: unknown): Promise<string | undefined> {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n return json === undefined ? undefined : clean(json, 180);\n}\n\nexport function sessionDir(dataDir: string, sessionId: string): string {\n return join(dataDir, PROGRESS_DIR, digest(sessionId));\n}\n\n/** A fresh key for one call, so two overlapping lookups never share a record. */\nexport function newCallId(): string {\n return randomUUID();\n}\n\n/**\n * Mark this session live, so an id-less tool call made from it can be\n * attributed. Written on every hook event, including the ones that route\n * nothing: an open session has to be distinguishable from a closed one.\n */\nexport async function noteSession(\n dataDir: string,\n sessionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), SESSION_FILE), { version: 1, at: now });\n}\n\n/** Record that this decision id was produced in this session. */\nexport async function bindDecision(\n dataDir: string,\n sessionId: string,\n decisionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${BINDING_PREFIX}${digest(decisionId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\n/**\n * ONE ROUTING ANSWER PER LOOKUP. The pre-call hook marks the native call it\n * redirected, by the harness's own `tool_use_id`, and the after-call hook reads\n * the mark before it asks again about the same call. Expires and is pruned like every\n * other record here.\n */\nexport async function markOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n offer: OfferedTerms,\n now = Date.now(),\n): Promise<void> {\n const saved: SavedOffer = {\n version: 1,\n at: now,\n ...(offer.offerId !== undefined && OFFER_ID_RE.test(offer.offerId)\n ? { offerId: offer.offerId }\n : {}),\n ...(offer.label !== undefined ? { label: sanitize(offer.label, 32) } : {}),\n ...(/^\\d{1,78}$/.test(offer.priceAtomic) ? { priceAtomic: offer.priceAtomic } : {}),\n };\n await write(\n join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`),\n saved,\n );\n}\n\nexport async function wasOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<boolean> {\n const path = join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`);\n const stamp = await readStamp(path);\n return stamp !== null && now - stamp.at <= EXPIRY_MS;\n}\n\n/**\n * A FREE LOOKUP NOTED ON A SEARCH. The pre-call hook keeps the server's line\n * under the harness's own `tool_use_id`, for the after-call hook to show once\n * the search has run. False when nothing was written: the offer id is not an\n * id, the record would pass the 4,096-byte bound every read here holds, or\n * the write failed. That search then gets no line and no tail.\n */\nexport async function markNoted(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n note: NotedOffer,\n now = Date.now(),\n): Promise<boolean> {\n if (!OFFER_ID_RE.test(note.offerId) || !note.line.includes(note.offerId)) return false;\n const saved: SavedNote = { version: 1, at: now, offerId: note.offerId, line: note.line };\n if (Buffer.byteLength(JSON.stringify(saved), 'utf8') > MAX_RECORD_BYTES) return false;\n return write(notePath(dataDir, sessionId, toolUseId), saved);\n}\n\n/**\n * The note {@link markNoted} left for this call, or null: none, expired,\n * damaged, or a line that does not carry its own offer id. What is on disk is\n * input, so every field is checked again.\n */\nexport async function noteOf(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<NotedOffer | null> {\n const row = await readJson(notePath(dataDir, sessionId, toolUseId));\n const stamp = stampOf(row);\n if (row === null || stamp === null || now - stamp.at > EXPIRY_MS) return null;\n const { offerId, line } = row;\n if (typeof offerId !== 'string' || !OFFER_ID_RE.test(offerId)) return null;\n if (typeof line !== 'string' || /[\\p{Cc}\\p{Cf}]/u.test(line) || !line.includes(offerId)) {\n return null;\n }\n return { offerId, line };\n}\n\nfunction notePath(dataDir: string, sessionId: string, toolUseId: string): string {\n return join(sessionDir(dataDir, sessionId), `${NOTE_PREFIX}${digest(toolUseId)}.json`);\n}\n\n/**\n * ONE NOTE PER QUERY. True, once, when this agent has not had this exact\n * search noted in the last {@link NOTE_REPEAT_MS}, and the claim is now its.\n * The same window-named exclusive create as {@link claimRedirect}, so two\n * parallel copies of one search get one note, after the window too.\n */\nexport async function claimNote(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n query: string,\n now = Date.now(),\n): Promise<boolean> {\n return claimOnce(\n (window) => {\n const key = digest(JSON.stringify([agentId ?? '', query, window]));\n return join(sessionDir(dataDir, sessionId), `${QUERY_PREFIX}${key}.json`);\n },\n NOTE_REPEAT_MS,\n now,\n );\n}\n\n/**\n * ONE RECORD PER AGENT, TARGET AND WINDOW. Subagents share the session id, so\n * the agent is in the key, and the main agent's part is the empty string, which\n * no `agent_id` can be: the decoder refuses an empty one. The target is in it\n * too, one file each, so parallel calls never share a record: one call's\n * redirect can be neither overwritten nor spent by another's. And so is the\n * {@link EXPIRY_MS} window the claim was made in, so a claim is only ever\n * created, never replaced: see {@link claimRedirect}.\n */\nfunction redirectPath(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n window: number,\n): string {\n const key = digest(JSON.stringify([agentId ?? '', target, window]));\n return join(sessionDir(dataDir, sessionId), `${REDIRECT_PREFIX}${key}.json`);\n}\n\n/**\n * NEVER REDIRECTED TWICE FOR ONE TARGET. True, once, when this agent has not\n * been redirected on this exact search or URL in the last {@link EXPIRY_MS},\n * and the claim is now its; the pre-call hook denies only on true. So the\n * agent's own retry of a redirected call runs, whether the lookup it was sent\n * to delivered, failed or was never called, and whatever other calls ran in\n * between.\n *\n * ONLY EVER AN EXCLUSIVE CREATE. Replacing an expired claim let two parallel\n * copies of one call both read the old stamp and both write, and both deny.\n * The claim's file is named by its window instead, so the one create per\n * window decides, and the previous window's claim, while it is still inside\n * {@link EXPIRY_MS}, is read and never touched: a claim made just before a\n * boundary still lasts its full span. A claim that cannot be written is false:\n * the call runs.\n */\nexport async function claimRedirect(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n now = Date.now(),\n): Promise<boolean> {\n return claimOnce(\n (window) => redirectPath(dataDir, sessionId, agentId, target, window),\n EXPIRY_MS,\n now,\n );\n}\n\n/**\n * The one create both claims make: the file named by the `span` window `now`\n * falls in, refused while the previous window's claim is inside its span. A\n * claim that cannot be written is false.\n */\nasync function claimOnce(\n pathFor: (window: number) => string,\n span: number,\n now: number,\n): Promise<boolean> {\n const window = Math.floor(now / span);\n const previous = await readStamp(pathFor(window - 1));\n if (previous !== null && now - previous.at <= span) return false;\n const stamp: Stamp = { version: 1, at: now };\n try {\n await writeFileAtomicExclusive(pathFor(window), JSON.stringify(stamp), {\n mode: 0o600,\n dirMode: 0o700,\n });\n return true;\n } catch {\n // Taken in this window, which is always inside the span, or not writable.\n return false;\n }\n}\n\n/**\n * THE READ HALF OF {@link claimRedirect}: true when this agent already holds a\n * live claim on this exact search or URL. The pre-call arms ask it BEFORE the\n * router, so the retry of a call they already redirected, which they would\n * only withhold, costs no decision and leaves no offer nobody sees. It never\n * writes and never decides on its own: a false here still goes through the\n * exclusive create, which is what keeps two parallel copies to one deny.\n */\nexport async function redirectClaimed(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n now = Date.now(),\n): Promise<boolean> {\n const window = Math.floor(now / EXPIRY_MS);\n for (const at of [window, window - 1]) {\n const stamp = await readStamp(redirectPath(dataDir, sessionId, agentId, target, at));\n if (stamp !== null && now - stamp.at <= EXPIRY_MS) return true;\n }\n return false;\n}\n\n/**\n * Which session directory a tool call belongs to, or null for \"cannot tell\".\n * Null is a normal answer and its only consequence is a footer that stays quiet.\n */\nexport async function resolveProgressSession(\n dataDir: string,\n opts: { id?: string; now?: number } = {},\n): Promise<string | null> {\n const now = opts.now ?? Date.now();\n const root = join(dataDir, PROGRESS_DIR);\n let names: string[];\n try {\n const directory = await opendir(root);\n names = [];\n for await (const entry of directory) {\n if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) names.push(entry.name);\n if (names.length >= MAX_SESSIONS) break;\n }\n } catch {\n return null;\n }\n if (opts.id !== undefined && opts.id.length > 0) {\n const marker = `${BINDING_PREFIX}${digest(opts.id)}.json`;\n for (const name of names) {\n const bound = await readStamp(join(root, name, marker));\n if (bound !== null && now - bound.at <= EXPIRY_MS) return join(root, name);\n }\n // A stale or unknown id says nothing about which session asked, so the\n // sole-activity rule below still applies rather than a wrong attribution.\n }\n const live: string[] = [];\n for (const name of names) {\n const touched = await readStamp(join(root, name, SESSION_FILE));\n if (touched !== null && now - touched.at <= SESSION_ACTIVE_MS) live.push(name);\n if (live.length > 1) return null;\n }\n return live.length === 1 ? join(root, live[0] as string) : null;\n}\n\n/**\n * Record one step of one call. The caller holds the directory (from\n * {@link sessionDir} or {@link resolveProgressSession}) and the call id, so a\n * step never has to re-resolve anything on the hot path.\n */\nexport async function writeProgress(\n directory: string,\n callId: string,\n step: ProgressStep,\n now = Date.now(),\n): Promise<void> {\n const endpoint = step.provider === undefined ? undefined : await endpointOf(step.provider);\n const parameters =\n step.parameters === undefined ? undefined : await parametersOf(step.parameters);\n const saved: SavedProgress = {\n version: 1,\n at: now,\n phase: step.phase,\n operation: sanitize(step.operation ?? 'request', 24) || 'request',\n ...(step.outcome !== undefined ? { outcome: sanitize(step.outcome, 40) } : {}),\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(step.label !== undefined ? { label: sanitize(step.label, 32) } : {}),\n ...(parameters !== undefined ? { parameters } : {}),\n ...(step.price !== undefined ? { price: sanitize(step.price, 24) } : {}),\n };\n await write(join(directory, `${digest(callId)}.json`), saved);\n}\n\nexport interface LookupFooter {\n /** A decision is in flight. */\n routing(): Promise<void>;\n /** The EXECUTED provider, which can differ from what the hint suggested. */\n calling(step: { provider: string; label?: string; parameters?: unknown }): Promise<void>;\n /** The outcome, and what the provider was paid for it. */\n done(\n outcome: string,\n step?: { provider?: string; label?: string; parameters?: unknown; price?: string },\n ): Promise<void>;\n}\n\n/** A footer for a session this call cannot be attributed to, or for one step\n * of a call whose own footer speaks for it: it writes nothing. */\nexport const SILENT_FOOTER: LookupFooter = {\n routing: async () => undefined,\n calling: async () => undefined,\n done: async () => undefined,\n};\n\n/**\n * The `request` tool's footer: the session is resolved ONCE, at the top of the\n * call, and each later step is one small write. An unresolvable session yields\n * {@link SILENT_FOOTER}, and the lookup runs exactly as it would have.\n */\nexport async function openLookupFooter(\n dataDir: string,\n opts: { id?: string; operation?: string; now?: () => number } = {},\n): Promise<LookupFooter> {\n const now = opts.now ?? Date.now;\n const directory = await resolveProgressSession(dataDir, {\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n now: now(),\n }).catch(() => null);\n if (directory === null) return SILENT_FOOTER;\n const callId = newCallId();\n const operation = opts.operation ?? 'request';\n const step = async (patch: ProgressStep): Promise<void> => {\n await writeProgress(directory, callId, { operation, ...patch }, now());\n };\n return {\n routing: async () => {\n await step({ phase: 'routing' });\n await pruneProgress(directory, now());\n },\n calling: async (calling) => step({ phase: 'calling', ...calling }),\n done: async (outcome, detail) => step({ phase: 'done', outcome, ...detail }),\n };\n}\n\n/**\n * Remove records past {@link EXPIRY_MS}. Run from a writer, never from the\n * renderer: the footer refreshes once a second and must stay read-only.\n */\nexport async function pruneProgress(directory: string, now = Date.now()): Promise<void> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const path = join(directory, entry.name);\n const record = agesByMtime(entry.name) ? await mtimeOf(path) : await readStamp(path);\n if (record === null || now - record.at > EXPIRY_MS) {\n await rm(path, { force: true }).catch(() => undefined);\n }\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\n/**\n * A FILE THAT IS NOT A WHOLE RECORD is aged by its mtime, never read as one: a\n * temp file between its write and its rename (every writer here names them\n * `.<name>.<suffix>`). Read as a record it is damaged, and the prune deleted\n * it out from under a parallel hook's rename. A docs body an older build left\n * (`augment-*.docs`) reads as damaged, and goes.\n */\nfunction agesByMtime(name: string): boolean {\n return name.startsWith('.');\n}\n\nasync function mtimeOf(path: string): Promise<Stamp | null> {\n try {\n return { version: 1, at: (await lstat(path)).mtimeMs };\n } catch {\n return null;\n }\n}\n\n/**\n * Remove the directories of sessions that are over.\n *\n * WITHOUT THIS THE ROOT ONLY GROWS, one directory per session this machine has\n * ever had, and a root big enough to hit {@link MAX_SESSIONS} would leave\n * {@link resolveProgressSession} scanning an arbitrary subset that need not\n * contain the session asking. Run from the hook, which is the one writer that\n * fires on every turn; a directory whose session is still live is never touched.\n */\nexport async function pruneSessions(dataDir: string, now = Date.now()): Promise<void> {\n const root = join(dataDir, PROGRESS_DIR);\n try {\n const directory = await opendir(root);\n let seen = 0;\n for await (const entry of directory) {\n if (++seen > MAX_SESSIONS) return;\n if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;\n const path = join(root, entry.name);\n const session = await readStamp(join(path, SESSION_FILE));\n if (session !== null && now - session.at <= SESSION_ACTIVE_MS) continue;\n // The touch is gone or old, so the only thing that can keep this\n // directory is a record still inside the renderer's window.\n if (await hasLiveRecord(path, now)) continue;\n await rm(path, { recursive: true, force: true }).catch(() => undefined);\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\nasync function hasLiveRecord(directory: string, now: number): Promise<boolean> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return true;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const record = await readStamp(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) return true;\n }\n } catch {\n return true;\n }\n return false;\n}\n\n/**\n * The footer for one session: one line, bounded, sanitized, and empty of\n * everything but this session's own calls. Read-only by construction.\n */\nexport async function renderProgress(\n dataDir: string,\n sessionId: string,\n options: { now?: number; columns?: number } = {},\n): Promise<string> {\n const now = options.now ?? Date.now();\n // The harness truncates to the real terminal width, and `COLUMNS` rarely\n // survives into a status-line process, so the default is a wide terminal\n // rather than a narrow one: cutting a provider's path off at 80 columns on a\n // 200-column terminal loses exactly the part worth reading.\n const columns = Math.max(45, Math.min(400, options.columns || 160));\n const directory = sessionDir(dataDir, sessionId);\n const records: SavedProgress[] = [];\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return bounded('x402 · activity exceeds display limit', columns);\n if (!entry.isFile() || !CALL_FILE_RE.test(entry.name)) continue;\n const record = await readCall(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) records.push(record);\n }\n } catch (error) {\n // A SESSION WITH NO DIRECTORY IS IDLE, not broken: it has simply not looked\n // anything up yet, and the router being on is the thing the idle line says.\n // Any OTHER read failure is this display failing, and a display that failed\n // prints nothing rather than a status it did not read.\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? READY : '';\n }\n const running = records\n .filter((row) => row.phase !== 'done' && now - row.at <= holdMs(row))\n .sort((a, b) => b.at - a.at);\n // Only a LOOKUP goes stale out loud. A hook decision has a five-second budget,\n // so one still in flight after its hold is a dead hook, and the footer says\n // ready rather than naming a stage nothing is working on.\n const stale = records.filter(\n (row) => row.phase !== 'done' && now - row.at > holdMs(row) && row.operation === 'request',\n );\n const finished = records\n .filter((row) => row.phase === 'done' && now - row.at <= RECENT_MS)\n .sort((a, b) => b.at - a.at);\n const head = running[0] ?? finished[0] ?? stale.sort((a, b) => b.at - a.at)[0];\n if (head === undefined) return READY;\n // OVERLAPPING CALLS ARE COUNTED, NOT HIDDEN. The newest running call is the\n // one worth naming; the rest are a count, because a second endpoint and its\n // parameters do not fit a line beside the first.\n const alsoRunning = running.length - (running[0] === head ? 1 : 0);\n const suffix = alsoRunning > 0 ? ` · +${alsoRunning} more` : '';\n return bounded(`${line(head, now)}${suffix}`, columns);\n}\n\n/** What the footer says when this session has nothing running or just finished.\n * It is the visible proof that the router is on, so it is never blank. */\nconst READY = 'x402 · ready';\n\n/**\n * How long this state holds the line. A lookup in flight holds it until it\n * lands, because a provider call can take a minute; everything else holds it\n * for {@link RECENT_MS}, which is how the demo reads: one state per second or\n * so, each one still there when the next arrives.\n */\nfunction holdMs(row: SavedProgress): number {\n return row.phase !== 'done' && row.operation === 'request' ? STALE_AFTER_MS : RECENT_MS;\n}\n\n/**\n * One call, as the footer says it: `x402 · <tool>: <state> <label or host/path>\n * · <parameters> · <price>`. Every field is sanitized AGAIN here, because what is\n * on disk is input to this process even when this process wrote it.\n */\nfunction line(row: SavedProgress, now: number): string {\n const operation = sanitize(row.operation, 24) || 'request';\n if (row.phase !== 'done' && now - row.at > STALE_AFTER_MS) {\n return `x402 · ${operation}: stale, no outcome recorded`;\n }\n // `selecting service` is the demo's own word for a decision in flight, and a\n // stage the hook names for itself wins over it.\n const state =\n row.phase === 'routing'\n ? sanitize(row.outcome ?? 'selecting service', 40)\n : row.phase === 'calling'\n ? 'calling'\n : sanitize(row.outcome ?? 'done', 40);\n return (\n `x402 · ${operation}: ${state}` +\n // The service's name where its decision gave one, else the URL called.\n (row.label !== undefined\n ? ` ${sanitize(row.label, 32)}`\n : row.endpoint !== undefined\n ? ` ${sanitize(row.endpoint, 110)}`\n : '') +\n (row.parameters !== undefined ? ` · ${sanitize(row.parameters, 180)}` : '') +\n (row.price !== undefined ? ` · ${sanitize(row.price, 24)}` : '')\n );\n}\n\n/** Whether it landed. Every caller but the note record ignores the answer. */\nasync function write(path: string, body: Stamp | SavedProgress | SavedNote): Promise<boolean> {\n try {\n await writeFileAtomic(path, JSON.stringify(body), { mode: 0o600, dirMode: 0o700 });\n return true;\n } catch {\n // The footer is the only thing that can be lost here, by design.\n return false;\n }\n}\n\n/** A marker's timestamp, or null for absent, damaged or not ours. */\nasync function readStamp(path: string): Promise<Stamp | null> {\n return stampOf(await readJson(path));\n}\n\nfunction stampOf(row: Record<string, unknown> | null): Stamp | null {\n if (row === null) return null;\n return row.version === 1 && typeof row.at === 'number' && Number.isFinite(row.at)\n ? { version: 1, at: row.at }\n : null;\n}\n\n/** A call record, or null. Every field is re-checked: what is on disk is input. */\nasync function readCall(path: string): Promise<SavedProgress | null> {\n const row = await readJson(path);\n const stamp = stampOf(row);\n if (row === null || stamp === null || typeof row.operation !== 'string') return null;\n if (!['routing', 'calling', 'done'].includes(row.phase as string)) return null;\n const optional = ['outcome', 'endpoint', 'label', 'parameters', 'price'] as const;\n if (!optional.every((key) => row[key] === undefined || typeof row[key] === 'string')) return null;\n return {\n ...stamp,\n phase: row.phase as ProgressPhase,\n operation: row.operation,\n ...Object.fromEntries(\n optional.filter((key) => row[key] !== undefined).map((key) => [key, row[key]]),\n ),\n };\n}\n\n/**\n * One bounded JSON object, or null. `O_NOFOLLOW` because these files live under\n * a directory the user can write: a symlink planted here must not turn a footer\n * read into a read of something else.\n */\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => undefined);\n if (file === undefined) return null;\n try {\n if ((await file.stat()).size > MAX_RECORD_BYTES) return null;\n const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_RECORD_BYTES) return null;\n const parsed: unknown = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));\n return parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)\n ? null\n : (parsed as Record<string, unknown>);\n } catch {\n return null;\n } finally {\n await file.close().catch(() => undefined);\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,YAAY,kBAAkB;AACvC,SAAS,iBAAiB;AAC1B,SAAS,OAAO,MAAM,SAAS,UAAU;AACzC,SAAS,YAAY;AAiCrB,IAAM,eAAe;AAErB,IAAM,iBAAiB;AAEvB,IAAM,eAAe;AAErB,IAAM,eAAe;AAErB,IAAM,kBAAkB;AAExB,IAAM,cAAc;AAGpB,IAAM,eAAe;AAErB,IAAM,eAAe;AAGd,IAAM,iBAAiB;AAOvB,IAAM,YAAY;AAElB,IAAM,YAAY,KAAK;AAEvB,IAAM,oBAAoB,KAAK;AAE/B,IAAM,iBAAiB,IAAI;AAElC,IAAM,cAAc;AAGpB,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAEzB,IAAM,cAAc;AAgFpB,IAAM,SAAS,CAAC,UAA0B,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK;AAEzF,SAAS,QAAQ,OAAe,OAAuB;AACrD,QAAM,QAAQ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