unbrowse 3.0.2 → 3.1.0-experiments.548e04c

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.
@@ -13,10 +13,15 @@ import {
13
13
  detectTelemetryHostType,
14
14
  ensureCliInstallTracked,
15
15
  ensureRegistered,
16
+ getAgentId,
16
17
  getApiKey,
18
+ getCreatorEarnings,
19
+ getMyProfile,
20
+ getTransactionHistory,
17
21
  recordFunnelTelemetryEvent,
18
22
  recordInstallTelemetryEvent,
19
23
  } from "./client/index.js";
24
+ import { appendImpact, getImpactLogPath, impactFromResult, readImpactSummary } from "./impact-log.js";
20
25
  import { findSitePack, findTask, allSitePacks, buildDepsGraph, planExecution, buildDepsMetadata, type SitePack } from "./cli/shortcuts.js";
21
26
  import { ensureLocalServer, checkServerVersion, stopServer, restartServer } from "./runtime/local-server.js";
22
27
  import { isBundledVirtualEntrypoint, isMainModule, resolveSiblingEntrypoint, runtimeArgsForEntrypoint } from "./runtime/paths.js";
@@ -30,6 +35,7 @@ loadEnv({ path: ".env.runtime", quiet: true });
30
35
 
31
36
  const BASE_URL = process.env.UNBROWSE_URL || "http://localhost:6969";
32
37
  const CLI_CLIENT_ID = process.env.UNBROWSE_CLIENT_ID || `cli-${process.ppid || process.pid}`;
38
+ let walletNudgeShown = false;
33
39
 
34
40
  // ---------------------------------------------------------------------------
35
41
  // Arg parser
@@ -184,6 +190,14 @@ function formatSavedDuration(ms: number): string {
184
190
  return `${ms}ms`;
185
191
  }
186
192
 
193
+ function formatCostUsd(uc: number): string {
194
+ // uc = micro-USD (1e-6 USD). 1M uc = $1.
195
+ const usd = uc / 1_000_000;
196
+ if (usd >= 1) return `$${usd.toFixed(2)}`;
197
+ if (usd >= 0.01) return `$${usd.toFixed(3)}`;
198
+ return `$${usd.toFixed(4)}`;
199
+ }
200
+
187
201
  function emitImpactSummary(result: Record<string, unknown>): void {
188
202
  const impact = result.impact as Record<string, unknown> | undefined;
189
203
  if (!impact) return;
@@ -192,12 +206,14 @@ function emitImpactSummary(result: Record<string, unknown>): void {
192
206
  const tokensSaved = typeof impact.tokens_saved === "number" ? impact.tokens_saved : 0;
193
207
  const timeSavedPct = typeof impact.time_saved_pct === "number" ? impact.time_saved_pct : 0;
194
208
  const tokensSavedPct = typeof impact.tokens_saved_pct === "number" ? impact.tokens_saved_pct : 0;
209
+ const costSavedUc = typeof impact.cost_saved_uc === "number" ? impact.cost_saved_uc : 0;
195
210
  const browserAvoided = impact.browser_avoided === true;
196
- if (timeSavedMs <= 0 && tokensSaved <= 0 && !browserAvoided) return;
211
+ if (timeSavedMs <= 0 && tokensSaved <= 0 && costSavedUc <= 0 && !browserAvoided) return;
197
212
 
198
213
  const parts: string[] = [];
199
214
  if (timeSavedMs > 0) parts.push(`${formatSavedDuration(timeSavedMs)} saved (${timeSavedPct}% faster)`);
200
215
  if (tokensSaved > 0) parts.push(`${tokensSaved.toLocaleString("en-US")} tokens saved (${tokensSavedPct}% less context)`);
216
+ if (costSavedUc > 0) parts.push(`${formatCostUsd(costSavedUc)} saved`);
201
217
  if (browserAvoided) parts.push("browser avoided");
202
218
  info(parts.join(" • "));
203
219
  }
@@ -370,10 +386,27 @@ async function cmdResolve(flags: Record<string, string | boolean>): Promise<void
370
386
 
371
387
  result = slimTrace(result);
372
388
  emitImpactSummary(result);
389
+ {
390
+ const entry = impactFromResult("resolve", result, { intent, domain, });
391
+ if (entry) appendImpact(entry);
392
+ }
373
393
  emitNextActionSummary(result);
374
394
 
375
395
  const skill = result.skill as Record<string, unknown> | undefined;
376
396
  const trace = result.trace as Record<string, unknown> | undefined;
397
+
398
+ // Nudge wallet setup after successful resolve that indexed routes
399
+ if (trace?.success && !walletNudgeShown) {
400
+ try {
401
+ const { checkWalletConfigured } = await import("./payments/wallet.js");
402
+ const wallet = checkWalletConfigured();
403
+ if (!wallet.configured) {
404
+ info("You're indexing routes but have no payout wallet. Run: npx @crossmint/lobster-cli setup");
405
+ walletNudgeShown = true;
406
+ }
407
+ } catch (_e) { /* non-fatal */ }
408
+ }
409
+
377
410
  if (skill?.skill_id && trace) {
378
411
  (result as Record<string, unknown>)._feedback = `unbrowse feedback --skill ${skill.skill_id} --endpoint ${trace.endpoint_id || "?"} --rating <1-5>`;
379
412
  }
@@ -548,6 +581,13 @@ async function cmdExecute(flags: Record<string, string | boolean>): Promise<void
548
581
  // Strip metadata bloat
549
582
  result = slimTrace(result);
550
583
  emitImpactSummary(result);
584
+ {
585
+ const entry = impactFromResult("execute", result, {
586
+ skill_id: skillId,
587
+ endpoint_id: typeof flags.endpoint === "string" ? flags.endpoint : undefined,
588
+ });
589
+ if (entry) appendImpact(entry);
590
+ }
551
591
  emitNextActionSummary(result);
552
592
 
553
593
  const pathFlag = flags.path as string | undefined;
@@ -812,6 +852,18 @@ async function cmdSetup(flags: Record<string, string | boolean>): Promise<void>
812
852
  }
813
853
  }
814
854
 
855
+ // Wallet status — tell the user if they're missing payout config
856
+ if (report.wallet.configured) {
857
+ info(`Wallet configured (${report.wallet.provider}): ${(report.wallet as Record<string, unknown>).wallet_address ?? "linked"}`);
858
+ } else if ((report.wallet as Record<string, unknown>).lobster_installed) {
859
+ info("Wallet not paired — your indexed routes won't earn payouts.");
860
+ info("Run: npx @crossmint/lobster-cli setup");
861
+ } else {
862
+ info("No wallet configured — you're indexing routes for free.");
863
+ info("Set up a wallet so you earn when agents use your routes:");
864
+ info(" npx @crossmint/lobster-cli setup");
865
+ }
866
+
815
867
  await recordInstallTelemetryEvent("setup", {
816
868
  hostType,
817
869
  status: report.browser_engine.action === "failed" ? "failed" : "installed",
@@ -913,6 +965,7 @@ export const CLI_REFERENCE = {
913
965
  { name: "forward", usage: "[--session id]", desc: "Navigate forward" },
914
966
  { name: "sync", usage: "[--session id]", desc: "Checkpoint current capture, keep tab open, queue background index + publish, then inspect via skill/publish review" },
915
967
  { name: "close", usage: "[--session id]", desc: "Checkpoint capture, queue background index + publish, close browse session, then inspect via skill/publish review" },
968
+ { name: "stats", usage: "[--json] [--pretty]", desc: "Show lifetime time/tokens/cost saved and marketplace earnings/spending" },
916
969
  ],
917
970
  globalFlags: [
918
971
  { flag: "--pretty", desc: "Indented JSON output" },
@@ -954,6 +1007,139 @@ export const CLI_REFERENCE = {
954
1007
  ],
955
1008
  };
956
1009
 
1010
+
1011
+ // ---------------------------------------------------------------------------
1012
+ // stats — show lifetime impact (savings + earnings) for the current agent
1013
+ // ---------------------------------------------------------------------------
1014
+
1015
+ function formatTotalDuration(ms: number): string {
1016
+ if (ms >= 3_600_000) return `${(ms / 3_600_000).toFixed(1)}h`;
1017
+ if (ms >= 60_000) return `${(ms / 60_000).toFixed(1)}m`;
1018
+ if (ms >= 1000) return `${(ms / 1000).toFixed(1)}s`;
1019
+ return `${ms}ms`;
1020
+ }
1021
+
1022
+ async function cmdStats(flags: Record<string, string | boolean>): Promise<void> {
1023
+ const pretty = !!flags.pretty;
1024
+ const jsonOnly = !!flags.json;
1025
+ const local = readImpactSummary();
1026
+ const agentId = getAgentId();
1027
+
1028
+ type EarningsLedger = { total_earned_uc: number; total_earned_usd: number; transaction_count: number; last_transaction_at?: string } | null;
1029
+ type SpendingLedger = { total_spent_uc: number; total_spent_usd: number; transaction_count: number; last_transaction_at?: string } | null;
1030
+
1031
+ let profile: Awaited<ReturnType<typeof getMyProfile>> | null = null;
1032
+ let earnings: { ledger: EarningsLedger; transactions: unknown[] } | null = null;
1033
+ let spending: { ledger: SpendingLedger; transactions: unknown[] } | null = null;
1034
+ const remoteErrors: Record<string, string> = {};
1035
+
1036
+ if (agentId) {
1037
+ const results = await Promise.allSettled([
1038
+ getMyProfile(),
1039
+ getCreatorEarnings(agentId),
1040
+ getTransactionHistory(agentId),
1041
+ ]);
1042
+ if (results[0].status === "fulfilled") profile = results[0].value;
1043
+ else remoteErrors.profile = (results[0].reason as Error)?.message ?? String(results[0].reason);
1044
+ if (results[1].status === "fulfilled") earnings = results[1].value as { ledger: EarningsLedger; transactions: unknown[] };
1045
+ else remoteErrors.earnings = (results[1].reason as Error)?.message ?? String(results[1].reason);
1046
+ if (results[2].status === "fulfilled") spending = results[2].value as { ledger: SpendingLedger; transactions: unknown[] };
1047
+ else remoteErrors.spending = (results[2].reason as Error)?.message ?? String(results[2].reason);
1048
+ } else {
1049
+ remoteErrors.profile = "No agent_id in local config. Run `unbrowse setup` to register.";
1050
+ }
1051
+
1052
+ const earnedUsd = earnings?.ledger?.total_earned_usd ?? 0;
1053
+ const spentUsd = spending?.ledger?.total_spent_usd ?? 0;
1054
+ const netUsd = earnedUsd - spentUsd;
1055
+ const savedUsd = local.total_cost_saved_uc / 1_000_000;
1056
+
1057
+ const payload = {
1058
+ agent_id: agentId,
1059
+ profile,
1060
+ impact: {
1061
+ total_runs: local.total_runs,
1062
+ successful_runs: local.successful_runs,
1063
+ browser_avoided_runs: local.browser_avoided_runs,
1064
+ total_time_saved_ms: local.total_time_saved_ms,
1065
+ total_time_saved_human: formatTotalDuration(local.total_time_saved_ms),
1066
+ total_tokens_saved: local.total_tokens_saved,
1067
+ total_cost_saved_usd: Number(savedUsd.toFixed(6)),
1068
+ avg_time_saved_pct: local.avg_time_saved_pct,
1069
+ avg_tokens_saved_pct: local.avg_tokens_saved_pct,
1070
+ by_source: local.by_source,
1071
+ first_entry_at: local.first_entry_at,
1072
+ last_entry_at: local.last_entry_at,
1073
+ log_path: getImpactLogPath(),
1074
+ },
1075
+ earnings: {
1076
+ total_earned_usd: earnedUsd,
1077
+ total_earned_uc: earnings?.ledger?.total_earned_uc ?? 0,
1078
+ transaction_count: earnings?.ledger?.transaction_count ?? 0,
1079
+ last_transaction_at: earnings?.ledger?.last_transaction_at ?? null,
1080
+ },
1081
+ spending: {
1082
+ total_spent_usd: spentUsd,
1083
+ total_spent_uc: spending?.ledger?.total_spent_uc ?? 0,
1084
+ transaction_count: spending?.ledger?.transaction_count ?? 0,
1085
+ last_transaction_at: spending?.ledger?.last_transaction_at ?? null,
1086
+ },
1087
+ net_usd: netUsd,
1088
+ ...(Object.keys(remoteErrors).length > 0 ? { remote_errors: remoteErrors } : {}),
1089
+ };
1090
+
1091
+ if (jsonOnly) {
1092
+ output(payload, pretty);
1093
+ return;
1094
+ }
1095
+
1096
+ // Human-readable view (to stderr like other info) + JSON to stdout for piping.
1097
+ const lines: string[] = [];
1098
+ lines.push("Unbrowse stats");
1099
+ lines.push(` agent_id: ${agentId ?? "(not registered — run `unbrowse setup`)"}`);
1100
+ if (profile?.name) lines.push(` name: ${profile.name}`);
1101
+ lines.push("");
1102
+ lines.push("Impact (local, this machine):");
1103
+ if (local.total_runs === 0) {
1104
+ lines.push(" No resolve/execute runs recorded yet.");
1105
+ lines.push(` Log file: ${getImpactLogPath()}`);
1106
+ } else {
1107
+ lines.push(` Runs: ${local.total_runs} (${local.successful_runs} successful, ${local.browser_avoided_runs} browser-avoided)`);
1108
+ if (local.total_time_saved_ms > 0) {
1109
+ lines.push(` Time saved: ${formatTotalDuration(local.total_time_saved_ms)} (avg ${local.avg_time_saved_pct}% faster)`);
1110
+ }
1111
+ if (local.total_tokens_saved > 0) {
1112
+ lines.push(` Tokens saved: ${local.total_tokens_saved.toLocaleString("en-US")} (avg ${local.avg_tokens_saved_pct}% less context)`);
1113
+ }
1114
+ if (savedUsd > 0) {
1115
+ lines.push(` Cost saved: ${formatCostUsd(local.total_cost_saved_uc)}`);
1116
+ }
1117
+ if (Object.keys(local.by_source).length > 0) {
1118
+ const topSources = Object.entries(local.by_source)
1119
+ .sort((a, b) => b[1] - a[1])
1120
+ .slice(0, 5)
1121
+ .map(([k, v]) => `${k}=${v}`)
1122
+ .join(", ");
1123
+ lines.push(` By source: ${topSources}`);
1124
+ }
1125
+ }
1126
+ lines.push("");
1127
+ lines.push("Money (backend ledger):");
1128
+ if (!agentId) {
1129
+ lines.push(" (not registered — earnings/spending unavailable)");
1130
+ } else if (remoteErrors.earnings || remoteErrors.spending) {
1131
+ if (remoteErrors.earnings) lines.push(` earnings: error — ${remoteErrors.earnings}`);
1132
+ if (remoteErrors.spending) lines.push(` spending: error — ${remoteErrors.spending}`);
1133
+ } else {
1134
+ lines.push(` Earned: $${earnedUsd.toFixed(4)} (${earnings?.ledger?.transaction_count ?? 0} payouts)`);
1135
+ lines.push(` Spent: $${spentUsd.toFixed(4)} (${spending?.ledger?.transaction_count ?? 0} payments)`);
1136
+ lines.push(` Net: ${netUsd >= 0 ? "+" : ""}$${netUsd.toFixed(4)}`);
1137
+ }
1138
+ lines.push("");
1139
+ info(lines.join("\n"));
1140
+ output(payload, pretty);
1141
+ }
1142
+
957
1143
  function printHelp(): void {
958
1144
  const r = CLI_REFERENCE;
959
1145
  const lines: string[] = ["unbrowse \u2014 shell-safe CLI for the local API", ""];
@@ -1463,6 +1649,7 @@ async function main(): Promise<void> {
1463
1649
  if (command === "restart") return cmdRestart(flags);
1464
1650
  if (command === "upgrade" || command === "update") return cmdUpgrade(flags);
1465
1651
  if (command === "connect-chrome") return cmdConnectChrome();
1652
+ if (command === "stats") return cmdStats(flags);
1466
1653
 
1467
1654
  // --- Shortcut resolution: unbrowse <site> [task] [flags] ---
1468
1655
  const KNOWN_COMMANDS = new Set([
@@ -1471,7 +1658,7 @@ async function main(): Promise<void> {
1471
1658
  "status", "stop", "restart", "upgrade", "update",
1472
1659
  "go", "submit", "snap", "click", "fill", "type", "press", "select", "scroll",
1473
1660
  "screenshot", "text", "markdown", "cookies", "eval", "back", "forward", "sync", "close",
1474
- "connect-chrome",
1661
+ "connect-chrome", "stats",
1475
1662
  ]);
1476
1663
 
1477
1664
  if (!KNOWN_COMMANDS.has(command)) {
@@ -1533,6 +1720,7 @@ async function main(): Promise<void> {
1533
1720
  case "sync": return cmdSync(flags);
1534
1721
  case "close": return cmdClose(flags);
1535
1722
  case "connect-chrome": return cmdConnectChrome();
1723
+ case "stats": return cmdStats(flags);
1536
1724
  default: info(`Unknown command: ${command}`); printHelp(); process.exit(1);
1537
1725
  }
1538
1726
  }
@@ -1,6 +1,6 @@
1
1
  import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "fs";
2
2
  import { join } from "path";
3
- import { homedir, hostname } from "os";
3
+ import { homedir, hostname, release as osRelease } from "os";
4
4
  import { randomBytes, createHash } from "crypto";
5
5
  import { createInterface } from "readline";
6
6
  import type {
@@ -16,6 +16,7 @@ import {
16
16
  CODE_HASH,
17
17
  DEFAULT_BACKEND_URL,
18
18
  GIT_SHA,
19
+ PACKAGE_VERSION,
19
20
  RELEASE_MANIFEST_BASE64,
20
21
  RELEASE_MANIFEST_SIGNATURE,
21
22
  TRACE_VERSION,
@@ -302,10 +303,21 @@ export async function recordInstallTelemetryEvent(
302
303
  skill_version: options?.skillVersion,
303
304
  status: options?.status ?? "installed",
304
305
  created_at: createdAt,
305
- properties: mergeTelemetryProperties(options?.properties, getTelemetryAttribution()),
306
+ properties: mergeTelemetryProperties({ ...getRuntimeContext(), ...options?.properties }, getTelemetryAttribution()),
306
307
  });
307
308
  }
308
309
 
310
+ function getRuntimeContext(): Record<string, unknown> {
311
+ return {
312
+ cli_version: PACKAGE_VERSION,
313
+ code_hash: CODE_HASH,
314
+ node_version: process.version,
315
+ platform: process.platform,
316
+ arch: process.arch,
317
+ os_release: osRelease(),
318
+ };
319
+ }
320
+
309
321
  export async function recordFunnelTelemetryEvent(
310
322
  name: string,
311
323
  options?: {
@@ -326,7 +338,7 @@ export async function recordFunnelTelemetryEvent(
326
338
  source: options?.source ?? "cli",
327
339
  host_type: options?.hostType ?? detectTelemetryHostType(),
328
340
  created_at: createdAt,
329
- properties: mergeTelemetryProperties(options?.properties, getTelemetryAttribution()),
341
+ properties: mergeTelemetryProperties({ ...getRuntimeContext(), ...options?.properties }, getTelemetryAttribution()),
330
342
  });
331
343
  }
332
344
 
@@ -497,7 +509,8 @@ async function apiRequest<T = unknown>(
497
509
  throw new Error("ToS update required. Restart unbrowse to accept new terms.");
498
510
  }
499
511
 
500
- // Handle x402 payment required — surface payment terms to the caller
512
+
513
+ // Handle x402 payment required — attempt lobster pay-and-retry before surfacing
501
514
  if (res.status === 402) {
502
515
  const paymentRequired = res.headers.get("PAYMENT-REQUIRED");
503
516
  const legacyPaymentTerms = res.headers.get("X-Payment-Required");
@@ -506,6 +519,29 @@ async function apiRequest<T = unknown>(
506
519
  : legacyPaymentTerms
507
520
  ? JSON.parse(legacyPaymentTerms)
508
521
  : (data as Record<string, unknown>).terms;
522
+
523
+ // Try lobster.cash automatic payment before throwing
524
+ try {
525
+ const { isLobsterAvailable, payAndRetry } = await import("../payments/lobster-pay.js");
526
+ if (isLobsterAvailable()) {
527
+ const fullUrl = `${API_URL}${path}`;
528
+ const paidResult = await payAndRetry<T>(fullUrl, {
529
+ body,
530
+ headers: {
531
+ "Content-Type": "application/json",
532
+ "Accept-Encoding": "gzip, deflate",
533
+ ...releaseAttestationHeaders,
534
+ ...(key ? { Authorization: `Bearer ${key}` } : {}),
535
+ },
536
+ });
537
+ if (paidResult) {
538
+ return { data: paidResult.data, headers: new Headers() };
539
+ }
540
+ }
541
+ } catch (payErr) {
542
+ console.warn(`[x402] lobster pay-and-retry failed: ${(payErr as Error).message}`);
543
+ }
544
+
509
545
  const err = new Error(`Payment required: ${(data as Record<string, unknown>).error ?? "This skill requires payment"}`);
510
546
  (err as Error & { x402: boolean; terms: unknown; status: number }).x402 = true;
511
547
  (err as Error & { terms: unknown }).terms = terms;
@@ -528,18 +564,10 @@ async function api<T = unknown>(method: string, path: string, body?: unknown, op
528
564
 
529
565
  // --- Install attribution ---
530
566
 
531
- function parseInstallAttribution(): { install_attribution?: Record<string, string>; landing_token?: string } {
532
- const result: { install_attribution?: Record<string, string>; landing_token?: string } = {};
533
- const b64 = process.env.UNBROWSE_ATTRIBUTION_B64;
534
- if (b64) {
535
- try {
536
- const decoded = JSON.parse(Buffer.from(b64, "base64").toString("utf8"));
537
- if (decoded && typeof decoded === "object") result.install_attribution = decoded;
538
- } catch { /* malformed — ignore */ }
539
- }
567
+ function parseInstallAttribution(): { landing_token?: string } {
540
568
  const token = process.env.UNBROWSE_LANDING_TOKEN;
541
- if (token && token.length < 2048) result.landing_token = token;
542
- return result;
569
+ if (token && token.length < 2048) return { landing_token: token };
570
+ return {};
543
571
  }
544
572
 
545
573
  // --- ToS acceptance ---
@@ -19,7 +19,6 @@ import { nanoid } from "nanoid";
19
19
  import { getRegistrableDomain } from "../domain.js";
20
20
  import { extractFromDOM, extractFromDOMWithHint } from "../extraction/index.js";
21
21
  import { buildSkillOperationGraph, getEndpointDescriptionMetadata, inferEndpointSemantic, resolveEndpointSemantic } from "../graph/index.js";
22
- import { augmentEndpointsWithAgent } from "../graph/agent-augment.js";
23
22
  import { log } from "../logger.js";
24
23
  import { TRACE_VERSION } from "../version.js";
25
24
  import { buildQueryBindingMap, extractTemplateQueryBindings, mergeContextTemplateParams } from "../template-params.js";
@@ -190,11 +189,10 @@ function normalizeEndpointForManifest(endpoint: EndpointDescriptor): EndpointDes
190
189
 
191
190
  async function prepareLearnedEndpoints(
192
191
  endpoints: EndpointDescriptor[],
193
- intent: string,
194
- domain: string,
192
+ _intent: string,
193
+ _domain: string,
195
194
  ): Promise<EndpointDescriptor[]> {
196
- const normalized = endpoints.map(normalizeEndpointForManifest);
197
- return augmentEndpointsWithAgent(normalized, { intent, domain });
195
+ return endpoints.map(normalizeEndpointForManifest);
198
196
  }
199
197
 
200
198
  function intentWantsStructuredRecords(intent?: string): boolean {
@@ -1882,28 +1880,40 @@ export async function executeEndpoint(
1882
1880
  wallet_configured: !!wallet.wallet_address,
1883
1881
  });
1884
1882
  if (gate.status === "payment_required" || gate.status === "wallet_not_configured" || gate.status === "insufficient_balance") {
1885
- const trace: ExecutionTrace = stampTrace({
1886
- trace_id: nanoid(),
1887
- skill_id: skill.skill_id,
1888
- endpoint_id: endpoint.endpoint_id,
1889
- started_at: new Date().toISOString(),
1890
- completed_at: new Date().toISOString(),
1891
- success: false,
1892
- status_code: 402,
1893
- error: "payment_required",
1894
- });
1895
- return {
1896
- trace,
1897
- result: {
1883
+ // If lobster wallet is available, let execution proceed —
1884
+ // the client-level apiRequest will handle 402 pay-and-retry automatically.
1885
+ let lobsterAvailable = false;
1886
+ try {
1887
+ const { isLobsterAvailable } = await import("../payments/lobster-pay.js");
1888
+ lobsterAvailable = isLobsterAvailable();
1889
+ } catch {}
1890
+
1891
+ if (lobsterAvailable && gate.status === "payment_required") {
1892
+ console.log(`[payment] ${skill.skill_id}: lobster available — proceeding with auto-pay`);
1893
+ } else {
1894
+ const trace: ExecutionTrace = stampTrace({
1895
+ trace_id: nanoid(),
1896
+ skill_id: skill.skill_id,
1897
+ endpoint_id: endpoint.endpoint_id,
1898
+ started_at: new Date().toISOString(),
1899
+ completed_at: new Date().toISOString(),
1900
+ success: false,
1901
+ status_code: 402,
1898
1902
  error: "payment_required",
1899
- price_usd: gate.requirement?.amount,
1900
- payment_status: gate.status,
1901
- message: gate.message,
1902
- wallet_provider: wallet.wallet_provider ?? "lobster.cash",
1903
- wallet_address: wallet.wallet_address,
1904
- indexing_fallback_available: true,
1905
- },
1906
- };
1903
+ });
1904
+ return {
1905
+ trace,
1906
+ result: {
1907
+ error: "payment_required",
1908
+ price_usd: gate.requirement?.amount,
1909
+ payment_status: gate.status,
1910
+ message: gate.message,
1911
+ wallet_provider: wallet.wallet_provider ?? "lobster.cash",
1912
+ wallet_address: wallet.wallet_address,
1913
+ indexing_fallback_available: true,
1914
+ },
1915
+ };
1916
+ }
1907
1917
  }
1908
1918
  }
1909
1919
 
@@ -2005,6 +2015,18 @@ export async function executeEndpoint(
2005
2015
  const epDomain = (() => { try { return new URL(endpoint.url_template).hostname; } catch { return skill.domain; } })();
2006
2016
  await reloadExecutionAuthState(skill, epDomain, authHeaders, cookies);
2007
2017
 
2018
+ // If endpoint has auth_tokens bindings, always resolve fresh tokens.
2019
+ // Vault headers may be stale — the DAG knows how to get fresh ones.
2020
+ log("exec", `auth_tokens check: ${endpoint.auth_tokens?.length ?? 0} bindings on ${endpoint.endpoint_id}`);
2021
+ if (endpoint.auth_tokens?.length) {
2022
+ try {
2023
+ const { resolveAuthTokens } = await import("./token-resolver.js");
2024
+ const resolved = await resolveAuthTokens(endpoint, cookies, authHeaders);
2025
+ log("exec", `token resolver returned ${Object.keys(resolved).length} headers: ${Object.keys(resolved).join(",") || "none"}`);
2026
+ Object.assign(authHeaders, resolved);
2027
+ } catch (e) { log("exec", `token resolver failed: ${e}`); }
2028
+ }
2029
+
2008
2030
  log("exec", `endpoint ${endpoint.endpoint_id}: cookies=${cookies.length} authHeaders=${Object.keys(authHeaders).length} hasAuth=${cookies.length > 0 || Object.keys(authHeaders).length > 0}`);
2009
2031
 
2010
2032
  // BUG-006: Merge path_params defaults — user params override captured defaults
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Token resolver — resolves auth_tokens bindings at execute time.
3
+ *
4
+ * Given an endpoint with auth_tokens, loads the trigger page via Kuri,
5
+ * extracts fresh token values from HTML/JS sources, and returns headers
6
+ * ready to inject into the outgoing request.
7
+ *
8
+ * This closes the gap for sites that rotate CSRF tokens per page-load,
9
+ * keep bearer tokens in JS bundles, or hydrate tokens into inline scripts.
10
+ */
11
+
12
+ import type { EndpointDescriptor, AuthTokenBinding } from "../types/index.js";
13
+ import { extractTokenFromHtml, extractTokenFromBundle } from "../reverse-engineer/token-sources.js";
14
+ import * as kuri from "../kuri/client.js";
15
+
16
+ const RESOLVE_TIMEOUT_MS = 12000;
17
+
18
+ /**
19
+ * Resolve auth_tokens bindings by loading the trigger page and scraping
20
+ * token values from their known source locations.
21
+ *
22
+ * Returns a map of header-name → resolved-value for all successfully
23
+ * resolved header-type bindings. Returns empty map if no bindings or
24
+ * all fail.
25
+ */
26
+ export async function resolveAuthTokens(
27
+ endpoint: EndpointDescriptor,
28
+ cookies: Array<{ name: string; value: string; domain: string }>,
29
+ existingAuthHeaders: Record<string, string>,
30
+ ): Promise<Record<string, string>> {
31
+ const bindings = endpoint.auth_tokens;
32
+ if (!bindings || bindings.length === 0) return {};
33
+
34
+ const triggerUrl = endpoint.trigger_url;
35
+ if (!triggerUrl) return {};
36
+
37
+ // Resolve ALL header bindings — DAG sources are authoritative over vault cache
38
+ const headerBindings = bindings.filter((b) => b.param_location === "header");
39
+ if (headerBindings.length === 0) return {};
40
+
41
+ const resolved: Record<string, string> = {};
42
+
43
+ try {
44
+ // Open a tab, inject cookies, navigate to trigger page
45
+ const tabId = await openResolverTab(triggerUrl, cookies);
46
+ if (!tabId) return {};
47
+
48
+ try {
49
+ await waitForLoad(tabId);
50
+
51
+ const html = await kuri.getPageHtml(tabId).catch(() => "");
52
+ if (typeof html !== "string" || !html.startsWith("<")) {
53
+ return {};
54
+ }
55
+
56
+ for (const binding of headerBindings) {
57
+ const value = await resolveBinding(binding, html, cookies);
58
+ if (value) {
59
+ resolved[binding.param_name] = binding.param_name.toLowerCase() === "authorization"
60
+ ? (value.startsWith("Bearer ") ? value : `Bearer ${value}`)
61
+ : value;
62
+ }
63
+ }
64
+ } finally {
65
+ await kuri.closeTab(tabId).catch(() => {});
66
+ }
67
+ } catch {
68
+ // Tab open/nav failed — return whatever we resolved so far
69
+ }
70
+
71
+ return resolved;
72
+ }
73
+
74
+ async function resolveBinding(
75
+ binding: AuthTokenBinding,
76
+ html: string,
77
+ cookies: Array<{ name: string; value: string; domain: string }>,
78
+ ): Promise<string | undefined> {
79
+ for (const source of binding.sources) {
80
+ let value: string | undefined;
81
+
82
+ if (source.kind === "cookie" && source.cookie_names?.length) {
83
+ // Resolve from cookies — CSRF tokens typically live here
84
+ for (const name of source.cookie_names) {
85
+ const cookie = cookies.find((c) => c.name === name);
86
+ if (cookie?.value) { value = cookie.value; break; }
87
+ }
88
+ } else if (source.kind === "html-meta" || source.kind === "html-inline-script") {
89
+ value = extractTokenFromHtml(source, html);
90
+ } else if (source.kind === "js-bundle" && source.bundle_url_pattern) {
91
+ try {
92
+ const resp = await fetch(source.bundle_url_pattern);
93
+ if (resp.ok) {
94
+ const body = await resp.text();
95
+ value = extractTokenFromBundle(source, body);
96
+ }
97
+ } catch { /* fetch failed — try next source */ }
98
+ }
99
+
100
+ if (value && value.length >= 8) return value;
101
+ }
102
+ return undefined;
103
+ }
104
+ async function openResolverTab(
105
+ url: string,
106
+ cookies: Array<{ name: string; value: string; domain: string }>,
107
+ ): Promise<string | undefined> {
108
+ try {
109
+ const tab = await kuri.newTab(url);
110
+ const tabId = typeof tab === "string" ? tab : (tab as { tab_id?: string })?.tab_id;
111
+ if (!tabId) return undefined;
112
+
113
+ if (cookies.length > 0) {
114
+ for (const c of cookies) {
115
+ await kuri.setCookie(tabId, c.name, c.value, c.domain).catch(() => {});
116
+ }
117
+ await kuri.navigate(tabId, url).catch(() => {});
118
+ }
119
+
120
+ return tabId;
121
+ } catch {
122
+ return undefined;
123
+ }
124
+ }
125
+
126
+ async function waitForLoad(tabId: string): Promise<void> {
127
+ const start = Date.now();
128
+ while (Date.now() - start < RESOLVE_TIMEOUT_MS) {
129
+ try {
130
+ const state = await kuri.evaluate(tabId, "document.readyState");
131
+ if (state === "complete" || state === "interactive") return;
132
+ } catch { /* page not ready */ }
133
+ await new Promise((r) => setTimeout(r, 500));
134
+ }
135
+ }
@@ -373,15 +373,20 @@ export function getEndpointDescriptionMetadata(endpoint: Pick<EndpointDescriptor
373
373
  warning?: string;
374
374
  } {
375
375
  const input = classifyDescriptionInput(endpoint.description);
376
- const display = (input.source === "agent"
377
- ? endpoint.description ?? ""
376
+ // Trust the LLM augmenter's semantic layer when it has run.
377
+ const agentAugmented = endpoint.semantic?.description_source === "agent";
378
+ // Schema-grounded auto descriptions (with real response fields) don't need
379
+ // external LLM review — the calling agent IS the LLM that reviews them.
380
+ const schemaGrounded = !!(endpoint.semantic?.example_fields?.length || endpoint.semantic?.response_summary);
381
+ const display = (input.source === "agent" || agentAugmented
382
+ ? endpoint.semantic?.description_out ?? endpoint.description ?? ""
378
383
  : endpoint.semantic?.description_out ?? endpoint.description ?? "").trim();
379
- const source = display ? (input.source === "agent" ? "agent" : "auto") : "missing";
384
+ const source = display ? (input.source === "agent" || agentAugmented ? "agent" : "auto") : "missing";
380
385
  return {
381
386
  display,
382
387
  source,
383
- needs_review: source !== "agent",
384
- ...(source !== "agent"
388
+ needs_review: source === "missing" || (source === "auto" && !schemaGrounded),
389
+ ...(source !== "agent" && !schemaGrounded
385
390
  ? { warning: input.warning ?? "Auto-generated description. Review before trusting or publishing." }
386
391
  : {}),
387
392
  };
@@ -931,9 +936,12 @@ export function inferEndpointSemantic(
931
936
  confidence: fields.length > 0 ? 0.8 : 0.4,
932
937
  observed_at: opts?.observedAt,
933
938
  sample_request_url: opts?.sampleRequestUrl,
939
+ auth_required: !!(
940
+ endpoint.auth_tokens?.length ||
941
+ Object.keys(endpoint.headers_template ?? {}).some((h) => /auth|csrf|token|bearer/i.test(h))
942
+ ),
934
943
  };
935
944
  }
936
-
937
945
  export function resolveEndpointSemantic(
938
946
  endpoint: EndpointDescriptor,
939
947
  opts?: {