callx402 0.0.0-stage → 1.0.0

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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +227 -2
  3. package/SPEC.md +264 -0
  4. package/bin/callx402.js +257 -0
  5. package/core/config.js +104 -0
  6. package/core/envelope.js +80 -0
  7. package/core/index.js +364 -0
  8. package/core/pipeline.js +371 -0
  9. package/core/remote.js +242 -0
  10. package/core/subsystems.js +136 -0
  11. package/dist/callx402-1.0.0.tgz +0 -0
  12. package/docs/ACTION_LANGUAGE.md +23 -0
  13. package/docs/MCP_IDENTITY.md +27 -0
  14. package/docs/README.md +315 -0
  15. package/docs/action-reference.md +247 -0
  16. package/docs/cli-help-verified-2026-10-06.txt +39 -0
  17. package/docs/logo.png +0 -0
  18. package/docs/problem-map.md +65 -0
  19. package/docs/troubleshooting/cx402-402afterfail-001-402-after-failed-settle.md +143 -0
  20. package/docs/troubleshooting/cx402-agentcap-001-agent-spending.md +114 -0
  21. package/docs/troubleshooting/cx402-eip3009-001-authorization-checklist.md +124 -0
  22. package/docs/troubleshooting/cx402-paidnores-001-paid-no-result.md +97 -0
  23. package/docs/troubleshooting/cx402-safretry-001-retry-after-payment.md +106 -0
  24. package/docs/troubleshooting/cx402-settlepend-001-settlement-pending.md +92 -0
  25. package/docs/troubleshooting/cx402-solanafail-001-solana-settlement.md +119 -0
  26. package/docs/troubleshooting/cx402-verset-001-verify-ok-settle-fails.md +101 -0
  27. package/docs/visuals/01-action-map.png +0 -0
  28. package/docs/visuals/02-diagnose.png +0 -0
  29. package/docs/visuals/03-resolve.png +0 -0
  30. package/docs/visuals/04-route.png +0 -0
  31. package/docs/visuals/05-preflight.png +0 -0
  32. package/docs/visuals/06-inspect.png +0 -0
  33. package/docs/visuals/07-status.png +0 -0
  34. package/docs/visuals/08-architecture.svg +49 -0
  35. package/docs/visuals/MANIFEST.md +40 -0
  36. package/docs/visuals/raw/01-help.out +39 -0
  37. package/docs/visuals/raw/02-diagnose.out +2 -0
  38. package/docs/visuals/raw/03-resolve.out +4 -0
  39. package/docs/visuals/raw/04-route.out +2 -0
  40. package/docs/visuals/raw/05-preflight.out +2 -0
  41. package/docs/visuals/raw/06-inspect.out +23 -0
  42. package/docs/visuals/raw/07-status.out +16 -0
  43. package/docs/visuals/render_terminal.py +149 -0
  44. package/docs/what-is-callx402.md +251 -0
  45. package/integrations/README.md +62 -0
  46. package/integrations/core.py +329 -0
  47. package/integrations/crewai/callx402_crewai.py +109 -0
  48. package/integrations/facilitator/settle-guard.js +99 -0
  49. package/integrations/langchain/callx402_tools.py +180 -0
  50. package/integrations/mcp-clients/README.md +121 -0
  51. package/integrations/n8n/callx402-incident-guard.json +1 -0
  52. package/mcp/README.md +63 -0
  53. package/mcp/index.js +239 -0
  54. package/package.json +39 -4
  55. package/scripts/drift-check.js +202 -0
  56. package/sdk/js/index.js +207 -0
  57. package/sdk/python/README.md +67 -0
  58. package/sdk/python/callx402/__init__.py +317 -0
  59. package/sdk/python/callx402/cli.py +193 -0
  60. package/sdk/python/pyproject.toml +30 -0
  61. package/sdk/python/setup.py +56 -0
  62. package/server/index.js +520 -0
  63. package/server/openapi.yaml +537 -0
  64. package/server.json +1 -0
  65. package/test/cli-dispatch.test.js +248 -0
  66. package/test/helpers.js +103 -0
  67. package/test/integrity.test.js +43 -0
  68. package/test/intent-pipeline.test.js +205 -0
  69. package/test/remote.test.js +166 -0
  70. package/test/safety.test.js +234 -0
  71. package/test/sdk.test.js +198 -0
  72. package/test/server.test.js +190 -0
  73. package/test/subsystems.test.js +118 -0
@@ -0,0 +1,371 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * core/pipeline.js — intent pipeline stage orchestration for `execute`.
5
+ *
6
+ * Stages:
7
+ * 0. idempotency dedupe (result-recovery store; duplicate key -> original
8
+ * result with deduped:true, no re-execution)
9
+ * 1. intent-engine parse(text) -> structured intent
10
+ * 2. capability-graph findTools -> candidates
11
+ * 3. economic-planner planGoal -> costed plan
12
+ * 4. SpendGuard budget check (over -> refuse, exit 4, zero side effects;
13
+ * over approvalThreshold without approval -> fail closed, exit 4)
14
+ * 5. router selectTool/choosePath -> route
15
+ * 6. execution kernel — ONLY when a live executable route exists; the
16
+ * dispatch layer has none wired, so this stage is reported honestly as
17
+ * 'no executable route available'. Never fakes execution.
18
+ * 7. effect proof — issued only on real execution
19
+ * 8. settlement resolve — only on real execution; UNKNOWN -> exit 5
20
+ * 9. delivery + reconciliation -> receipt note
21
+ * 10. RevRule emit (idempotent, flag-gated)
22
+ *
23
+ * Money-safety invariants:
24
+ * - Over-budget intent -> SpendGuard refusal, exit 4, zero execution side effects.
25
+ * - Duplicate idempotencyKey -> original stored result, deduped:true.
26
+ * - Explicit retry/force when prior settlement is UNKNOWN -> REFUSED (exit 5).
27
+ * - Settlement UNKNOWN -> never auto-retry, never repay (exit 5).
28
+ */
29
+
30
+ const os = require('os');
31
+ const path = require('path');
32
+
33
+ const { EXIT, ok, fail, exitCodeFor } = require('./envelope');
34
+ const { loadConfig } = require('./config');
35
+ const { getSubsystem } = require('./subsystems');
36
+ const { dispatchRemote } = require('./remote');
37
+
38
+ const SPEED_POLICY = { fast: 'FASTEST_VERIFIED', cheap: 'LOWEST_TOTAL_COST', balanced: 'BEST_VALUE' };
39
+
40
+ function idempotencyFile(config) {
41
+ if (process.env.CALLX402_IDEMPOTENCY_FILE) return process.env.CALLX402_IDEMPOTENCY_FILE;
42
+ return path.join(os.homedir(), '.config', 'callx402', 'idempotency.jsonl');
43
+ }
44
+
45
+ function stageRec(stages, name, status, detail) {
46
+ stages.push({ name, status, detail: detail === undefined ? null : detail, at: new Date().toISOString() });
47
+ }
48
+
49
+ function storeResult(store, identity, result) {
50
+ if (!store || !identity) return;
51
+ try {
52
+ store.put({ identity, toolName: 'callx402.execute', payer: 'local', paymentAuthFingerprint: 'none', traceId: result.idempotencyKey || '', operationId: identity, result, storedAt: new Date().toISOString() });
53
+ } catch (_) { /* dedupe persistence is best-effort; never fail the run */ }
54
+ }
55
+
56
+ /**
57
+ * runIntent(text, opts, { config, deps }) -> { result, exitCode }
58
+ *
59
+ * opts: maxBudget, deadline, speed, risk, networks, assets, providers,
60
+ * approvalThreshold, idempotencyKey, timeoutMs, dryRun, approve,
61
+ * forceRetry / retry (explicit retry flag).
62
+ */
63
+ async function runIntent(text, opts = {}, ctx = {}) {
64
+ const config = ctx.config || loadConfig();
65
+ const deps = ctx.deps || {};
66
+
67
+ // SPEC §5: remote mode posts the intent to the callx402 server's /call.
68
+ if (config.mode === 'remote' && Object.keys(deps).length === 0) {
69
+ return dispatchRemote(config, 'execute', { intent: text, ...opts }, { timeoutMs: opts.timeoutMs });
70
+ }
71
+
72
+ const stages = [];
73
+ const S = (name, status, detail) => stageRec(stages, name, status, detail);
74
+
75
+ if (!text || !String(text).trim()) {
76
+ const r = fail('execute', { code: 'usage', message: 'intent text is required', disposition: 'No intent supplied.' });
77
+ return { result: r, exitCode: EXIT.USAGE };
78
+ }
79
+
80
+ const idempotencyKey = opts.idempotencyKey || null;
81
+ const identity = idempotencyKey ? `callx402_idem_${idempotencyKey}` : null;
82
+
83
+ // ---- Stage 0: idempotency dedupe -------------------------------------
84
+ const recovery = getSubsystem('recovery', { config, deps });
85
+ let store = null;
86
+ if (recovery.reachable) {
87
+ try {
88
+ store = recovery.module.createRecoveryStore({ file: idempotencyFile(config) });
89
+ S('idempotency', 'ok', { file: idempotencyFile(config), key: idempotencyKey });
90
+ } catch (err) {
91
+ S('idempotency', 'skipped', `recovery store unavailable: ${err.message}`);
92
+ }
93
+ } else {
94
+ S('idempotency', 'skipped', `result-recovery unreachable: ${recovery.error || 'unknown'}`);
95
+ }
96
+
97
+ if (store && identity) {
98
+ const prior = store.get(identity);
99
+ if (prior && prior.result) {
100
+ const retryRequested = opts.forceRetry === true || opts.retry === true;
101
+ if (retryRequested && prior.result.settlement === 'UNKNOWN') {
102
+ const r = fail('execute', {
103
+ code: 'unsafe_retry_refused',
104
+ message: 'Refused: the stored run settled UNKNOWN. An explicit retry after UNKNOWN settlement could double-spend. Resolve the settlement manually first (callx402 resolve --evidence ...).',
105
+ disposition: 'Unsafe retry refused: prior settlement state is UNKNOWN.',
106
+ idempotencyKey, deduped: true,
107
+ data: { stages },
108
+ });
109
+ return { result: r, exitCode: EXIT.SETTLEMENT_UNKNOWN };
110
+ }
111
+ const dup = { ...prior.result, deduped: true, idempotencyKey };
112
+ return { result: dup, exitCode: exitCodeFor(dup) };
113
+ }
114
+ }
115
+
116
+ // ---- Stage 1: intent parse ------------------------------------------
117
+ const intentSub = getSubsystem('intent', { config, deps });
118
+ let intent = null;
119
+ if (!intentSub.reachable) {
120
+ S('intent', 'skipped', `intent-engine unreachable: ${intentSub.error || 'unknown'}`);
121
+ } else if (!intentSub.enabled) {
122
+ S('intent', 'disabled', `intent-engine disabled; set ${intentSub.flag}=1 to enable parsing`);
123
+ } else {
124
+ try {
125
+ // Awaited: an async (or slow) intent engine must respect timeoutMs via
126
+ // the runAction race; awaiting a sync value is a no-op.
127
+ intent = await intentSub.module.parse(String(text));
128
+ const budgetHint = intent && intent.constraints && (intent.constraints.MAX_PRICE ?? intent.constraints.AMOUNT);
129
+ S('intent', 'ok', { goals: intent.goals, action_class: intent.action_class, budgetHint: budgetHint ?? null });
130
+ } catch (err) {
131
+ S('intent', 'failed', err.message);
132
+ }
133
+ }
134
+
135
+ let maxBudget = opts.maxBudget != null ? Number(opts.maxBudget)
136
+ : (intent && intent.constraints && Number.isFinite(Number(intent.constraints.MAX_PRICE)) ? Number(intent.constraints.MAX_PRICE)
137
+ : Number(config.defaultBudgetUsd));
138
+ if (!Number.isFinite(maxBudget) || maxBudget < 0) maxBudget = Number(config.defaultBudgetUsd);
139
+ const approvalThreshold = opts.approvalThreshold != null ? Number(opts.approvalThreshold) : Number(config.approvalThresholdUsd);
140
+
141
+ // ---- Stage 2: capability graph --------------------------------------
142
+ const capSub = getSubsystem('capabilities', { config, deps });
143
+ let candidates = [];
144
+ if (!capSub.reachable) {
145
+ S('capabilities', 'skipped', `capability-graph unreachable: ${capSub.error || 'unknown'}`);
146
+ } else if (!capSub.enabled) {
147
+ S('capabilities', 'disabled', `capability-graph disabled; set ${capSub.flag}=1 to enable tool discovery`);
148
+ } else {
149
+ try {
150
+ const graph = await capSub.module.createGraph();
151
+ const stats = graph.stats ? await graph.stats() : {};
152
+ const toolCount = stats.tools || 0;
153
+ if (toolCount === 0) {
154
+ S('capabilities', 'ok', { candidates: 0, note: 'capability graph is empty: no tools registered' });
155
+ } else {
156
+ const found = await graph.findTools(String(text));
157
+ candidates = Array.isArray(found.candidates) ? found.candidates : [];
158
+ S('capabilities', 'ok', { candidates: candidates.length, stats: graph.stats ? await graph.stats() : {} });
159
+ }
160
+ } catch (err) {
161
+ S('capabilities', 'failed', err.message);
162
+ }
163
+ }
164
+
165
+ // ---- Stage 3: economic planner --------------------------------------
166
+ const plannerSub = getSubsystem('planner', { config, deps });
167
+ let plan = null;
168
+ const speedPolicy = (SPEED_POLICY[String(opts.speed || 'balanced').toLowerCase()] || 'BEST_VALUE');
169
+ if (!plannerSub.reachable) {
170
+ S('planner', 'skipped', `economic-planner unreachable: ${plannerSub.error || 'unknown'}`);
171
+ } else if (!plannerSub.enabled) {
172
+ S('planner', 'disabled', `economic-planner disabled; set ${plannerSub.flag}=1 to enable costed planning`);
173
+ } else {
174
+ try {
175
+ const steps = [{
176
+ id: 'goal',
177
+ name: (intent && intent.goals && intent.goals[0] && intent.goals[0].goal) || 'goal',
178
+ candidates: candidates.length > 0
179
+ ? candidates.slice(0, 8).map((c, i) => ({ tool: String(c.id || c.name || `tool-${i}`), price_usd: Number(c.price_usd ?? c.cost_usd ?? 0) || 0 }))
180
+ : [{ tool: 'no-registered-tool', price_usd: 0 }],
181
+ }];
182
+ plan = await plannerSub.module.planGoal({
183
+ goal: String(text).slice(0, 120),
184
+ steps,
185
+ maxBudgetUsd: maxBudget,
186
+ objective: speedPolicy === 'FASTEST_VERIFIED' ? 'FASTEST' : speedPolicy === 'LOWEST_TOTAL_COST' ? 'CHEAPEST' : 'BEST_VALUE',
187
+ networks: opts.networks || null,
188
+ assets: opts.assets || null,
189
+ providers: opts.providers || null,
190
+ });
191
+ S('planner', plan && plan.valid ? 'ok' : 'no_plan', plan && plan.valid
192
+ ? { cost: plan.total_cost_usd ?? plan.cost_usd ?? null, plans_considered: plan.plans_considered }
193
+ : (plan && plan.reason) || 'planner returned no valid plan');
194
+ } catch (err) {
195
+ S('planner', 'failed', err.message);
196
+ }
197
+ }
198
+
199
+ const plannedCost = plan && plan.valid
200
+ ? Number(plan.total_cost_usd ?? plan.cost_usd ?? 0)
201
+ : (candidates.length > 0 ? Math.min(...candidates.map((c) => Number(c.price_usd ?? c.cost_usd ?? 0)).filter(Number.isFinite)) : 0);
202
+
203
+ // ---- Stage 4: SpendGuard budget check --------------------------------
204
+ const sgSub = getSubsystem('spendguard', { config, deps });
205
+ if (!sgSub.reachable) {
206
+ S('spendguard', 'skipped', `spendguard unreachable: ${sgSub.error || 'unknown'}; budget enforced by direct comparison only`);
207
+ } else if (!sgSub.enabled) {
208
+ S('spendguard', 'disabled', `spendguard disabled; set ${sgSub.flag}=1 to enable task-level guards`);
209
+ }
210
+ let remainingUsd = maxBudget;
211
+ if (sgSub.reachable && sgSub.enabled) {
212
+ try {
213
+ const taskGuard = await sgSub.module.createTaskSpendGuard({
214
+ taskId: `callx402-${Date.now()}`,
215
+ totalTaskBudgetUsd: maxBudget,
216
+ approvedNetworks: opts.networks || (config.defaultNetwork ? [config.defaultNetwork] : null),
217
+ approvedAssets: opts.assets || (config.defaultAsset ? [config.defaultAsset] : null),
218
+ approvedProviders: opts.providers || null,
219
+ });
220
+ const st = await taskGuard.status();
221
+ remainingUsd = Number(st.remainingTaskUsd ?? maxBudget);
222
+ S('spendguard', 'ok', { remainingTaskUsd: remainingUsd, budgetUsd: maxBudget });
223
+ } catch (err) {
224
+ S('spendguard', 'failed', err.message);
225
+ }
226
+ }
227
+
228
+ // Money-safety: over budget -> refuse with zero side effects. Nothing has
229
+ // executed at this point, so refusal is inherently clean.
230
+ if (plannedCost > maxBudget) {
231
+ S('budget', 'refused', { plannedCost, maxBudget });
232
+ const r = fail('execute', {
233
+ subsystem: 'spendguard', subsystemStatus: sgSub.subsystemStatus,
234
+ code: 'budget_refused',
235
+ message: `Planned cost $${plannedCost.toFixed(2)} exceeds budget $${maxBudget.toFixed(2)}. Nothing was executed and no money moved. Raise --max-budget or narrow the goal.`,
236
+ disposition: 'Budget refused: planned cost exceeds budget; zero side effects.',
237
+ data: { stages, plannedCost, maxBudget },
238
+ idempotencyKey,
239
+ });
240
+ return { result: r, exitCode: EXIT.BUDGET_REFUSED };
241
+ }
242
+ if (Number.isFinite(approvalThreshold) && plannedCost > approvalThreshold && opts.approve !== true && !opts.dryRun) {
243
+ S('budget', 'refused', { plannedCost, approvalThreshold, reason: 'approval_required' });
244
+ const r = fail('execute', {
245
+ subsystem: 'spendguard', subsystemStatus: sgSub.subsystemStatus,
246
+ code: 'approval_required',
247
+ message: `Planned cost $${plannedCost.toFixed(2)} exceeds the approval threshold $${approvalThreshold.toFixed(2)}. Re-run with --approve to authorize, or nothing will happen.`,
248
+ disposition: 'Fail closed: cost above approval threshold without explicit approval.',
249
+ data: { stages, plannedCost, approvalThreshold },
250
+ idempotencyKey,
251
+ });
252
+ return { result: r, exitCode: EXIT.BUDGET_REFUSED };
253
+ }
254
+ S('budget', 'ok', { plannedCost, maxBudget, approved: opts.approve === true });
255
+
256
+ // ---- Stage 5: router --------------------------------------------------
257
+ const routerSub = getSubsystem('router', { config, deps });
258
+ let route = null;
259
+ if (!routerSub.reachable) {
260
+ S('router', 'skipped', `router unreachable: ${routerSub.error || 'unknown'}`);
261
+ } else if (!routerSub.enabled) {
262
+ S('router', 'disabled', `router disabled; set ${routerSub.flag}=1 to enable route selection`);
263
+ } else if (candidates.length === 0) {
264
+ S('router', 'skipped', 'no candidate tools discovered; nothing to rank');
265
+ } else {
266
+ try {
267
+ const routerOpts = {
268
+ policy: speedPolicy,
269
+ networks: opts.networks || null,
270
+ assets: opts.assets || null,
271
+ providers: opts.providers || null,
272
+ };
273
+ // normalizeCandidate(c, opts): opts is required by the real
274
+ // smart-router; constraint opts ride along for recording doubles.
275
+ const normalized = [];
276
+ for (const c of candidates) {
277
+ try {
278
+ normalized.push(routerSub.module.normalizeCandidate
279
+ ? await routerSub.module.normalizeCandidate(c, routerOpts)
280
+ : c);
281
+ } catch (_) { /* skip un-normalizable candidates */ }
282
+ }
283
+ const ranked = await routerSub.module.rankTools(normalized, routerOpts);
284
+ const selected = await routerSub.module.selectTool(ranked);
285
+ route = { selected, policy: speedPolicy };
286
+ S('router', 'ok', { selected: selected && (selected.tool || selected.id || selected.name), policy: speedPolicy });
287
+ } catch (err) {
288
+ S('router', 'failed', err.message);
289
+ }
290
+ }
291
+
292
+ // ---- Stage 6: execution kernel — live route required ------------------
293
+ // The dispatch layer wires no live tool endpoints: without a real executable
294
+ // route we report honestly and stop. Never fabricate execution.
295
+ const kernelSub = getSubsystem('kernel', { config, deps });
296
+ const hasLiveRoute = !!(route && route.selected && route.selected.executable === true);
297
+ if (opts.dryRun === true) {
298
+ S('execution', 'dry_run', 'dry-run: planning only, no execution attempted');
299
+ } else if (!hasLiveRoute) {
300
+ S('execution', 'no_route', 'no executable route available: no live tool endpoint is wired to this dispatch. No execution performed, no money moved.');
301
+ } else if (!kernelSub.enabled) {
302
+ S('execution', 'disabled', `execution kernel disabled; set ${kernelSub.flag}=1 and wire a live route to execute`);
303
+ }
304
+
305
+ const executed = hasLiveRoute && kernelSub.enabled && opts.dryRun !== true;
306
+
307
+ // ---- Stages 7-9: effect proof / settlement / delivery ----------------
308
+ let settlement = null;
309
+ let receipt = {};
310
+ if (executed) {
311
+ // Only reachable with a real executable route; placeholder branch kept
312
+ // explicit so the honesty invariant is auditable.
313
+ S('effect_proof', 'not_implemented', 'live execution path is not wired in this build');
314
+ S('settlement', 'not_implemented', 'live execution path is not wired in this build');
315
+ S('delivery', 'not_implemented', 'live execution path is not wired in this build');
316
+ } else {
317
+ S('effect_proof', 'skipped', 'no execution: no effect proof issued');
318
+ S('settlement', 'skipped', 'no execution: nothing to settle');
319
+ S('delivery', 'skipped', 'no execution: nothing delivered');
320
+ }
321
+
322
+ // ---- Stage 10: RevRule emit (idempotent) ------------------------------
323
+ const revSub = getSubsystem('revrule', { config, deps });
324
+ if (!revSub.reachable) {
325
+ S('revrule', 'skipped', `revrule unreachable: ${revSub.error || 'unknown'}`);
326
+ } else if (!revSub.enabled) {
327
+ S('revrule', 'disabled', `revrule disabled; set ${revSub.flag}=1 to emit economic events`);
328
+ } else {
329
+ try {
330
+ const emitter = await revSub.module.createEmitter({ sink: await revSub.module.createMemorySink(), idempotencyRegistry: await revSub.module.createIdempotencyRegistry() });
331
+ const ev = await emitter.emitOnce({
332
+ operationId: idempotencyKey || `plan-${Date.now()}`,
333
+ toolId: 'callx402.execute',
334
+ payer: 'local',
335
+ payTo: 'none',
336
+ amountAt: plannedCost,
337
+ amountAtomic: Math.round(Number(plannedCost || 0) * 1e6),
338
+ asset: config.defaultAsset || 'USDC',
339
+ network: config.defaultNetwork || 'base',
340
+ type: 'callx402.intent_planned',
341
+ intent: String(text).slice(0, 120),
342
+ maxBudget,
343
+ idempotencyKey: idempotencyKey || `plan-${Date.now()}`,
344
+ executed,
345
+ });
346
+ S('revrule', ev.emitted ? 'ok' : 'deduped', ev.emitted ? { eventId: ev.eventId } : { reason: ev.reason });
347
+ } catch (err) {
348
+ S('revrule', 'failed', err.message);
349
+ }
350
+ }
351
+
352
+ const disposition = executed
353
+ ? 'Intent executed through a live route.'
354
+ : opts.dryRun === true
355
+ ? 'Dry run: plan validated, no execution performed.'
356
+ : 'No executable route available: intent parsed and planned honestly, but no live tool endpoint is wired to this dispatch, so nothing was executed and no money moved.';
357
+
358
+ const r = ok('execute', {
359
+ subsystem: 'pipeline',
360
+ subsystemStatus: 'ok',
361
+ disposition,
362
+ data: { stages, intent: intent ? { goals: intent.goals, action_class: intent.action_class, risk_level: intent.risk_level } : null, plannedCost, maxBudget, route: route ? { policy: route.policy } : null, dryRun: opts.dryRun === true, executed },
363
+ settlement,
364
+ receipt,
365
+ idempotencyKey,
366
+ });
367
+ storeResult(store, identity, r);
368
+ return { result: r, exitCode: EXIT.OK };
369
+ }
370
+
371
+ module.exports = { runIntent };
package/core/remote.js ADDED
@@ -0,0 +1,242 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * core/remote.js — remote-mode dispatch (SPEC §5).
5
+ *
6
+ * When config.mode === 'remote', runAction/runIntent delegate to a callx402
7
+ * HTTP server at config.remoteUrl instead of dispatching into local
8
+ * subsystems. The server's envelope is returned as-is; its exit code is
9
+ * derived with exitCodeFor.
10
+ *
11
+ * Money-safety: remote is a transport change only. Budget refusals,
12
+ * settlement-UNKNOWN, and unsafe-retry refusals surface exactly as the
13
+ * remote server reports them; this layer never retries.
14
+ *
15
+ * Auth: when config.authToken (CALLX402_AUTH_TOKEN) is set, requests carry
16
+ * `Authorization: Bearer <token>`, matching server/index.js.
17
+ *
18
+ * The deps seam (internal/test) disables remote dispatch: an explicit
19
+ * subsystem override means "dispatch locally against these handles".
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const http = require('http');
24
+ const https = require('https');
25
+ const path = require('path');
26
+
27
+ const { EXIT, ok, fail, exitCodeFor } = require('./envelope');
28
+
29
+ const DEFAULT_REMOTE_TIMEOUT_MS = 15000;
30
+
31
+ // CLI/server route map. Actions without a server route fail closed with a
32
+ // clear usage error (never silently degraded).
33
+ const POST_ROUTES = {
34
+ execute: '/call',
35
+ rescue: '/rescue',
36
+ route: '/route',
37
+ resolve: '/resolve',
38
+ diagnose: '/diagnose',
39
+ doctor: '/diagnose',
40
+ };
41
+
42
+ const REMOTE_UNSUPPORTED = {
43
+ monitor: 'monitor streams local sentinel snapshots; no server route exists',
44
+ preflight: 'preflight runs local preflight checks; no server route exists',
45
+ inspect: 'inspect queries the local capability graph; no server route exists',
46
+ };
47
+
48
+ function pick(obj, keys) {
49
+ const out = {};
50
+ for (const k of keys) {
51
+ if (obj && obj[k] !== undefined) out[k] = obj[k];
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** Parse --evidence style input locally so malformed input fails before any network call. */
57
+ function parseEvidenceInput(input) {
58
+ if (input === undefined || input === null || input === '') return undefined;
59
+ if (typeof input !== 'string') return input;
60
+ const s = input.trim();
61
+ if (s.startsWith('@')) {
62
+ const raw = fs.readFileSync(path.resolve(s.slice(1)), 'utf8');
63
+ return JSON.parse(raw);
64
+ }
65
+ return JSON.parse(s);
66
+ }
67
+
68
+ function requestJson(urlStr, { method = 'POST', body = null, authToken = null, timeoutMs }) {
69
+ return new Promise((resolve, reject) => {
70
+ const u = new URL(urlStr);
71
+ const lib = u.protocol === 'https:' ? https : http;
72
+ const data = body === null || body === undefined ? null : JSON.stringify(body);
73
+ const headers = {};
74
+ if (data !== null) {
75
+ headers['content-type'] = 'application/json';
76
+ headers['content-length'] = Buffer.byteLength(data);
77
+ }
78
+ if (authToken) headers['authorization'] = 'Bearer ' + authToken;
79
+ const req = lib.request(u, { method, headers, timeout: timeoutMs }, (res) => {
80
+ let raw = '';
81
+ res.on('data', (c) => { raw += c; });
82
+ res.on('end', () => resolve({ status: res.statusCode, body: raw }));
83
+ });
84
+ req.on('timeout', () => req.destroy(new Error(`request timed out after ${timeoutMs}ms`)));
85
+ req.on('error', reject);
86
+ if (data !== null) req.end(data);
87
+ else req.end();
88
+ });
89
+ }
90
+
91
+ function unreachableResult(action, remoteUrl, err) {
92
+ const detail = (err && err.message) || String(err);
93
+ return {
94
+ result: fail(action, {
95
+ code: 'remote_unreachable',
96
+ message: `remote callx402 server at ${remoteUrl} is unreachable (${detail}). Set CALLX402_MODE=local to dispatch locally, or start a callx402 server (node server/index.js) at that URL. Nothing was executed remotely.`,
97
+ disposition: `Remote server unreachable: ${remoteUrl}.`,
98
+ data: { remoteUrl },
99
+ }),
100
+ exitCode: EXIT.UNAVAILABLE,
101
+ };
102
+ }
103
+
104
+ function buildCall(action, args) {
105
+ switch (action) {
106
+ case 'execute':
107
+ return {
108
+ route: POST_ROUTES.execute,
109
+ body: {
110
+ intent: args.intent || args.text || '',
111
+ ...pick(args, ['maxBudget', 'deadline', 'speed', 'risk', 'networks', 'assets', 'providers', 'approvalThreshold', 'idempotencyKey', 'dryRun', 'timeoutMs']),
112
+ },
113
+ };
114
+ case 'rescue':
115
+ return { route: POST_ROUTES.rescue, body: { incidentId: args.incident || null, ...pick(args, ['network', 'context']) } };
116
+ case 'route':
117
+ return { route: POST_ROUTES.route, body: { goal: args.goal || args.intent || args.text || '', ...pick(args, ['speed', 'networks', 'assets', 'providers']) } };
118
+ case 'resolve': {
119
+ let evidence;
120
+ try {
121
+ evidence = parseEvidenceInput(args.evidence);
122
+ } catch (err) {
123
+ return { usageError: `malformed evidence JSON: ${err.message}` };
124
+ }
125
+ return { route: POST_ROUTES.resolve, body: { evidence: evidence === undefined ? {} : evidence } };
126
+ }
127
+ case 'diagnose':
128
+ case 'doctor': {
129
+ let evidence;
130
+ try {
131
+ evidence = parseEvidenceInput(args.evidence ?? args.target);
132
+ } catch (err) {
133
+ return { usageError: `malformed evidence JSON: ${err.message}` };
134
+ }
135
+ const body = { target: typeof args.target === 'string' ? args.target : null };
136
+ if (evidence !== undefined) body.evidence = evidence;
137
+ return { route: POST_ROUTES.diagnose, body };
138
+ }
139
+ default:
140
+ return { usageError: null }; // handled by caller
141
+ }
142
+ }
143
+
144
+ /**
145
+ * dispatchRemote(config, action, args, { timeoutMs }) -> Promise<{ result, exitCode }>
146
+ */
147
+ async function dispatchRemote(config, action, args = {}, opts = {}) {
148
+ const remoteUrl = String(config.remoteUrl || '').replace(/\/+$/, '');
149
+
150
+ if (!remoteUrl) {
151
+ return {
152
+ result: fail(action, {
153
+ code: 'usage',
154
+ message: 'CALLX402_MODE=remote requires a remote URL: set CALLX402_REMOTE_URL (or config remoteUrl), e.g. http://127.0.0.1:8787.',
155
+ disposition: 'Remote mode configured without a remote URL.',
156
+ }),
157
+ exitCode: EXIT.USAGE,
158
+ };
159
+ }
160
+
161
+ if (action === 'config') {
162
+ // Client-side config management never goes over the wire.
163
+ return {
164
+ result: fail(action, { code: 'usage', message: 'config is always local; it is not dispatched to the remote server.' }),
165
+ exitCode: EXIT.USAGE,
166
+ };
167
+ }
168
+
169
+ if (REMOTE_UNSUPPORTED[action]) {
170
+ return {
171
+ result: fail(action, {
172
+ code: 'usage',
173
+ message: `${action}: ${REMOTE_UNSUPPORTED[action]}. The callx402 server exposes /call, /rescue, /route, /resolve, /diagnose and /health only. Run with CALLX402_MODE=local for ${action}.`,
174
+ disposition: `${action} is not available in remote mode.`,
175
+ data: { remoteUrl },
176
+ }),
177
+ exitCode: EXIT.USAGE,
178
+ };
179
+ }
180
+
181
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : DEFAULT_REMOTE_TIMEOUT_MS;
182
+ const authToken = config.authToken || null;
183
+
184
+ try {
185
+ if (action === 'status') {
186
+ const { body } = await requestJson(remoteUrl + '/health', { method: 'GET', authToken, timeoutMs });
187
+ let parsed = null;
188
+ try { parsed = JSON.parse(body); } catch (_) { /* handled below */ }
189
+ if (!parsed || typeof parsed !== 'object') {
190
+ return {
191
+ result: fail(action, { code: 'remote_bad_response', message: `remote server at ${remoteUrl} returned a non-JSON /health response.`, data: { remoteUrl } }),
192
+ exitCode: EXIT.FAIL,
193
+ };
194
+ }
195
+ if (parsed.ok !== true) {
196
+ const r = fail(action, {
197
+ code: (parsed.error && parsed.error.code) || 'remote_error',
198
+ message: (parsed.error && parsed.error.message) || `remote /health reported failure at ${remoteUrl}.`,
199
+ data: { remoteUrl, version: parsed.version || null },
200
+ });
201
+ return { result: r, exitCode: exitCodeFor(r) };
202
+ }
203
+ return {
204
+ result: ok('status', {
205
+ subsystem: null,
206
+ disposition: `remote callx402 status from ${remoteUrl}: v${parsed.version || '?'}.`,
207
+ data: { version: parsed.version || null, remoteUrl, subsystems: parsed.subsystems || {} },
208
+ }),
209
+ exitCode: EXIT.OK,
210
+ };
211
+ }
212
+
213
+ if (!POST_ROUTES[action]) {
214
+ return {
215
+ result: fail(action, { code: 'unknown_action', message: `unknown action '${action}' for remote dispatch.` }),
216
+ exitCode: EXIT.USAGE,
217
+ };
218
+ }
219
+
220
+ const call = buildCall(action, args);
221
+ if (call.usageError) {
222
+ return {
223
+ result: fail(action, { code: 'usage', message: call.usageError, disposition: 'Malformed input.' }),
224
+ exitCode: EXIT.USAGE,
225
+ };
226
+ }
227
+ const { body } = await requestJson(remoteUrl + call.route, { method: 'POST', body: call.body, authToken, timeoutMs });
228
+ let env = null;
229
+ try { env = JSON.parse(body); } catch (_) { /* handled below */ }
230
+ if (!env || typeof env !== 'object' || typeof env.ok !== 'boolean') {
231
+ return {
232
+ result: fail(action, { code: 'remote_bad_response', message: `remote server at ${remoteUrl}${call.route} returned a non-envelope response.`, data: { remoteUrl, route: call.route } }),
233
+ exitCode: EXIT.FAIL,
234
+ };
235
+ }
236
+ return { result: env, exitCode: exitCodeFor(env) };
237
+ } catch (err) {
238
+ return unreachableResult(action, remoteUrl, err);
239
+ }
240
+ }
241
+
242
+ module.exports = { dispatchRemote, POST_ROUTES, REMOTE_UNSUPPORTED, DEFAULT_REMOTE_TIMEOUT_MS };