tenjin-cli 0.1.0-alpha.4 → 0.1.0-alpha.7
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 +269 -38
- package/dist/{buy-OOOLUDND.js → buy-XVOMNWKN.js} +21 -18
- package/dist/{candidate-TWCWTFGA.js → candidate-DJB2NNTG.js} +7 -8
- package/dist/{chunk-KXIX7YDV.js → chunk-2KIDDWQO.js} +5 -5
- package/dist/{chunk-NXCJN2FJ.js → chunk-2L73UI6T.js} +51 -42
- package/dist/chunk-2L73UI6T.js.map +1 -0
- package/dist/{chunk-OJD54DIU.js → chunk-2YX6LTCD.js} +5 -5
- package/dist/{chunk-H5ETJRQD.js → chunk-5X4EBGGU.js} +22 -14
- package/dist/chunk-5X4EBGGU.js.map +1 -0
- package/dist/chunk-6S44OLND.js +699 -0
- package/dist/chunk-6S44OLND.js.map +1 -0
- package/dist/{chunk-FU6MCSLG.js → chunk-7WDY4AXV.js} +2 -64
- package/dist/chunk-7WDY4AXV.js.map +1 -0
- package/dist/{chunk-VV4P5RVK.js → chunk-BBUYCDSG.js} +16 -4
- package/dist/chunk-BBUYCDSG.js.map +1 -0
- package/dist/chunk-CYRYVZPN.js +213 -0
- package/dist/chunk-CYRYVZPN.js.map +1 -0
- package/dist/{chunk-FHB3VKZW.js → chunk-DAJ56EUU.js} +5 -3
- package/dist/chunk-DAJ56EUU.js.map +1 -0
- package/dist/chunk-DH6D6QIO.js +239 -0
- package/dist/chunk-DH6D6QIO.js.map +1 -0
- package/dist/chunk-E6BNARCS.js +614 -0
- package/dist/chunk-E6BNARCS.js.map +1 -0
- package/dist/chunk-GABYDXWL.js +190 -0
- package/dist/chunk-GABYDXWL.js.map +1 -0
- package/dist/{chunk-EUQN3L5X.js → chunk-GM4RZUVU.js} +21 -9
- package/dist/chunk-GM4RZUVU.js.map +1 -0
- package/dist/{chunk-C4TIWOAM.js → chunk-GXYNLMUQ.js} +28 -11
- package/dist/chunk-GXYNLMUQ.js.map +1 -0
- package/dist/{chunk-6WWVYYSB.js → chunk-J6CVKC4M.js} +86 -4
- package/dist/chunk-J6CVKC4M.js.map +1 -0
- package/dist/{chunk-5JH7ZB6Z.js → chunk-KT2DGKFT.js} +76 -10
- package/dist/chunk-KT2DGKFT.js.map +1 -0
- package/dist/chunk-L6AV2Q73.js +105 -0
- package/dist/chunk-L6AV2Q73.js.map +1 -0
- package/dist/{chunk-333FOTUJ.js → chunk-MJZZTKCC.js} +108 -2
- package/dist/chunk-MJZZTKCC.js.map +1 -0
- package/dist/{chunk-XNNOR7F7.js → chunk-OTDI5FXG.js} +3 -5
- package/dist/{chunk-XNNOR7F7.js.map → chunk-OTDI5FXG.js.map} +1 -1
- package/dist/chunk-PIIWLEEG.js +337 -0
- package/dist/chunk-PIIWLEEG.js.map +1 -0
- package/dist/{chunk-ULLWHHIT.js → chunk-PLU3E63S.js} +468 -559
- package/dist/chunk-PLU3E63S.js.map +1 -0
- package/dist/chunk-QW2Q2KAH.js +27 -0
- package/dist/chunk-QW2Q2KAH.js.map +1 -0
- package/dist/{chunk-S3KZ3PPK.js → chunk-RGFBBNGP.js} +291 -59
- package/dist/chunk-RGFBBNGP.js.map +1 -0
- package/dist/chunk-SGK2B724.js +67 -0
- package/dist/chunk-SGK2B724.js.map +1 -0
- package/dist/chunk-UYP7G3GZ.js +412 -0
- package/dist/chunk-UYP7G3GZ.js.map +1 -0
- package/dist/{chunk-DPUMEMGM.js → chunk-VZ3AJCO5.js} +3 -5
- package/dist/{chunk-DPUMEMGM.js.map → chunk-VZ3AJCO5.js.map} +1 -1
- package/dist/{chunk-QH6677FJ.js → chunk-WDJTGVKN.js} +2 -2
- package/dist/{chunk-QH6677FJ.js.map → chunk-WDJTGVKN.js.map} +1 -1
- package/dist/{chunk-4GR7DGD6.js → chunk-WI5EOAQQ.js} +33 -256
- package/dist/{chunk-4GR7DGD6.js.map → chunk-WI5EOAQQ.js.map} +1 -1
- package/dist/{chunk-DPET3TW5.js → chunk-WRWCDLVK.js} +13 -12
- package/dist/chunk-WRWCDLVK.js.map +1 -0
- package/dist/chunk-XBJ3VLWX.js +35 -0
- package/dist/chunk-XBJ3VLWX.js.map +1 -0
- package/dist/chunk-ZEWY3RJ3.js +149 -0
- package/dist/chunk-ZEWY3RJ3.js.map +1 -0
- package/dist/chunk-ZFE7STX7.js +143 -0
- package/dist/chunk-ZFE7STX7.js.map +1 -0
- package/dist/{cli-AFSLAKR6.js → cli-7B2QNJG3.js} +247 -26
- package/dist/cli-7B2QNJG3.js.map +1 -0
- package/dist/{config-DBEEM3UA.js → config-SAQEQRFB.js} +7 -6
- package/dist/{doctor-XDA3YU6H.js → doctor-ENJ22XWN.js} +10 -8
- package/dist/{publish-IH7RJXGB.js → edit-2QO5GQDU.js} +19 -17
- package/dist/index.js +1 -1
- package/dist/{inspect-YBGDAG47.js → inspect-IPKKQB2S.js} +16 -15
- package/dist/{install-7J6KKEEP.js → install-7ZIYISQ7.js} +180 -133
- package/dist/install-7ZIYISQ7.js.map +1 -0
- package/dist/outcome-NSDE2KAJ.js +20 -0
- package/dist/publish-7WIFFNFG.js +40 -0
- package/dist/read-5TQR7LCF.js +158 -0
- package/dist/read-5TQR7LCF.js.map +1 -0
- package/dist/{run-DCZFEW2C.js → run-NPKIP26Y.js} +109 -34
- package/dist/{run-DCZFEW2C.js.map → run-NPKIP26Y.js.map} +1 -1
- package/dist/search-63ELMRZH.js +24 -0
- package/dist/send-ENE47KQE.js +222 -0
- package/dist/send-ENE47KQE.js.map +1 -0
- package/dist/session-FZU4VFFE.js +87 -0
- package/dist/session-FZU4VFFE.js.map +1 -0
- package/dist/{usdc-AU6ZIKA6.js → usdc-4VCDHFWX.js} +20 -4
- package/dist/{wallet-UWHSHWC6.js → wallet-OCCGEH6H.js} +8 -8
- package/dist/{wallet-HKG3GSTX.js → wallet-RBDVNZVR.js} +17 -7
- package/dist/wallet-RBDVNZVR.js.map +1 -0
- package/package.json +1 -1
- package/skills/tenjin/SKILL.md +32 -7
- package/skills/tenjin-publish/SKILL.md +109 -16
- package/skills/tenjin-search/SKILL.md +174 -15
- package/dist/chunk-333FOTUJ.js.map +0 -1
- package/dist/chunk-5JH7ZB6Z.js.map +0 -1
- package/dist/chunk-6WWVYYSB.js.map +0 -1
- package/dist/chunk-BXUS5UCT.js +0 -212
- package/dist/chunk-BXUS5UCT.js.map +0 -1
- package/dist/chunk-C4TIWOAM.js.map +0 -1
- package/dist/chunk-CJU555P5.js +0 -333
- package/dist/chunk-CJU555P5.js.map +0 -1
- package/dist/chunk-DPET3TW5.js.map +0 -1
- package/dist/chunk-EUQN3L5X.js.map +0 -1
- package/dist/chunk-FHB3VKZW.js.map +0 -1
- package/dist/chunk-FU6MCSLG.js.map +0 -1
- package/dist/chunk-H5ETJRQD.js.map +0 -1
- package/dist/chunk-MM4TGTST.js +0 -59
- package/dist/chunk-MM4TGTST.js.map +0 -1
- package/dist/chunk-MUBUQVC3.js +0 -67
- package/dist/chunk-MUBUQVC3.js.map +0 -1
- package/dist/chunk-NXCJN2FJ.js.map +0 -1
- package/dist/chunk-R7BMDJZM.js +0 -167
- package/dist/chunk-R7BMDJZM.js.map +0 -1
- package/dist/chunk-S3KZ3PPK.js.map +0 -1
- package/dist/chunk-ULLWHHIT.js.map +0 -1
- package/dist/chunk-VV4P5RVK.js.map +0 -1
- package/dist/chunk-YFREUEUI.js +0 -78
- package/dist/chunk-YFREUEUI.js.map +0 -1
- package/dist/cli-AFSLAKR6.js.map +0 -1
- package/dist/install-7J6KKEEP.js.map +0 -1
- package/dist/outcome-ZFGHX2XW.js +0 -20
- package/dist/search-R6NIQFXI.js +0 -24
- /package/dist/{buy-OOOLUDND.js.map → buy-XVOMNWKN.js.map} +0 -0
- /package/dist/{candidate-TWCWTFGA.js.map → candidate-DJB2NNTG.js.map} +0 -0
- /package/dist/{chunk-KXIX7YDV.js.map → chunk-2KIDDWQO.js.map} +0 -0
- /package/dist/{chunk-OJD54DIU.js.map → chunk-2YX6LTCD.js.map} +0 -0
- /package/dist/{config-DBEEM3UA.js.map → config-SAQEQRFB.js.map} +0 -0
- /package/dist/{doctor-XDA3YU6H.js.map → doctor-ENJ22XWN.js.map} +0 -0
- /package/dist/{inspect-YBGDAG47.js.map → edit-2QO5GQDU.js.map} +0 -0
- /package/dist/{outcome-ZFGHX2XW.js.map → inspect-IPKKQB2S.js.map} +0 -0
- /package/dist/{publish-IH7RJXGB.js.map → outcome-NSDE2KAJ.js.map} +0 -0
- /package/dist/{search-R6NIQFXI.js.map → publish-7WIFFNFG.js.map} +0 -0
- /package/dist/{usdc-AU6ZIKA6.js.map → search-63ELMRZH.js.map} +0 -0
- /package/dist/{wallet-HKG3GSTX.js.map → usdc-4VCDHFWX.js.map} +0 -0
- /package/dist/{wallet-UWHSHWC6.js.map → wallet-OCCGEH6H.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { listCandidates } from '../lib/candidate-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 verbatim (spec 10), and records the searchId +\n * candidates locally so `outcome --last` and `buy <resourceId>` can use them. No\n * wallet, no signing: search is anonymous.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/agent/searches/<searchId>/outcomes. tenjin#463 renamed both the field\n * (from `lookupId`) and that path, and this client follows the rename end to end,\n * so nothing on the wire or in the local store still speaks `lookupId`.\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}\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 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 candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n });\n\n // A parked-candidate nudge on stderr (not in the machine JSON), MISS only: a\n // MISS is the moment to publish the answer you are about to derive, and stale\n // drafts should not rot unseen. A HIT is not a publish moment, and hot search\n // paths should not get advisory noise every call. One line, only when parked.\n if (response.decision === 'MISS') await emitCandidateNudge(ctx);\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 const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${c.price} atomic, ${sanitizeForTerminal(c.url)}`,\n ),\n ];\n\n return { data: response, humanLines };\n}\n\nconst STALE_MS = 7 * 24 * 60 * 60 * 1000;\n\n/** One stderr line naming parked candidates (and how many are stale >7d), so a\n * search is a reminder to publish/tidy the local pen. Silent when none parked. */\nasync function emitCandidateNudge(ctx: CommandContext): Promise<void> {\n const records = await listCandidates(ctx.dataDir);\n if (records.length === 0) return;\n const now = Date.now();\n const stale = records.filter((r) => now - Date.parse(r.meta.created) > STALE_MS).length;\n ctx.io.stderr.write(\n `${records.length} candidate(s) parked (${stale} stale >7d) - tenjin candidate list\\n`,\n );\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,eAAsB,UACpB,MACA,KACA,OAAmB,CAAC,GACI;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,QAAqB,EAAE,UAAU,KAAK,SAAS;AACrD,MAAI,KAAK,aAAa,OAAW,OAAM,WAAW,iBAAiB,KAAK,QAAQ;AAChF,MAAI,KAAK,g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AAA,MACrE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAIA,SAAS,eAAe,OAA2C;AACjE,QAAM,MAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACxB,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,MAAM,GAAG;AACX,YAAM,IAAI,SAAS,SAAS,yBAAyB,KAAK,UAAU,IAAI,CAAC,IAAI;AAAA,QAC3E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,UAAM,MAAM,KAAK,MAAM,GAAG,EAAE,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":[]}
|
package/dist/chunk-MM4TGTST.js
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
findStoredCandidate
|
|
4
|
-
} from "./chunk-XNNOR7F7.js";
|
|
5
|
-
import {
|
|
6
|
-
UUID_RE
|
|
7
|
-
} from "./chunk-WWX32ML4.js";
|
|
8
|
-
import {
|
|
9
|
-
CliError
|
|
10
|
-
} from "./chunk-6WWVYYSB.js";
|
|
11
|
-
|
|
12
|
-
// src/lib/resource-ref.ts
|
|
13
|
-
function assertOnBaseOrigin(url, baseUrl, what) {
|
|
14
|
-
let target;
|
|
15
|
-
let base;
|
|
16
|
-
try {
|
|
17
|
-
target = new URL(url);
|
|
18
|
-
base = new URL(baseUrl);
|
|
19
|
-
} catch {
|
|
20
|
-
throw new CliError("USAGE", `Invalid ${what}: ${JSON.stringify(url)}`, {
|
|
21
|
-
fix: "Pass an absolute https URL on the configured base URL."
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
if (target.origin !== base.origin) {
|
|
25
|
-
throw new CliError(
|
|
26
|
-
"USAGE",
|
|
27
|
-
`${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,
|
|
28
|
-
{
|
|
29
|
-
fix: "The CLI signs SIWX and payments only for the configured base URL. Pass --base-url if you meant a different deployment."
|
|
30
|
-
}
|
|
31
|
-
);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
async function resolveResourceRef(arg, dataDir, baseUrl) {
|
|
35
|
-
const trimmed = arg.trim();
|
|
36
|
-
if (/^https?:\/\//i.test(trimmed)) {
|
|
37
|
-
assertOnBaseOrigin(trimmed, baseUrl, "resource URL");
|
|
38
|
-
return { url: trimmed };
|
|
39
|
-
}
|
|
40
|
-
if (UUID_RE.test(trimmed)) {
|
|
41
|
-
const candidate = await findStoredCandidate(dataDir, trimmed);
|
|
42
|
-
if (candidate === null) {
|
|
43
|
-
throw new CliError("RESOURCE_NOT_FOUND", `No local search knows resource ${trimmed}.`, {
|
|
44
|
-
fix: "Run `tenjin search` to surface it first, or pass the full read URL."
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
assertOnBaseOrigin(candidate.url, baseUrl, "stored candidate URL");
|
|
48
|
-
return { url: candidate.url, resourceId: trimmed };
|
|
49
|
-
}
|
|
50
|
-
throw new CliError("USAGE", `Not a resource URL or id: ${JSON.stringify(arg)}`, {
|
|
51
|
-
fix: "Pass a full https read URL (a candidate `url`) or a resourceId uuid."
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export {
|
|
56
|
-
assertOnBaseOrigin,
|
|
57
|
-
resolveResourceRef
|
|
58
|
-
};
|
|
59
|
-
//# sourceMappingURL=chunk-MM4TGTST.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/resource-ref.ts"],"sourcesContent":["import { CliError } from './errors';\nimport { findStoredCandidate } from './search-store';\nimport { UUID_RE } from './ids';\n\n/**\n * Resolve a `<resource-url-or-id>` CLI argument to the payable read URL. A full\n * http(s) URL must live on the configured base URL's origin; a bare uuid is a\n * resourceId, resolved to its URL through the local search store (the read route\n * is keyed by handle/slug, so an id alone cannot build the URL). Anything else is\n * a usage error with a clear fix.\n *\n * The origin pin is a MONEY-PATH trust boundary, not pedantry: `buy` sends a\n * wallet-signed SIWX header (a bearer credential scoped to the configured\n * domain) and an EIP-3009 payment authorization to whatever host the resolved\n * URL names. An off-origin URL, whether typed by hand or planted in a search\n * candidate, would hand both to that host. Nothing signed may leave for a host\n * the user did not configure.\n */\n\nexport interface ResourceRef {\n url: string;\n resourceId?: string;\n}\n\n/** Throws USAGE unless `url` parses and shares the base URL's origin. */\nexport function assertOnBaseOrigin(url: string, baseUrl: string, what: string): void {\n let target: URL;\n let base: URL;\n try {\n target = new URL(url);\n base = new URL(baseUrl);\n } catch {\n throw new CliError('USAGE', `Invalid ${what}: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute https URL on the configured base URL.',\n });\n }\n if (target.origin !== base.origin) {\n throw new CliError(\n 'USAGE',\n `${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,\n {\n fix: 'The CLI signs SIWX and payments only for the configured base URL. Pass --base-url if you meant a different deployment.',\n },\n );\n }\n}\n\nexport async function resolveResourceRef(\n arg: string,\n dataDir: string,\n baseUrl: string,\n): Promise<ResourceRef> {\n const trimmed = arg.trim();\n if (/^https?:\\/\\//i.test(trimmed)) {\n assertOnBaseOrigin(trimmed, baseUrl, 'resource URL');\n return { url: trimmed };\n }\n if (UUID_RE.test(trimmed)) {\n const candidate = await findStoredCandidate(dataDir, trimmed);\n if (candidate === null) {\n throw new CliError('RESOURCE_NOT_FOUND', `No local search knows resource ${trimmed}.`, {\n fix: 'Run `tenjin search` to surface it first, or pass the full read URL.',\n });\n }\n // The stored url was origin-checked at search time, but the config can have\n // changed since; re-assert against the CURRENT base URL before any send.\n assertOnBaseOrigin(candidate.url, baseUrl, 'stored candidate URL');\n return { url: candidate.url, resourceId: trimmed };\n }\n throw new CliError('USAGE', `Not a resource URL or id: ${JSON.stringify(arg)}`, {\n fix: 'Pass a full https read URL (a candidate `url`) or a resourceId uuid.',\n });\n}\n"],"mappings":";;;;;;;;;;;;AAyBO,SAAS,mBAAmB,KAAa,SAAiB,MAAoB;AACnF,MAAI;AACJ,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG;AACpB,WAAO,IAAI,IAAI,OAAO;AAAA,EACxB,QAAQ;AACN,UAAM,IAAI,SAAS,SAAS,WAAW,IAAI,KAAK,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,MACrE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,OAAO,WAAW,KAAK,QAAQ;AACjC,UAAM,IAAI;AAAA,MACR;AAAA,MACA,GAAG,IAAI,WAAW,OAAO,MAAM,2CAA2C,KAAK,MAAM;AAAA,MACrF;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,mBACpB,KACA,SACA,SACsB;AACtB,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,gBAAgB,KAAK,OAAO,GAAG;AACjC,uBAAmB,SAAS,SAAS,cAAc;AACnD,WAAO,EAAE,KAAK,QAAQ;AAAA,EACxB;AACA,MAAI,QAAQ,KAAK,OAAO,GAAG;AACzB,UAAM,YAAY,MAAM,oBAAoB,SAAS,OAAO;AAC5D,QAAI,cAAc,MAAM;AACtB,YAAM,IAAI,SAAS,sBAAsB,kCAAkC,OAAO,KAAK;AAAA,QACrF,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAGA,uBAAmB,UAAU,KAAK,SAAS,sBAAsB;AACjE,WAAO,EAAE,KAAK,UAAU,KAAK,YAAY,QAAQ;AAAA,EACnD;AACA,QAAM,IAAI,SAAS,SAAS,6BAA6B,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,IAC9E,KAAK;AAAA,EACP,CAAC;AACH;","names":[]}
|
package/dist/chunk-MUBUQVC3.js
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
|
|
3
|
-
// src/lib/atomic-json.ts
|
|
4
|
-
import { chmod, link, mkdir, open, rename, rm, writeFile } from "fs/promises";
|
|
5
|
-
import { randomBytes } from "crypto";
|
|
6
|
-
import { basename, dirname, join } from "path";
|
|
7
|
-
var isWindows = process.platform === "win32";
|
|
8
|
-
async function writeFileAtomic(targetPath, data, opts = {}) {
|
|
9
|
-
const dir = dirname(targetPath);
|
|
10
|
-
const fileMode = opts.mode ?? 420;
|
|
11
|
-
const dirMode = opts.dirMode ?? 493;
|
|
12
|
-
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
13
|
-
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
14
|
-
try {
|
|
15
|
-
await writeFile(tmpPath, data, isWindows ? void 0 : { mode: fileMode });
|
|
16
|
-
if (!isWindows) await chmod(tmpPath, fileMode);
|
|
17
|
-
await rename(tmpPath, targetPath);
|
|
18
|
-
} catch (err) {
|
|
19
|
-
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
20
|
-
throw err;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
async function writeFileAtomicExclusive(targetPath, data, opts = {}) {
|
|
24
|
-
const dir = dirname(targetPath);
|
|
25
|
-
const fileMode = opts.mode ?? 420;
|
|
26
|
-
const dirMode = opts.dirMode ?? 493;
|
|
27
|
-
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
28
|
-
if (isWindows) {
|
|
29
|
-
const handle = await open(targetPath, "wx");
|
|
30
|
-
try {
|
|
31
|
-
await handle.writeFile(data);
|
|
32
|
-
await handle.sync();
|
|
33
|
-
} finally {
|
|
34
|
-
await handle.close();
|
|
35
|
-
}
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
39
|
-
try {
|
|
40
|
-
const handle = await open(tmpPath, "wx", fileMode);
|
|
41
|
-
try {
|
|
42
|
-
await handle.writeFile(data);
|
|
43
|
-
await handle.chmod(fileMode);
|
|
44
|
-
await handle.sync();
|
|
45
|
-
} finally {
|
|
46
|
-
await handle.close();
|
|
47
|
-
}
|
|
48
|
-
await link(tmpPath, targetPath);
|
|
49
|
-
await fsyncDir(dir);
|
|
50
|
-
} finally {
|
|
51
|
-
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
async function fsyncDir(dir) {
|
|
55
|
-
const handle = await open(dir, "r");
|
|
56
|
-
try {
|
|
57
|
-
await handle.sync();
|
|
58
|
-
} finally {
|
|
59
|
-
await handle.close();
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export {
|
|
64
|
-
writeFileAtomic,
|
|
65
|
-
writeFileAtomicExclusive
|
|
66
|
-
};
|
|
67
|
-
//# sourceMappingURL=chunk-MUBUQVC3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/atomic-json.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never called on win32. */\nasync function fsyncDir(dir: string): Promise<void> {\n const handle = await open(dir, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n"],"mappings":";;;AAAA,SAAS,OAAO,MAAM,OAAO,MAAM,QAAQ,IAAI,iBAAiB;AAChE,SAAS,mBAAmB;AAC5B,SAAS,UAAU,SAAS,YAAY;AAGxC,IAAM,YAAY,QAAQ,aAAa;AAqBvC,eAAsB,gBACpB,YACA,MACA,OAA2B,CAAC,GACb;AACf,QAAM,MAAM,QAAQ,UAAU;AAC9B,QAAM,WAAW,KAAK,QAAQ;AAC9B,QAAM,UAAU,KAAK,WAAW;AAEhC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,GAAI,YAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,EAAG,CAAC;AAE7E,QAAM,UAAU,KAAK,KAAK,IAAI,SAAS,UAAU,CAAC,IAAI,YAAY,CAAC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GA,eAAe,SAAS,KAA4B;AAClD,QAAM,SAAS,MAAM,KAAK,KAAK,GAAG;AAClC,MAAI;AACF,UAAM,OAAO,KAAK;AAAA,EACpB,UAAE;AACA,UAAM,OAAO,MAAM;AAAA,EACrB;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 1;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > 10) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n return {\n schemaVersion: 1,\n question,\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads. `decision` is uppercase on the wire.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n temporalMode: z.string(),\n appliesTo: z.record(z.string(), z.array(z.string())),\n questionsAnswered: z.array(z.string()),\n tasksSupported: z.array(z.string()),\n scope: z.string().nullable(),\n exclusions: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** Per-field caps for a browse pointer's free-form strings. `url` gets its own,\n * looser bound so a legitimate read URL is never mangled while an invented one\n * still cannot run away. Declared above the schema because the schema enforces\n * the `url` bound at parse time (see below). */\nconst BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 } as const;\n\n// A browse pointer, carried ONLY on a MISS (tenjin#460): a piece from the broad\n// discoverable corpus with deliberately NO matchReasons, NO estimatedTokens and\n// no confidence field. It is a \"you might browse this\" hint, never a scored\n// answer candidate, so it is kept strictly out of `candidates` and never\n// recorded in the local search store.\n//\n// That store exclusion makes `inspect`/`buy`/`outcome` unreachable BY\n// `resourceId` (resolveResourceRef's uuid arm needs a store hit and fails with\n// RESOURCE_NOT_FOUND), but NOT by url: resolveResourceRef's URL arm is gated on\n// origin alone and never consults the store, so `tenjin buy <browse url>` does\n// pay. That is by design here, since the url is the payable read endpoint and\n// the contract re-emits it verbatim, but it is a real spend path, so the human\n// hint line carries the price and every spend gate still applies. Do not\n// restate the old \"never reachable by inspect/buy/outcome\" claim: it was false.\n//\n// A malformed pointer fails the WHOLE response into CONTRACT_MISMATCH rather\n// than being dropped. Deliberate: this client is fail-closed on every other\n// contract deviation, and silently swallowing a bad tail would hide server\n// drift that contract.test.ts exists to catch. Pinned in agent-api.test.ts.\n//\n// The `url` bound is enforced HERE rather than by truncation in the projection\n// below, and that asymmetry with `title`/`handle` is deliberate. Those two are\n// display strings: clipping one degrades gracefully and the human still reads\n// something true. `url` is an actionable payable pointer, and a clipped url is\n// not a shorter url, it is a DIFFERENT and broken one that still looks payable\n// in `--json`. Refusing is also the only ordering-independent answer: capping\n// first would hand the origin assertion in `runSearch` a string the server never\n// sent. 512 is far above any real read endpoint, so exceeding it is server drift.\nexport const searchBrowseSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),\n title: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchBrowse = z.infer<typeof searchBrowseSchema>;\n\nexport const searchResponseSchema = z.object({\n schemaVersion: z.literal(1),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(searchCandidateSchema).optional(),\n // Omitted entirely by the server when empty, and only ever present on a MISS.\n // Not enforced here (a stricter schema would reject an otherwise-usable\n // response); truncateResponse drops it on a CANDIDATES decision instead.\n browse: z.array(searchBrowseSchema).optional(),\n});\n\nexport type SearchResponse = z.infer<typeof searchResponseSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check --base-url and your network, then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/**\n * The server bounds every card string (response budget ~1k tokens, spec 09);\n * re-apply the same caps defensively so a misbehaving server cannot blow up an\n * agent transcript through the CLI (spec 10 response-size discipline).\n */\nconst CAND_BOUNDS = {\n title: 200,\n scope: 240,\n exclusions: 240,\n listItems: 4,\n listItemChars: 160,\n matchReasons: 3,\n matchReasonChars: 80,\n appliesToKeys: 6,\n appliesToValues: 5,\n appliesToValueChars: 80,\n} as const;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResponse): SearchResponse {\n const out: SearchResponse = { ...res };\n if (res.candidates !== undefined) out.candidates = res.candidates.map(truncateCandidate);\n // Browse pointers ride the same defensive discipline, and then some. The\n // schema is `.passthrough()` so a server-invented key would otherwise survive\n // at unbounded length into `--json` and MCP structuredContent; we rebuild each\n // pointer explicitly from the five contract fields instead of spreading, which\n // drops unknown keys and is what makes the contract.test.ts \"no score-like\n // field\" pin hold at runtime and not just against the fixture. Count is capped\n // at the server's BROWSE_MAX, and every free-form string (title, url, handle)\n // at its own bound.\n //\n // `browse` is MISS-only by contract; drop it outright on a CANDIDATES decision\n // rather than trust the server, since humanLines renders no hint line there and\n // it would otherwise be an unrendered channel of server text and payable urls.\n if (res.browse !== undefined && res.decision === 'MISS') {\n out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({\n resourceId: b.resourceId,\n // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,\n // so this is the url the server sent, verbatim and payable.\n url: b.url,\n title: cap(b.title, BROWSE_BOUNDS.title),\n price: b.price,\n creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) },\n }));\n } else {\n delete out.browse;\n }\n return out;\n}\n\n/** Mirrors the server's BROWSE_MAX (lib/search-browse.ts): a MISS carries at\n * most three browse pointers. */\nconst BROWSE_MAX = 3;\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n const capList = (list: string[], items: number, chars: number): string[] =>\n list.slice(0, items).map((s) => cap(s, chars));\n const appliesTo: Record<string, string[]> = {};\n for (const key of Object.keys(c.appliesTo).slice(0, CAND_BOUNDS.appliesToKeys)) {\n appliesTo[cap(key, CAND_BOUNDS.appliesToValueChars)] = capList(\n c.appliesTo[key] ?? [],\n CAND_BOUNDS.appliesToValues,\n CAND_BOUNDS.appliesToValueChars,\n );\n }\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n scope: c.scope === null ? null : cap(c.scope, CAND_BOUNDS.scope),\n exclusions: c.exclusions === null ? null : cap(c.exclusions, CAND_BOUNDS.exclusions),\n questionsAnswered: capList(\n c.questionsAnswered,\n CAND_BOUNDS.listItems,\n CAND_BOUNDS.listItemChars,\n ),\n tasksSupported: capList(c.tasksSupported, CAND_BOUNDS.listItems, CAND_BOUNDS.listItemChars),\n matchReasons: capList(c.matchReasons, CAND_BOUNDS.matchReasons, CAND_BOUNDS.matchReasonChars),\n appliesTo,\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;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ACjC,QAAQ;AAAA,IACR,WAAW,KAAK;AAAA,IAChB,SAAS,EAAE,mBAAmB,cAAc;AAAA,IAC5C,UAAU,MAAM,WAAW,IAAI,MAAM,CAAC,IAAI;AAAA,IAC1C,WAAW,KAAK;AAAA,EAClB,CAAC;AACD,MAAI,CAAC,IAAI,GAAI,OAAM,WAAW,KAAK,GAAG;AACtC,MAAI,IAAI,WAAW,IAAK,OAAM,eAAe,KAAK,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC;AAGtE,MAAI,IAAI,WAAW,KAAK;AACtB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,mBAAmB,IAAI,IAAI,KAAK,0BAA0B,IAAI,MAAM;AAAA,MACpE;AAAA,QACE,KAAK;AAAA,QACL,SAAS,IAAI;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACA,QAAM,WACJ,OAAO,IAAI,SAAS,YAAY,IAAI,SAAS,QAAQ,cAAc,IAAI,OACnE,OAAQ,IAAI,KAA+B,QAAQ,IACnD,MAAM;AACZ,SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,IAAI,WAAW,MAAM,OAAO;AACzE;","names":[]}
|
package/dist/chunk-R7BMDJZM.js
DELETED
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
createLocalWallet,
|
|
4
|
-
describeWallet,
|
|
5
|
-
resolvePassphraseForCreate,
|
|
6
|
-
resolveWalletProvider
|
|
7
|
-
} from "./chunk-S3KZ3PPK.js";
|
|
8
|
-
import {
|
|
9
|
-
walletFileExists
|
|
10
|
-
} from "./chunk-DPET3TW5.js";
|
|
11
|
-
import {
|
|
12
|
-
LockTimeoutError,
|
|
13
|
-
withFileLock
|
|
14
|
-
} from "./chunk-YBMMV4Y4.js";
|
|
15
|
-
import {
|
|
16
|
-
loadRawConfig,
|
|
17
|
-
resolveSettings,
|
|
18
|
-
toMoney
|
|
19
|
-
} from "./chunk-BXUS5UCT.js";
|
|
20
|
-
import {
|
|
21
|
-
CliError,
|
|
22
|
-
walletPath
|
|
23
|
-
} from "./chunk-6WWVYYSB.js";
|
|
24
|
-
import {
|
|
25
|
-
getUsdcBalance
|
|
26
|
-
} from "./chunk-333FOTUJ.js";
|
|
27
|
-
|
|
28
|
-
// src/commands/wallet.ts
|
|
29
|
-
import { mkdir } from "fs/promises";
|
|
30
|
-
import { join } from "path";
|
|
31
|
-
var FUNDING_LINE = "Send USDC on Base. $5 covers ~50 typical resources.";
|
|
32
|
-
var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
|
|
33
|
-
var isWindows = process.platform === "win32";
|
|
34
|
-
async function runWalletCreate(ctx, opts = {}) {
|
|
35
|
-
const { address, walletPath: path, source } = await createWalletLocked(ctx.dataDir, opts);
|
|
36
|
-
const warnings = custodyWarnings();
|
|
37
|
-
return {
|
|
38
|
-
data: {
|
|
39
|
-
address,
|
|
40
|
-
walletPath: path,
|
|
41
|
-
provider: "local",
|
|
42
|
-
policyEnforcement: "client-only",
|
|
43
|
-
keyStorage: KEY_STORAGE,
|
|
44
|
-
passphraseSource: source,
|
|
45
|
-
warnings
|
|
46
|
-
},
|
|
47
|
-
humanLines: [
|
|
48
|
-
`Wallet created: ${address}`,
|
|
49
|
-
`Key stored ${KEY_STORAGE}.`,
|
|
50
|
-
passphraseNote(source),
|
|
51
|
-
FUNDING_LINE,
|
|
52
|
-
...warnings
|
|
53
|
-
]
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
async function createWalletLocked(dir, opts) {
|
|
57
|
-
await mkdir(dir, { recursive: true, mode: 448 });
|
|
58
|
-
const lockPath = join(dir, "wallet.create.lock");
|
|
59
|
-
try {
|
|
60
|
-
return await withFileLock(lockPath, async () => {
|
|
61
|
-
await refuseIfWalletExists(dir);
|
|
62
|
-
const { passphrase, source } = await resolvePassphraseForCreate({
|
|
63
|
-
env: process.env,
|
|
64
|
-
dir,
|
|
65
|
-
...opts.passphrase
|
|
66
|
-
});
|
|
67
|
-
const { address, walletPath: path } = await createLocalWallet(dir, passphrase);
|
|
68
|
-
return { address, walletPath: path, source };
|
|
69
|
-
});
|
|
70
|
-
} catch (err) {
|
|
71
|
-
if (err instanceof LockTimeoutError) {
|
|
72
|
-
throw new CliError("INTERNAL", err.message, {
|
|
73
|
-
fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
|
|
74
|
-
cause: err
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
throw err;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
function passphraseNote(source) {
|
|
81
|
-
switch (source) {
|
|
82
|
-
case "keychain":
|
|
83
|
-
return "Passphrase saved to your macOS keychain (service tenjin-cli); signing will be transparent on this machine.";
|
|
84
|
-
case "dpapi":
|
|
85
|
-
return "Passphrase saved to a DPAPI-encrypted file, readable only by you on this Windows machine; signing will be transparent here.";
|
|
86
|
-
case "secret-service":
|
|
87
|
-
return "Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli); signing will be transparent on this machine.";
|
|
88
|
-
case "env":
|
|
89
|
-
return "Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.";
|
|
90
|
-
case "prompt":
|
|
91
|
-
return "Remember your passphrase: it is required to sign and cannot be recovered.";
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
async function runWalletShow(ctx, opts = {}) {
|
|
95
|
-
const provider = resolveWalletProvider(ctx, opts);
|
|
96
|
-
const desc = await describeWallet(provider);
|
|
97
|
-
const { walletPath: path, keyStorage, passphraseSource, warnings } = await provider.diagnostics();
|
|
98
|
-
const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];
|
|
99
|
-
if (keyStorage !== void 0) humanLines.push(`Key storage: ${keyStorage}`);
|
|
100
|
-
if (passphraseSource !== void 0) humanLines.push(`Passphrase: ${passphraseSource}`);
|
|
101
|
-
humanLines.push(...warnings);
|
|
102
|
-
return {
|
|
103
|
-
data: {
|
|
104
|
-
address: desc.address,
|
|
105
|
-
provider: desc.provider,
|
|
106
|
-
credentialSource: desc.credentialSource,
|
|
107
|
-
policyEnforcement: desc.policyEnforcement,
|
|
108
|
-
...path !== void 0 ? { walletPath: path } : {},
|
|
109
|
-
...keyStorage !== void 0 ? { keyStorage } : {},
|
|
110
|
-
...passphraseSource !== void 0 ? { passphraseSource } : {},
|
|
111
|
-
warnings
|
|
112
|
-
},
|
|
113
|
-
humanLines
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
async function runWalletBalance(ctx, opts = {}) {
|
|
117
|
-
const provider = resolveWalletProvider(ctx, opts);
|
|
118
|
-
const desc = await describeWallet(provider);
|
|
119
|
-
const config = await loadRawConfig(ctx.dataDir);
|
|
120
|
-
const rpcUrl = resolveSettings({
|
|
121
|
-
config,
|
|
122
|
-
flags: { baseUrl: ctx.flags.baseUrl },
|
|
123
|
-
env: process.env
|
|
124
|
-
}).rpcUrl.value;
|
|
125
|
-
let atomic;
|
|
126
|
-
try {
|
|
127
|
-
atomic = await getUsdcBalance(desc.address, rpcUrl);
|
|
128
|
-
} catch (err) {
|
|
129
|
-
throw new CliError("RPC_ERROR", `Could not read the USDC balance from ${rpcUrl}.`, {
|
|
130
|
-
fix: "Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.",
|
|
131
|
-
cause: err
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
const balance = toMoney(atomic.toString());
|
|
135
|
-
return {
|
|
136
|
-
data: { address: desc.address, balance },
|
|
137
|
-
humanLines: [`Balance: ${balance.usd} USDC on Base`]
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
async function refuseIfWalletExists(dir) {
|
|
141
|
-
if (!await walletFileExists(dir)) return;
|
|
142
|
-
const path = walletPath(dir);
|
|
143
|
-
throw new CliError("WALLET_EXISTS", `A wallet already exists at ${path}.`, {
|
|
144
|
-
fix: `Keys are non-recoverable; move it aside first (e.g. \`mv ${path} ${path}.bak\`) to create a new one.`
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
function custodyWarnings() {
|
|
148
|
-
const warnings = [];
|
|
149
|
-
if (hasEnvKey()) {
|
|
150
|
-
warnings.push("TENJIN_WALLET_KEY is set and shadows this file at runtime.");
|
|
151
|
-
}
|
|
152
|
-
if (isWindows) {
|
|
153
|
-
warnings.push("File permissions are not enforced on Windows; the key file is not restricted.");
|
|
154
|
-
}
|
|
155
|
-
return warnings;
|
|
156
|
-
}
|
|
157
|
-
function hasEnvKey() {
|
|
158
|
-
const envKey = process.env.TENJIN_WALLET_KEY;
|
|
159
|
-
return envKey !== void 0 && envKey.length > 0;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
export {
|
|
163
|
-
runWalletCreate,
|
|
164
|
-
runWalletShow,
|
|
165
|
-
runWalletBalance
|
|
166
|
-
};
|
|
167
|
-
//# sourceMappingURL=chunk-R7BMDJZM.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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 createLocalWallet,\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { 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 = '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 /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const { address, walletPath: path, source } = 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 warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n passphraseNote(source),\n FUNDING_LINE,\n ...warnings,\n ],\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 (which is\n * last-writer-wins on every platform) BEFORE the exclusive file write, so a\n * different process can win the file, orphaning the winning wallet from the\n * passphrase the store now holds (which then decrypts nothing, unrecoverably).\n * Serializing means the loser blocks until the winner commits, then trips\n * refuseIfWalletExists and exits WALLET_EXISTS having never generated or stored a\n * passphrase. The store-before-write ordering stays (it still guards the\n * single-process crash window), and the exclusive write stays the final authority.\n */\nasync function createWalletLocked(\n dir: string,\n opts: WalletCreateOptions,\n): Promise<{ address: string; walletPath: string; source: PassphraseSource }> {\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 await refuseIfWalletExists(dir);\n const { passphrase, source } = await resolvePassphraseForCreate({\n env: process.env,\n dir,\n ...opts.passphrase,\n });\n const { address, walletPath: path } = await createLocalWallet(dir, passphrase);\n return { address, walletPath: path, source };\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): string {\n switch (source) {\n case 'keychain':\n return 'Passphrase saved to your macOS keychain (service tenjin-cli); signing will be transparent on this machine.';\n case 'dpapi':\n return 'Passphrase saved to a DPAPI-encrypted file, 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); 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 { walletPath: path, keyStorage, passphraseSource, warnings } = 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 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 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\n/** create refuses to overwrite: keys are non-recoverable and may hold funds. */\nasync function refuseIfWalletExists(dir: string): Promise<void> {\n if (!(await walletFileExists(dir))) return;\n const path = walletPath(dir);\n throw new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Keys are non-recoverable; move it aside first (e.g. \\`mv ${path} ${path}.bak\\`) to create a new one.`,\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;AAkBrB,IAAM,eAAe;AACrB,IAAM,cAAc;AACpB,IAAM,YAAY,QAAQ,aAAa;AAOvC,eAAsB,gBACpB,KACA,OAA4B,CAAC,GACL;AACxB,QAAM,EAAE,SAAS,YAAY,MAAM,OAAO,IAAI,MAAM,mBAAmB,IAAI,SAAS,IAAI;AAExF,Q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