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.
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Local per-agent impact log.
3
+ *
4
+ * Every resolve/execute appends one line here with the savings it delivered
5
+ * (time, tokens, dollars, browser avoided). `unbrowse stats` and the
6
+ * unbrowse_stats MCP tool read this file to show lifetime impact without
7
+ * needing a new backend endpoint.
8
+ *
9
+ * Format: JSONL at ~/.unbrowse/impact-log.jsonl (or $UNBROWSE_CONFIG_DIR).
10
+ * Rotates when the file exceeds ~5MB.
11
+ */
12
+
13
+ import { existsSync, mkdirSync, appendFileSync, statSync, readFileSync, renameSync, unlinkSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { dirname, join } from "node:path";
16
+
17
+ const MAX_LOG_BYTES = 5 * 1024 * 1024;
18
+ const MAX_ROTATIONS = 3;
19
+
20
+ export interface ImpactLogEntry {
21
+ ts: string;
22
+ command: "resolve" | "execute" | "browse" | string;
23
+ source?: string;
24
+ domain?: string;
25
+ intent?: string;
26
+ skill_id?: string;
27
+ endpoint_id?: string;
28
+ time_saved_ms?: number;
29
+ time_saved_pct?: number;
30
+ tokens_saved?: number;
31
+ tokens_saved_pct?: number;
32
+ cost_saved_uc?: number;
33
+ browser_avoided?: boolean;
34
+ success?: boolean;
35
+ }
36
+
37
+ export interface ImpactSummary {
38
+ total_runs: number;
39
+ successful_runs: number;
40
+ browser_avoided_runs: number;
41
+ total_time_saved_ms: number;
42
+ total_tokens_saved: number;
43
+ total_cost_saved_uc: number;
44
+ avg_time_saved_pct: number;
45
+ avg_tokens_saved_pct: number;
46
+ by_source: Record<string, number>;
47
+ first_entry_at: string | null;
48
+ last_entry_at: string | null;
49
+ }
50
+
51
+ function getLogDir(): string {
52
+ if (process.env.UNBROWSE_CONFIG_DIR) return process.env.UNBROWSE_CONFIG_DIR;
53
+ const profile = process.env.UNBROWSE_PROFILE?.trim();
54
+ return profile
55
+ ? join(homedir(), ".unbrowse", "profiles", profile)
56
+ : join(homedir(), ".unbrowse");
57
+ }
58
+
59
+ export function getImpactLogPath(): string {
60
+ return join(getLogDir(), "impact-log.jsonl");
61
+ }
62
+
63
+ function ensureDir(path: string): void {
64
+ const dir = dirname(path);
65
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
66
+ }
67
+
68
+ function rotateIfNeeded(path: string): void {
69
+ try {
70
+ if (!existsSync(path)) return;
71
+ const size = statSync(path).size;
72
+ if (size < MAX_LOG_BYTES) return;
73
+ for (let i = MAX_ROTATIONS; i >= 1; i--) {
74
+ const older = `${path}.${i}`;
75
+ if (!existsSync(older)) continue;
76
+ if (i === MAX_ROTATIONS) {
77
+ try { unlinkSync(older); } catch {}
78
+ } else {
79
+ try { renameSync(older, `${path}.${i + 1}`); } catch {}
80
+ }
81
+ }
82
+ renameSync(path, `${path}.1`);
83
+ } catch {
84
+ // best-effort; never throw from logging
85
+ }
86
+ }
87
+
88
+ /** Append a single impact record. Fire-and-forget; never throws. */
89
+ export function appendImpact(entry: ImpactLogEntry): void {
90
+ try {
91
+ const hasSignal =
92
+ (entry.time_saved_ms ?? 0) > 0 ||
93
+ (entry.tokens_saved ?? 0) > 0 ||
94
+ (entry.cost_saved_uc ?? 0) > 0 ||
95
+ entry.browser_avoided === true;
96
+ if (!hasSignal) return;
97
+
98
+ const path = getImpactLogPath();
99
+ ensureDir(path);
100
+ rotateIfNeeded(path);
101
+ appendFileSync(path, JSON.stringify(entry) + "\n", "utf8");
102
+ } catch {
103
+ // never surface logging errors
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Extract an ImpactLogEntry from an orchestrator result's `impact` field.
109
+ * Returns null if the result has no impact data.
110
+ */
111
+ export function impactFromResult(
112
+ command: string,
113
+ result: unknown,
114
+ extras: { intent?: string; domain?: string; skill_id?: string; endpoint_id?: string } = {},
115
+ ): ImpactLogEntry | null {
116
+ if (!result || typeof result !== "object") return null;
117
+ const r = result as Record<string, unknown>;
118
+ const impact = (r.impact ?? null) as Record<string, unknown> | null;
119
+ if (!impact || typeof impact !== "object") return null;
120
+
121
+ const num = (v: unknown): number | undefined =>
122
+ typeof v === "number" && Number.isFinite(v) ? v : undefined;
123
+
124
+ return {
125
+ ts: new Date().toISOString(),
126
+ command,
127
+ source: typeof impact.source === "string" ? impact.source : undefined,
128
+ domain: extras.domain,
129
+ intent: extras.intent,
130
+ skill_id: extras.skill_id ?? (typeof r.skill_id === "string" ? r.skill_id : undefined),
131
+ endpoint_id: extras.endpoint_id ?? (typeof r.endpoint_id === "string" ? r.endpoint_id : undefined),
132
+ time_saved_ms: num(impact.time_saved_ms),
133
+ time_saved_pct: num(impact.time_saved_pct),
134
+ tokens_saved: num(impact.tokens_saved),
135
+ tokens_saved_pct: num(impact.tokens_saved_pct),
136
+ cost_saved_uc: num(impact.cost_saved_uc),
137
+ browser_avoided: impact.browser_avoided === true,
138
+ success: r.error == null,
139
+ };
140
+ }
141
+
142
+ /** Read and aggregate the full impact log (across rotations). Safe on missing file. */
143
+ export function readImpactSummary(): ImpactSummary {
144
+ const path = getImpactLogPath();
145
+ const summary: ImpactSummary = {
146
+ total_runs: 0,
147
+ successful_runs: 0,
148
+ browser_avoided_runs: 0,
149
+ total_time_saved_ms: 0,
150
+ total_tokens_saved: 0,
151
+ total_cost_saved_uc: 0,
152
+ avg_time_saved_pct: 0,
153
+ avg_tokens_saved_pct: 0,
154
+ by_source: {},
155
+ first_entry_at: null,
156
+ last_entry_at: null,
157
+ };
158
+
159
+ const files: string[] = [];
160
+ for (let i = MAX_ROTATIONS; i >= 1; i--) {
161
+ const rotated = `${path}.${i}`;
162
+ if (existsSync(rotated)) files.push(rotated);
163
+ }
164
+ if (existsSync(path)) files.push(path);
165
+ if (files.length === 0) return summary;
166
+
167
+ let timePctSum = 0;
168
+ let timePctCount = 0;
169
+ let tokenPctSum = 0;
170
+ let tokenPctCount = 0;
171
+
172
+ for (const file of files) {
173
+ let raw: string;
174
+ try {
175
+ raw = readFileSync(file, "utf8");
176
+ } catch {
177
+ continue;
178
+ }
179
+ for (const line of raw.split("\n")) {
180
+ const trimmed = line.trim();
181
+ if (!trimmed) continue;
182
+ let e: ImpactLogEntry;
183
+ try {
184
+ e = JSON.parse(trimmed) as ImpactLogEntry;
185
+ } catch {
186
+ continue;
187
+ }
188
+ summary.total_runs += 1;
189
+ if (e.success !== false) summary.successful_runs += 1;
190
+ if (e.browser_avoided) summary.browser_avoided_runs += 1;
191
+ summary.total_time_saved_ms += e.time_saved_ms ?? 0;
192
+ summary.total_tokens_saved += e.tokens_saved ?? 0;
193
+ summary.total_cost_saved_uc += e.cost_saved_uc ?? 0;
194
+ if (typeof e.time_saved_pct === "number") {
195
+ timePctSum += e.time_saved_pct;
196
+ timePctCount += 1;
197
+ }
198
+ if (typeof e.tokens_saved_pct === "number") {
199
+ tokenPctSum += e.tokens_saved_pct;
200
+ tokenPctCount += 1;
201
+ }
202
+ if (e.source) {
203
+ summary.by_source[e.source] = (summary.by_source[e.source] ?? 0) + 1;
204
+ }
205
+ if (!summary.first_entry_at || e.ts < summary.first_entry_at) summary.first_entry_at = e.ts;
206
+ if (!summary.last_entry_at || e.ts > summary.last_entry_at) summary.last_entry_at = e.ts;
207
+ }
208
+ }
209
+
210
+ summary.avg_time_saved_pct = timePctCount > 0 ? Math.round(timePctSum / timePctCount) : 0;
211
+ summary.avg_tokens_saved_pct = tokenPctCount > 0 ? Math.round(tokenPctSum / tokenPctCount) : 0;
212
+ return summary;
213
+ }
214
+
215
+ /** For tests only. */
216
+ export function _clearImpactLogForTests(): void {
217
+ const path = getImpactLogPath();
218
+ try {
219
+ if (existsSync(path)) unlinkSync(path);
220
+ for (let i = 1; i <= MAX_ROTATIONS + 1; i++) {
221
+ const rotated = `${path}.${i}`;
222
+ if (existsSync(rotated)) unlinkSync(rotated);
223
+ }
224
+ } catch {
225
+ // ignore
226
+ }
227
+ }
@@ -216,7 +216,10 @@ function falseyEnv(value: string | undefined): boolean {
216
216
  }
217
217
 
218
218
  export function resolveKuriLaunchConfig(env: NodeJS.ProcessEnv = process.env): KuriLaunchConfig {
219
- const headless = envFlag(env.KURI_HEADLESS ?? env.HEADLESS);
219
+ const explicitHeadless = env.KURI_HEADLESS ?? env.HEADLESS;
220
+ const headless = explicitHeadless !== undefined
221
+ ? envFlag(explicitHeadless)
222
+ : (process.platform === "linux" && !env.DISPLAY); // auto-headless when no display on Linux
220
223
  const cleanRoom = envFlag(env.UNBROWSE_LOCAL_ONLY) || envFlag(env.KURI_CLEAN_ROOM);
221
224
  const browserCookieOptOut = falseyEnv(env.UNBROWSE_IMPORT_BROWSER_COOKIES);
222
225
  const explicitAttach = envFlag(env.KURI_ATTACH_EXISTING_CHROME ?? env.UNBROWSE_ATTACH_EXISTING_CHROME);
@@ -240,6 +243,7 @@ function currentBundledKuriTarget(): string | null {
240
243
  if (process.platform === "darwin" && process.arch === "x64") return "darwin-x64";
241
244
  if (process.platform === "linux" && process.arch === "arm64") return "linux-arm64";
242
245
  if (process.platform === "linux" && process.arch === "x64") return "linux-x64";
246
+ if (process.platform === "win32" && process.arch === "x64") return "win-x64";
243
247
  return null;
244
248
  }
245
249
 
@@ -82,11 +82,19 @@ export function mergeEndpoints(
82
82
  dom_extraction: ep.dom_extraction ?? dupe.dom_extraction,
83
83
  semantic: ep.semantic ?? dupe.semantic,
84
84
  response_schema: ep.response_schema ?? dupe.response_schema,
85
- headers_template: ep.headers_template ?? dupe.headers_template,
85
+ headers_template: Object.keys(ep.headers_template ?? {}).length > 0 ? ep.headers_template : dupe.headers_template,
86
86
  query: ep.query ?? dupe.query,
87
87
  path_params: ep.path_params ?? dupe.path_params,
88
88
  body: ep.body ?? dupe.body,
89
+ body_params: ep.body_params ?? dupe.body_params,
89
90
  trigger_url: ep.trigger_url ?? dupe.trigger_url,
91
+ csrf_plan: ep.csrf_plan ?? dupe.csrf_plan,
92
+ oauth_plan: ep.oauth_plan ?? dupe.oauth_plan,
93
+ search_form: ep.search_form ?? dupe.search_form,
94
+ policy: ep.policy ?? dupe.policy,
95
+ graph_visibility: ep.graph_visibility ?? dupe.graph_visibility,
96
+ corroboration: ep.corroboration ?? dupe.corroboration,
97
+ auth_tokens: ep.auth_tokens ?? dupe.auth_tokens,
90
98
  };
91
99
  }
92
100
  return merged;