unbrowse 3.0.4 → 3.1.0-experiments.5e7a7bb

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.
@@ -8,6 +8,8 @@ import { fileURLToPath } from "node:url";
8
8
  import { ensureLocalServer } from "./runtime/local-server.js";
9
9
  import { listWorkflowPublishArtifacts, readWorkflowPublishArtifact } from "./workflow/publish.js";
10
10
  import type { WorkflowPublishArtifact, WorkflowPublishRecipe } from "./types/index.js";
11
+ import { appendImpact, getImpactLogPath, impactFromResult, readImpactSummary } from "./impact-log.js";
12
+ import { getAgentId, getCreatorEarnings, getMyProfile, getTransactionHistory } from "./client/index.js";
11
13
 
12
14
  loadEnv({ quiet: true });
13
15
  loadEnv({ path: ".env.runtime", quiet: true });
@@ -824,6 +826,61 @@ async function executeResolvedEndpoint(result: Record<string, unknown>, args: Re
824
826
  }) as Promise<Record<string, unknown>>;
825
827
  }
826
828
 
829
+ // ---------------------------------------------------------------------------
830
+ // Impact visibility — every tool result includes a "saved X" line so agents
831
+ // see concrete value (time, tokens, cost, browser-avoided) on every call.
832
+ // ---------------------------------------------------------------------------
833
+
834
+ function formatImpactUsd(uc: number): string {
835
+ const usd = uc / 1_000_000;
836
+ if (usd >= 1) return `$${usd.toFixed(2)}`;
837
+ if (usd >= 0.01) return `$${usd.toFixed(3)}`;
838
+ return `$${usd.toFixed(4)}`;
839
+ }
840
+
841
+ function formatImpactDuration(ms: number): string {
842
+ if (ms >= 3_600_000) return `${(ms / 3_600_000).toFixed(1)}h`;
843
+ if (ms >= 60_000) return `${(ms / 60_000).toFixed(1)}m`;
844
+ if (ms >= 10_000) return `${Math.round(ms / 1000)}s`;
845
+ if (ms >= 1000) return `${(ms / 1000).toFixed(1)}s`;
846
+ return `${ms}ms`;
847
+ }
848
+
849
+ /** Build a one-line impact summary, or "" if nothing meaningful happened. */
850
+ function summarizeImpact(result: unknown): string {
851
+ if (!result || typeof result !== "object") return "";
852
+ const impact = (result as Record<string, unknown>).impact as Record<string, unknown> | undefined;
853
+ if (!impact) return "";
854
+ const timeMs = typeof impact.time_saved_ms === "number" ? impact.time_saved_ms : 0;
855
+ const tokens = typeof impact.tokens_saved === "number" ? impact.tokens_saved : 0;
856
+ const timePct = typeof impact.time_saved_pct === "number" ? impact.time_saved_pct : 0;
857
+ const tokensPct = typeof impact.tokens_saved_pct === "number" ? impact.tokens_saved_pct : 0;
858
+ const costUc = typeof impact.cost_saved_uc === "number" ? impact.cost_saved_uc : 0;
859
+ const browserAvoided = impact.browser_avoided === true;
860
+ if (timeMs <= 0 && tokens <= 0 && costUc <= 0 && !browserAvoided) return "";
861
+ const parts: string[] = [];
862
+ if (timeMs > 0) parts.push(`${formatImpactDuration(timeMs)} saved (${timePct}% faster)`);
863
+ if (tokens > 0) parts.push(`${tokens.toLocaleString("en-US")} tokens saved (${tokensPct}% less context)`);
864
+ if (costUc > 0) parts.push(`${formatImpactUsd(costUc)} saved`);
865
+ if (browserAvoided) parts.push("browser avoided");
866
+ return `Impact: ${parts.join(" • ")}`;
867
+ }
868
+
869
+ /** Append impact to the local log (fire-and-forget). Called from resolve/execute handlers. */
870
+ function recordImpactForTool(
871
+ command: "resolve" | "execute",
872
+ result: unknown,
873
+ args: Record<string, unknown>,
874
+ ): void {
875
+ const entry = impactFromResult(command, result, {
876
+ intent: typeof args.intent === "string" ? args.intent : undefined,
877
+ domain: typeof args.domain === "string" ? args.domain : undefined,
878
+ skill_id: typeof args.skill === "string" ? args.skill : undefined,
879
+ endpoint_id: typeof args.endpoint === "string" ? args.endpoint : undefined,
880
+ });
881
+ if (entry) appendImpact(entry);
882
+ }
883
+
827
884
  const tools: ToolDefinition[] = [
828
885
  {
829
886
  name: "unbrowse_health",
@@ -903,7 +960,11 @@ const tools: ToolDefinition[] = [
903
960
 
904
961
  result = addResolveMissGuidance(result, args);
905
962
  const nestedError = resolveNestedError(result);
906
- return nestedError ? errorResult(nestedError, result) : successResult(maybePostProcessResult(result, args), "Resolve result.");
963
+ recordImpactForTool("resolve", result, args);
964
+ if (nestedError) return errorResult(nestedError, result);
965
+ const processed = maybePostProcessResult(result, args);
966
+ const impactLine = summarizeImpact(result);
967
+ return successResult(processed, impactLine ? `Resolve result. ${impactLine}` : "Resolve result.");
907
968
  },
908
969
  },
909
970
  {
@@ -946,10 +1007,113 @@ const tools: ToolDefinition[] = [
946
1007
 
947
1008
  const result = await api("POST", `/v1/skills/${args.skill}/execute`, body) as Record<string, unknown>;
948
1009
  const nestedError = resolveNestedError(result);
1010
+ recordImpactForTool("execute", result, args);
949
1011
  if (nestedError) return errorResult(nestedError, result);
950
1012
  const processed = maybePostProcessResult(result, args);
951
1013
  const withHints = addExecuteNextStepHints(isPlainObject(processed) ? processed as Record<string, unknown> : { result: processed }, args);
952
- return successResult(withHints, "Execution result. See _workflow_hints for required next steps.");
1014
+ const impactLine = summarizeImpact(result);
1015
+ return successResult(
1016
+ withHints,
1017
+ impactLine
1018
+ ? `Execution result. ${impactLine}. See _workflow_hints for required next steps.`
1019
+ : "Execution result. See _workflow_hints for required next steps.",
1020
+ );
1021
+ },
1022
+ },
1023
+ {
1024
+ name: "unbrowse_stats",
1025
+ description: "Show lifetime impact for this agent: total time saved, tokens saved, cost saved, browser calls avoided, and marketplace earnings/spending. Read-only — safe to call anytime. Use this to show the user the concrete value Unbrowse has delivered.",
1026
+ inputSchema: {
1027
+ type: "object",
1028
+ properties: {
1029
+ include_recent: { type: "boolean", description: "Include recent earnings/spending transactions. Default false." },
1030
+ },
1031
+ additionalProperties: false,
1032
+ },
1033
+ annotations: { readOnlyHint: true },
1034
+ handler: async (args) => {
1035
+ await ensureServerReady();
1036
+ const local = readImpactSummary();
1037
+ const agentId = getAgentId();
1038
+
1039
+ type EarningsLedger = { total_earned_uc: number; total_earned_usd: number; transaction_count: number; last_transaction_at?: string } | null;
1040
+ type SpendingLedger = { total_spent_uc: number; total_spent_usd: number; transaction_count: number; last_transaction_at?: string } | null;
1041
+
1042
+ let profile: Awaited<ReturnType<typeof getMyProfile>> | null = null;
1043
+ let earnings: { ledger: EarningsLedger; transactions: unknown[] } | null = null;
1044
+ let spending: { ledger: SpendingLedger; transactions: unknown[] } | null = null;
1045
+ const remoteErrors: Record<string, string> = {};
1046
+
1047
+ if (agentId) {
1048
+ const results = await Promise.allSettled([
1049
+ getMyProfile(),
1050
+ getCreatorEarnings(agentId),
1051
+ getTransactionHistory(agentId),
1052
+ ]);
1053
+ if (results[0].status === "fulfilled") profile = results[0].value;
1054
+ else remoteErrors.profile = (results[0].reason as Error)?.message ?? String(results[0].reason);
1055
+ if (results[1].status === "fulfilled") earnings = results[1].value as { ledger: EarningsLedger; transactions: unknown[] };
1056
+ else remoteErrors.earnings = (results[1].reason as Error)?.message ?? String(results[1].reason);
1057
+ if (results[2].status === "fulfilled") spending = results[2].value as { ledger: SpendingLedger; transactions: unknown[] };
1058
+ else remoteErrors.spending = (results[2].reason as Error)?.message ?? String(results[2].reason);
1059
+ } else {
1060
+ remoteErrors.profile = "No agent_id in local config. Run `unbrowse setup` to register.";
1061
+ }
1062
+
1063
+ const earnedUsd = earnings?.ledger?.total_earned_usd ?? 0;
1064
+ const spentUsd = spending?.ledger?.total_spent_usd ?? 0;
1065
+ const savedUsd = local.total_cost_saved_uc / 1_000_000;
1066
+
1067
+ const includeRecent = args.include_recent === true;
1068
+ const payload = {
1069
+ agent_id: agentId,
1070
+ profile,
1071
+ impact: {
1072
+ total_runs: local.total_runs,
1073
+ successful_runs: local.successful_runs,
1074
+ browser_avoided_runs: local.browser_avoided_runs,
1075
+ total_time_saved_ms: local.total_time_saved_ms,
1076
+ total_time_saved_human: formatImpactDuration(local.total_time_saved_ms),
1077
+ total_tokens_saved: local.total_tokens_saved,
1078
+ total_cost_saved_usd: Number(savedUsd.toFixed(6)),
1079
+ avg_time_saved_pct: local.avg_time_saved_pct,
1080
+ avg_tokens_saved_pct: local.avg_tokens_saved_pct,
1081
+ by_source: local.by_source,
1082
+ first_entry_at: local.first_entry_at,
1083
+ last_entry_at: local.last_entry_at,
1084
+ log_path: getImpactLogPath(),
1085
+ },
1086
+ earnings: {
1087
+ total_earned_usd: earnedUsd,
1088
+ total_earned_uc: earnings?.ledger?.total_earned_uc ?? 0,
1089
+ transaction_count: earnings?.ledger?.transaction_count ?? 0,
1090
+ last_transaction_at: earnings?.ledger?.last_transaction_at ?? null,
1091
+ ...(includeRecent && earnings?.transactions ? { recent: earnings.transactions.slice(0, 10) } : {}),
1092
+ },
1093
+ spending: {
1094
+ total_spent_usd: spentUsd,
1095
+ total_spent_uc: spending?.ledger?.total_spent_uc ?? 0,
1096
+ transaction_count: spending?.ledger?.transaction_count ?? 0,
1097
+ last_transaction_at: spending?.ledger?.last_transaction_at ?? null,
1098
+ ...(includeRecent && spending?.transactions ? { recent: spending.transactions.slice(0, 10) } : {}),
1099
+ },
1100
+ net_usd: earnedUsd - spentUsd,
1101
+ ...(Object.keys(remoteErrors).length > 0 ? { remote_errors: remoteErrors } : {}),
1102
+ };
1103
+
1104
+ const headline: string[] = [];
1105
+ if (local.total_runs > 0) {
1106
+ const bits: string[] = [];
1107
+ if (local.total_time_saved_ms > 0) bits.push(`${formatImpactDuration(local.total_time_saved_ms)} saved`);
1108
+ if (local.total_tokens_saved > 0) bits.push(`${local.total_tokens_saved.toLocaleString("en-US")} tokens saved`);
1109
+ if (savedUsd > 0) bits.push(`${formatImpactUsd(local.total_cost_saved_uc)} saved`);
1110
+ if (local.browser_avoided_runs > 0) bits.push(`${local.browser_avoided_runs} browser calls avoided`);
1111
+ if (bits.length > 0) headline.push(`Lifetime impact (${local.total_runs} runs): ${bits.join(" • ")}`);
1112
+ }
1113
+ if (agentId && !remoteErrors.earnings && !remoteErrors.spending) {
1114
+ headline.push(`Marketplace: +$${earnedUsd.toFixed(4)} earned, -$${spentUsd.toFixed(4)} spent, net ${earnedUsd - spentUsd >= 0 ? "+" : ""}$${(earnedUsd - spentUsd).toFixed(4)}`);
1115
+ }
1116
+ return successResult(payload, headline.length > 0 ? headline.join(" • ") : "Unbrowse stats (no runs recorded yet).");
953
1117
  },
954
1118
  },
955
1119
  {
@@ -18,6 +18,7 @@ import { buildSkillOperationGraph } from "../graph/index.js";
18
18
  import { augmentEndpointsWithAgent } from "../graph/agent-augment.js";
19
19
  import { findExistingSkillForDomain, cachePublishedSkill } from "../client/index.js";
20
20
  import { storeCredential } from "../vault/index.js";
21
+ import { getRegistrableDomain } from "../domain.js";
21
22
  import { generateLocalDescription } from "./index.js";
22
23
  import { nanoid } from "nanoid";
23
24
  import type { EndpointDescriptor, SkillManifest } from "../types/index.js";
@@ -311,7 +312,7 @@ export async function agenticBrowserResolve(
311
312
  // Auth extraction + vault storage
312
313
  const capturedAuthHeaders = extractAuthHeaders(allRequests);
313
314
  if (Object.keys(capturedAuthHeaders).length > 0) {
314
- await storeCredential(`${domain}-session`, JSON.stringify({ headers: capturedAuthHeaders })).catch(() => {});
315
+ await storeCredential(`${getRegistrableDomain(domain)}-session`, JSON.stringify({ headers: capturedAuthHeaders })).catch(() => {});
315
316
  }
316
317
 
317
318
  // Merge with existing skill
@@ -3015,7 +3015,11 @@ export async function resolveAndExecute(
3015
3015
  console.log(`[prefetch] error: ${(prefetchErr as Error).message}`);
3016
3016
  }
3017
3017
  // --- Payment gate: only for marketplace-sourced paid skills ---
3018
- if (source === "marketplace" && skill.base_price_usd && skill.base_price_usd > 0) {
3018
+ const dynamicPrice = source === "marketplace"
3019
+ ? (skill.base_price_usd ?? await (await import("../payments/index.js")).fetchDynamicPrice(skill.skill_id))
3020
+ : null;
3021
+ const effectivePrice = typeof dynamicPrice === "string" ? parseFloat(dynamicPrice) : (dynamicPrice ?? 0);
3022
+ if (source === "marketplace" && effectivePrice > 0) {
3019
3023
  try {
3020
3024
  const walletCheck = checkWalletConfigured();
3021
3025
  const wallet = getLocalWalletContext();
@@ -3023,7 +3027,7 @@ export async function resolveAndExecute(
3023
3027
  skill.skill_id,
3024
3028
  candidate.endpoint.endpoint_id,
3025
3029
  {
3026
- price_usd: String(skill.base_price_usd),
3030
+ price_usd: String(effectivePrice),
3027
3031
  wallet_configured: walletCheck.configured,
3028
3032
  },
3029
3033
  );
@@ -3038,7 +3042,7 @@ export async function resolveAndExecute(
3038
3042
  return {
3039
3043
  result: {
3040
3044
  error: "payment_required",
3041
- price_usd: skill.base_price_usd,
3045
+ price_usd: effectivePrice,
3042
3046
  payment_status: paymentResult.status,
3043
3047
  message: paymentResult.message,
3044
3048
  next_step: paymentResult.next_step,
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Lobster.cash x402 payment bridge.
3
+ *
4
+ * Handles the pay-and-retry cycle:
5
+ * 1. Receives x402 payment terms from a 402 response
6
+ * 2. Calls `lobstercash x402 fetch <url>` to pay + retry
7
+ * 3. Returns the paid response body
8
+ *
9
+ * Delegation boundary:
10
+ * - Unbrowse owns: detecting 402, passing the URL, using the result
11
+ * - Lobster owns: wallet signing, transaction broadcast, proof construction
12
+ */
13
+
14
+ import { execFile, execFileSync } from "node:child_process";
15
+ import { existsSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ const LOBSTER_PAY_TIMEOUT_MS = 30_000;
20
+
21
+ /**
22
+ * Resolve the lobster CLI command. Prefers the direct binary if
23
+ * installed globally, otherwise falls back to npx.
24
+ */
25
+ function getLobsterCommand(): { cmd: string; prefix: string[] } | null {
26
+ // 1. Direct binary in PATH
27
+ try {
28
+ execFileSync("lobstercash", ["--version"], { stdio: "ignore", timeout: 3_000 });
29
+ return { cmd: "lobstercash", prefix: [] };
30
+ } catch (_e) { /* not in PATH */ }
31
+
32
+ // 2. Check npm global bin (often not in agent PATH)
33
+ try {
34
+ const npmPrefix = execFileSync("npm", ["config", "get", "prefix"], { encoding: "utf8", timeout: 5_000 }).trim();
35
+ const lobsterPath = join(npmPrefix, "bin", "lobstercash");
36
+ if (existsSync(lobsterPath)) {
37
+ execFileSync(lobsterPath, ["--version"], { stdio: "ignore", timeout: 3_000 });
38
+ return { cmd: lobsterPath, prefix: [] };
39
+ }
40
+ } catch (_e) { /* npm not available */ }
41
+
42
+ return null;
43
+ }
44
+
45
+ let cachedCommand: { cmd: string; prefix: string[] } | null | undefined = undefined;
46
+ function lobsterCmd(): { cmd: string; prefix: string[] } | null {
47
+ if (cachedCommand === undefined) cachedCommand = getLobsterCommand();
48
+ return cachedCommand;
49
+ }
50
+
51
+ export interface LobsterPayResult {
52
+ success: boolean;
53
+ body: string;
54
+ statusCode?: number;
55
+ error?: string;
56
+ }
57
+
58
+ /**
59
+ * Check if the lobster CLI is available and wallet is configured.
60
+ */
61
+ export function isLobsterAvailable(): boolean {
62
+ const agentsPath = join(process.env.HOME || homedir(), ".lobster", "agents.json");
63
+ return existsSync(agentsPath);
64
+ }
65
+
66
+ /**
67
+ * Pay for an x402-gated URL via lobster.cash and return the response.
68
+ *
69
+ * Shells out to `lobstercash x402 fetch <url>` which handles:
70
+ * - Reading 402 + payment terms
71
+ * - Signing + broadcasting the USDC transfer
72
+ * - Retrying with PAYMENT-SIGNATURE header
73
+ * - Returning the paid response
74
+ */
75
+ export function lobsterX402Fetch(
76
+ url: string,
77
+ options?: {
78
+ jsonBody?: string;
79
+ headers?: Record<string, string>;
80
+ timeoutMs?: number;
81
+ },
82
+ ): Promise<LobsterPayResult> {
83
+ return new Promise((resolve) => {
84
+ const resolved = lobsterCmd();
85
+ if (!resolved) {
86
+ resolve({ success: false, body: "", error: "lobstercash CLI not in PATH" });
87
+ return;
88
+ }
89
+ const { cmd, prefix } = resolved;
90
+ const args = [...prefix, "x402", "fetch", url, "--debug"];
91
+
92
+ if (options?.jsonBody) {
93
+ args.push("--json", options.jsonBody);
94
+ }
95
+
96
+ if (options?.headers) {
97
+ for (const [key, value] of Object.entries(options.headers)) {
98
+ args.push("--header", `${key}:${value}`);
99
+ }
100
+ }
101
+
102
+ const timeout = options?.timeoutMs ?? LOBSTER_PAY_TIMEOUT_MS;
103
+ args.push("--timeout", String(timeout));
104
+
105
+ execFile(cmd, args, { timeout: timeout + 5_000, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
106
+ if (err) {
107
+ const msg = stderr?.trim() || err.message;
108
+ console.warn(`[lobster-pay] x402 fetch failed: ${msg}`);
109
+ resolve({ success: false, body: "", error: msg });
110
+ return;
111
+ }
112
+
113
+ if (stderr) {
114
+ for (const line of stderr.split("\n").filter(Boolean)) {
115
+ console.log(`[lobster-pay] ${line}`);
116
+ }
117
+ }
118
+
119
+ // Parse status from stdout header line: "Status: 200"
120
+ const statusMatch = stdout.match(/^Status:\s*(\d+)/m);
121
+ const statusCode = statusMatch ? parseInt(statusMatch[1], 10) : undefined;
122
+
123
+ if (statusCode && statusCode >= 400) {
124
+ resolve({ success: false, body: stdout, statusCode, error: `HTTP ${statusCode}` });
125
+ return;
126
+ }
127
+
128
+ resolve({ success: true, body: stdout, statusCode });
129
+ });
130
+ });
131
+ }
132
+
133
+ /**
134
+ * Pay for an x402-gated API request and return the parsed JSON response.
135
+ *
136
+ * This is the high-level entry point for the pay-and-retry loop.
137
+ * Returns null if payment fails or lobster is unavailable.
138
+ */
139
+ export async function payAndRetry<T = unknown>(
140
+ fullUrl: string,
141
+ options?: {
142
+ body?: unknown;
143
+ headers?: Record<string, string>;
144
+ },
145
+ ): Promise<{ data: T; paid: true } | null> {
146
+ if (!isLobsterAvailable()) {
147
+ console.log("[lobster-pay] lobster.cash not configured — skipping payment");
148
+ return null;
149
+ }
150
+
151
+ console.log(`[lobster-pay] attempting x402 payment for ${fullUrl}`);
152
+
153
+ const result = await lobsterX402Fetch(fullUrl, {
154
+ jsonBody: options?.body ? JSON.stringify(options.body) : undefined,
155
+ headers: options?.headers,
156
+ });
157
+
158
+ if (!result.success) {
159
+ console.warn(`[lobster-pay] payment failed: ${result.error}`);
160
+ return null;
161
+ }
162
+ try {
163
+ // lobstercash x402 fetch outputs header lines before the JSON body:
164
+ // x402 FETCH <url>
165
+ // Status: 200
166
+ // Content-Type: application/json
167
+ // <blank line>
168
+ // {"actual":"json",...}
169
+ // Extract the JSON portion by finding the first '{' or '['
170
+ const raw = result.body;
171
+ const jsonStart = Math.min(
172
+ ...[raw.indexOf("{"), raw.indexOf("[")].filter((i) => i >= 0),
173
+ );
174
+ const jsonStr = jsonStart >= 0 ? raw.slice(jsonStart) : raw;
175
+ const data = JSON.parse(jsonStr) as T;
176
+ console.log("[lobster-pay] payment successful — got paid response");
177
+ return { data, paid: true };
178
+ } catch (_e) {
179
+ console.warn("[lobster-pay] paid response was not valid JSON");
180
+ return null;
181
+ }
182
+ }