tenjin-cli 0.1.0-alpha.27 → 0.1.0-alpha.29
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 +18 -26
- package/dist/alive-3J3CHOQP.js +21 -0
- package/dist/{chunk-XVYATBKD.js → chunk-25GGN553.js} +897 -522
- package/dist/chunk-25GGN553.js.map +1 -0
- package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
- package/dist/chunk-2SNUOHAT.js.map +1 -0
- package/dist/{chunk-5NEHH2E5.js → chunk-3FY5HG7R.js} +86 -19
- package/dist/chunk-3FY5HG7R.js.map +1 -0
- package/dist/{chunk-YQOQ6XEI.js → chunk-4FYMDRD3.js} +51 -41
- package/dist/chunk-4FYMDRD3.js.map +1 -0
- package/dist/chunk-6W5GYG3W.js +128 -0
- package/dist/chunk-6W5GYG3W.js.map +1 -0
- package/dist/{chunk-G4AM2SOL.js → chunk-AMEUXNJT.js} +4 -8
- package/dist/{chunk-G4AM2SOL.js.map → chunk-AMEUXNJT.js.map} +1 -1
- package/dist/chunk-EWLU46J6.js +100 -0
- package/dist/chunk-EWLU46J6.js.map +1 -0
- package/dist/chunk-LRCJ2IZ5.js +115 -0
- package/dist/{chunk-HC3QEZKT.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
- package/dist/{chunk-X7I343ZY.js → chunk-LX5OT4TQ.js} +3 -3
- package/dist/{chunk-X7I343ZY.js.map → chunk-LX5OT4TQ.js.map} +1 -1
- package/dist/{chunk-DATCR7AU.js → chunk-MG3G644T.js} +5 -7
- package/dist/{chunk-DATCR7AU.js.map → chunk-MG3G644T.js.map} +1 -1
- package/dist/{chunk-BOAI23CX.js → chunk-MOG7PB3A.js} +21 -15
- package/dist/chunk-MOG7PB3A.js.map +1 -0
- package/dist/{chunk-GU4GGKYP.js → chunk-MRUPDSUM.js} +14 -59
- package/dist/chunk-MRUPDSUM.js.map +1 -0
- package/dist/{chunk-AWKQSKUL.js → chunk-OOSRB3OF.js} +2 -2
- package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
- package/dist/chunk-ORWL5BSN.js.map +1 -0
- package/dist/chunk-P4LVLFO4.js +29 -0
- package/dist/chunk-P4LVLFO4.js.map +1 -0
- package/dist/{chunk-VXIBZ6W5.js → chunk-QTGUDCIR.js} +5 -5
- package/dist/{chunk-YKM2ZTA2.js → chunk-R4AO7GC2.js} +462 -105
- package/dist/chunk-R4AO7GC2.js.map +1 -0
- package/dist/{chunk-OHZYNZSD.js → chunk-RJEPZMYY.js} +12 -8
- package/dist/chunk-RJEPZMYY.js.map +1 -0
- package/dist/chunk-SBL4THYT.js +2074 -0
- package/dist/chunk-SBL4THYT.js.map +1 -0
- package/dist/{chunk-VNNXAYJE.js → chunk-SFEQGENI.js} +2 -2
- package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
- package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
- package/dist/{chunk-5FGO6TYT.js → chunk-TROZ6HL4.js} +3 -5
- package/dist/{chunk-5FGO6TYT.js.map → chunk-TROZ6HL4.js.map} +1 -1
- package/dist/{chunk-SKQQOEWH.js → chunk-USOLCBKC.js} +6 -8
- package/dist/{chunk-SKQQOEWH.js.map → chunk-USOLCBKC.js.map} +1 -1
- package/dist/{chunk-64SE3QC5.js → chunk-VKQXVCZR.js} +54 -5
- package/dist/chunk-VKQXVCZR.js.map +1 -0
- package/dist/{chunk-VIOUZW7Z.js → chunk-VVAHFCX2.js} +209 -37
- package/dist/chunk-VVAHFCX2.js.map +1 -0
- package/dist/{chunk-4L7KMA7P.js → chunk-WM7TJEBP.js} +8 -10
- package/dist/{chunk-4L7KMA7P.js.map → chunk-WM7TJEBP.js.map} +1 -1
- package/dist/{chunk-2TYQD22Q.js → chunk-XDYKZRLN.js} +23 -16
- package/dist/chunk-XDYKZRLN.js.map +1 -0
- package/dist/{chunk-LAIZ2AQA.js → chunk-XJQ6CH7X.js} +3 -2
- package/dist/{chunk-O7CUHHYU.js → chunk-ZQNGTLOC.js} +8 -10
- package/dist/{chunk-O7CUHHYU.js.map → chunk-ZQNGTLOC.js.map} +1 -1
- package/dist/{cli-6JNIPZQ6.js → cli-JPTDHGRX.js} +58 -52
- package/dist/{cli-6JNIPZQ6.js.map → cli-JPTDHGRX.js.map} +1 -1
- package/dist/{config-G75YT6NC.js → config-YYKDH2TH.js} +12 -15
- package/dist/{doctor-3GMDOW4Y.js → doctor-SSTXGCHX.js} +298 -269
- package/dist/doctor-SSTXGCHX.js.map +1 -0
- package/dist/{fund-3IPR5YRJ.js → fund-QWVWRVDK.js} +95 -43
- package/dist/{fund-3IPR5YRJ.js.map → fund-QWVWRVDK.js.map} +1 -1
- package/dist/hook-command-VWJXRT7H.js +31 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
- package/dist/hosts/claude/tenjin/.mcp.json +12 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/install-2GXXD4DK.js +51 -0
- package/dist/{install-identity-PM4AGFFX.js → install-identity-FK3YF227.js} +7 -9
- package/dist/{install-wallet-6756NOB5.js → install-wallet-TC22U52X.js} +21 -17
- package/dist/{install-wallet-6756NOB5.js.map → install-wallet-TC22U52X.js.map} +1 -1
- package/dist/{mcp-33FAAZ7F.js → mcp-42H2F4NY.js} +2128 -372
- package/dist/mcp-42H2F4NY.js.map +1 -0
- package/dist/package-6DJA3Y2O.js +37 -0
- package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
- package/dist/{pay-XOYR4PCH.js → pay-LSDJBIAZ.js} +20 -18
- package/dist/payments-SPECLBRQ.js +105 -0
- package/dist/payments-SPECLBRQ.js.map +1 -0
- package/dist/{send-CVGNOQW3.js → send-MHAOLPK3.js} +13 -17
- package/dist/{send-CVGNOQW3.js.map → send-MHAOLPK3.js.map} +1 -1
- package/dist/status-O2RWLPS5.js +114 -0
- package/dist/status-O2RWLPS5.js.map +1 -0
- package/dist/{status-line-3IQKGRUH.js → status-line-45TVCRM3.js} +7 -9
- package/dist/{status-line-3IQKGRUH.js.map → status-line-45TVCRM3.js.map} +1 -1
- package/dist/uninstall-VOK2Z5M4.js +146 -0
- package/dist/uninstall-VOK2Z5M4.js.map +1 -0
- package/dist/update-FGP3HNLD.js +33 -0
- package/dist/update-FGP3HNLD.js.map +1 -0
- package/dist/{wallet-B3FVHNTS.js → wallet-DA7OFNEW.js} +18 -14
- package/dist/wallet-DA7OFNEW.js.map +1 -0
- package/docs/agent-permissions.md +35 -22
- package/docs/safety-model.md +3 -1
- package/package.json +2 -2
- package/dist/chunk-2TYQD22Q.js.map +0 -1
- package/dist/chunk-5NEHH2E5.js.map +0 -1
- package/dist/chunk-64SE3QC5.js.map +0 -1
- package/dist/chunk-6ZSGER3A.js +0 -52
- package/dist/chunk-6ZSGER3A.js.map +0 -1
- package/dist/chunk-B2L53TMK.js.map +0 -1
- package/dist/chunk-BOAI23CX.js.map +0 -1
- package/dist/chunk-DSNXKUXI.js +0 -172
- package/dist/chunk-DSNXKUXI.js.map +0 -1
- package/dist/chunk-GU4GGKYP.js.map +0 -1
- package/dist/chunk-H2L33M7F.js +0 -944
- package/dist/chunk-H2L33M7F.js.map +0 -1
- package/dist/chunk-HC3QEZKT.js +0 -87
- package/dist/chunk-JLEF5WHM.js +0 -132
- package/dist/chunk-JLEF5WHM.js.map +0 -1
- package/dist/chunk-MAQUL5BD.js +0 -99
- package/dist/chunk-MAQUL5BD.js.map +0 -1
- package/dist/chunk-OHZYNZSD.js.map +0 -1
- package/dist/chunk-PY7MQUKP.js +0 -755
- package/dist/chunk-PY7MQUKP.js.map +0 -1
- package/dist/chunk-PZ5N6BAL.js.map +0 -1
- package/dist/chunk-TGLKKLQG.js +0 -11
- package/dist/chunk-TGLKKLQG.js.map +0 -1
- package/dist/chunk-VIOUZW7Z.js.map +0 -1
- package/dist/chunk-XVYATBKD.js.map +0 -1
- package/dist/chunk-YKM2ZTA2.js.map +0 -1
- package/dist/chunk-YQOQ6XEI.js.map +0 -1
- package/dist/doctor-3GMDOW4Y.js.map +0 -1
- package/dist/hook-command-ZXX4FT4N.js +0 -32
- package/dist/install-6OROTYHZ.js +0 -72
- package/dist/mcp-33FAAZ7F.js.map +0 -1
- package/dist/payments-UTQDBO7H.js +0 -48
- package/dist/payments-UTQDBO7H.js.map +0 -1
- package/dist/status-NACN4DGX.js +0 -72
- package/dist/status-NACN4DGX.js.map +0 -1
- package/dist/status-line-wiring-QXBOOY2T.js +0 -31
- package/dist/uninstall-NYFKSYW4.js +0 -175
- package/dist/uninstall-NYFKSYW4.js.map +0 -1
- package/dist/update-RJDA5ZY3.js +0 -442
- package/dist/update-RJDA5ZY3.js.map +0 -1
- /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
- /package/dist/{chunk-AWKQSKUL.js.map → chunk-OOSRB3OF.js.map} +0 -0
- /package/dist/{chunk-VXIBZ6W5.js.map → chunk-QTGUDCIR.js.map} +0 -0
- /package/dist/{chunk-VNNXAYJE.js.map → chunk-SFEQGENI.js.map} +0 -0
- /package/dist/{chunk-LAIZ2AQA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
- /package/dist/{hook-command-ZXX4FT4N.js.map → config-YYKDH2TH.js.map} +0 -0
- /package/dist/{install-6OROTYHZ.js.map → hook-command-VWJXRT7H.js.map} +0 -0
- /package/dist/{install-identity-PM4AGFFX.js.map → install-2GXXD4DK.js.map} +0 -0
- /package/dist/{paths-MUXHUOCM.js.map → install-identity-FK3YF227.js.map} +0 -0
- /package/dist/{pay-XOYR4PCH.js.map → package-6DJA3Y2O.js.map} +0 -0
- /package/dist/{status-line-wiring-QXBOOY2T.js.map → paths-POPTXJO6.js.map} +0 -0
- /package/dist/{wallet-B3FVHNTS.js.map → pay-LSDJBIAZ.js.map} +0 -0
|
@@ -4,6 +4,9 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
4
4
|
function normCreator(value) {
|
|
5
5
|
return value.trim().toLowerCase();
|
|
6
6
|
}
|
|
7
|
+
function allowsCreator(policy, creator) {
|
|
8
|
+
return policy.allowlistCreators.length === 0 || policy.allowlistCreators.map(normCreator).includes(normCreator(creator));
|
|
9
|
+
}
|
|
7
10
|
function evaluateSpendPolicy(policy, req) {
|
|
8
11
|
if (req.maxPriceAtomic !== void 0 && req.amountAtomic > req.maxPriceAtomic) {
|
|
9
12
|
return {
|
|
@@ -12,15 +15,12 @@ function evaluateSpendPolicy(policy, req) {
|
|
|
12
15
|
message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`
|
|
13
16
|
};
|
|
14
17
|
}
|
|
15
|
-
if (policy.
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
message: `Creator "${req.creator}" is not in allowlistCreators.`
|
|
22
|
-
};
|
|
23
|
-
}
|
|
18
|
+
if (!allowsCreator(policy, req.creator)) {
|
|
19
|
+
return {
|
|
20
|
+
decision: "deny",
|
|
21
|
+
reason: "not_allowlisted",
|
|
22
|
+
message: `Creator "${req.creator}" is not in allowlistCreators.`
|
|
23
|
+
};
|
|
24
24
|
}
|
|
25
25
|
if (req.mode === "manual") {
|
|
26
26
|
return req.amountAtomic > 0n ? {
|
|
@@ -48,23 +48,28 @@ function evaluateSpendPolicy(policy, req) {
|
|
|
48
48
|
}
|
|
49
49
|
return { decision: "allow", reason: "within_policy", message: "within spend policy" };
|
|
50
50
|
}
|
|
51
|
-
function
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
});
|
|
60
|
-
if (evaluation.decision !== "allow") return evaluation;
|
|
61
|
-
spent += step.amountAtomic;
|
|
51
|
+
function evaluatePlan(policy, payments, sessionSpentAtomic) {
|
|
52
|
+
const outside = payments.find((payment) => !allowsCreator(policy, payment.creator));
|
|
53
|
+
if (outside !== void 0) {
|
|
54
|
+
return {
|
|
55
|
+
decision: "deny",
|
|
56
|
+
reason: "not_allowlisted",
|
|
57
|
+
message: `Creator "${outside.creator}" is not in allowlistCreators.`
|
|
58
|
+
};
|
|
62
59
|
}
|
|
63
|
-
|
|
60
|
+
if (payments.length === 0) {
|
|
61
|
+
return { decision: "allow", reason: "within_policy", message: "No payment required." };
|
|
62
|
+
}
|
|
63
|
+
return evaluateSpendPolicy(policy, {
|
|
64
|
+
mode: "automatic",
|
|
65
|
+
amountAtomic: payments.reduce((sum, payment) => sum + payment.amountAtomic, 0n),
|
|
66
|
+
creator: payments[0].creator,
|
|
67
|
+
sessionSpentAtomic
|
|
68
|
+
});
|
|
64
69
|
}
|
|
65
70
|
|
|
66
71
|
export {
|
|
67
72
|
evaluateSpendPolicy,
|
|
68
|
-
|
|
73
|
+
evaluatePlan
|
|
69
74
|
};
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
75
|
+
//# sourceMappingURL=chunk-2SNUOHAT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/policy.ts"],"sourcesContent":["/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\nexport type PaymentMode = 'automatic' | 'manual';\n\nexport interface SpendPolicy {\n /** Automatic per-call ceiling; zero blocks positive automatic payments. */\n maxAutoSpendAtomic: bigint;\n /** Rolling ceiling on automatic exposure. null = no ceiling; zero blocks positive automatic payments. */\n sessionBudgetAtomic: bigint | null;\n /** Creators (handle or 0x-address, lowercased) all payments are restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n /** Omitted by legacy consumers: conservatively automatic. */\n mode?: PaymentMode;\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/** Whether `allowlistCreators` lets this creator be paid: any, when it is empty. */\nfunction allowsCreator(policy: SpendPolicy, creator: string): boolean {\n return (\n policy.allowlistCreators.length === 0 ||\n policy.allowlistCreators.map(normCreator).includes(normCreator(creator))\n );\n}\n\n/** Hard price/creator checks apply in both modes. Manual payments require consent;\n * automatic payments must fit both configured ceilings without prompting. */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (!allowsCreator(policy, req.creator)) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n\n if (req.mode === 'manual') {\n return req.amountAtomic > 0n\n ? {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'Manual payment requires explicit consent.',\n }\n : { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n\n if (policy.sessionBudgetAtomic !== null) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'deny',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/**\n * WHETHER ONE CALL'S PAYMENTS FIT, AS A WHOLE, before any is signed. Every\n * payee meets the allowlist on its own; their TOTAL meets the session budget\n * with what the window already spent, and `maxAutoSpend`, which is the\n * automatic limit for the whole call however many payments it makes. The\n * first refusal is the answer; each payment still meets the gate when it is\n * signed.\n */\nexport function evaluatePlan(\n policy: SpendPolicy,\n payments: readonly { amountAtomic: bigint; creator: string }[],\n sessionSpentAtomic: bigint,\n): PolicyEvaluation {\n const outside = payments.find((payment) => !allowsCreator(policy, payment.creator));\n if (outside !== undefined) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${outside.creator}\" is not in allowlistCreators.`,\n };\n }\n if (payments.length === 0) {\n return { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n return evaluateSpendPolicy(policy, {\n mode: 'automatic',\n amountAtomic: payments.reduce((sum, payment) => sum + payment.amountAtomic, 0n),\n creator: payments[0]!.creator,\n sessionSpentAtomic,\n });\n}\n"],"mappings":";;;AAiEA,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAGA,SAAS,cAAc,QAAqB,SAA0B;AACpE,SACE,OAAO,kBAAkB,WAAW,KACpC,OAAO,kBAAkB,IAAI,WAAW,EAAE,SAAS,YAAY,OAAO,CAAC;AAE3E;AAIO,SAAS,oBAAoB,QAAqB,KAAqC;AAC5F,MAAI,IAAI,mBAAmB,UAAa,IAAI,eAAe,IAAI,gBAAgB;AAC7E,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,gCAAgC,IAAI,cAAc;AAAA,IACtF;AAAA,EACF;AAEA,MAAI,CAAC,cAAc,QAAQ,IAAI,OAAO,GAAG;AACvC,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,YAAY,IAAI,OAAO;AAAA,IAClC;AAAA,EACF;AAEA,MAAI,IAAI,SAAS,UAAU;AACzB,WAAO,IAAI,eAAe,KACtB;AAAA,MACE,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,IACA,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,uBAAuB;AAAA,EACpF;AAEA,MAAI,OAAO,wBAAwB,MAAM;AACvC,UAAM,YAAY,IAAI,qBAAqB,IAAI;AAC/C,QAAI,YAAY,OAAO,qBAAqB;AAC1C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;AAUO,SAAS,aACd,QACA,UACA,oBACkB;AAClB,QAAM,UAAU,SAAS,KAAK,CAAC,YAAY,CAAC,cAAc,QAAQ,QAAQ,OAAO,CAAC;AAClF,MAAI,YAAY,QAAW;AACzB,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,YAAY,QAAQ,OAAO;AAAA,IACtC;AAAA,EACF;AACA,MAAI,SAAS,WAAW,GAAG;AACzB,WAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,uBAAuB;AAAA,EACvF;AACA,SAAO,oBAAoB,QAAQ;AAAA,IACjC,MAAM;AAAA,IACN,cAAc,SAAS,OAAO,CAAC,KAAK,YAAY,MAAM,QAAQ,cAAc,EAAE;AAAA,IAC9E,SAAS,SAAS,CAAC,EAAG;AAAA,IACtB;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1,29 +1,27 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
resolvePublicDestination
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-XJQ6CH7X.js";
|
|
5
5
|
import {
|
|
6
6
|
releaseUnchargedExposure
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import {
|
|
9
|
-
mask
|
|
10
|
-
} from "./chunk-7QKHZQKW.js";
|
|
7
|
+
} from "./chunk-QTGUDCIR.js";
|
|
11
8
|
import {
|
|
12
9
|
withFileLock
|
|
13
10
|
} from "./chunk-MEFB5KHA.js";
|
|
11
|
+
import {
|
|
12
|
+
mask
|
|
13
|
+
} from "./chunk-7QKHZQKW.js";
|
|
14
14
|
import {
|
|
15
15
|
hasCode
|
|
16
16
|
} from "./chunk-2I4QTOLB.js";
|
|
17
17
|
import {
|
|
18
|
-
USDC_ADDRESS
|
|
19
|
-
} from "./chunk-VIOUZW7Z.js";
|
|
20
|
-
import {
|
|
18
|
+
USDC_ADDRESS,
|
|
21
19
|
writeFileAtomic
|
|
22
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-VVAHFCX2.js";
|
|
23
21
|
import {
|
|
24
22
|
downloadsDir,
|
|
25
23
|
paidLedgerPath
|
|
26
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-SJLTEINJ.js";
|
|
27
25
|
|
|
28
26
|
// src/router/paid.ts
|
|
29
27
|
import { randomBytes } from "node:crypto";
|
|
@@ -59,6 +57,30 @@ async function appendPaidRecord(dataDir, record) {
|
|
|
59
57
|
} catch {
|
|
60
58
|
}
|
|
61
59
|
}
|
|
60
|
+
async function updatePaidRecord(dataDir, nonce, patch) {
|
|
61
|
+
try {
|
|
62
|
+
const path = paidLedgerPath(dataDir);
|
|
63
|
+
const key = nonce.toLowerCase();
|
|
64
|
+
await withFileLock(`${path}.lock`, async () => {
|
|
65
|
+
const current = parseLedger(await readFile(path, "utf8").catch(() => ""));
|
|
66
|
+
let found = false;
|
|
67
|
+
const lines = current.map(({ line, record }) => {
|
|
68
|
+
if (record?.authorization?.nonce.toLowerCase() !== key) return line;
|
|
69
|
+
found = true;
|
|
70
|
+
return JSON.stringify({
|
|
71
|
+
...record,
|
|
72
|
+
...patch.savedFiles !== void 0 ? { savedFiles: patch.savedFiles } : {},
|
|
73
|
+
...patch.txHash !== void 0 && record.settlement === "unknown" ? { txHash: patch.txHash, settlement: "settled" } : {}
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
if (found) {
|
|
77
|
+
await writeFileAtomic(path, lines.map((line) => `${line}
|
|
78
|
+
`).join(""), { mode: 384 });
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
} catch {
|
|
82
|
+
}
|
|
83
|
+
}
|
|
62
84
|
var AUTHORIZATION_STATE_SELECTOR = "0xe94a0102";
|
|
63
85
|
var WORD_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
64
86
|
var MAX_RECONCILE_CHECKS = 3;
|
|
@@ -166,6 +188,10 @@ async function reconcilePayments(dataDir, opts) {
|
|
|
166
188
|
releasedAtomic: releasedAtomic.toString()
|
|
167
189
|
};
|
|
168
190
|
}
|
|
191
|
+
async function readPaidRecords(dataDir) {
|
|
192
|
+
const raw = await readFile(paidLedgerPath(dataDir), "utf8").catch(() => "");
|
|
193
|
+
return parseLedger(raw).flatMap(({ record }) => record === null ? [] : [record]);
|
|
194
|
+
}
|
|
169
195
|
function parseLedger(raw) {
|
|
170
196
|
return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => {
|
|
171
197
|
try {
|
|
@@ -244,24 +270,42 @@ function pinnedLookup(target) {
|
|
|
244
270
|
}
|
|
245
271
|
});
|
|
246
272
|
}
|
|
273
|
+
var CAPPED = /* @__PURE__ */ Symbol("capped");
|
|
274
|
+
var FAILED = /* @__PURE__ */ Symbol("failed");
|
|
247
275
|
async function saveMedia(dataDir, stem, urls, deps = {}) {
|
|
248
276
|
const saved = [];
|
|
277
|
+
let capped = false;
|
|
278
|
+
let failed = false;
|
|
249
279
|
for (const [index, url] of urls.entries()) {
|
|
250
280
|
const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);
|
|
251
|
-
if (path
|
|
281
|
+
if (path === CAPPED) capped = true;
|
|
282
|
+
else if (path === FAILED) failed = true;
|
|
283
|
+
else if (path !== null) saved.push(path);
|
|
252
284
|
}
|
|
253
|
-
return saved;
|
|
285
|
+
return { saved, capped, failed };
|
|
254
286
|
}
|
|
287
|
+
var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429]);
|
|
255
288
|
async function saveOne(dataDir, stem, raw, deps) {
|
|
256
289
|
const transport = deps.transport ?? pinnedGet;
|
|
257
|
-
const
|
|
290
|
+
const cap = deps.maxBytes ?? MAX_MEDIA_BYTES;
|
|
291
|
+
const { budget } = deps;
|
|
292
|
+
if (budget !== void 0 && budget.leftBytes <= 0) return CAPPED;
|
|
293
|
+
let charged = 0;
|
|
294
|
+
let kept = false;
|
|
295
|
+
let capped = false;
|
|
296
|
+
let refused = false;
|
|
258
297
|
const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);
|
|
259
298
|
let target = raw;
|
|
260
299
|
let path = null;
|
|
261
300
|
try {
|
|
262
301
|
let res = null;
|
|
263
302
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
|
|
264
|
-
const pinned = await resolvePublicDestination(target, deps.destination ?? {})
|
|
303
|
+
const pinned = await resolvePublicDestination(target, deps.destination ?? {}).catch(
|
|
304
|
+
(err) => {
|
|
305
|
+
refused = true;
|
|
306
|
+
throw err;
|
|
307
|
+
}
|
|
308
|
+
);
|
|
265
309
|
res = await transport(pinned, signal);
|
|
266
310
|
if (res.status < 300 || res.status >= 400 || res.location === void 0) break;
|
|
267
311
|
res.discard();
|
|
@@ -270,12 +314,18 @@ async function saveOne(dataDir, stem, raw, deps) {
|
|
|
270
314
|
}
|
|
271
315
|
if (res === null || res.status < 200 || res.status >= 300) {
|
|
272
316
|
res?.discard();
|
|
273
|
-
|
|
317
|
+
const status = res?.status ?? 0;
|
|
318
|
+
return status >= 500 || RETRYABLE_STATUS.has(status) ? FAILED : null;
|
|
274
319
|
}
|
|
275
|
-
|
|
320
|
+
const declared = res.contentLength ?? 0;
|
|
321
|
+
if (declared > cap) {
|
|
276
322
|
res.discard();
|
|
277
323
|
return null;
|
|
278
324
|
}
|
|
325
|
+
if (budget !== void 0 && declared > budget.leftBytes) {
|
|
326
|
+
res.discard();
|
|
327
|
+
return CAPPED;
|
|
328
|
+
}
|
|
279
329
|
const ext = new URL(target).pathname.split(".").pop()?.toLowerCase() ?? "bin";
|
|
280
330
|
const file = await createUniqueFile(
|
|
281
331
|
downloadsDir(dataDir),
|
|
@@ -287,19 +337,32 @@ async function saveOne(dataDir, stem, raw, deps) {
|
|
|
287
337
|
try {
|
|
288
338
|
for await (const chunk of res.body) {
|
|
289
339
|
size += chunk.byteLength;
|
|
290
|
-
if (size >
|
|
340
|
+
if (size > cap) {
|
|
291
341
|
res.discard();
|
|
342
|
+
refused = true;
|
|
292
343
|
throw new Error("media over the size cap");
|
|
293
344
|
}
|
|
345
|
+
if (budget !== void 0) {
|
|
346
|
+
if (chunk.byteLength > budget.leftBytes) {
|
|
347
|
+
res.discard();
|
|
348
|
+
capped = true;
|
|
349
|
+
throw new Error("media over the call's download cap");
|
|
350
|
+
}
|
|
351
|
+
budget.leftBytes -= chunk.byteLength;
|
|
352
|
+
charged += chunk.byteLength;
|
|
353
|
+
}
|
|
294
354
|
await writeAll(file.handle, chunk);
|
|
295
355
|
}
|
|
296
356
|
} finally {
|
|
297
357
|
await file.handle.close();
|
|
298
358
|
}
|
|
359
|
+
kept = true;
|
|
299
360
|
return path;
|
|
300
361
|
} catch {
|
|
301
362
|
if (path !== null) await rm(path, { force: true }).catch(() => void 0);
|
|
302
|
-
return null;
|
|
363
|
+
return capped ? CAPPED : refused ? null : FAILED;
|
|
364
|
+
} finally {
|
|
365
|
+
if (budget !== void 0 && !kept) budget.leftBytes += charged;
|
|
303
366
|
}
|
|
304
367
|
}
|
|
305
368
|
async function writeAll(handle, bytes) {
|
|
@@ -327,11 +390,15 @@ export {
|
|
|
327
390
|
maskDeep,
|
|
328
391
|
recordedSent,
|
|
329
392
|
appendPaidRecord,
|
|
393
|
+
updatePaidRecord,
|
|
330
394
|
reconcilePayments,
|
|
395
|
+
readPaidRecords,
|
|
331
396
|
MAX_MEDIA_FILES,
|
|
397
|
+
MAX_MEDIA_BYTES,
|
|
332
398
|
mediaUrlsIn,
|
|
399
|
+
pinnedLookup,
|
|
333
400
|
saveMedia,
|
|
334
401
|
writeAll,
|
|
335
402
|
createUniqueFile
|
|
336
403
|
};
|
|
337
|
-
//# sourceMappingURL=chunk-
|
|
404
|
+
//# sourceMappingURL=chunk-3FY5HG7R.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/paid.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { appendFile, mkdir, open, readFile, rm, type FileHandle } from 'node:fs/promises';\nimport { request as httpsRequest } from 'node:https';\nimport type { LookupFunction } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { resolvePublicDestination, type DestinationOptions } from '../lib/destination';\nimport { hasCode } from '../lib/errno';\nimport { withFileLock } from '../lib/lock';\nimport { downloadsDir, paidLedgerPath } from '../lib/paths';\nimport { mask } from '../lib/redact';\nimport { USDC_ADDRESS } from '../lib/usdc-balance';\nimport { releaseUnchargedExposure } from '../lib/wallet/spend';\n\n/**\n * WHAT A PAID ROUTER CALL BOUGHT, KEPT ON THIS MACHINE. One JSON line per paid\n * call in `~/.tenjin/paid/ledger.jsonl`: who was paid, for what, how much, the\n * settlement it carried and the files it saved. It is the user's own record\n * and the receipt `tenjin payments reconcile` resolves an unknown settlement\n * against. Nothing here can fail a lookup: every write swallows its own error.\n */\n\nexport type Settlement = 'settled' | 'unknown' | 'not_charged';\n\n/** The EIP-3009 authorization that was signed, enough to ask the token later\n * whether it was used. */\nexport interface SignedAuthorization {\n from: string;\n nonce: string;\n /** Unix seconds; after it the authorization can no longer be used. */\n validBefore: string;\n}\n\nexport interface PaidRecord {\n version: 1;\n ts: string;\n capabilityId: string;\n provider: string;\n url: string;\n /** The input or query sent, masked and cut to {@link MAX_SENT_CHARS}. */\n sent: string;\n amountAtomic: string;\n txHash?: string;\n settlement: Settlement;\n savedFiles: string[];\n authorization?: SignedAuthorization;\n /** When reconcile last asked the chain about it, so a slow or rate-limited\n * RPC is not asked about the same record on every lookup. */\n lastCheckedAt?: string;\n}\n\nexport const MAX_SENT_CHARS = 4_096;\n\n/**\n * A JSON value with every object key and string leaf masked on its own. The\n * mask anchors on word boundaries, which a serialized string hides: after an\n * escaped `\\n` a key reads as `nsk-ant-…`, one word, and passes.\n */\nexport function maskDeep(value: unknown): unknown {\n if (typeof value === 'string') return mask(value);\n if (Array.isArray(value)) return value.map(maskDeep);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n mask(key),\n maskDeep(entry),\n ]),\n );\n }\n return value;\n}\n\n/** The input or query as it is recorded: secrets masked, then cut. */\nexport function recordedSent(sent: string): string {\n return mask(sent).slice(0, MAX_SENT_CHARS);\n}\n\nexport async function appendPaidRecord(dataDir: string, record: PaidRecord): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n // Under the lock reconcile rewrites with, so an append is never lost to it.\n await withFileLock(`${path}.lock`, () =>\n appendFile(path, `${JSON.stringify(record)}\\n`, { mode: 0o600 }),\n );\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/**\n * A JOB'S ROW, FINISHED IN PLACE. A paid call whose seller was still working\n * is recorded when it is paid, so a crash mid-poll loses no row; the files the\n * job later saved, and the settlement its last answer named, are written onto\n * that same row, found by its authorization's nonce, under the lock reconcile\n * rewrites with. One payment, one row. Never throws.\n */\nexport async function updatePaidRecord(\n dataDir: string,\n nonce: string,\n patch: { savedFiles?: string[]; txHash?: string },\n): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n const key = nonce.toLowerCase();\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n let found = false;\n const lines = current.map(({ line, record }) => {\n if (record?.authorization?.nonce.toLowerCase() !== key) return line;\n found = true;\n return JSON.stringify({\n ...record,\n ...(patch.savedFiles !== undefined ? { savedFiles: patch.savedFiles } : {}),\n ...(patch.txHash !== undefined && record.settlement === 'unknown'\n ? { txHash: patch.txHash, settlement: 'settled' }\n : {}),\n });\n });\n if (found) {\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n }\n });\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/** `authorizationState(address,bytes32)`: the first four bytes of its keccak-256. */\nconst AUTHORIZATION_STATE_SELECTOR = '0xe94a0102';\nconst WORD_RE = /^0x[0-9a-fA-F]{64}$/;\n/** How many unknown settlements one pass asks the chain about. */\nexport const MAX_RECONCILE_CHECKS = 3;\n/** How long a record the chain could not answer for waits before it is asked\n * about again by the lookup-time pass. */\nexport const RECHECK_MS = 10 * 60_000;\nconst RECONCILE_TIMEOUT_MS = 1_500;\n\n/**\n * Whether USDC on Base has used this authorization: true once a facilitator\n * settled it, false while it has not. Null when the RPC could not say.\n */\nexport async function authorizationUsed(\n authorization: SignedAuthorization,\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number; blockTag?: string } = {},\n): Promise<boolean | null> {\n const result = await rpcCall(\n rpcUrl,\n 'eth_call',\n [\n {\n to: USDC_ADDRESS,\n data: `${AUTHORIZATION_STATE_SELECTOR}${authorization.from.slice(2).toLowerCase().padStart(64, '0')}${authorization.nonce.slice(2).toLowerCase()}`,\n },\n opts.blockTag ?? 'latest',\n ],\n opts,\n );\n if (typeof result !== 'string' || !WORD_RE.test(result)) return null;\n return BigInt(result) !== 0n;\n}\n\n/**\n * The chain's own clock: the latest block's number and timestamp (seconds).\n * Expiry is decided against it, not this machine's clock, and the state is\n * read at that same block: a node that lags, or a clock running ahead, then\n * agrees with itself. Null when the RPC could not say.\n */\nexport async function latestBlock(\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},\n): Promise<{ tag: string; timestamp: number } | null> {\n const result = await rpcCall(rpcUrl, 'eth_getBlockByNumber', ['latest', false], opts);\n if (result === null || typeof result !== 'object') return null;\n const { number, timestamp } = result as { number?: unknown; timestamp?: unknown };\n if (typeof number !== 'string' || !/^0x[0-9a-fA-F]+$/.test(number)) return null;\n if (typeof timestamp !== 'string' || !/^0x[0-9a-fA-F]+$/.test(timestamp)) return null;\n return { tag: number, timestamp: Number(BigInt(timestamp)) };\n}\n\nasync function rpcCall(\n rpcUrl: string,\n method: string,\n params: unknown[],\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number },\n): Promise<unknown> {\n try {\n const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),\n signal: AbortSignal.timeout(opts.timeoutMs ?? RECONCILE_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return ((await res.json()) as { result?: unknown } | null)?.result ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ReconcileOutcome {\n /** Records asked about in this pass. */\n checked: number;\n /** The authorization was used: the amount was charged. */\n settled: number;\n /** It expired unused: nothing was charged. */\n notCharged: number;\n /** Still unknown: not yet expired, no authorization on record, or the RPC\n * could not answer. */\n unknown: number;\n /** What the not-charged payments gave back to today's automatic budget. */\n releasedAtomic: string;\n}\n\n/**\n * RESOLVE \"SETTLEMENT UNKNOWN\" FROM THE CHAIN. A paid call whose seller never\n * confirmed settlement leaves a record marked `unknown`. Once the chain's\n * latest block is past its authorization's `validBefore`, the token's own\n * `authorizationState(from, nonce)` read AT THAT BLOCK is final: used means\n * charged, unused means it can never be charged, since no later block can\n * carry it. This machine's clock only decides whether the chain is worth\n * asking. At most `max` records are asked about per pass, and\n * a record the RPC cannot answer for stays unknown, stamped `lastCheckedAt`,\n * and is not asked about again for `recheckMs`.\n *\n * The chain is asked outside the lock; the file is re-read and rewritten under\n * it, so an append made meanwhile is kept.\n */\nexport async function reconcilePayments(\n dataDir: string,\n opts: {\n rpcUrl: string;\n fetchImpl?: typeof fetch;\n now?: () => number;\n max?: number;\n timeoutMs?: number;\n /** Defaults to {@link RECHECK_MS}; the command passes 0. */\n recheckMs?: number;\n },\n): Promise<ReconcileOutcome> {\n const path = paidLedgerPath(dataDir);\n const now = (opts.now ?? Date.now)();\n const records = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const open = records.filter(\n (entry): entry is { line: string; record: PaidRecord } =>\n entry.record !== null && entry.record.settlement === 'unknown',\n );\n const recheckMs = opts.recheckMs ?? RECHECK_MS;\n const due = open.filter(\n ({ record }) =>\n record.authorization !== undefined &&\n Number(record.authorization.validBefore) * 1_000 < now &&\n (record.lastCheckedAt === undefined || now - Date.parse(record.lastCheckedAt) >= recheckMs),\n );\n const answers = new Map<string, Settlement>();\n const asked = new Set<string>();\n let checked = 0;\n const rpc = {\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n const block = due.length > 0 ? await latestBlock(opts.rpcUrl, rpc) : null;\n for (const { record } of due.slice(0, opts.max ?? MAX_RECONCILE_CHECKS)) {\n // Not past validBefore on the chain yet: not asked, and not stamped.\n if (block !== null && Number(record.authorization!.validBefore) >= block.timestamp) continue;\n checked += 1;\n asked.add(record.authorization!.nonce);\n if (block === null) continue;\n const used = await authorizationUsed(record.authorization!, opts.rpcUrl, {\n ...rpc,\n blockTag: block.tag,\n });\n if (used !== null) answers.set(record.authorization!.nonce, used ? 'settled' : 'not_charged');\n }\n // NOT CHARGED GIVES THE DAILY BUDGET BACK FIRST: exactly that payment's\n // exposure, by its nonce, while it is still inside the window that counted\n // it. Only then is the record marked; a release that could not be written\n // leaves it unknown, and the next pass asks again. A second release of the\n // same nonce finds nothing, so a retry never gives back twice.\n let releasedAtomic = 0n;\n for (const [nonce, answer] of [...answers]) {\n if (answer !== 'not_charged') continue;\n const released = await releaseUnchargedExposure(dataDir, nonce, {\n ...(opts.now !== undefined ? { now: opts.now } : {}),\n });\n if (released === null) answers.delete(nonce);\n else releasedAtomic += released;\n }\n if (asked.size > 0) {\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const lines = current.map(({ line, record }) => {\n const nonce =\n record?.settlement === 'unknown' && record.authorization !== undefined\n ? record.authorization.nonce\n : undefined;\n if (nonce === undefined || !asked.has(nonce)) return line;\n const answer = answers.get(nonce);\n const stamp = new Date(now).toISOString();\n return JSON.stringify(\n answer === undefined\n ? { ...record, lastCheckedAt: stamp }\n : { ...record, settlement: answer, lastCheckedAt: stamp, reconciledAt: stamp },\n );\n });\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n });\n }\n const settled = [...answers.values()].filter((value) => value === 'settled').length;\n return {\n checked,\n settled,\n notCharged: answers.size - settled,\n unknown: open.length - answers.size,\n releasedAtomic: releasedAtomic.toString(),\n };\n}\n\n/** Every paid record in the ledger, oldest first; a line that is not one is skipped. */\nexport async function readPaidRecords(dataDir: string): Promise<PaidRecord[]> {\n const raw = await readFile(paidLedgerPath(dataDir), 'utf8').catch(() => '');\n return parseLedger(raw).flatMap(({ record }) => (record === null ? [] : [record]));\n}\n\n/** Every line, and the record it holds when it is one; other lines ride along. */\nfunction parseLedger(raw: string): { line: string; record: PaidRecord | null }[] {\n return raw\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n try {\n const value = JSON.parse(line) as PaidRecord;\n return { line, record: value !== null && value.version === 1 ? value : null };\n } catch {\n return { line, record: null };\n }\n });\n}\n\n/** The media a paid result links to, by the extension its path ends in. */\nconst MEDIA_EXTENSIONS = new Set([\n 'png',\n 'jpg',\n 'jpeg',\n 'webp',\n 'gif',\n 'svg',\n 'mp3',\n 'wav',\n 'm4a',\n 'ogg',\n 'mp4',\n 'webm',\n 'mov',\n]);\nexport const MAX_MEDIA_FILES = 5;\nexport const MAX_MEDIA_BYTES = 200 * 1024 * 1024;\nexport const MEDIA_TIMEOUT_MS = 60_000;\nconst MAX_REDIRECTS = 3;\nconst URL_RE = /https:\\/\\/[^\\s\"'<>\\\\]+/g;\n\n/** Every https URL in the result whose path ends in a media extension, in\n * order and without repeats, at most {@link MAX_MEDIA_FILES}. */\nexport function mediaUrlsIn(result: string, limit = MAX_MEDIA_FILES): string[] {\n const found: string[] = [];\n for (const match of result.matchAll(URL_RE)) {\n if (found.length >= limit) break;\n let url: URL;\n try {\n url = new URL(match[0]);\n } catch {\n continue;\n }\n const ext = url.pathname.split('.').pop()?.toLowerCase() ?? '';\n if (!url.pathname.includes('.') || !MEDIA_EXTENSIONS.has(ext)) continue;\n if (!found.includes(url.toString())) found.push(url.toString());\n }\n return found;\n}\n\n/** One GET the media download makes, connected to the address it validated. */\nexport interface PinnedTarget {\n url: URL;\n /** The address `resolvePublicDestination` checked; the socket goes here. */\n address: string;\n family: 4 | 6;\n}\n\nexport interface MediaResponse {\n status: number;\n location?: string;\n contentLength?: number;\n body: AsyncIterable<Uint8Array>;\n /** Drop the connection without reading the rest. */\n discard: () => void;\n}\n\nexport type MediaTransport = (target: PinnedTarget, signal: AbortSignal) => Promise<MediaResponse>;\n\nexport interface MediaDeps {\n /** Test seam; production connects with {@link pinnedGet}. */\n transport?: MediaTransport;\n destination?: DestinationOptions;\n now?: () => number;\n timeoutMs?: number;\n maxBytes?: number;\n /** What the call may still write, shared by every file it saves, side by\n * side or not: charged as each chunk is written, so a download still in\n * flight holds only what it wrote. A chunk that would take it below zero\n * stops that file, and a file that is not kept gives its bytes back. */\n budget?: { leftBytes: number };\n}\n\n/**\n * CONNECT TO THE ADDRESS THAT WAS CHECKED. `fetch` resolves the name again on\n * its own, so a host answering publicly to the check and privately a moment\n * later (DNS rebinding) would get the request. `node:https` with a `lookup`\n * that hands back the one validated address closes that: the socket goes to\n * it, and TLS still verifies the certificate against the URL's own host name.\n */\nexport const pinnedGet: MediaTransport = (target, signal) =>\n new Promise((resolve, reject) => {\n const req = httpsRequest(\n target.url,\n {\n method: 'GET',\n signal,\n lookup: pinnedLookup(target),\n },\n (res) => {\n const length = Number(res.headers['content-length']);\n const location = res.headers.location;\n resolve({\n status: res.statusCode ?? 0,\n ...(typeof location === 'string' ? { location } : {}),\n ...(Number.isFinite(length) ? { contentLength: length } : {}),\n body: res,\n discard: () => res.destroy(),\n });\n },\n );\n req.on('error', reject);\n req.end();\n });\n\n/** A `lookup` that answers every name with the one validated address. */\nexport function pinnedLookup(target: Pick<PinnedTarget, 'address' | 'family'>): LookupFunction {\n return ((_host: string, options: { all?: boolean }, callback: LookupCallback) => {\n if (options.all === true) {\n callback(null, [{ address: target.address, family: target.family }]);\n } else {\n callback(null, target.address, target.family);\n }\n }) as unknown as LookupFunction;\n}\n\ntype LookupCallback = (\n err: Error | null,\n address: string | { address: string; family: number }[],\n family?: number,\n) => void;\n\n/** A file the budget left too little room for. */\nconst CAPPED = Symbol('capped');\n/** A file a later try could save: the network, the file's server or this\n * disk failed, not a rule of ours. */\nconst FAILED = Symbol('failed');\n\n/**\n * Download each URL into the downloads dir, one at a time, each under its own\n * size cap and deadline, every hop of a redirect validated and connected to\n * the address it validated. Returns the paths that were written, whether the\n * budget left a file too little room (`capped`), and whether a download\n * failed in a way a later try could get past (`failed`); a later call could\n * save either. A URL that fails is skipped and never fails the call.\n */\nexport async function saveMedia(\n dataDir: string,\n stem: string,\n urls: string[],\n deps: MediaDeps = {},\n): Promise<{ saved: string[]; capped: boolean; failed: boolean }> {\n const saved: string[] = [];\n let capped = false;\n let failed = false;\n for (const [index, url] of urls.entries()) {\n const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);\n if (path === CAPPED) capped = true;\n else if (path === FAILED) failed = true;\n else if (path !== null) saved.push(path);\n }\n return { saved, capped, failed };\n}\n\n/** Statuses a later try could get past: the server, not the link, failed. */\nconst RETRYABLE_STATUS = new Set([408, 429]);\n\nasync function saveOne(\n dataDir: string,\n stem: string,\n raw: string,\n deps: MediaDeps,\n): Promise<string | typeof CAPPED | typeof FAILED | null> {\n const transport = deps.transport ?? pinnedGet;\n const cap = deps.maxBytes ?? MAX_MEDIA_BYTES;\n const { budget } = deps;\n if (budget !== undefined && budget.leftBytes <= 0) return CAPPED;\n // What this file has taken from the call's budget, given back unless kept.\n let charged = 0;\n let kept = false;\n // Stopped by the call's budget, not by the file's own cap.\n let capped = false;\n // Stopped by a rule of ours (an address, the file's cap), which no later\n // try gets past.\n let refused = false;\n const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);\n let target = raw;\n let path: string | null = null;\n try {\n let res: MediaResponse | null = null;\n for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {\n const pinned = await resolvePublicDestination(target, deps.destination ?? {}).catch(\n (err: unknown) => {\n refused = true;\n throw err;\n },\n );\n res = await transport(pinned, signal);\n if (res.status < 300 || res.status >= 400 || res.location === undefined) break;\n res.discard();\n target = new URL(res.location, target).toString();\n res = null;\n }\n if (res === null || res.status < 200 || res.status >= 300) {\n res?.discard();\n const status = res?.status ?? 0;\n return status >= 500 || RETRYABLE_STATUS.has(status) ? FAILED : null;\n }\n const declared = res.contentLength ?? 0;\n if (declared > cap) {\n res.discard();\n return null;\n }\n if (budget !== undefined && declared > budget.leftBytes) {\n res.discard();\n return CAPPED;\n }\n const ext = new URL(target).pathname.split('.').pop()?.toLowerCase() ?? 'bin';\n const file = await createUniqueFile(\n downloadsDir(dataDir),\n `${stem}-${(deps.now ?? Date.now)()}`,\n MEDIA_EXTENSIONS.has(ext) ? ext : 'bin',\n );\n path = file.path;\n let size = 0;\n try {\n for await (const chunk of res.body) {\n size += chunk.byteLength;\n if (size > cap) {\n res.discard();\n refused = true;\n throw new Error('media over the size cap');\n }\n // Charged before the write, in the same turn as the check, so files\n // saving side by side can never write past the call's cap between\n // them.\n if (budget !== undefined) {\n if (chunk.byteLength > budget.leftBytes) {\n res.discard();\n capped = true;\n throw new Error(\"media over the call's download cap\");\n }\n budget.leftBytes -= chunk.byteLength;\n charged += chunk.byteLength;\n }\n await writeAll(file.handle, chunk);\n }\n } finally {\n await file.handle.close();\n }\n kept = true;\n return path;\n } catch {\n if (path !== null) await rm(path, { force: true }).catch(() => undefined);\n return capped ? CAPPED : refused ? null : FAILED;\n } finally {\n if (budget !== undefined && !kept) budget.leftBytes += charged;\n }\n}\n\n/**\n * EVERY BYTE, OR A THROW. `FileHandle.write` may write fewer bytes than it was\n * handed and says so only in `bytesWritten`; a caller that ignores it saves a\n * file with a hole in it. A write that makes no progress is an error.\n */\nexport async function writeAll(\n handle: Pick<FileHandle, 'write'>,\n bytes: Uint8Array,\n): Promise<void> {\n let offset = 0;\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);\n if (bytesWritten <= 0) throw new Error('the file write made no progress');\n offset += bytesWritten;\n }\n}\n\n/**\n * A NEW FILE, NEVER ANOTHER CALL'S. The name is the stem plus a random suffix,\n * created with an exclusive flag, so two lookups finishing in the same\n * millisecond each get their own file; a clash is retried with a new suffix.\n */\nexport async function createUniqueFile(\n directory: string,\n stem: string,\n ext: string,\n): Promise<{ path: string; handle: FileHandle }> {\n await mkdir(directory, { recursive: true });\n const safe = stem.replace(/[^A-Za-z0-9_-]+/g, '-').slice(0, 100) || 'lookup';\n for (let attempt = 0; ; attempt += 1) {\n const path = join(directory, `${safe}-${randomBytes(4).toString('hex')}.${ext}`);\n try {\n return { path, handle: await open(path, 'wx', 0o600) };\n } catch (err) {\n if (attempt >= 4 || !hasCode(err, 'EEXIST')) throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,OAAO,MAAM,UAAU,UAA2B;AACvE,SAAS,WAAW,oBAAoB;AAExC,SAAS,SAAS,YAAY;AA+CvB,IAAM,iBAAiB;AAOvB,SAAS,SAAS,OAAyB;AAChD,MAAI,OAAO,UAAU,SAAU,QAAO,KAAK,KAAK;AAChD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,QAAQ;AACnD,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,KAAgC,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM;AAAA,QACr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AM;AAC1B,qBAAW,MAAM;AAAA,QACnB;AACA,cAAM,SAAS,KAAK,QAAQ,KAAK;AAAA,MACnC;AAAA,IACF,UAAE;AACA,YAAM,KAAK,OAAO,MAAM;AAAA,IAC1B;AACA,WAAO;AACP,WAAO;AAAA,EACT,QAAQ;AACN,QAAI,SAAS,KAAM,OAAM,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AACxE,WAAO,SAAS,SAAS,UAAU,OAAO;AAAA,EAC5C,UAAE;AACA,QAAI,WAAW,UAAa,CAAC,KAAM,QAAO,aAAa;AAAA,EACzD;AACF;AAOA,eAAsB,SACpB,QACA,OACe;AACf,MAAI,SAAS;AACb,SAAO,SAAS,MAAM,YAAY;AAChC,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAM,aAAa,MAAM;AACpF,QAAI,gBAAgB,EAAG,OAAM,IAAI,MAAM,iCAAiC;AACxE,cAAU;AAAA,EACZ;AACF;AAOA,eAAsB,iBACpB,WACA,MACA,KAC+C;AAC/C,QAAM,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAC1C,QAAM,OAAO,KAAK,QAAQ,oBAAoB,GAAG,EAAE,MAAM,GAAG,GAAG,KAAK;AACpE,WAAS,UAAU,KAAK,WAAW,GAAG;AACpC,UAAM,OAAO,KAAK,WAAW,GAAG,IAAI,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,IAAI,GAAG,EAAE;AAC/E,QAAI;AACF,aAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,MAAM,MAAM,GAAK,EAAE;AAAA,IACvD,SAAS,KAAK;AACZ,UAAI,WAAW,KAAK,CAAC,QAAQ,KAAK,QAAQ,EAAG,OAAM;AAAA,IACrD;AAAA,EACF;AACF;","names":["open"]}
|
|
@@ -1,24 +1,38 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
isPublicAddress
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-XJQ6CH7X.js";
|
|
5
5
|
import {
|
|
6
6
|
UNREACHABLE_BACKOFF_MS,
|
|
7
7
|
clearRouterMemo,
|
|
8
8
|
readRouterMemo,
|
|
9
9
|
requestToolAccess,
|
|
10
10
|
writeRouterMemo
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-MOG7PB3A.js";
|
|
12
|
+
import {
|
|
13
|
+
readSpendSummary,
|
|
14
|
+
spentOf
|
|
15
|
+
} from "./chunk-LX5OT4TQ.js";
|
|
12
16
|
import {
|
|
13
17
|
ChoicesSchema,
|
|
14
18
|
OfferSpecSchema,
|
|
15
19
|
ROUTER_PATH,
|
|
16
20
|
requestDecision
|
|
17
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-VKQXVCZR.js";
|
|
18
22
|
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
23
|
+
launchedByPlugin,
|
|
24
|
+
requestToolName,
|
|
25
|
+
unpaidNotice
|
|
26
|
+
} from "./chunk-EWLU46J6.js";
|
|
27
|
+
import {
|
|
28
|
+
FEE_REQUIRED,
|
|
29
|
+
depositSentence,
|
|
30
|
+
firstNoticeFor,
|
|
31
|
+
isFeeRequired
|
|
32
|
+
} from "./chunk-MRUPDSUM.js";
|
|
33
|
+
import {
|
|
34
|
+
evaluateSpendPolicy
|
|
35
|
+
} from "./chunk-2SNUOHAT.js";
|
|
22
36
|
import {
|
|
23
37
|
mask
|
|
24
38
|
} from "./chunk-7QKHZQKW.js";
|
|
@@ -37,50 +51,37 @@ import {
|
|
|
37
51
|
sessionDir,
|
|
38
52
|
wasOffered,
|
|
39
53
|
writeProgress
|
|
40
|
-
} from "./chunk-
|
|
54
|
+
} from "./chunk-OOSRB3OF.js";
|
|
55
|
+
import {
|
|
56
|
+
routerSettings
|
|
57
|
+
} from "./chunk-MG3G644T.js";
|
|
58
|
+
import {
|
|
59
|
+
sessionServedByPlugin
|
|
60
|
+
} from "./chunk-6W5GYG3W.js";
|
|
41
61
|
import {
|
|
42
62
|
proxyVariable
|
|
43
63
|
} from "./chunk-S4SAZ7OD.js";
|
|
44
64
|
import {
|
|
45
65
|
composeUserAgent
|
|
46
|
-
} from "./chunk-
|
|
47
|
-
import {
|
|
48
|
-
FEE_REQUIRED,
|
|
49
|
-
firstNoticeFor,
|
|
50
|
-
isFeeRequired,
|
|
51
|
-
unpaidNotice
|
|
52
|
-
} from "./chunk-GU4GGKYP.js";
|
|
53
|
-
import {
|
|
54
|
-
REQUEST_TOOL
|
|
55
|
-
} from "./chunk-TGLKKLQG.js";
|
|
56
|
-
import {
|
|
57
|
-
evaluateSpendPolicy
|
|
58
|
-
} from "./chunk-B2L53TMK.js";
|
|
59
|
-
import {
|
|
60
|
-
routerSettings
|
|
61
|
-
} from "./chunk-DATCR7AU.js";
|
|
66
|
+
} from "./chunk-RJEPZMYY.js";
|
|
62
67
|
import {
|
|
63
68
|
resolveContextSettings
|
|
64
|
-
} from "./chunk-
|
|
65
|
-
import {
|
|
66
|
-
parseUsdToAtomic,
|
|
67
|
-
toMoney
|
|
68
|
-
} from "./chunk-6ZSGER3A.js";
|
|
69
|
+
} from "./chunk-AMEUXNJT.js";
|
|
69
70
|
import {
|
|
70
71
|
external_exports,
|
|
71
72
|
isSameDeployment,
|
|
72
73
|
loadRawConfig,
|
|
74
|
+
parseUsdToAtomic,
|
|
73
75
|
rememberingBalanceReader,
|
|
74
76
|
resolveExperimentalBazaar,
|
|
75
|
-
resolveSettings
|
|
76
|
-
|
|
77
|
-
import {
|
|
77
|
+
resolveSettings,
|
|
78
|
+
toMoney,
|
|
78
79
|
writeFileAtomic,
|
|
79
80
|
writeFileAtomicExclusive
|
|
80
|
-
} from "./chunk-
|
|
81
|
+
} from "./chunk-VVAHFCX2.js";
|
|
81
82
|
import {
|
|
82
83
|
walletPath
|
|
83
|
-
} from "./chunk-
|
|
84
|
+
} from "./chunk-SJLTEINJ.js";
|
|
84
85
|
|
|
85
86
|
// src/router/hooks.ts
|
|
86
87
|
import { readFile } from "node:fs/promises";
|
|
@@ -404,7 +405,10 @@ async function readSpec(dataDir, id) {
|
|
|
404
405
|
await file.close().catch(() => void 0);
|
|
405
406
|
}
|
|
406
407
|
}
|
|
407
|
-
var KeptChoicesSchema = external_exports.strictObject({
|
|
408
|
+
var KeptChoicesSchema = external_exports.strictObject({
|
|
409
|
+
choices: ChoicesSchema,
|
|
410
|
+
hint: external_exports.string().max(2e3)
|
|
411
|
+
});
|
|
408
412
|
function choicesPath(dataDir, id) {
|
|
409
413
|
return join2(dataDir, SPECS_DIR, `${digest(id)}.choices.json`);
|
|
410
414
|
}
|
|
@@ -904,8 +908,8 @@ function promptSkipReason(prompt) {
|
|
|
904
908
|
}
|
|
905
909
|
var HINT_SOURCE = "Tenjin router (installed by the user)";
|
|
906
910
|
var BARE_CALL_RE = /(?<![\w$])request\(\{/g;
|
|
907
|
-
function toolNamed(hint) {
|
|
908
|
-
return hint.replace(BARE_CALL_RE, `${
|
|
911
|
+
function toolNamed(hint, env = process.env) {
|
|
912
|
+
return hint.replace(BARE_CALL_RE, `${requestToolName(env)}({`);
|
|
909
913
|
}
|
|
910
914
|
function attributed(hint) {
|
|
911
915
|
return `${HINT_SOURCE}: ${toolNamed(hint)}`;
|
|
@@ -972,7 +976,7 @@ async function spendShortfall(decision, deps, deadline) {
|
|
|
972
976
|
const price = `$${toMoney(decision.providerPriceAtomic).usd}`;
|
|
973
977
|
const approval = (detail) => ({
|
|
974
978
|
withheld: "offer needs approval",
|
|
975
|
-
note: `Note: ${price} ${detail}; request will return needs_approval with
|
|
979
|
+
note: `Note: ${price} ${detail}; request will pay nothing and return needs_approval with what it costs.`
|
|
976
980
|
});
|
|
977
981
|
let rpcUrl;
|
|
978
982
|
try {
|
|
@@ -1011,9 +1015,10 @@ async function spendShortfall(decision, deps, deadline) {
|
|
|
1011
1015
|
);
|
|
1012
1016
|
return null;
|
|
1013
1017
|
}
|
|
1014
|
-
|
|
1018
|
+
const short = BigInt(decision.providerPriceAtomic) - balance;
|
|
1019
|
+
return short > 0n ? {
|
|
1015
1020
|
withheld: "wallet needs USDC",
|
|
1016
|
-
note: `Note: the wallet holds $${toMoney(balance.toString()).usd}; fund it with \`tenjin wallet fund\`.`
|
|
1021
|
+
note: `Note: the wallet holds $${toMoney(balance.toString()).usd}, $${toMoney(short.toString()).usd} short of its ${price}; fund it with \`tenjin wallet fund\`.`
|
|
1017
1022
|
} : null;
|
|
1018
1023
|
}
|
|
1019
1024
|
async function vetOffer(offer, deps, deadline, canAskUser) {
|
|
@@ -1454,6 +1459,8 @@ async function decide({ packet }, deps, config, sessionId, deadline) {
|
|
|
1454
1459
|
...route !== null ? { route } : {}
|
|
1455
1460
|
}
|
|
1456
1461
|
);
|
|
1462
|
+
const deposited = route?.deposited?.() ?? 0n;
|
|
1463
|
+
if (deposited > 0n) deps.notice?.(depositSentence(deposited));
|
|
1457
1464
|
const why = outcome.status === "skipped" ? outcome.why : outcome.freePath ?? (outcome.status === "decided" && isFeeRequired(outcome.decision) ? FEE_REQUIRED : void 0);
|
|
1458
1465
|
const memoed = deps.route !== void 0 && route === null;
|
|
1459
1466
|
if (why !== void 0 && !(memoed && why === FEE_REQUIRED)) {
|
|
@@ -1535,7 +1542,9 @@ async function runHookCommand(kind, io, deps) {
|
|
|
1535
1542
|
let response;
|
|
1536
1543
|
try {
|
|
1537
1544
|
const raw = await (deps.readEvent ?? readStdin)();
|
|
1538
|
-
|
|
1545
|
+
const event = JSON.parse(raw);
|
|
1546
|
+
if (!launchedByPlugin(deps.env) && await sessionServedByPlugin(deps.dataDir, event)) return;
|
|
1547
|
+
response = await runHookKind(kind, event, deps);
|
|
1539
1548
|
} catch {
|
|
1540
1549
|
response = null;
|
|
1541
1550
|
}
|
|
@@ -1579,6 +1588,7 @@ async function readStdin() {
|
|
|
1579
1588
|
export {
|
|
1580
1589
|
storeSpecs,
|
|
1581
1590
|
readSpec,
|
|
1591
|
+
KeptChoicesSchema,
|
|
1582
1592
|
storeChoices,
|
|
1583
1593
|
readChoices,
|
|
1584
1594
|
claimSpecPayment,
|
|
@@ -1590,4 +1600,4 @@ export {
|
|
|
1590
1600
|
runHookCommand,
|
|
1591
1601
|
runHookKind
|
|
1592
1602
|
};
|
|
1593
|
-
//# sourceMappingURL=chunk-
|
|
1603
|
+
//# sourceMappingURL=chunk-4FYMDRD3.js.map
|