tenjin-cli 0.1.0-alpha.11 → 0.1.0-alpha.13
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 +236 -596
- package/dist/{buy-THMVOPUH.js → buy-X4VPHFUA.js} +20 -20
- package/dist/{chunk-GKV6VZSZ.js → chunk-3NZCU6SD.js} +7 -7
- package/dist/chunk-3NZCU6SD.js.map +1 -0
- package/dist/{chunk-Y7ERTA7D.js → chunk-3P3ES4XU.js} +4 -6
- package/dist/chunk-3P3ES4XU.js.map +1 -0
- package/dist/{chunk-OZHJ3FLR.js → chunk-47YKYDOF.js} +5 -5
- package/dist/{chunk-IXTENA2H.js → chunk-6JKD46OJ.js} +12 -10
- package/dist/{chunk-IXTENA2H.js.map → chunk-6JKD46OJ.js.map} +1 -1
- package/dist/chunk-736DW4V3.js +65 -0
- package/dist/chunk-736DW4V3.js.map +1 -0
- package/dist/{chunk-IB63U6BM.js → chunk-B676GPS2.js} +34 -11
- package/dist/chunk-B676GPS2.js.map +1 -0
- package/dist/{chunk-4NTZETIL.js → chunk-BRAVLUGI.js} +2 -2
- package/dist/{chunk-UY6CGULW.js → chunk-CA3JV7FX.js} +2 -2
- package/dist/{chunk-UY6CGULW.js.map → chunk-CA3JV7FX.js.map} +1 -1
- package/dist/{chunk-ALUNME53.js → chunk-ELVDOTU7.js} +50 -66
- package/dist/chunk-ELVDOTU7.js.map +1 -0
- package/dist/{chunk-IAFYUFIC.js → chunk-GCGMXA2O.js} +13 -11
- package/dist/{chunk-IAFYUFIC.js.map → chunk-GCGMXA2O.js.map} +1 -1
- package/dist/{chunk-XWHXX2BI.js → chunk-IAR25V2E.js} +6 -6
- package/dist/{chunk-6UY2UQMY.js → chunk-IFPKA32J.js} +4 -4
- package/dist/{chunk-JTYIX6OD.js → chunk-IGHSLJUF.js} +6 -4
- package/dist/{chunk-JTYIX6OD.js.map → chunk-IGHSLJUF.js.map} +1 -1
- package/dist/{chunk-2SDUV6MQ.js → chunk-IKAJSA7E.js} +12 -10
- package/dist/{chunk-2SDUV6MQ.js.map → chunk-IKAJSA7E.js.map} +1 -1
- package/dist/{chunk-NUF2PKJO.js → chunk-J6FUAIRR.js} +4 -6
- package/dist/{chunk-NUF2PKJO.js.map → chunk-J6FUAIRR.js.map} +1 -1
- package/dist/{chunk-CNUXRXI2.js → chunk-JVBMPU5G.js} +5 -7
- package/dist/{chunk-CNUXRXI2.js.map → chunk-JVBMPU5G.js.map} +1 -1
- package/dist/{chunk-VWY3U732.js → chunk-L4XNT3UW.js} +21 -16
- package/dist/chunk-L4XNT3UW.js.map +1 -0
- package/dist/{chunk-EDVI7RRD.js → chunk-NKN4YC5C.js} +6 -6
- package/dist/{chunk-EDVI7RRD.js.map → chunk-NKN4YC5C.js.map} +1 -1
- package/dist/{chunk-P74I3WH4.js → chunk-OC3EIDCP.js} +3 -5
- package/dist/{chunk-P74I3WH4.js.map → chunk-OC3EIDCP.js.map} +1 -1
- package/dist/{chunk-E6YOODH7.js → chunk-OE36HRWG.js} +31 -5
- package/dist/{chunk-E6YOODH7.js.map → chunk-OE36HRWG.js.map} +1 -1
- package/dist/chunk-OUJDDY5L.js +189 -0
- package/dist/chunk-OUJDDY5L.js.map +1 -0
- package/dist/{chunk-6BGYHARE.js → chunk-OWVVI4VQ.js} +15 -15
- package/dist/{chunk-4TCU3YRD.js → chunk-OXUJ3FXU.js} +5 -1
- package/dist/{chunk-4TCU3YRD.js.map → chunk-OXUJ3FXU.js.map} +1 -1
- package/dist/{chunk-PZRAAAY2.js → chunk-PAOVPSP6.js} +10 -3
- package/dist/chunk-PAOVPSP6.js.map +1 -0
- package/dist/{chunk-3GSZUADW.js → chunk-SPUORKD7.js} +3 -3
- package/dist/{chunk-UFPJBS4C.js → chunk-T4UWMVKV.js} +9 -7
- package/dist/{chunk-UFPJBS4C.js.map → chunk-T4UWMVKV.js.map} +1 -1
- package/dist/{chunk-GUUAYR3K.js → chunk-TXVC46SA.js} +8 -8
- package/dist/chunk-TXVC46SA.js.map +1 -0
- package/dist/{chunk-SFGXAZ3M.js → chunk-UUARTUY2.js} +42 -9
- package/dist/chunk-UUARTUY2.js.map +1 -0
- package/dist/{chunk-ZE7KOO7A.js → chunk-WMFRCSNC.js} +8 -8
- package/dist/{chunk-TDDN5GXR.js → chunk-WU5CZPLD.js} +5 -5
- package/dist/{chunk-RSBN67PA.js → chunk-WVHPGQH5.js} +4 -6
- package/dist/{chunk-RSBN67PA.js.map → chunk-WVHPGQH5.js.map} +1 -1
- package/dist/{chunk-PZSUWDF2.js → chunk-XGZ5EVMB.js} +2 -2
- package/dist/{chunk-O25VWJCG.js → chunk-XXY77EZJ.js} +24 -24
- package/dist/{chunk-OCN27NJV.js → chunk-YMUJZWHB.js} +10 -8
- package/dist/{chunk-OCN27NJV.js.map → chunk-YMUJZWHB.js.map} +1 -1
- package/dist/{cli-Y2HBOSGK.js → cli-XK5JZWU6.js} +51 -146
- package/dist/cli-XK5JZWU6.js.map +1 -0
- package/dist/{config-WDGMZKHU.js → config-CNK7MYUR.js} +7 -7
- package/dist/doctor-R7N7FUX5.js +27 -0
- package/dist/{edit-E7N6F3OY.js → edit-QSUEG7CL.js} +19 -19
- package/dist/{fund-OKK627GL.js → fund-JF6A76YS.js} +16 -16
- package/dist/index.js +1 -1
- package/dist/{inspect-573WHEV4.js → inspect-NFNAA4LA.js} +17 -17
- package/dist/{install-SQAYMNQC.js → install-YQVM3SUW.js} +20 -21
- package/dist/{install-SQAYMNQC.js.map → install-YQVM3SUW.js.map} +1 -1
- package/dist/outcome-IUSYFJTN.js +22 -0
- package/dist/{publish-N5U4XYVA.js → publish-O2I6IAEL.js} +20 -20
- package/dist/{read-PJ7Z6UGF.js → read-UF7QVQOU.js} +21 -21
- package/dist/{run-FSO3MMXN.js → run-GDZWHNWZ.js} +30 -30
- package/dist/search-JVOHEF3E.js +23 -0
- package/dist/{send-F34ZDXDZ.js → send-SI254H3R.js} +11 -10
- package/dist/{send-F34ZDXDZ.js.map → send-SI254H3R.js.map} +1 -1
- package/dist/{session-4N4ZT3AH.js → session-GJZJEXLJ.js} +14 -14
- package/dist/{skill-heal-XBEK272G.js → skill-heal-BPFT22XS.js} +5 -6
- package/dist/{skill-heal-XBEK272G.js.map → skill-heal-BPFT22XS.js.map} +1 -1
- package/dist/{uninstall-BTKPHPDL.js → uninstall-7ZZG6WQ5.js} +6 -7
- package/dist/{uninstall-BTKPHPDL.js.map → uninstall-7ZZG6WQ5.js.map} +1 -1
- package/dist/update-FPSBITLB.js +315 -0
- package/dist/update-FPSBITLB.js.map +1 -0
- package/dist/{wallet-UL4P2JRO.js → wallet-NS7TYWNN.js} +5 -6
- package/dist/{wallet-WJ6UP5OU.js → wallet-TZVD2M4I.js} +9 -9
- package/docs/agent-permissions.md +13 -2
- package/docs/command-reference.md +251 -0
- package/docs/safety-model.md +45 -0
- package/package.json +1 -1
- package/skills/tenjin/SKILL.md +3 -3
- package/skills/tenjin-publish/SKILL.md +27 -11
- package/skills/tenjin-search/SKILL.md +14 -13
- package/dist/chunk-2I4QTOLB.js +0 -11
- package/dist/chunk-2I4QTOLB.js.map +0 -1
- package/dist/chunk-ALUNME53.js.map +0 -1
- package/dist/chunk-GKV6VZSZ.js.map +0 -1
- package/dist/chunk-GUUAYR3K.js.map +0 -1
- package/dist/chunk-IB63U6BM.js.map +0 -1
- package/dist/chunk-PZRAAAY2.js.map +0 -1
- package/dist/chunk-SFGXAZ3M.js.map +0 -1
- package/dist/chunk-VWY3U732.js.map +0 -1
- package/dist/chunk-Y7ERTA7D.js.map +0 -1
- package/dist/cli-Y2HBOSGK.js.map +0 -1
- package/dist/doctor-CSIWKWM2.js +0 -27
- package/dist/outcome-W3KYGF23.js +0 -22
- package/dist/search-ZWOP4EGK.js +0 -23
- /package/dist/{buy-THMVOPUH.js.map → buy-X4VPHFUA.js.map} +0 -0
- /package/dist/{chunk-OZHJ3FLR.js.map → chunk-47YKYDOF.js.map} +0 -0
- /package/dist/{chunk-4NTZETIL.js.map → chunk-BRAVLUGI.js.map} +0 -0
- /package/dist/{chunk-XWHXX2BI.js.map → chunk-IAR25V2E.js.map} +0 -0
- /package/dist/{chunk-6UY2UQMY.js.map → chunk-IFPKA32J.js.map} +0 -0
- /package/dist/{chunk-6BGYHARE.js.map → chunk-OWVVI4VQ.js.map} +0 -0
- /package/dist/{chunk-3GSZUADW.js.map → chunk-SPUORKD7.js.map} +0 -0
- /package/dist/{chunk-ZE7KOO7A.js.map → chunk-WMFRCSNC.js.map} +0 -0
- /package/dist/{chunk-TDDN5GXR.js.map → chunk-WU5CZPLD.js.map} +0 -0
- /package/dist/{chunk-PZSUWDF2.js.map → chunk-XGZ5EVMB.js.map} +0 -0
- /package/dist/{chunk-O25VWJCG.js.map → chunk-XXY77EZJ.js.map} +0 -0
- /package/dist/{config-WDGMZKHU.js.map → config-CNK7MYUR.js.map} +0 -0
- /package/dist/{doctor-CSIWKWM2.js.map → doctor-R7N7FUX5.js.map} +0 -0
- /package/dist/{edit-E7N6F3OY.js.map → edit-QSUEG7CL.js.map} +0 -0
- /package/dist/{fund-OKK627GL.js.map → fund-JF6A76YS.js.map} +0 -0
- /package/dist/{inspect-573WHEV4.js.map → inspect-NFNAA4LA.js.map} +0 -0
- /package/dist/{outcome-W3KYGF23.js.map → outcome-IUSYFJTN.js.map} +0 -0
- /package/dist/{publish-N5U4XYVA.js.map → publish-O2I6IAEL.js.map} +0 -0
- /package/dist/{read-PJ7Z6UGF.js.map → read-UF7QVQOU.js.map} +0 -0
- /package/dist/{run-FSO3MMXN.js.map → run-GDZWHNWZ.js.map} +0 -0
- /package/dist/{search-ZWOP4EGK.js.map → search-JVOHEF3E.js.map} +0 -0
- /package/dist/{session-4N4ZT3AH.js.map → session-GJZJEXLJ.js.map} +0 -0
- /package/dist/{wallet-UL4P2JRO.js.map → wallet-NS7TYWNN.js.map} +0 -0
- /package/dist/{wallet-WJ6UP5OU.js.map → wallet-TZVD2M4I.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
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-CA3JV7FX.js";
|
|
5
5
|
import {
|
|
6
6
|
CliError
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-PAOVPSP6.js";
|
|
8
8
|
|
|
9
9
|
// src/lib/client-meta.ts
|
|
10
10
|
var TENJIN_USER_AGENT = `tenjin-cli/${package_default.version} (+https://tenjin.blog)`;
|
|
@@ -196,4 +196,4 @@ export {
|
|
|
196
196
|
httpRequest,
|
|
197
197
|
fetchFailureToCliError
|
|
198
198
|
};
|
|
199
|
-
//# sourceMappingURL=chunk-
|
|
199
|
+
//# sourceMappingURL=chunk-SPUORKD7.js.map
|
|
@@ -12,26 +12,28 @@ import {
|
|
|
12
12
|
resolveWalletProvider,
|
|
13
13
|
restoreParkedWallet,
|
|
14
14
|
verifyAndPreserveOutgoingWallet
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-JVBMPU5G.js";
|
|
16
16
|
import {
|
|
17
17
|
walletExistsError,
|
|
18
18
|
walletFileExists
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-3P3ES4XU.js";
|
|
20
20
|
import {
|
|
21
21
|
LockTimeoutError,
|
|
22
22
|
withFileLock
|
|
23
23
|
} from "./chunk-FKSAUOJU.js";
|
|
24
24
|
import {
|
|
25
|
-
loadRawConfig,
|
|
26
|
-
resolveSettings,
|
|
27
25
|
toMoney
|
|
28
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-736DW4V3.js";
|
|
27
|
+
import {
|
|
28
|
+
loadRawConfig,
|
|
29
|
+
resolveSettings
|
|
30
|
+
} from "./chunk-ELVDOTU7.js";
|
|
29
31
|
import {
|
|
30
32
|
walletPath
|
|
31
33
|
} from "./chunk-ZQIQ55KK.js";
|
|
32
34
|
import {
|
|
33
35
|
CliError
|
|
34
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-PAOVPSP6.js";
|
|
35
37
|
|
|
36
38
|
// src/commands/wallet.ts
|
|
37
39
|
import { mkdir } from "fs/promises";
|
|
@@ -239,4 +241,4 @@ export {
|
|
|
239
241
|
runWalletShow,
|
|
240
242
|
runWalletBalance
|
|
241
243
|
};
|
|
242
|
-
//# sourceMappingURL=chunk-
|
|
244
|
+
//# sourceMappingURL=chunk-T4UWMVKV.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { walletPath } from '../lib/paths';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { getUsdcBalance } from '../lib/usdc';\nimport {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n parkOutgoingWallet,\n prepareLocalWallet,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { walletExistsError, walletFileExists } from '../lib/wallet/store';\nimport { resolvePassphraseForCreate, type PassphraseSource } from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst FUNDING_LINE =\n 'Fund it with `tenjin fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.';\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\n\nexport interface WalletCreateOptions {\n /**\n * Explicitly replace the existing active wallet (mirrors the `--yes`-style\n * explicit-flag precedent): the outgoing wallet is ARCHIVED — passphrase\n * verified against its keystore and preserved under its own address, keystore\n * parked beside the new one — never destroyed. Without it, create refuses\n * when a wallet exists. There is always exactly ONE active wallet.\n */\n replace?: boolean;\n /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /**\n * The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to\n * process.env. A seam rather than a global read so a caller (and above all a\n * test) can settle the passphrase source WITHOUT mutating the real process\n * environment, which under a parallel runner leaks across whole test files.\n */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const {\n address,\n walletPath: path,\n source,\n replaced,\n } = await createWalletLocked(ctx.dataDir, opts);\n\n const warnings = custodyWarnings();\n return {\n data: {\n address,\n walletPath: path,\n provider: 'local',\n policyEnforcement: 'client-only',\n keyStorage: KEY_STORAGE,\n passphraseSource: source,\n ...(replaced !== undefined\n ? {\n replaced: {\n address: replaced.address,\n archivedWalletPath: replaced.archivedPath,\n passphrasePreserved: replaced.passphraseLocation,\n ...(replaced.unarchivedReason !== undefined\n ? { unarchivedReason: replaced.unarchivedReason }\n : {}),\n },\n }\n : {}),\n warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n passphraseNote(source, address),\n ...(replaced !== undefined ? replacedNote(replaced, path) : []),\n FUNDING_LINE,\n ...warnings,\n ],\n };\n}\n\n/** Where the outgoing wallet's funds live, why they remain reachable, and how to restore it. */\nfunction replacedNote(replaced: ArchivedWalletInfo, activeWalletPath: string): string[] {\n const passphraseLine =\n replaced.passphraseLocation === 'store'\n ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).`\n : replaced.passphraseLocation === 'env'\n ? 'its passphrase is TENJIN_WALLET_PASSPHRASE — keep that value.'\n : replaced.unarchivedReason === 'rejected-characters'\n ? 'its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : replaced.unarchivedReason === 'no-store'\n ? 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.'\n : 'its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.';\n return [\n `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,\n `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,\n `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \\`mv ${replaced.archivedPath} ${activeWalletPath}\\`.`,\n ];\n}\n\n/**\n * Run the whole create critical section under a cross-process file lock: the\n * existence pre-check, the passphrase generate-and-store, and the no-clobber\n * write. Without the lock these interleave across two concurrent creates — each\n * generates a distinct passphrase and persists it to the OS store BEFORE the\n * exclusive file write, so a different process could win the file while this\n * one's per-address entry names a wallet that never landed. Serializing means\n * the loser blocks until the winner commits, then trips the exists check and\n * exits WALLET_EXISTS having never generated or stored a passphrase. The\n * store-before-write ordering stays (it still guards the single-process crash\n * window), and the exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * OS-store entry is keyed to the new wallet's own address (issue #32).\n *\n * `--replace` ordering closes the no-active-wallet window: verify-and-preserve\n * the outgoing wallet (no file moves), fully PREPARE the replacement (key,\n * stored passphrase, encrypted keystore — every fallible step) while the old\n * wallet is still active, and only then park the old keystore and commit the\n * new one. A commit failure rolls the park back, so at every exit either the\n * old or the new wallet is the active one.\n */\nasync function createWalletLocked(\n dir: string,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n source: PassphraseSource;\n replaced?: ArchivedWalletInfo;\n}> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write below re-ensures it at 0700 regardless.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = join(dir, 'wallet.create.lock');\n try {\n return await withFileLock(lockPath, async () => {\n const env = opts.env ?? process.env;\n let source: PassphraseSource = 'env';\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n { env, dir, ...opts.passphrase },\n forAddress,\n );\n source = resolved.source;\n return resolved.passphrase;\n };\n\n if (!(await walletFileExists(dir))) {\n const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);\n return { address, walletPath: path, source };\n }\n\n if (opts.replace !== true) throw walletExistsError(dir);\n const preserved = await verifyAndPreserveOutgoingWallet({\n dir,\n env,\n ...(opts.passphrase !== undefined ? { passphrase: opts.passphrase } : {}),\n });\n const prepared = await prepareLocalWallet(passphraseFor);\n const archivedPath = await parkOutgoingWallet(dir, preserved.account);\n try {\n const { address, walletPath: path } = await commitLocalWallet(dir, prepared);\n return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };\n } catch (err) {\n try {\n await restoreParkedWallet(dir, archivedPath);\n } catch (restoreErr) {\n // The no-clobber restore also refuses when a wallet.json appeared out\n // of band (commit EEXIST) — never overwrite it; name both files.\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.',\n {\n fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it — move it aside first. Then restore with \\`mv ${archivedPath} ${walletPath(dir)}\\`.`,\n cause: restoreErr,\n },\n );\n }\n // Old wallet restored as the active one; say so rather than surfacing a\n // raw fs error (or a WALLET_EXISTS whose fix suggests re-running --replace).\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.',\n {\n fix: 'Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.',\n cause: err,\n },\n );\n }\n });\n } catch (err) {\n // A lock timeout is not the user's error; surface it as INTERNAL with the one\n // manual step (there is no auto-steal), keeping the JSON error contract. Every\n // other error — notably the loser's WALLET_EXISTS — propagates unchanged.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\n/** Where the encryption passphrase lives, and what the user must remember. */\nfunction passphraseNote(source: PassphraseSource, address: string): string {\n const account = address.toLowerCase();\n switch (source) {\n case 'keychain':\n return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'dpapi':\n return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;\n case 'secret-service':\n return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'env':\n return 'Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.';\n case 'prompt':\n return 'Remember your passphrase: it is required to sign and cannot be recovered.';\n }\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n // Diagnostics are the provider's own: a remote provider reports no local file\n // path or perms warning, so `show` never contaminates a remote wallet's output\n // with a stale local wallet.json's state. keyStorage/passphraseSource are the\n // custody posture reported without decrypting or requiring a passphrase.\n const {\n walletPath: path,\n keyStorage,\n passphraseSource,\n archivedWallets,\n warnings,\n } = await provider.diagnostics();\n\n const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];\n if (keyStorage !== undefined) humanLines.push(`Key storage: ${keyStorage}`);\n if (passphraseSource !== undefined) humanLines.push(`Passphrase: ${passphraseSource}`);\n if (archivedWallets !== undefined && archivedWallets.length > 0) {\n // A recovery hint, not a wallet switcher: exactly one wallet is ever active.\n humanLines.push(\n `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(', ')}`,\n );\n }\n humanLines.push(...warnings);\n\n return {\n data: {\n address: desc.address,\n provider: desc.provider,\n credentialSource: desc.credentialSource,\n policyEnforcement: desc.policyEnforcement,\n ...(path !== undefined ? { walletPath: path } : {}),\n ...(keyStorage !== undefined ? { keyStorage } : {}),\n ...(passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(archivedWallets !== undefined && archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n },\n humanLines,\n };\n}\n\nexport async function runWalletBalance(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n\n const config = await loadRawConfig(ctx.dataDir);\n const rpcUrl = resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n }).rpcUrl.value;\n\n let atomic: bigint;\n try {\n atomic = await getUsdcBalance(desc.address, rpcUrl);\n } catch (err) {\n throw new CliError('RPC_ERROR', `Could not read the USDC balance from ${rpcUrl}.`, {\n fix: 'Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.',\n cause: err,\n });\n }\n\n const balance = toMoney(atomic.toString());\n return {\n data: { address: desc.address, balance },\n humanLines: [`Balance: ${balance.usd} USDC on Base`],\n };\n}\n\nfunction custodyWarnings(): string[] {\n const warnings: string[] = [];\n if (hasEnvKey()) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows this file at runtime.');\n }\n if (isWindows) {\n warnings.push('File permissions are not enforced on Windows; the key file is not restricted.');\n }\n return warnings;\n}\n\nfunction hasEnvKey(): boolean {\n const envKey = process.env.TENJIN_WALLET_KEY;\n return envKey !== undefined && envKey.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,YAAY;AAwBrB,IAAM,eACJ;AACF,IAAM,cAAc;AACpB,IAAM,YAAY,QAAQ,aAAa;AAsBvC,eAAsB,gBACpB,KACA,OAA4B,CAAC,GACL;AACxB,QAAM;AAAA,IACJ;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF,IAAI,MAAM,mBAAmB,IAAI,SAAS,IAAI;AAE9C,QAAM,WAAW,gBAAgB;AACjC,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA,YAAY;AAAA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jD,GAAI,qBAAqB,SAAY,EAAE,iBAAiB,IAAI,CAAC;AAAA,MAC7D,GAAI,oBAAoB,UAAa,gBAAgB,SAAS,IAAI,EAAE,gBAAgB,IAAI,CAAC;AAAA,MACzF;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF;AAEA,eAAsB,iBACpB,KACA,OAAqC,CAAC,GACd;AACxB,QAAM,WAAW,sBAAsB,KAAK,IAAI;AAChD,QAAM,OAAO,MAAM,eAAe,QAAQ;AAE1C,QAAM,SAAS,MAAM,cAAc,IAAI,OAAO;AAC9C,QAAM,SAAS,gBAAgB;AAAA,IAC7B;AAAA,IACA,OAAO,EAAE,SAAS,IAAI,MAAM,QAAQ;AAAA,IACpC,KAAK,QAAQ;AAAA,EACf,CAAC,EAAE,OAAO;AAEV,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,eAAe,KAAK,SAAS,MAAM;AAAA,EACpD,SAAS,KAAK;AACZ,UAAM,IAAI,SAAS,aAAa,wCAAwC,MAAM,KAAK;AAAA,MACjF,KAAK;AAAA,MACL,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AAEA,QAAM,UAAU,QAAQ,OAAO,SAAS,CAAC;AACzC,SAAO;AAAA,IACL,MAAM,EAAE,SAAS,KAAK,SAAS,QAAQ;AAAA,IACvC,YAAY,CAAC,YAAY,QAAQ,GAAG,eAAe;AAAA,EACrD;AACF;AAEA,SAAS,kBAA4B;AACnC,QAAM,WAAqB,CAAC;AAC5B,MAAI,UAAU,GAAG;AACf,aAAS,KAAK,4DAA4D;AAAA,EAC5E;AACA,MAAI,WAAW;AACb,aAAS,KAAK,+EAA+E;AAAA,EAC/F;AACA,SAAO;AACT;AAEA,SAAS,YAAqB;AAC5B,QAAM,SAAS,QAAQ,IAAI;AAC3B,SAAO,WAAW,UAAa,OAAO,SAAS;AACjD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { walletPath } from '../lib/paths';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { getUsdcBalance } from '../lib/usdc';\nimport {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n parkOutgoingWallet,\n prepareLocalWallet,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { walletExistsError, walletFileExists } from '../lib/wallet/store';\nimport { resolvePassphraseForCreate, type PassphraseSource } from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst FUNDING_LINE =\n 'Fund it with `tenjin fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.';\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\n\nexport interface WalletCreateOptions {\n /**\n * Explicitly replace the existing active wallet (mirrors the `--yes`-style\n * explicit-flag precedent): the outgoing wallet is ARCHIVED — passphrase\n * verified against its keystore and preserved under its own address, keystore\n * parked beside the new one — never destroyed. Without it, create refuses\n * when a wallet exists. There is always exactly ONE active wallet.\n */\n replace?: boolean;\n /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /**\n * The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to\n * process.env. A seam rather than a global read so a caller (and above all a\n * test) can settle the passphrase source WITHOUT mutating the real process\n * environment, which under a parallel runner leaks across whole test files.\n */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const {\n address,\n walletPath: path,\n source,\n replaced,\n } = await createWalletLocked(ctx.dataDir, opts);\n\n const warnings = custodyWarnings();\n return {\n data: {\n address,\n walletPath: path,\n provider: 'local',\n policyEnforcement: 'client-only',\n keyStorage: KEY_STORAGE,\n passphraseSource: source,\n ...(replaced !== undefined\n ? {\n replaced: {\n address: replaced.address,\n archivedWalletPath: replaced.archivedPath,\n passphrasePreserved: replaced.passphraseLocation,\n ...(replaced.unarchivedReason !== undefined\n ? { unarchivedReason: replaced.unarchivedReason }\n : {}),\n },\n }\n : {}),\n warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n passphraseNote(source, address),\n ...(replaced !== undefined ? replacedNote(replaced, path) : []),\n FUNDING_LINE,\n ...warnings,\n ],\n };\n}\n\n/** Where the outgoing wallet's funds live, why they remain reachable, and how to restore it. */\nfunction replacedNote(replaced: ArchivedWalletInfo, activeWalletPath: string): string[] {\n const passphraseLine =\n replaced.passphraseLocation === 'store'\n ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).`\n : replaced.passphraseLocation === 'env'\n ? 'its passphrase is TENJIN_WALLET_PASSPHRASE — keep that value.'\n : replaced.unarchivedReason === 'rejected-characters'\n ? 'its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : replaced.unarchivedReason === 'no-store'\n ? 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.'\n : 'its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.';\n return [\n `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,\n `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,\n `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \\`mv ${replaced.archivedPath} ${activeWalletPath}\\`.`,\n ];\n}\n\n/**\n * Run the whole create critical section under a cross-process file lock: the\n * existence pre-check, the passphrase generate-and-store, and the no-clobber\n * write. Without the lock these interleave across two concurrent creates — each\n * generates a distinct passphrase and persists it to the OS store BEFORE the\n * exclusive file write, so a different process could win the file while this\n * one's per-address entry names a wallet that never landed. Serializing means\n * the loser blocks until the winner commits, then trips the exists check and\n * exits WALLET_EXISTS having never generated or stored a passphrase. The\n * store-before-write ordering stays (it still guards the single-process crash\n * window), and the exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * OS-store entry is keyed to the new wallet's own address (issue #32).\n *\n * `--replace` ordering closes the no-active-wallet window: verify-and-preserve\n * the outgoing wallet (no file moves), fully PREPARE the replacement (key,\n * stored passphrase, encrypted keystore — every fallible step) while the old\n * wallet is still active, and only then park the old keystore and commit the\n * new one. A commit failure rolls the park back, so at every exit either the\n * old or the new wallet is the active one.\n */\nasync function createWalletLocked(\n dir: string,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n source: PassphraseSource;\n replaced?: ArchivedWalletInfo;\n}> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write below re-ensures it at 0700 regardless.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = join(dir, 'wallet.create.lock');\n try {\n return await withFileLock(lockPath, async () => {\n const env = opts.env ?? process.env;\n let source: PassphraseSource = 'env';\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n { env, dir, ...opts.passphrase },\n forAddress,\n );\n source = resolved.source;\n return resolved.passphrase;\n };\n\n if (!(await walletFileExists(dir))) {\n const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);\n return { address, walletPath: path, source };\n }\n\n if (opts.replace !== true) throw walletExistsError(dir);\n const preserved = await verifyAndPreserveOutgoingWallet({\n dir,\n env,\n ...(opts.passphrase !== undefined ? { passphrase: opts.passphrase } : {}),\n });\n const prepared = await prepareLocalWallet(passphraseFor);\n const archivedPath = await parkOutgoingWallet(dir, preserved.account);\n try {\n const { address, walletPath: path } = await commitLocalWallet(dir, prepared);\n return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };\n } catch (err) {\n try {\n await restoreParkedWallet(dir, archivedPath);\n } catch (restoreErr) {\n // The no-clobber restore also refuses when a wallet.json appeared out\n // of band (commit EEXIST) — never overwrite it; name both files.\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.',\n {\n fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it — move it aside first. Then restore with \\`mv ${archivedPath} ${walletPath(dir)}\\`.`,\n cause: restoreErr,\n },\n );\n }\n // Old wallet restored as the active one; say so rather than surfacing a\n // raw fs error (or a WALLET_EXISTS whose fix suggests re-running --replace).\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.',\n {\n fix: 'Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.',\n cause: err,\n },\n );\n }\n });\n } catch (err) {\n // A lock timeout is not the user's error; surface it as INTERNAL with the one\n // manual step (there is no auto-steal), keeping the JSON error contract. Every\n // other error — notably the loser's WALLET_EXISTS — propagates unchanged.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\n/** Where the encryption passphrase lives, and what the user must remember. */\nfunction passphraseNote(source: PassphraseSource, address: string): string {\n const account = address.toLowerCase();\n switch (source) {\n case 'keychain':\n return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'dpapi':\n return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;\n case 'secret-service':\n return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'env':\n return 'Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.';\n case 'prompt':\n return 'Remember your passphrase: it is required to sign and cannot be recovered.';\n }\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n // Diagnostics are the provider's own: a remote provider reports no local file\n // path or perms warning, so `show` never contaminates a remote wallet's output\n // with a stale local wallet.json's state. keyStorage/passphraseSource are the\n // custody posture reported without decrypting or requiring a passphrase.\n const {\n walletPath: path,\n keyStorage,\n passphraseSource,\n archivedWallets,\n warnings,\n } = await provider.diagnostics();\n\n const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];\n if (keyStorage !== undefined) humanLines.push(`Key storage: ${keyStorage}`);\n if (passphraseSource !== undefined) humanLines.push(`Passphrase: ${passphraseSource}`);\n if (archivedWallets !== undefined && archivedWallets.length > 0) {\n // A recovery hint, not a wallet switcher: exactly one wallet is ever active.\n humanLines.push(\n `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(', ')}`,\n );\n }\n humanLines.push(...warnings);\n\n return {\n data: {\n address: desc.address,\n provider: desc.provider,\n credentialSource: desc.credentialSource,\n policyEnforcement: desc.policyEnforcement,\n ...(path !== undefined ? { walletPath: path } : {}),\n ...(keyStorage !== undefined ? { keyStorage } : {}),\n ...(passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(archivedWallets !== undefined && archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n },\n humanLines,\n };\n}\n\nexport async function runWalletBalance(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n\n const config = await loadRawConfig(ctx.dataDir);\n const rpcUrl = resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n }).rpcUrl.value;\n\n let atomic: bigint;\n try {\n atomic = await getUsdcBalance(desc.address, rpcUrl);\n } catch (err) {\n throw new CliError('RPC_ERROR', `Could not read the USDC balance from ${rpcUrl}.`, {\n fix: 'Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.',\n cause: err,\n });\n }\n\n const balance = toMoney(atomic.toString());\n return {\n data: { address: desc.address, balance },\n humanLines: [`Balance: ${balance.usd} USDC on Base`],\n };\n}\n\nfunction custodyWarnings(): string[] {\n const warnings: string[] = [];\n if (hasEnvKey()) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows this file at runtime.');\n }\n if (isWindows) {\n warnings.push('File permissions are not enforced on Windows; the key file is not restricted.');\n }\n return warnings;\n}\n\nfunction hasEnvKey(): boolean {\n const envKey = process.env.TENJIN_WALLET_KEY;\n return envKey !== undefined && envKey.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,YAAY;AAwBrB,IAAM,eACJ;AACF,IAAM,cAAc;AACpB,IAAM,YAAY,QAAQ,aAAa;AAsBvC,eAAsB,gBACpB,KACA,OAA4B,CAAC,GACL;AACxB,QAAM;AAAA,IACJ;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF,IAAI,MAAM,mBAAmB,IAAI,SAAS,IAAI;AAE9C,QAAM,WAAW,gBAAgB;AACjC,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA,YAAY;AAAA,MACZ,UAAU;AAAA,MACV,mBAAmB;AAAA,MACnB,YAAY;AAAA,MACZ,kBAAkB;AAAA,MAClB,GAAI,aAAa,SACb;AAAA,QACE,UAAU;AAAA,UACR,SAAS,SAAS;AAAA,UAClB,oBAAoB,SAAS;AAAA,UAC7B,qBAAqB,SAAS;AAAA,UAC9B,GAAI,SAAS,qBAAqB,SAC9B,EAAE,kBAAkB,SAAS,iBAAiB,IAC9C,CAAC;AAAA,QACP;AAAA,MACF,IACA,CAAC;AAAA,MACL;AAAA,IACF;AAAA,IACA,YAAY;AAAA,MACV,mBAAmB,OAAO;AAAA,MAC1B,cAAc,WAAW;AAAA,MACzB,eAAe,QAAQ,O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QAAQ;AAAA,IACpC,KAAK,QAAQ;AAAA,EACf,CAAC,EAAE,OAAO;AAEV,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,eAAe,KAAK,SAAS,MAAM;AAAA,EACpD,SAAS,KAAK;AACZ,UAAM,IAAI,SAAS,aAAa,wCAAwC,MAAM,KAAK;AAAA,MACjF,KAAK;AAAA,MACL,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AAEA,QAAM,UAAU,QAAQ,OAAO,SAAS,CAAC;AACzC,SAAO;AAAA,IACL,MAAM,EAAE,SAAS,KAAK,SAAS,QAAQ;AAAA,IACvC,YAAY,CAAC,YAAY,QAAQ,GAAG,eAAe;AAAA,EACrD;AACF;AAEA,SAAS,kBAA4B;AACnC,QAAM,WAAqB,CAAC;AAC5B,MAAI,UAAU,GAAG;AACf,aAAS,KAAK,4DAA4D;AAAA,EAC5E;AACA,MAAI,WAAW;AACb,aAAS,KAAK,+EAA+E;AAAA,EAC/F;AACA,SAAO;AACT;AAEA,SAAS,YAAqB;AAC5B,QAAM,SAAS,QAAQ,IAAI;AAC3B,SAAO,WAAW,UAAa,OAAO,SAAS;AACjD;","names":[]}
|
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
assertOnBaseOrigin
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-IFPKA32J.js";
|
|
5
5
|
import {
|
|
6
6
|
recordSearch
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-BRAVLUGI.js";
|
|
8
8
|
import {
|
|
9
9
|
MAX_LIMIT,
|
|
10
10
|
buildSearchRequest,
|
|
11
11
|
postSearch
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-NKN4YC5C.js";
|
|
13
13
|
import {
|
|
14
14
|
sanitizeForTerminal
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-B676GPS2.js";
|
|
16
16
|
import {
|
|
17
17
|
resolveContextSettings
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-IGHSLJUF.js";
|
|
19
19
|
import {
|
|
20
20
|
formatUsdDisplay,
|
|
21
21
|
isPaidPrice,
|
|
22
22
|
parseUsdToAtomic
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-736DW4V3.js";
|
|
24
24
|
import {
|
|
25
25
|
CliError
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-PAOVPSP6.js";
|
|
27
27
|
|
|
28
28
|
// src/commands/search.ts
|
|
29
29
|
async function runSearch(args, ctx, deps = {}) {
|
|
@@ -172,4 +172,4 @@ function parseAppliesTo(pairs) {
|
|
|
172
172
|
export {
|
|
173
173
|
runSearch
|
|
174
174
|
};
|
|
175
|
-
//# sourceMappingURL=chunk-
|
|
175
|
+
//# sourceMappingURL=chunk-TXVC46SA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, isPaidPrice, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, MAX_LIMIT, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin search \"<question>\"`, one POST to /api/agent/search. Prints the compact\n * CANDIDATES/MISS response (spec 10) and records the searchId + candidates\n * locally so `outcome --last` and `buy <resourceId>` can use them. No wallet, no\n * signing: search is anonymous.\n *\n * The machine envelope is the server's response verbatim plus exactly one\n * CLI-owned key, `publishBack`, and only on a MISS. It carries no server data: it\n * is the local searchId and the two commands that close the loop, which is\n * information the CLI owns and the contract does not describe.\n *\n * Search is the breadth step: a candidate is a lean hit (identity, price,\n * freshness, why it matched), and the full answer card comes from `tenjin inspect`,\n * which is free. So a candidate line stays short on purpose.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/searches/<searchId>/outcomes. tenjin#463 renamed the field (from\n * `lookupId`) and tenjin#616 dropped the `/agent` prefix from the path; this\n * client follows both end to end, so nothing on the wire or in the local store\n * still speaks `lookupId` or the prefixed spelling.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n /** Environment seam (TENJIN_SESSION_ID); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runSearch(\n args: SearchArgs,\n ctx: CommandContext,\n deps: SearchDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: SearchInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const sessionId = readSessionId(deps.env ?? process.env);\n const request = buildSearchRequest(input);\n const response = await postSearch(request, {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n evalCohort: settings.evalCohort,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const candidates = response.candidates ?? [];\n // Ingest trust boundary: a candidate url that points off the configured origin\n // would later route a wallet-signed SIWX header and payment to that host via\n // `buy <resourceId>`. Refuse the whole response as a contract violation.\n for (const c of candidates) {\n try {\n assertOnBaseOrigin(c.url, settings.baseUrl, 'search candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Search candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n // Browse pointers are never buyable through `buy <resourceId>` (they are not\n // recorded), but their urls are still emitted into the agent's transcript, so\n // they get the same origin check rather than a weaker one.\n for (const b of response.browse ?? []) {\n try {\n assertOnBaseOrigin(b.url, settings.baseUrl, 'browse pointer URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Browse pointer ${b.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordSearch(ctx.dataDir, {\n searchId: response.searchId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n // A deliberate search, as opposed to one the WebSearch hook rode along with.\n // The Stop hook nags on the two differently, so the tag has to be written\n // here rather than inferred later from anything.\n source: 'cli',\n // Usually absent; see readSessionId. An unstamped entry is raised in every\n // session, which is the safe direction for a reminder.\n ...(sessionId !== undefined ? { sessionId } : {}),\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n // The pointers stay unrecorded on purpose (see below); only how many of them\n // cost money, so `outcome` can tell a MISS that offered a payable browse tail\n // from one that offered nothing to buy. A zero-priced pointer does not count:\n // `read` delivers it for nothing, so there was no purchase to decline. Zero on\n // a CANDIDATES decision, where the contract carries no browse array and the\n // parser drops any that appears.\n paidBrowseCount: (response.browse ?? []).filter((b) => isPaidPrice(b.price) === true).length,\n });\n\n // One stderr line on a MISS (never in the machine JSON): a MISS is the moment\n // to publish the answer you are about to derive. There is deliberately no\n // second line about drafts waiting somewhere — a reminder that re-raises work\n // nobody chose to come back to is the class this CLI stopped emitting.\n if (response.decision === 'MISS') {\n ctx.io.stderr.write(`${publishBackLine(response.searchId)}\\n`);\n }\n\n // A MISS may carry up to 3 browse pointers from the broad corpus. They are\n // pointers, NOT candidates: rendered as ONE hint line with no scores and no\n // per-item detail, so a MISS still reads as a MISS and an agent is never\n // nudged to treat a browse pointer as an answer. The machine JSON keeps the\n // full `browse` array; this line is only the human tail.\n //\n // The price rides this line because a browse url IS payable: it is the read\n // endpoint that answers a 402, and `buy <url>` resolves the URL arm by origin\n // without consulting the search store, so a browse pointer can be bought even\n // though `buy <resourceId>` can never reach one. All spend gates (price cap,\n // session budget, allowlist, confirm) still run; showing the price keeps the\n // only human-visible surface from being a blind spend.\n //\n // It renders in DOLLARS, not atomic units, because the whole point of the line\n // is that a human can size the spend against the gates they set, and every gate\n // is entered in decimal USD (`--max-price 0.10`, the `maxAutoSpend` config).\n // `formatUsdDisplay` is the canonical human-copy form (always two decimals, so\n // a dime reads \"0.10\" and not \"0.1\"); the machine `browse` array in --json still\n // carries the exact atomic string, per the money-units contract in the README.\n const browse = response.browse ?? [];\n const browseHint =\n browse.length > 0\n ? [\n `no match, ${browse.length} piece(s) you could browse: ${browse\n .map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`)\n .join('; ')}`,\n ]\n : [];\n\n // `truncated` means the server's size backstop dropped candidates, either a\n // trailing few the limit had room for or a single oversized one. The response\n // ceiling GROWS with the number of candidates returned (tenjin#501), so the\n // remedy is counter-intuitive and worth stating outright: a larger --limit\n // recovers the tail, a smaller one returns strictly fewer. Only at the maximum\n // is the tail unrecoverable and narrowing the question the answer.\n //\n // The CLI knows the limit it sent, so it names the next step instead of\n // restating the rule and leaving the reader to work out which half applies.\n // The flag stays in the machine envelope (--json) untouched, where it is\n // omitted rather than false when it did not fire.\n //\n // Rendering it on a MISS too is DEFENSIVE, not wire behavior: the server only\n // ever sets the flag alongside candidates it dropped. Handling both keeps the\n // flag from going unrendered if that ever changes.\n const truncatedHint =\n response.truncated === true\n ? [\n request.limit < MAX_LIMIT\n ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)`\n : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`,\n ]\n : [];\n\n const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n // Dollars for the same reason the browse hint uses them: this is the\n // human's cue to size the spend against gates they entered in decimal\n // USD. The machine `candidates` array in --json keeps atomic.\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`,\n ),\n ...truncatedHint,\n ];\n\n // The one CLI-owned field in this envelope. Everything else is the server's\n // response verbatim (spec 10), so the addition is namespaced under a key the\n // contract does not define and is present ONLY on a MISS: a MISS is the moment\n // the demand this searcher just expressed can still be met, and the searchId is\n // what ties the answer they are about to derive back to it. A CANDIDATES\n // response is byte-identical to what it was.\n const data =\n response.decision === 'MISS'\n ? { ...response, publishBack: publishBackHint(response.searchId) }\n : response;\n\n return { data, humanLines };\n}\n\n/**\n * The session to stamp this search with, so the Stop hook can tell one session's\n * open loops from a sibling's, or undefined when nothing can say.\n *\n * Two sources, in precedence order. TENJIN_SESSION_ID is the explicit operator\n * override and wins. CLAUDE_CODE_SESSION_ID is what Claude Code exports to Bash\n * tool subprocesses, which is what a `tenjin search` runs as; its value is the\n * same `session_id` the hook scripts are handed on stdin, so a CLI search and a\n * WebSearch-hook search in one session stamp identically. It is verified against\n * a live session rather than documented, hence the fallback rather than a\n * requirement: on a harness that does not export it this stays undefined, and\n * undefined is the safe answer — the hook raises an unstamped entry in every\n * session rather than in none.\n */\nfunction readSessionId(env: NodeJS.ProcessEnv): string | undefined {\n return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);\n}\n\nfunction firstNonEmpty(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/** The publish-back hint, as machine fields rather than prose to re-parse. */\nfunction publishBackHint(searchId: string): {\n searchId: string;\n reason: string;\n publish: string;\n decline: string;\n} {\n return {\n searchId,\n reason: 'Nothing on the marketplace answered this. If you solve it, publish it back.',\n // Both arms carry the searchId, because both are commands to run verbatim and\n // a publish without it leaves this very loop open (see publish's --search-id).\n // The second arm is DECLINE, not park: nothing is saved to come back to, and\n // reporting the outcome is what closes the loop so it never raises again.\n publish: `tenjin publish <file.md> --json --search-id ${searchId}`,\n decline: `tenjin outcome --search-id ${searchId} --status regenerated --json`,\n };\n}\n\n/** The same hint as one stderr line for a human. */\nfunction publishBackLine(searchId: string): string {\n return `Nobody has published this yet - if you solve it, publish it back (tenjin publish <file.md> --search-id ${searchId}); if you will not, close the loop: tenjin outcome --search-id ${searchId} --status regenerated`;\n}\n\nfunction parseLimit(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n)) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(raw)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n return n;\n}\n\n/** `products=Vercel` or `products=Vercel,Next` → { products: [\"Vercel\",\"Next\"] }. Repeated\n * keys merge their values. */\nfunction parseAppliesTo(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to: ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const values = pair\n .slice(eq + 1)\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length === 0) {\n throw new CliError('USAGE', `--applies-to ${JSON.stringify(key)} has no values`, {\n fix: 'Give each key at least one value, e.g. products=Vercel.',\n });\n }\n out[key] = [...(out[key] ?? []), ...values];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,eAAsB,UACpB,MACA,KACA,OAAmB,CAAC,GACI;AACxB,QAAM,WAAW,MAAM,uBAAuB,GA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,EAAE,KAAK;AACnC,UAAM,SAAS,KACZ,MAAM,KAAK,CAAC,EACZ,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC7B,QAAI,OAAO,WAAW,GAAG;AACvB,YAAM,IAAI,SAAS,SAAS,gBAAgB,KAAK,UAAU,GAAG,CAAC,kBAAkB;AAAA,QAC/E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,QAAI,GAAG,IAAI,CAAC,GAAI,IAAI,GAAG,KAAK,CAAC,GAAI,GAAG,MAAM;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
loadProjectConfig
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-IGHSLJUF.js";
|
|
5
5
|
import {
|
|
6
6
|
LockTimeoutError,
|
|
7
7
|
withFileLock
|
|
8
8
|
} from "./chunk-FKSAUOJU.js";
|
|
9
|
+
import {
|
|
10
|
+
parseUsdToAtomic,
|
|
11
|
+
toMoney
|
|
12
|
+
} from "./chunk-736DW4V3.js";
|
|
9
13
|
import {
|
|
10
14
|
CONFIG_KEYS,
|
|
11
15
|
HOOKS_CONFIG_KEYS,
|
|
@@ -13,27 +17,29 @@ import {
|
|
|
13
17
|
PublishModeSchema,
|
|
14
18
|
RawConfigSchema,
|
|
15
19
|
SEND_MAX_UNSET,
|
|
20
|
+
UPDATE_CONFIG_KEYS,
|
|
16
21
|
loadRawConfig,
|
|
17
22
|
parseSearchHookModeFlag,
|
|
18
23
|
parseStopNagFlag,
|
|
19
|
-
|
|
20
|
-
resolveSettings
|
|
21
|
-
|
|
22
|
-
} from "./chunk-ALUNME53.js";
|
|
24
|
+
parseUpdateModeFlag,
|
|
25
|
+
resolveSettings
|
|
26
|
+
} from "./chunk-ELVDOTU7.js";
|
|
23
27
|
import {
|
|
24
28
|
configPath
|
|
25
29
|
} from "./chunk-ZQIQ55KK.js";
|
|
26
30
|
import {
|
|
27
31
|
CliError,
|
|
28
32
|
writeFileAtomic
|
|
29
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-PAOVPSP6.js";
|
|
30
34
|
|
|
31
35
|
// src/commands/config.ts
|
|
32
36
|
import { mkdir } from "fs/promises";
|
|
33
37
|
import { styleText } from "util";
|
|
34
38
|
var CONFIRM_ABOVE = "above:";
|
|
35
39
|
var KEY_WIDTH = Math.max(
|
|
36
|
-
...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].map(
|
|
40
|
+
...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...UPDATE_CONFIG_KEYS].map(
|
|
41
|
+
(key) => key.length
|
|
42
|
+
)
|
|
37
43
|
);
|
|
38
44
|
var KEY_DESCRIPTIONS = {
|
|
39
45
|
maxAutoSpend: "auto-approve a read up to this amount",
|
|
@@ -47,7 +53,8 @@ var KEY_DESCRIPTIONS = {
|
|
|
47
53
|
"publish.mode": "review=always ask, auto=ask on findings, full-auto=only hard blocks stop it",
|
|
48
54
|
"publish.defaultPrice": "price used when none is given",
|
|
49
55
|
"hooks.searchMode": "harness WebSearch hook: auto=ask Tenjin first, remind=static reminder, off=inert",
|
|
50
|
-
"hooks.stopNag": "end-of-turn reminder about searches nothing answered yet"
|
|
56
|
+
"hooks.stopNag": "end-of-turn reminder about searches nothing answered yet",
|
|
57
|
+
"update.mode": "nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm"
|
|
51
58
|
};
|
|
52
59
|
function isPublishKey(key) {
|
|
53
60
|
return PUBLISH_CONFIG_KEYS.includes(key);
|
|
@@ -55,6 +62,9 @@ function isPublishKey(key) {
|
|
|
55
62
|
function isHooksKey(key) {
|
|
56
63
|
return HOOKS_CONFIG_KEYS.includes(key);
|
|
57
64
|
}
|
|
65
|
+
function isUpdateKey(key) {
|
|
66
|
+
return UPDATE_CONFIG_KEYS.includes(key);
|
|
67
|
+
}
|
|
58
68
|
async function runConfigList(ctx) {
|
|
59
69
|
const settings = await resolveFromContext(ctx);
|
|
60
70
|
const data = {};
|
|
@@ -74,6 +84,14 @@ async function runConfigList(ctx) {
|
|
|
74
84
|
data[key] = entry;
|
|
75
85
|
humanLines.push(describedLine(key, entry));
|
|
76
86
|
}
|
|
87
|
+
for (const key of UPDATE_CONFIG_KEYS) {
|
|
88
|
+
const entry = {
|
|
89
|
+
value: settings.updateMode.value,
|
|
90
|
+
source: settings.updateMode.source
|
|
91
|
+
};
|
|
92
|
+
data[key] = entry;
|
|
93
|
+
humanLines.push(describedLine(key, entry));
|
|
94
|
+
}
|
|
77
95
|
return { data, humanLines };
|
|
78
96
|
}
|
|
79
97
|
async function runConfigGet({ key }, ctx) {
|
|
@@ -89,6 +107,11 @@ async function runConfigGet({ key }, ctx) {
|
|
|
89
107
|
const entry2 = renderHooksSetting(key, await resolveFromContext(ctx));
|
|
90
108
|
return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
|
|
91
109
|
}
|
|
110
|
+
if (isUpdateKey(key)) {
|
|
111
|
+
const { updateMode } = await resolveFromContext(ctx);
|
|
112
|
+
const entry2 = { value: updateMode.value, source: updateMode.source };
|
|
113
|
+
return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
|
|
114
|
+
}
|
|
92
115
|
const configKey = assertKey(key);
|
|
93
116
|
const settings = await resolveFromContext(ctx);
|
|
94
117
|
const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);
|
|
@@ -97,6 +120,7 @@ async function runConfigGet({ key }, ctx) {
|
|
|
97
120
|
async function runConfigSet({ key, value }, ctx) {
|
|
98
121
|
if (isPublishKey(key)) return setPublishKey(key, value, ctx);
|
|
99
122
|
if (isHooksKey(key)) return setHooksKey(key, value, ctx);
|
|
123
|
+
if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);
|
|
100
124
|
const configKey = assertKey(key);
|
|
101
125
|
const stored = parseValue(configKey, value);
|
|
102
126
|
await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));
|
|
@@ -123,6 +147,15 @@ async function setHooksKey(key, value, ctx) {
|
|
|
123
147
|
const entry = { value: parsed, source: "file" };
|
|
124
148
|
return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
|
|
125
149
|
}
|
|
150
|
+
async function setUpdateKey(key, value, ctx) {
|
|
151
|
+
const parsed = parseUpdateModeFlag(value, key);
|
|
152
|
+
await persist(ctx.dataDir, (existing) => ({
|
|
153
|
+
...existing,
|
|
154
|
+
update: { ...existing.update, mode: parsed }
|
|
155
|
+
}));
|
|
156
|
+
const entry = { value: parsed, source: "file" };
|
|
157
|
+
return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
|
|
158
|
+
}
|
|
126
159
|
function parsePublishMode(value) {
|
|
127
160
|
const parsed = PublishModeSchema.safeParse(value);
|
|
128
161
|
if (parsed.success) return parsed.data;
|
|
@@ -313,4 +346,4 @@ export {
|
|
|
313
346
|
persistSearchHookMode,
|
|
314
347
|
persistInstallHarness
|
|
315
348
|
};
|
|
316
|
-
//# sourceMappingURL=chunk-
|
|
349
|
+
//# sourceMappingURL=chunk-UUARTUY2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/config.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport {\n CONFIG_KEYS,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n loadRawConfig,\n parseSearchHookModeFlag,\n parseStopNagFlag,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n SearchHookMode,\n UpdateConfigKey,\n} from '../lib/config';\nimport type { HarnessTarget } from '../lib/skill-wiring';\nimport { loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * How one config key is presented in `data`. `value` is the machine form: dual\n * Money for the spend keys, the stored string for `confirm`/URLs, the string[]\n * for the allowlist. `threshold` rides along only for `confirm: above:<atomic>`\n * so an agent reads the dollar amount without re-parsing the string.\n */\ninterface RenderedValue {\n value: Money | string | string[] | boolean;\n threshold?: Money;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n}\n\nconst CONFIRM_ABOVE = 'above:';\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...UPDATE_CONFIG_KEYS].map(\n (key) => key.length,\n ),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'auto-approve a read up to this amount',\n sessionBudget: 'cap on total auto-spend per session',\n confirm: 'when to ask before paying',\n sendMaxAmount:\n 'hard cap per tenjin send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL',\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'hooks.searchMode':\n 'harness WebSearch hook: auto=ask Tenjin first, remind=static reminder, off=inert',\n 'hooks.stopNag': 'end-of-turn reminder about searches nothing answered yet',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n};\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n { key, value }: { key: string; value: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) return setPublishKey(key, value, ctx);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice`. mode validates to the enum;\n * defaultPrice parses decimal USD at the edge into atomic (matching the spend\n * keys). The subkey is merged into the nested publish block, so a sibling subkey\n * (or an unknown one a newer CLI wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey = key === 'publish.mode' ? 'mode' : 'defaultPrice';\n const stored = key === 'publish.mode' ? (entry.value as string) : (entry.value as Money).atomic;\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set hooks.searchMode`. Merged into the nested hooks block through the\n * same locked read-modify-write every other set uses, so a subkey a newer CLI\n * wrote survives. The installed hook script reads this file on every run, so the\n * new mode takes effect immediately with no re-install.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const subkey = key === 'hooks.searchMode' ? 'searchMode' : 'stopNag';\n const parsed =\n key === 'hooks.searchMode' ? parseSearchHookModeFlag(value, key) : parseStopNagFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [subkey]: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Persist `hooks.searchMode` through the same locked merge-write, for `install`'s\n * hook decision. The mode is already a validated SearchHookMode.\n */\nexport async function persistSearchHookMode(dir: string, mode: SearchHookMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, searchMode: mode },\n }));\n}\n\n/**\n * Record the explicit `--harness` set `install` was given, through the same locked\n * merge-write. It REPLACES the previous record rather than unioning with it: the last\n * explicit request is the current intent, and re-running install with the right flag\n * is then the way out of a mistaken one. Detected harnesses are never recorded — they\n * are re-probed on every `doctor` — so this file holds only what detection cannot see.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly HarnessTarget[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: a plain enum string either way. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const resolved = key === 'hooks.searchMode' ? settings.hooksSearchMode : settings.hooksStopNag;\n return { value: resolved.value, source: resolved.source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n if (key === 'confirm' && stored.startsWith(CONFIRM_ABOVE)) {\n return { value: stored, threshold: toMoney(stored.slice(CONFIRM_ABOVE.length)) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'maxAutoSpend':\n case 'sessionBudget':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'confirm':\n return parseConfirm(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'evalCohort':\n return parseBoolean(value);\n }\n}\n\nfunction parseBoolean(value: string): boolean {\n if (value === 'true') return true;\n if (value === 'false') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"true\" or \"false\".',\n });\n}\n\nfunction parseConfirm(value: string): string {\n if (value === 'always') return 'always';\n if (value.startsWith(CONFIRM_ABOVE)) {\n return `${CONFIRM_ABOVE}${parseUsdToAtomic(value.slice(CONFIRM_ABOVE.length))}`;\n }\n throw new CliError('USAGE', `Invalid confirm value: ${JSON.stringify(value)}`, {\n fix: 'Use \"always\" or \"above:<usd>\", e.g. above:0.25.',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n if (entry.threshold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O,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,MAAI,MAAM,cAAc,OAAW,QAAO,SAAS,MAAM,UAAU,GAAG;AACtE,SAAO;AACT;","names":["settings","entry"]}
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
rateLimitError
|
|
4
|
-
} from "./chunk-EDVI7RRD.js";
|
|
5
2
|
import {
|
|
6
3
|
SIWX_HEADER,
|
|
7
4
|
decodePaymentRequiredHeader,
|
|
8
5
|
decodePaymentResponseHeader
|
|
9
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-OWVVI4VQ.js";
|
|
7
|
+
import {
|
|
8
|
+
rateLimitError
|
|
9
|
+
} from "./chunk-NKN4YC5C.js";
|
|
10
10
|
import {
|
|
11
11
|
httpRequest
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-SPUORKD7.js";
|
|
13
13
|
import {
|
|
14
14
|
SLUG_RE,
|
|
15
15
|
UUID_RE
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-736DW4V3.js";
|
|
17
17
|
import {
|
|
18
18
|
CliError,
|
|
19
19
|
external_exports
|
|
20
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-PAOVPSP6.js";
|
|
21
21
|
|
|
22
22
|
// src/lib/read-client.ts
|
|
23
23
|
var PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
|
|
@@ -230,4 +230,4 @@ function readMessage(json) {
|
|
|
230
230
|
export {
|
|
231
231
|
fetchRead
|
|
232
232
|
};
|
|
233
|
-
//# sourceMappingURL=chunk-
|
|
233
|
+
//# sourceMappingURL=chunk-WMFRCSNC.js.map
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
buildSiwxHeader
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-OWVVI4VQ.js";
|
|
5
5
|
import {
|
|
6
6
|
isSessionUsable,
|
|
7
7
|
loadSessionFile,
|
|
8
8
|
signWithSession
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-J6FUAIRR.js";
|
|
10
10
|
import {
|
|
11
11
|
originOf
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-XGZ5EVMB.js";
|
|
13
13
|
import {
|
|
14
14
|
sessionPath
|
|
15
15
|
} from "./chunk-ZQIQ55KK.js";
|
|
16
16
|
import {
|
|
17
17
|
writeFileAtomic
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-PAOVPSP6.js";
|
|
19
19
|
|
|
20
20
|
// src/lib/session-key.ts
|
|
21
21
|
import { webcrypto } from "crypto";
|
|
@@ -142,4 +142,4 @@ export {
|
|
|
142
142
|
createSessionKeyAuth,
|
|
143
143
|
createSiwxAuth
|
|
144
144
|
};
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
145
|
+
//# sourceMappingURL=chunk-WU5CZPLD.js.map
|
|
@@ -2,14 +2,12 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
HOSTED_SKILL_NAME,
|
|
4
4
|
readSkillFile
|
|
5
|
-
} from "./chunk-
|
|
6
|
-
import {
|
|
7
|
-
hasCode
|
|
8
|
-
} from "./chunk-2I4QTOLB.js";
|
|
5
|
+
} from "./chunk-OC3EIDCP.js";
|
|
9
6
|
import {
|
|
10
7
|
CliError,
|
|
8
|
+
hasCode,
|
|
11
9
|
writeFileAtomic
|
|
12
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-PAOVPSP6.js";
|
|
13
11
|
|
|
14
12
|
// src/lib/skill-writer.ts
|
|
15
13
|
import { existsSync } from "fs";
|
|
@@ -149,4 +147,4 @@ export {
|
|
|
149
147
|
installSkill,
|
|
150
148
|
resolveThroughLink
|
|
151
149
|
};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
150
|
+
//# sourceMappingURL=chunk-WVHPGQH5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/skill-writer.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { hasCode } from './errno';\nimport { CliError } from './errors';\nimport { HOSTED_SKILL_NAME, readSkillFile } from './skill-wiring';\n\n/**\n * Writing one packaged skill into one harness directory, and the path guards that\n * write needs. Its own module, free of the command layer's dependencies, because\n * `install` and the post-command self-heal both write skills and the heal runs on\n * every command: reaching into commands/install would parse the wallet's viem\n * chunk on a `tenjin config`.\n */\n\nexport type SkillInstallStatus =\n 'installed' | 'updated' | 'up-to-date' | 'would-install' | 'would-update';\n\nexport interface SkillInstallResult {\n status: SkillInstallStatus;\n warning?: string;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n}\n\nexport interface SkillWriteOptions {\n /**\n * Write THROUGH a symlinked destination (default), or replace it. `install`\n * follows the link, because the operator pointed it somewhere on purpose. The\n * unattended self-heal does not, and passes false: it has already refused every\n * link it could see, and this closes the gap between that look and this write,\n * where a link appearing in between would otherwise be followed. `rename` never\n * follows its final component, so the worst a race can now do is leave our\n * regular file where the new link was.\n */\n followSymlinks?: boolean;\n}\n\nexport async function installSkill(\n srcDir: string,\n destDir: string,\n dryRun: boolean,\n name: string,\n opts: SkillWriteOptions = {},\n): Promise<SkillInstallResult> {\n const src = await readTree(srcDir);\n if (src === null) {\n // assertSkillsSource already guards SKILL.md; this is defensive for an empty dir.\n throw new CliError('INTERNAL', `Packaged skill source ${srcDir} is empty`);\n }\n\n // Only the files this package SHIPS are read and written. Everything else in the\n // directory belongs to the operator: never inspected, listed, or removed. That is\n // what package managers do (npm, dpkg, Homebrew all own their files, not the\n // directory), and wholesale replacement was the single cause behind a run of\n // data-loss, symlink and enumeration bugs.\n //\n // Resolved on BOTH paths, dry run included, so a dry run cannot promise a write\n // the real run refuses.\n const writeTo = new Map<string, string>();\n await assertReachable(destDir, name);\n await assertNoCaseCollision(destDir, name);\n for (const rel of src.keys()) {\n const declared = join(destDir, rel);\n writeTo.set(\n rel,\n opts.followSymlinks === false ? declared : await resolveThroughLink(declared, name),\n );\n }\n\n let differs = false;\n let preexisting = false;\n for (const [rel, content] of src) {\n const current = await readShippedFile(writeTo.get(rel)!, name, destDir);\n if (rel === 'SKILL.md') preexisting = current !== null;\n if (current === null || !current.equals(content)) differs = true;\n }\n const change = !preexisting ? 'create' : differs ? 'update' : 'none';\n\n if (!dryRun && change !== 'none') {\n for (const [rel, content] of src) {\n const target = writeTo.get(rel)!;\n try {\n // An existing file keeps the mode it has. A skill an operator (or their\n // dotfiles) made group-readable or read-only is theirs to have set that\n // way, and an update is no reason to hand it back at the default 0644.\n const current = await stat(target).catch(() => null);\n await writeFileAtomic(\n target,\n content,\n current === null ? {} : { mode: current.mode & 0o777 },\n );\n } catch (err) {\n // Culprit is derived from the file that FAILED, not assumed to be the\n // skills root: an existing skill directory that refuses the temp file is\n // itself the thing to chmod, and a symlinked SKILL.md fails in the link's\n // TARGET directory, which no path under destDir names.\n throw wrapWriteError(\n err,\n destDir,\n `the ${name} skill`,\n await deepestExisting(dirname(target)),\n { expected: ': a skill is a directory holding SKILL.md' },\n );\n }\n }\n }\n\n if (change === 'create') return { status: dryRun ? 'would-install' : 'installed', preexisting };\n if (change === 'none') return { status: 'up-to-date', preexisting };\n return {\n status: dryRun ? 'would-update' : 'updated',\n preexisting,\n // The hosted skill is a MIRROR of tenjin.blog/skills.md (roadmap G4), so a\n // differing local copy is a replacement, not the drift warning the CLI skills\n // get. Neither side carries a version or date, so the wording claims no\n // direction: the local file may well be a newer fetch than this package's copy.\n warning:\n name === HOSTED_SKILL_NAME\n ? `${destDir}: the hosted Tenjin skill differed and ${dryRun ? 'would be' : 'was'} replaced by this package's mirror of tenjin.blog/skills.md, which may be older; it stays as the zero-install fallback. Re-fetch it from tenjin.blog/skills.md if you need the current one.`\n : `${destDir}: local edits to ${name}'s SKILL.md ${dryRun ? 'would be' : 'were'} overwritten (the packaged copy is canonical).`,\n };\n}\n\n/**\n * Read a shipped file, or null when it is not there.\n *\n * The node-type guard lives in `readSkillFile`, shared with the wiring check and\n * the staleness check, because all three read the same operator-controlled paths\n * and a pipe at one of them used to hang whichever command got there first.\n */\nasync function readShippedFile(\n path: string,\n name: string,\n destDir: string,\n): Promise<Buffer | null> {\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return null;\n if (read.kind === 'ok') return read.bytes;\n if (read.kind === 'not-regular') {\n throw new CliError('INTERNAL', `${path} is not a regular file, so ${name} was not written.`, {\n fix: `A skill file must be a regular file. Check what is there (\\`ls -l ${path}\\`) and remove or replace it, then re-run \\`tenjin install\\`.`,\n });\n }\n // Names the FILE, not its directory: this is a read failure, and pointing at a\n // perfectly writable parent is what sent operators to chmod the wrong thing.\n throw wrapWriteError(read.err, destDir, `the ${name} skill`, path, { verb: 'read' });\n}\n\n/**\n * A destination the operator manages through a symlink is written THROUGH it, so\n * their link survives and their target is what actually changes. Same call the\n * settings.json writer makes, and the same reason: committing with `rename` over a\n * link would replace it with a regular file and strand the target.\n */\nexport async function resolveThroughLink(path: string, name: string): Promise<string> {\n const entry = await lstat(path).catch(() => null);\n if (entry === null || !entry.isSymbolicLink()) return path;\n const target = await realpath(path).catch(() => null);\n if (target !== null) return target;\n throw new CliError('INTERNAL', `${path} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a path that exists, or remove it (\\`ls -ld ${path}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * On a case-insensitive filesystem (the macOS default), a user directory named a\n * case variant of a shipped skill ALIASES the skill's path, so the write would\n * replace the user's own SKILL.md under a warning naming a path that is not on\n * disk. Detected by the alias itself: the destination resolves but the parent\n * lists only a differently-cased entry, which also means a case-SENSITIVE\n * filesystem (where both names can coexist) never trips this. Dry runs too.\n */\nasync function assertNoCaseCollision(destDir: string, name: string): Promise<void> {\n if (!existsSync(destDir)) return;\n const entries = await readdir(dirname(destDir)).catch(() => null);\n if (entries === null || entries.includes(name)) return;\n const variant = entries.find((e) => e.toLowerCase() === name.toLowerCase());\n if (variant === undefined) return;\n const actual = join(dirname(destDir), variant);\n throw new CliError(\n 'INTERNAL',\n `${actual} is a case variant of the ${name} skill and this filesystem treats them as the same directory, so ${name} was not written.`,\n {\n fix: `Rename or remove ${actual}, then re-run \\`tenjin install\\`.`,\n },\n );\n}\n\n/**\n * Fail a destination directory that is a BROKEN SYMLINK, on dry runs too, so a dry\n * run cannot report `would-install` where the real run cannot write. It checks only\n * that: an unwritable but real directory passes here and fails at the write, with\n * the permission-denied error.\n */\nasync function assertReachable(destDir: string, name: string): Promise<void> {\n const entry = await lstat(destDir).catch(() => null);\n if (entry?.isSymbolicLink() !== true) return;\n if ((await realpath(destDir).catch(() => null)) !== null) return;\n throw new CliError('INTERNAL', `${destDir} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a directory that exists, or remove it (\\`ls -ld ${destDir}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * The directory a denied WRITE should point the operator at: the deepest existing\n * ancestor of the failed target's directory, RESOLVED. An existing skill directory\n * that refuses the temp file names itself; a directory that could not be created\n * names the ancestor that refused to create it, because `ls -ld` on a path that is\n * not there says nothing. Resolved because a destination managed through a symlink\n * denies the write in the link's TARGET, and telling the operator to chmod the\n * link's path leaves them staring at a healthy link.\n */\nexport async function deepestExisting(dir: string): Promise<string> {\n for (let cur = dir; ; cur = dirname(cur)) {\n if (existsSync(cur)) return realpath(cur).catch(() => cur);\n if (dirname(cur) === cur) return cur;\n }\n}\n\n/** A raw errno under INTERNAL reads as a CLI bug and carries no fix. */\nexport function wrapWriteError(\n err: unknown,\n /** The destination as the operator knows it (the declared path, pre-resolution). */\n dest: string,\n /** What could not be written, e.g. `the tenjin-search skill` or `the Tenjin pointer`. */\n subject: string,\n /**\n * The path to point the operator at. A READ failure names the file itself, which\n * is the thing whose mode is wrong. A WRITE failure names the deepest existing\n * directory on the failed target's resolved path.\n */\n culprit: string,\n opts: {\n /** Which side failed; a read error reported as \"could not write\" misleads. */\n verb?: 'read' | 'write';\n /** Sentence tail for the wrong-kind fix, telling the operator the expected shape. */\n expected?: string;\n } = {},\n): unknown {\n const verb = opts.verb ?? 'write';\n const denied = hasCode(err, 'EACCES') || hasCode(err, 'EPERM');\n const missing = hasCode(err, 'ENOENT');\n // A skills directory that resolves to a regular file, or a SKILL.md that resolves\n // to a directory. Pathological, but a raw ENOTDIR/EISDIR says nothing about which\n // path is the wrong kind of thing.\n const wrongKind = hasCode(err, 'ENOTDIR') || hasCode(err, 'EISDIR');\n if (!denied && !missing && !wrongKind) return err;\n const fix = denied\n ? `Permission denied on ${culprit}. Check it (\\`ls -ld ${culprit}\\`), then re-run \\`tenjin install\\`.`\n : wrongKind\n ? `${dest} (or a path inside it) is not the kind of thing it needs to be${opts.expected ?? ''}. Check it (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`\n : `${dest} could not be created; if it is a symlink, check that its target exists (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`;\n return new CliError(\n 'INTERNAL',\n `Could not ${verb} ${subject} ${verb === 'read' ? 'at' : 'to'} ${dest}.`,\n { fix, cause: err },\n );\n}\n\n/**\n * Read a directory tree into a rel-path -> content map, or null when it does not\n * exist. Reads as raw `Buffer`, not `utf8`: today's skills are markdown-only, but\n * this is a general recursive dir-copy, and decoding to a string here would\n * silently corrupt a future non-text asset (an image, a font) on write, or worse,\n * make two different corrupted binaries both decode to U+FFFD and compare equal.\n */\nasync function readTree(dir: string): Promise<Map<string, Buffer> | null> {\n if (!existsSync(dir)) return null;\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n const files = new Map<string, Buffer>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const full = join(entry.parentPath, entry.name);\n files.set(relative(dir, full), await readFile(full));\n }\n return files;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,SAAS,UAAU,YAAY;AACzD,SAAS,SAAS,MAAM,gBAAgB;AAqCxC,eAAsB,aACpB,QACA,SACA,QACA,MACA,OAA0B,CAAC,GACE;AAC7B,QAAM,MAAM,MAAM,SAAS,MAAM;AACjC,MAAI,QAAQ,MAAM;AAEhB,UAAM,IAAI,SAAS,YAAY,yBAAyB,MAAM,WAAW;AAAA,EAC3E;AAUA,QAAM,UAAU,oBAAI,IAAoB;AACxC,QAAM,gBAAgB,SAAS,IAAI;AACnC,QAAM,sBAAsB,SAAS,IAAI;AACzC,aAAW,OAAO,IAAI,KAAK,GAAG;AAC5B,UAAM,WAAW,KAAK,SAAS,GAAG;AAClC,YAAQ;AAAA,MACN;AAAA,MACA,KAAK,mBAAmB,QAAQ,WAAW,MAAM,mBAAmB,UAAU,IAAI;AAAA,IACpF;AAAA,EACF;AAEA,MAAI,UAAU;AACd,MAAI,cAAc;AAClB,aAAW,CAAC,KAAK,OAAO,KAAK,KAAK;AAChC,UAAM,UAAU,MAAM,gBAAgB,QAAQ,IAAI,GAAG,GAAI,MAAM,OAAO;AACtE,QAAI,QAAQ,WAAY,eAAc,YAAY;AAClD,QAAI,YAAY,QAAQ,CAAC,QAAQ,OAAO,OAAO,EAAG,WAAU;AAAA,EAC9D;AACA,QAAM,SAAS,CAAC,cAAc,WAAW,UAAU,WAAW;AAE9D,MAAI,CAAC,UAAU,WAAW,QAAQ;AAChC,eAAW,CAAC,KAAK,OAAO,KAAK,KAAK;AAChC,YAAM,SAAS,QAAQ,IAAI,GAAG;AAC9B,UAAI;AAIF,cAAM,UAAU,MAAM,KAAK,MAAM,EAAE,MAAM,MA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A,EACnC;AACF;AAGO,SAAS,eACd,KAEA,MAEA,SAMA,SACA,OAKI,CAAC,GACI;AACT,QAAM,OAAO,KAAK,QAAQ;AAC1B,QAAM,SAAS,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,OAAO;AAC7D,QAAM,UAAU,QAAQ,KAAK,QAAQ;AAIrC,QAAM,YAAY,QAAQ,KAAK,SAAS,KAAK,QAAQ,KAAK,QAAQ;AAClE,MAAI,CAAC,UAAU,CAAC,WAAW,CAAC,UAAW,QAAO;AAC9C,QAAM,MAAM,SACR,wBAAwB,OAAO,wBAAwB,OAAO,yCAC9D,YACE,GAAG,IAAI,iEAAiE,KAAK,YAAY,EAAE,wBAAwB,IAAI,yCACvH,GAAG,IAAI,qFAAqF,IAAI;AACtG,SAAO,IAAI;AAAA,IACT;AAAA,IACA,aAAa,IAAI,IAAI,OAAO,IAAI,SAAS,SAAS,OAAO,IAAI,IAAI,IAAI;AAAA,IACrE,EAAE,KAAK,OAAO,IAAI;AAAA,EACpB;AACF;AASA,eAAe,SAAS,KAAkD;AACxE,MAAI,CAAC,WAAW,GAAG,EAAG,QAAO;AAC7B,QAAM,UAAU,MAAM,QAAQ,KAAK,EAAE,WAAW,MAAM,eAAe,KAAK,CAAC;AAC3E,QAAM,QAAQ,oBAAI,IAAoB;AACtC,aAAW,SAAS,SAAS;AAC3B,QAAI,CAAC,MAAM,OAAO,EAAG;AACrB,UAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;AAC9C,UAAM,IAAI,SAAS,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI,CAAC;AAAA,EACrD;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/skill-writer.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { hasCode } from './errno';\nimport { CliError } from './errors';\nimport { HOSTED_SKILL_NAME, readSkillFile } from './skill-wiring';\n\n/**\n * Writing one packaged skill into one harness directory, and the path guards that\n * write needs. Its own module, free of the command layer's dependencies, because\n * `install` and the post-command self-heal both write skills and the heal runs on\n * every command: reaching into commands/install would parse the wallet's viem\n * chunk on a `tenjin config`.\n */\n\nexport type SkillInstallStatus =\n 'installed' | 'updated' | 'up-to-date' | 'would-install' | 'would-update';\n\nexport interface SkillInstallResult {\n status: SkillInstallStatus;\n warning?: string;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n}\n\nexport interface SkillWriteOptions {\n /**\n * Write THROUGH a symlinked destination (default), or replace it. `install`\n * follows the link, because the operator pointed it somewhere on purpose. The\n * unattended self-heal does not, and passes false: it has already refused every\n * link it could see, and this closes the gap between that look and this write,\n * where a link appearing in between would otherwise be followed. `rename` never\n * follows its final component, so the worst a race can now do is leave our\n * regular file where the new link was.\n */\n followSymlinks?: boolean;\n}\n\nexport async function installSkill(\n srcDir: string,\n destDir: string,\n dryRun: boolean,\n name: string,\n opts: SkillWriteOptions = {},\n): Promise<SkillInstallResult> {\n const src = await readTree(srcDir);\n if (src === null) {\n // assertSkillsSource already guards SKILL.md; this is defensive for an empty dir.\n throw new CliError('INTERNAL', `Packaged skill source ${srcDir} is empty`);\n }\n\n // Only the files this package SHIPS are read and written. Everything else in the\n // directory belongs to the operator: never inspected, listed, or removed. That is\n // what package managers do (npm, dpkg, Homebrew all own their files, not the\n // directory), and wholesale replacement was the single cause behind a run of\n // data-loss, symlink and enumeration bugs.\n //\n // Resolved on BOTH paths, dry run included, so a dry run cannot promise a write\n // the real run refuses.\n const writeTo = new Map<string, string>();\n await assertReachable(destDir, name);\n await assertNoCaseCollision(destDir, name);\n for (const rel of src.keys()) {\n const declared = join(destDir, rel);\n writeTo.set(\n rel,\n opts.followSymlinks === false ? declared : await resolveThroughLink(declared, name),\n );\n }\n\n let differs = false;\n let preexisting = false;\n for (const [rel, content] of src) {\n const current = await readShippedFile(writeTo.get(rel)!, name, destDir);\n if (rel === 'SKILL.md') preexisting = current !== null;\n if (current === null || !current.equals(content)) differs = true;\n }\n const change = !preexisting ? 'create' : differs ? 'update' : 'none';\n\n if (!dryRun && change !== 'none') {\n for (const [rel, content] of src) {\n const target = writeTo.get(rel)!;\n try {\n // An existing file keeps the mode it has. A skill an operator (or their\n // dotfiles) made group-readable or read-only is theirs to have set that\n // way, and an update is no reason to hand it back at the default 0644.\n const current = await stat(target).catch(() => null);\n await writeFileAtomic(\n target,\n content,\n current === null ? {} : { mode: current.mode & 0o777 },\n );\n } catch (err) {\n // Culprit is derived from the file that FAILED, not assumed to be the\n // skills root: an existing skill directory that refuses the temp file is\n // itself the thing to chmod, and a symlinked SKILL.md fails in the link's\n // TARGET directory, which no path under destDir names.\n throw wrapWriteError(\n err,\n destDir,\n `the ${name} skill`,\n await deepestExisting(dirname(target)),\n { expected: ': a skill is a directory holding SKILL.md' },\n );\n }\n }\n }\n\n if (change === 'create') return { status: dryRun ? 'would-install' : 'installed', preexisting };\n if (change === 'none') return { status: 'up-to-date', preexisting };\n return {\n status: dryRun ? 'would-update' : 'updated',\n preexisting,\n // The hosted skill is a MIRROR of tenjin.blog/skills.md (roadmap G4), so a\n // differing local copy is a replacement, not the drift warning the CLI skills\n // get. Neither side carries a version or date, so the wording claims no\n // direction: the local file may well be a newer fetch than this package's copy.\n warning:\n name === HOSTED_SKILL_NAME\n ? `${destDir}: the hosted Tenjin skill differed and ${dryRun ? 'would be' : 'was'} replaced by this package's mirror of tenjin.blog/skills.md, which may be older; it stays as the zero-install fallback. Re-fetch it from tenjin.blog/skills.md if you need the current one.`\n : `${destDir}: local edits to ${name}'s SKILL.md ${dryRun ? 'would be' : 'were'} overwritten (the packaged copy is canonical).`,\n };\n}\n\n/**\n * Read a shipped file, or null when it is not there.\n *\n * The node-type guard lives in `readSkillFile`, shared with the wiring check and\n * the staleness check, because all three read the same operator-controlled paths\n * and a pipe at one of them used to hang whichever command got there first.\n */\nasync function readShippedFile(\n path: string,\n name: string,\n destDir: string,\n): Promise<Buffer | null> {\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return null;\n if (read.kind === 'ok') return read.bytes;\n if (read.kind === 'not-regular') {\n throw new CliError('INTERNAL', `${path} is not a regular file, so ${name} was not written.`, {\n fix: `A skill file must be a regular file. Check what is there (\\`ls -l ${path}\\`) and remove or replace it, then re-run \\`tenjin install\\`.`,\n });\n }\n // Names the FILE, not its directory: this is a read failure, and pointing at a\n // perfectly writable parent is what sent operators to chmod the wrong thing.\n throw wrapWriteError(read.err, destDir, `the ${name} skill`, path, { verb: 'read' });\n}\n\n/**\n * A destination the operator manages through a symlink is written THROUGH it, so\n * their link survives and their target is what actually changes. Same call the\n * settings.json writer makes, and the same reason: committing with `rename` over a\n * link would replace it with a regular file and strand the target.\n */\nexport async function resolveThroughLink(path: string, name: string): Promise<string> {\n const entry = await lstat(path).catch(() => null);\n if (entry === null || !entry.isSymbolicLink()) return path;\n const target = await realpath(path).catch(() => null);\n if (target !== null) return target;\n throw new CliError('INTERNAL', `${path} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a path that exists, or remove it (\\`ls -ld ${path}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * On a case-insensitive filesystem (the macOS default), a user directory named a\n * case variant of a shipped skill ALIASES the skill's path, so the write would\n * replace the user's own SKILL.md under a warning naming a path that is not on\n * disk. Detected by the alias itself: the destination resolves but the parent\n * lists only a differently-cased entry, which also means a case-SENSITIVE\n * filesystem (where both names can coexist) never trips this. Dry runs too.\n */\nasync function assertNoCaseCollision(destDir: string, name: string): Promise<void> {\n if (!existsSync(destDir)) return;\n const entries = await readdir(dirname(destDir)).catch(() => null);\n if (entries === null || entries.includes(name)) return;\n const variant = entries.find((e) => e.toLowerCase() === name.toLowerCase());\n if (variant === undefined) return;\n const actual = join(dirname(destDir), variant);\n throw new CliError(\n 'INTERNAL',\n `${actual} is a case variant of the ${name} skill and this filesystem treats them as the same directory, so ${name} was not written.`,\n {\n fix: `Rename or remove ${actual}, then re-run \\`tenjin install\\`.`,\n },\n );\n}\n\n/**\n * Fail a destination directory that is a BROKEN SYMLINK, on dry runs too, so a dry\n * run cannot report `would-install` where the real run cannot write. It checks only\n * that: an unwritable but real directory passes here and fails at the write, with\n * the permission-denied error.\n */\nasync function assertReachable(destDir: string, name: string): Promise<void> {\n const entry = await lstat(destDir).catch(() => null);\n if (entry?.isSymbolicLink() !== true) return;\n if ((await realpath(destDir).catch(() => null)) !== null) return;\n throw new CliError('INTERNAL', `${destDir} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a directory that exists, or remove it (\\`ls -ld ${destDir}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * The directory a denied WRITE should point the operator at: the deepest existing\n * ancestor of the failed target's directory, RESOLVED. An existing skill directory\n * that refuses the temp file names itself; a directory that could not be created\n * names the ancestor that refused to create it, because `ls -ld` on a path that is\n * not there says nothing. Resolved because a destination managed through a symlink\n * denies the write in the link's TARGET, and telling the operator to chmod the\n * link's path leaves them staring at a healthy link.\n */\nexport async function deepestExisting(dir: string): Promise<string> {\n for (let cur = dir; ; cur = dirname(cur)) {\n if (existsSync(cur)) return realpath(cur).catch(() => cur);\n if (dirname(cur) === cur) return cur;\n }\n}\n\n/** A raw errno under INTERNAL reads as a CLI bug and carries no fix. */\nexport function wrapWriteError(\n err: unknown,\n /** The destination as the operator knows it (the declared path, pre-resolution). */\n dest: string,\n /** What could not be written, e.g. `the tenjin-search skill` or `the Tenjin pointer`. */\n subject: string,\n /**\n * The path to point the operator at. A READ failure names the file itself, which\n * is the thing whose mode is wrong. A WRITE failure names the deepest existing\n * directory on the failed target's resolved path.\n */\n culprit: string,\n opts: {\n /** Which side failed; a read error reported as \"could not write\" misleads. */\n verb?: 'read' | 'write';\n /** Sentence tail for the wrong-kind fix, telling the operator the expected shape. */\n expected?: string;\n } = {},\n): unknown {\n const verb = opts.verb ?? 'write';\n const denied = hasCode(err, 'EACCES') || hasCode(err, 'EPERM');\n const missing = hasCode(err, 'ENOENT');\n // A skills directory that resolves to a regular file, or a SKILL.md that resolves\n // to a directory. Pathological, but a raw ENOTDIR/EISDIR says nothing about which\n // path is the wrong kind of thing.\n const wrongKind = hasCode(err, 'ENOTDIR') || hasCode(err, 'EISDIR');\n if (!denied && !missing && !wrongKind) return err;\n const fix = denied\n ? `Permission denied on ${culprit}. Check it (\\`ls -ld ${culprit}\\`), then re-run \\`tenjin install\\`.`\n : wrongKind\n ? `${dest} (or a path inside it) is not the kind of thing it needs to be${opts.expected ?? ''}. Check it (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`\n : `${dest} could not be created; if it is a symlink, check that its target exists (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`;\n return new CliError(\n 'INTERNAL',\n `Could not ${verb} ${subject} ${verb === 'read' ? 'at' : 'to'} ${dest}.`,\n { fix, cause: err },\n );\n}\n\n/**\n * Read a directory tree into a rel-path -> content map, or null when it does not\n * exist. Reads as raw `Buffer`, not `utf8`: today's skills are markdown-only, but\n * this is a general recursive dir-copy, and decoding to a string here would\n * silently corrupt a future non-text asset (an image, a font) on write, or worse,\n * make two different corrupted binaries both decode to U+FFFD and compare equal.\n */\nasync function readTree(dir: string): Promise<Map<string, Buffer> | null> {\n if (!existsSync(dir)) return null;\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n const files = new Map<string, Buffer>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const full = join(entry.parentPath, entry.name);\n files.set(relative(dir, full), await readFile(full));\n }\n return files;\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,SAAS,UAAU,YAAY;AACzD,SAAS,SAAS,MAAM,gBAAgB;AAqCxC,eAAsB,aACpB,QACA,SACA,QACA,MACA,OAA0B,CAAC,GACE;AAC7B,QAAM,MAAM,MAAM,SAAS,MAAM;AACjC,MAAI,QAAQ,MAAM;AA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