@phren/cli 0.3.75 → 0.3.77

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.
@@ -29469,6 +29469,68 @@ var init_projects = __esm({
29469
29469
  }
29470
29470
  });
29471
29471
 
29472
+ // src/content/secrets.ts
29473
+ function looksLikePlaceholderSecret(value2) {
29474
+ const v2 = value2.trim().replace(/^['"`]+|['"`]+$/g, "").trim();
29475
+ if (!v2) return true;
29476
+ if (/^(?:<[^<>]*>|\{\{[^{}]*\}\}|\$\{[^{}]*\}|%[^%]*%|__.+__|\$[A-Za-z_][A-Za-z0-9_]*)$/.test(v2)) return true;
29477
+ if (/^(?:[*.]{3,}|[xX]{4,}|0{8,})$/.test(v2)) return true;
29478
+ if (/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(v2)) return true;
29479
+ if (/^(?:changeme|change[_-]?me|placeholder|redacted|example|dummy|sample|fake|todo|fixme|none|null|undefined|secret|pass|passwd|password|token|apikey|api[_-]?key)$/i.test(v2)) return true;
29480
+ if (/^(?:your|my|the|some)[_-][a-z0-9_-]*$/i.test(v2)) return true;
29481
+ if (/[_-]?goes[_-]?here$/i.test(v2)) return true;
29482
+ return false;
29483
+ }
29484
+ function firstRealSecretValue(text7, re2) {
29485
+ for (const match of text7.matchAll(re2)) {
29486
+ const value2 = match[1];
29487
+ if (value2 && !looksLikePlaceholderSecret(value2)) return value2;
29488
+ }
29489
+ return null;
29490
+ }
29491
+ function scanForSecrets(text7) {
29492
+ if (/AKIA[0-9A-Z]{16}/.test(text7)) return "AWS access key";
29493
+ if (/(?:aws[_-]?secret|AWS_SECRET)[_-]?(?:access[_-]?)?key[_-]?(?:id)?['":=\s]+[A-Za-z0-9/+=]{40}/i.test(text7)) return "AWS secret access key";
29494
+ if (/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/.test(text7)) return "JWT token";
29495
+ if (/github_pat_[A-Za-z0-9_]{22,}/.test(text7)) return "GitHub fine-grained token";
29496
+ if (/\bAIza[0-9A-Za-z_-]{35}\b/.test(text7)) return "Google API key";
29497
+ if (/https:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9]+\/B[A-Za-z0-9]+\/[A-Za-z0-9]+/.test(text7)) return "Slack webhook URL";
29498
+ if (!/^[0-9a-f]{40}$/.test(text7) && /(?=[A-Za-z0-9+/]*[+/])(?=[A-Za-z+/]*[0-9])[A-Za-z0-9+/]{40,}={0,2}/.test(text7.replace(/[0-9a-f]{40}/g, ""))) return "long base64 secret";
29499
+ if (/(mongodb|postgres|mysql|redis):\/\/[^@\s]+:[^@\s]+@/i.test(text7)) return "connection string with credentials";
29500
+ if (/-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/.test(text7)) return "SSH private key";
29501
+ if (/sk-ant-api\d{2}-[A-Za-z0-9_\-]{10,}/.test(text7)) return "Anthropic API key";
29502
+ if (/sk-proj-[A-Za-z0-9_\-]{30,}/.test(text7)) return "OpenAI API key";
29503
+ if (/ghp_[A-Za-z0-9]{36}/.test(text7)) return "GitHub personal access token";
29504
+ if (/gho_[A-Za-z0-9]{36}/.test(text7)) return "GitHub OAuth token";
29505
+ if (/gh[pousr]_[A-Za-z0-9]{36}/.test(text7)) return "GitHub token";
29506
+ if (/xoxb-[0-9]+-[A-Za-z0-9-]+/.test(text7)) return "Slack bot token";
29507
+ if (/xoxp-[0-9]+-[A-Za-z0-9-]+/.test(text7)) return "Slack user token";
29508
+ if (/sk_live_[A-Za-z0-9]{24,}/.test(text7)) return "Stripe secret key";
29509
+ if (/pk_live_[A-Za-z0-9]{24,}/.test(text7)) return "Stripe publishable key";
29510
+ if (/npm_[A-Za-z0-9]{36}/.test(text7)) return "npm access token";
29511
+ if (/"private_key_id"\s*:\s*"[^"]{20,}"/.test(text7)) return "GCP service account key";
29512
+ if (firstRealSecretValue(text7, URL_CREDENTIALS_RE)) return "URL with embedded credentials";
29513
+ if (firstRealSecretValue(text7, BEARER_RE)) return "bearer token";
29514
+ if (firstRealSecretValue(text7, NPM_AUTH_TOKEN_RE)) return "registry auth token";
29515
+ if (firstRealSecretValue(text7, NAMED_SECRET_RE)) return "API key or secret";
29516
+ return null;
29517
+ }
29518
+ function redactSecretsForLog(text7) {
29519
+ const secretType = scanForSecrets(text7);
29520
+ if (!secretType) return text7;
29521
+ return `[redacted: withheld, contained ${secretType}]`;
29522
+ }
29523
+ var NAMED_SECRET_RE, BEARER_RE, NPM_AUTH_TOKEN_RE, URL_CREDENTIALS_RE;
29524
+ var init_secrets = __esm({
29525
+ "src/content/secrets.ts"() {
29526
+ "use strict";
29527
+ NAMED_SECRET_RE = /['"]?(?:api_?key|secret|token|password)['"]?\s*[=:]\s*['"]?([a-zA-Z0-9_\-.]{20,})/gi;
29528
+ BEARER_RE = /\bauthorization['"]?\s*[=:]\s*['"]?\s*bearer\s+([A-Za-z0-9\-._~+/]{20,}=*)/gi;
29529
+ NPM_AUTH_TOKEN_RE = /_auth(?:Token)?\s*=\s*['"]?([A-Za-z0-9\-._~+/]{16,}=*)/gi;
29530
+ URL_CREDENTIALS_RE = /\bhttps?:\/\/[^/\s:@]+:([^/\s:@]+)@[^\s]+/gi;
29531
+ }
29532
+ });
29533
+
29472
29534
  // src/bridge/changes.ts
29473
29535
  import { execFile as execFile2 } from "node:child_process";
29474
29536
  import { randomBytes } from "node:crypto";
@@ -29547,7 +29609,7 @@ async function treeDiff(root, before, after2, env, signal) {
29547
29609
  const specs = [.../* @__PURE__ */ new Set([original, file5])].map((name2) => `:(literal)${name2}`);
29548
29610
  const counts = (await git2(root, [...NO_DIFF, "--numstat", before, after2, "--", ...specs], env, signal)).split(" ");
29549
29611
  const binary = counts[0] === "-" || counts[1] === "-";
29550
- const redacted = secretName(original) || secretName(file5) || binary;
29612
+ let redacted = secretName(original) || secretName(file5) || binary;
29551
29613
  let overflowed = false;
29552
29614
  let patch = redacted ? "" : await git2(root, [...NO_DIFF, before, after2, "--", ...specs], env, signal).catch((error62) => {
29553
29615
  const failure2 = error62;
@@ -29555,6 +29617,10 @@ async function treeDiff(root, before, after2, env, signal) {
29555
29617
  overflowed = true;
29556
29618
  return String(failure2.stdout ?? "");
29557
29619
  });
29620
+ if (patch && secretPatch(patch)) {
29621
+ patch = "";
29622
+ redacted = true;
29623
+ }
29558
29624
  const truncated = overflowed || patch.length > 2e5;
29559
29625
  if (truncated) patch = patch.slice(0, 2e5) + "\n\u2026 (truncated)\n";
29560
29626
  const added = Number(counts[0]) || 0, removed = Number(counts[1]) || 0;
@@ -29626,7 +29692,7 @@ function outputCallIds(raw, source) {
29626
29692
  if (!Array.isArray(content)) return [];
29627
29693
  return content.flatMap((block) => block && typeof block === "object" && block.type === "tool_result" ? ids(block.tool_use_id) : []);
29628
29694
  }
29629
- var exec2, changedFileSchema, changeRowSchema, secretName, capturePool, SHELL_TOOLS, NAMED, FILE_TOOLS, CaptureTimeout, failedRepository, Scratch, SCRATCH_AGE, REPOSITORY_TTL, NO_DIFF, CLAIM_RETENTION, PENDING_FOR, BUDGET, DAY, ToolChanges;
29695
+ var exec2, changedFileSchema, changeRowSchema, secretName, secretPatch, capturePool, SHELL_TOOLS, NAMED, FILE_TOOLS, CaptureTimeout, failedRepository, Scratch, SCRATCH_AGE, REPOSITORY_TTL, NO_DIFF, CLAIM_RETENTION, PENDING_FOR, BUDGET, DAY, ToolChanges;
29630
29696
  var init_changes = __esm({
29631
29697
  "src/bridge/changes.ts"() {
29632
29698
  "use strict";
@@ -29637,6 +29703,7 @@ var init_changes = __esm({
29637
29703
  init_limits();
29638
29704
  init_transcripts();
29639
29705
  init_metrics();
29706
+ init_secrets();
29640
29707
  exec2 = promisify2(execFile2);
29641
29708
  changedFileSchema = external_exports.object({
29642
29709
  root: external_exports.string(),
@@ -29650,7 +29717,8 @@ var init_changes = __esm({
29650
29717
  truncated: external_exports.boolean().optional()
29651
29718
  });
29652
29719
  changeRowSchema = external_exports.object({ toolUseId: external_exports.string(), files: external_exports.array(changedFileSchema) });
29653
- secretName = (file5) => /^(?:\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx|keychain-db|tfstate)|id_rsa.*|id_ed25519.*|(?:.*\.)?credentials\.json|\.netrc|\.npmrc|\.pypirc)$/i.test(path19.basename(file5));
29720
+ secretName = (file5) => /^(?:\.env(?:\..*)?|.*\.env|.*\.(?:pem|key|p8|p12|pfx|jks|keystore|keychain-db|tfstate|tfvars|ovpn)|id_(?:rsa|dsa|ecdsa|ed25519)(?:[_.].*)?|(?:.*\.)?credentials(?:\.json)?|\.credentials|\.git-credentials|\.netrc|\.npmrc|\.pypirc|\.pgpass|kubeconfig)$/i.test(path19.basename(file5));
29721
+ secretPatch = (patch) => scanForSecrets(patch.replace(/(?=[A-Za-z0-9+/]*[+/])[A-Za-z0-9+/]{40,}={0,2}/g, "")) !== null;
29654
29722
  capturePool = new ProcessPool(2);
29655
29723
  SHELL_TOOLS = /* @__PURE__ */ new Set(["Bash", "bash", "shell", "Shell", "exec_command", "shell_command", "local_shell", "write_stdin"]);
29656
29724
  NAMED = /(?<![\w@:/])(?:~\/|\.\/|\/)[\w.@+~-]+(?:\/[\w.@+~-]+)*/g;
@@ -30051,7 +30119,7 @@ var init_changes = __esm({
30051
30119
  if (!line) continue;
30052
30120
  try {
30053
30121
  const row = changeRowSchema.parse(JSON.parse(line));
30054
- entry2.files.set(row.toolUseId, row.files.map((file6) => secretName(file6.path) || file6.redacted || /^(?:Binary files |GIT binary patch)/m.test(file6.patch) ? { ...file6, patch: "", redacted: true } : file6));
30122
+ entry2.files.set(row.toolUseId, row.files.map((file6) => secretName(file6.path) || file6.redacted || /^(?:Binary files |GIT binary patch)/m.test(file6.patch) || secretPatch(file6.patch) ? { ...file6, patch: "", redacted: true } : file6));
30055
30123
  } catch {
30056
30124
  }
30057
30125
  }
@@ -39521,7 +39589,7 @@ var init_package_metadata = __esm({
39521
39589
  __dirname = path41.dirname(fileURLToPath3(import.meta.url));
39522
39590
  ROOT = path41.join(__dirname, "..");
39523
39591
  PACKAGE_JSON_PATH = path41.join(ROOT, "package.json");
39524
- BUNDLED_VERSION = true ? "0.3.75" : "0.0.0";
39592
+ BUNDLED_VERSION = true ? "0.3.77" : "0.0.0";
39525
39593
  PACKAGE_JSON = readPackageJson();
39526
39594
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
39527
39595
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -39596,68 +39664,6 @@ var init_management_preset = __esm({
39596
39664
  }
39597
39665
  });
39598
39666
 
39599
- // src/content/secrets.ts
39600
- function looksLikePlaceholderSecret(value2) {
39601
- const v2 = value2.trim().replace(/^['"`]+|['"`]+$/g, "").trim();
39602
- if (!v2) return true;
39603
- if (/^(?:<[^<>]*>|\{\{[^{}]*\}\}|\$\{[^{}]*\}|%[^%]*%|__.+__|\$[A-Za-z_][A-Za-z0-9_]*)$/.test(v2)) return true;
39604
- if (/^(?:[*.]{3,}|[xX]{4,}|0{8,})$/.test(v2)) return true;
39605
- if (/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(v2)) return true;
39606
- if (/^(?:changeme|change[_-]?me|placeholder|redacted|example|dummy|sample|fake|todo|fixme|none|null|undefined|secret|pass|passwd|password|token|apikey|api[_-]?key)$/i.test(v2)) return true;
39607
- if (/^(?:your|my|the|some)[_-][a-z0-9_-]*$/i.test(v2)) return true;
39608
- if (/[_-]?goes[_-]?here$/i.test(v2)) return true;
39609
- return false;
39610
- }
39611
- function firstRealSecretValue(text7, re2) {
39612
- for (const match of text7.matchAll(re2)) {
39613
- const value2 = match[1];
39614
- if (value2 && !looksLikePlaceholderSecret(value2)) return value2;
39615
- }
39616
- return null;
39617
- }
39618
- function scanForSecrets(text7) {
39619
- if (/AKIA[0-9A-Z]{16}/.test(text7)) return "AWS access key";
39620
- if (/(?:aws[_-]?secret|AWS_SECRET)[_-]?(?:access[_-]?)?key[_-]?(?:id)?['":=\s]+[A-Za-z0-9/+=]{40}/i.test(text7)) return "AWS secret access key";
39621
- if (/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/.test(text7)) return "JWT token";
39622
- if (/github_pat_[A-Za-z0-9_]{22,}/.test(text7)) return "GitHub fine-grained token";
39623
- if (/\bAIza[0-9A-Za-z_-]{35}\b/.test(text7)) return "Google API key";
39624
- if (/https:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9]+\/B[A-Za-z0-9]+\/[A-Za-z0-9]+/.test(text7)) return "Slack webhook URL";
39625
- if (!/^[0-9a-f]{40}$/.test(text7) && /(?=[A-Za-z0-9+/]*[+/])(?=[A-Za-z+/]*[0-9])[A-Za-z0-9+/]{40,}={0,2}/.test(text7.replace(/[0-9a-f]{40}/g, ""))) return "long base64 secret";
39626
- if (/(mongodb|postgres|mysql|redis):\/\/[^@\s]+:[^@\s]+@/i.test(text7)) return "connection string with credentials";
39627
- if (/-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/.test(text7)) return "SSH private key";
39628
- if (/sk-ant-api\d{2}-[A-Za-z0-9_\-]{10,}/.test(text7)) return "Anthropic API key";
39629
- if (/sk-proj-[A-Za-z0-9_\-]{30,}/.test(text7)) return "OpenAI API key";
39630
- if (/ghp_[A-Za-z0-9]{36}/.test(text7)) return "GitHub personal access token";
39631
- if (/gho_[A-Za-z0-9]{36}/.test(text7)) return "GitHub OAuth token";
39632
- if (/gh[pousr]_[A-Za-z0-9]{36}/.test(text7)) return "GitHub token";
39633
- if (/xoxb-[0-9]+-[A-Za-z0-9-]+/.test(text7)) return "Slack bot token";
39634
- if (/xoxp-[0-9]+-[A-Za-z0-9-]+/.test(text7)) return "Slack user token";
39635
- if (/sk_live_[A-Za-z0-9]{24,}/.test(text7)) return "Stripe secret key";
39636
- if (/pk_live_[A-Za-z0-9]{24,}/.test(text7)) return "Stripe publishable key";
39637
- if (/npm_[A-Za-z0-9]{36}/.test(text7)) return "npm access token";
39638
- if (/"private_key_id"\s*:\s*"[^"]{20,}"/.test(text7)) return "GCP service account key";
39639
- if (firstRealSecretValue(text7, URL_CREDENTIALS_RE)) return "URL with embedded credentials";
39640
- if (firstRealSecretValue(text7, BEARER_RE)) return "bearer token";
39641
- if (firstRealSecretValue(text7, NPM_AUTH_TOKEN_RE)) return "registry auth token";
39642
- if (firstRealSecretValue(text7, NAMED_SECRET_RE)) return "API key or secret";
39643
- return null;
39644
- }
39645
- function redactSecretsForLog(text7) {
39646
- const secretType = scanForSecrets(text7);
39647
- if (!secretType) return text7;
39648
- return `[redacted: withheld, contained ${secretType}]`;
39649
- }
39650
- var NAMED_SECRET_RE, BEARER_RE, NPM_AUTH_TOKEN_RE, URL_CREDENTIALS_RE;
39651
- var init_secrets = __esm({
39652
- "src/content/secrets.ts"() {
39653
- "use strict";
39654
- NAMED_SECRET_RE = /['"]?(?:api_?key|secret|token|password)['"]?\s*[=:]\s*['"]?([a-zA-Z0-9_\-.]{20,})/gi;
39655
- BEARER_RE = /\bauthorization['"]?\s*[=:]\s*['"]?\s*bearer\s+([A-Za-z0-9\-._~+/]{20,}=*)/gi;
39656
- NPM_AUTH_TOKEN_RE = /_auth(?:Token)?\s*=\s*['"]?([A-Za-z0-9\-._~+/]{16,}=*)/gi;
39657
- URL_CREDENTIALS_RE = /\bhttps?:\/\/[^/\s:@]+:([^/\s:@]+)@[^\s]+/gi;
39658
- }
39659
- });
39660
-
39661
39667
  // src/hooks.ts
39662
39668
  import * as fs17 from "fs";
39663
39669
  import { createHmac } from "crypto";
@@ -42184,6 +42190,7 @@ var init_registry = __esm({
42184
42190
  "bridge serve",
42185
42191
  "bridge ssh",
42186
42192
  "pair",
42193
+ "unpair",
42187
42194
  "bridge fanouts archive",
42188
42195
  "bridge accounts",
42189
42196
  "bridge askpass",
@@ -42253,6 +42260,7 @@ var init_registry = __esm({
42253
42260
  ]),
42254
42261
  ...routes("POST", [
42255
42262
  "/v1/push/register",
42263
+ "/v1/push/forget",
42256
42264
  "/v1/push/answer",
42257
42265
  "/v1/push/target",
42258
42266
  "/v1/push/presence",
@@ -54026,7 +54034,7 @@ function redactApproval(value2) {
54026
54034
  } catch {
54027
54035
  return "\u2026";
54028
54036
  }
54029
- }).replace(/\bAuthorization\s*:\s*Bearer\s+(\S+)/gi, (_whole, token2) => `Authorization: Bearer \u2026${/["']$/.test(token2) ? token2.slice(-1) : ""}`).replace(/(^|\s)(--(?:token|password|secret|api-key|access-token))(?:\s+|=)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1$2 \u2026").replace(/(\b(?:mysql|mysqldump|mysqladmin|mariadb)\b[^\n]*?\s-p)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1\u2026").replace(/(^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=(?:"[^"]*"|'[^']*'|[^\s;]+)/g, "$1$2=\u2026").replace(/\b(?:gh[po]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[abp]-[A-Za-z0-9-]+|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Fa-f0-9]{32,}|[A-Za-z0-9_-]{32,})\b/g, "\u2026");
54037
+ }).replace(/\bAuthorization\s*:\s*Bearer\s+(\S+)/gi, (_whole, token2) => `Authorization: Bearer \u2026${/["']$/.test(token2) ? token2.slice(-1) : ""}`).replace(/(^|\s)(--(?:token|password|secret|api-key|access-token))(?:\s+|=)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1$2 \u2026").replace(/(\b(?:curl|wget|https?|httpie|xh)\b[^\n]*?\s(?:-u|--user|--proxy-user)(?:=|\s+))(?:"[^"]*"|'[^']*'|\S+)/gi, "$1\u2026").replace(/(Authorization:\s*(?!Bearer\s)[A-Za-z]+\s+)[^\s"']+/gi, "$1\u2026").replace(/(\b(?:proxy-authorization|cookie|set-cookie|x-api-key|api-key|apikey|x-auth-token|x-[a-z-]*(?:token|key|secret)[a-z-]*):\s*)[^"'\n]+/gi, "$1\u2026").replace(/(\bsshpass\b[^\n]*?\s-p\s*)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1\u2026").replace(/(\b(?:docker|podman|helm|npm)\s+login\b[^\n]*?\s-p(?:=|\s+))(?:"[^"]*"|'[^']*'|\S+)/gi, "$1\u2026").replace(/(\b(?:password|passwd|pwd|pass|secret|token|api[_-]?key|access[_-]?token|client[_-]?secret|auth)=)[^&\s"']+/gi, "$1\u2026").replace(/(\b(?:mysql|mysqldump|mysqladmin|mariadb)\b[^\n]*?\s-p)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1\u2026").replace(/(^|[\s;|(]|(?<![^\s&])&)([A-Za-z_][A-Za-z0-9_]*)=(?:"[^"]*"|'[^']*'|[^\s;]+)/g, "$1$2=\u2026").replace(/\b(?:gh[po]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[abp]-[A-Za-z0-9-]+|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Fa-f0-9]{32,}|[A-Za-z0-9_-]{32,})\b/g, "\u2026");
54030
54038
  }
54031
54039
  function shortApproval(value2) {
54032
54040
  const line = oneLine(redactApproval(value2));
@@ -67038,12 +67046,13 @@ function browserId(value2) {
67038
67046
  if (!value2 || !BROWSER_ID.test(value2)) throw new BridgeError(400, "Invalid browser identifier.");
67039
67047
  return value2;
67040
67048
  }
67041
- var BrowserRecordings;
67049
+ var RECORDING_LIMITS, BrowserRecordings;
67042
67050
  var init_browser_recordings = __esm({
67043
67051
  "src/bridge/browser-recordings.ts"() {
67044
67052
  "use strict";
67045
67053
  init_protocol();
67046
67054
  init_browser_protocol();
67055
+ RECORDING_LIMITS = { url: 1024, title: 200, reason: 1024, navigations: 500, navigationsPerSecond: 10, pages: 100, handoffs: 500, saveEveryMs: 1e3 };
67047
67056
  BrowserRecordings = class {
67048
67057
  constructor(root) {
67049
67058
  this.root = root;
@@ -67059,6 +67068,31 @@ var init_browser_recordings = __esm({
67059
67068
  fs47.writeFileSync(path109.join(dir, "meta.tmp"), JSON.stringify(meta3), { mode: 384 });
67060
67069
  fs47.renameSync(path109.join(dir, "meta.tmp"), path109.join(dir, "meta.json"));
67061
67070
  }
67071
+ /** Frames arrive up to four times a second; their counters reach the file at most once a second, and at the end. */
67072
+ saveSoon(state) {
67073
+ const wait = state.savedAt + RECORDING_LIMITS.saveEveryMs - Date.now();
67074
+ if (wait <= 0) {
67075
+ this.saveNow(state);
67076
+ return;
67077
+ }
67078
+ state.timer ??= setTimeout(() => {
67079
+ state.timer = void 0;
67080
+ if (this.active.get(state.meta.id) === state) try {
67081
+ this.saveNow(state);
67082
+ } catch {
67083
+ }
67084
+ }, wait).unref();
67085
+ }
67086
+ saveNow(state) {
67087
+ clearTimeout(state.timer);
67088
+ state.timer = void 0;
67089
+ this.save(state.meta);
67090
+ state.savedAt = Date.now();
67091
+ }
67092
+ forget(id3) {
67093
+ clearTimeout(this.active.get(id3)?.timer);
67094
+ this.active.delete(id3);
67095
+ }
67062
67096
  start(hello, now = Date.now()) {
67063
67097
  const dir = this.dir(hello.browserId);
67064
67098
  fs47.mkdirSync(dir, { mode: 448 });
@@ -67066,20 +67100,32 @@ var init_browser_recordings = __esm({
67066
67100
  fs47.writeFileSync(path109.join(dir, "index.jsonl"), "", { mode: 384 });
67067
67101
  const meta3 = { id: hello.browserId, browserId: hello.browserId, session: hello.session, cwd: hello.cwd, engine: hello.engine, headless: hello.headless, startedAt: now, endedAt: null, frames: 0, bytes: 0, pages: [], navigations: [], handoffs: [] };
67068
67102
  this.save(meta3);
67069
- this.active.set(meta3.id, { meta: meta3, last: /* @__PURE__ */ new Map() });
67103
+ this.active.set(meta3.id, { meta: meta3, last: /* @__PURE__ */ new Map(), savedAt: Date.now(), second: 0, inSecond: 0 });
67070
67104
  }
67071
67105
  page(page, now = Date.now()) {
67072
67106
  const state = this.active.get(page.browserId);
67073
67107
  if (!state) return;
67074
- const nav = { t: now, pageId: page.pageId, url: page.url, title: page.title };
67108
+ const nav = { t: now, pageId: page.pageId, url: page.url.slice(0, RECORDING_LIMITS.url), title: page.title.slice(0, RECORDING_LIMITS.title) };
67075
67109
  const previous = state.meta.navigations.filter((n) => n.pageId === page.pageId).at(-1);
67076
- if (previous?.url === page.url && previous.title === page.title) return;
67110
+ if (previous?.url === nav.url && previous.title === nav.title) return;
67077
67111
  const existing = state.meta.pages.find((p) => p.pageId === page.pageId);
67078
67112
  if (existing) Object.assign(existing, { url: nav.url, title: nav.title });
67079
- else state.meta.pages.push({ ...nav });
67080
- if (previous?.url === page.url && !previous.title) previous.title = page.title;
67081
- else state.meta.navigations.push(nav);
67082
- this.save(state.meta);
67113
+ else if (state.meta.pages.length < RECORDING_LIMITS.pages) state.meta.pages.push({ ...nav });
67114
+ else return;
67115
+ if (previous?.url === nav.url && !previous.title) previous.title = nav.title;
67116
+ else {
67117
+ const second = Math.floor(now / 1e3);
67118
+ if (state.second !== second) {
67119
+ state.second = second;
67120
+ state.inSecond = 0;
67121
+ }
67122
+ if (state.meta.navigations.length >= RECORDING_LIMITS.navigations || ++state.inSecond > RECORDING_LIMITS.navigationsPerSecond) {
67123
+ this.saveSoon(state);
67124
+ return;
67125
+ }
67126
+ state.meta.navigations.push(nav);
67127
+ }
67128
+ this.saveNow(state);
67083
67129
  }
67084
67130
  frame(info, jpeg) {
67085
67131
  const state = this.active.get(info.browserId);
@@ -67094,20 +67140,21 @@ var init_browser_recordings = __esm({
67094
67140
  state.meta.bytes += jpeg.length;
67095
67141
  state.meta.frames++;
67096
67142
  state.last.set(info.pageId, { t: info.t, jpeg });
67097
- this.save(state.meta);
67143
+ this.saveSoon(state);
67098
67144
  }
67099
67145
  handoff(id3, kind, reason3) {
67100
67146
  const state = this.active.get(id3);
67101
67147
  if (!state) return;
67102
- state.meta.handoffs.push({ t: Date.now(), kind, ...reason3 ? { reason: reason3 } : {} });
67103
- this.save(state.meta);
67148
+ if (state.meta.handoffs.length >= RECORDING_LIMITS.handoffs) return;
67149
+ state.meta.handoffs.push({ t: Date.now(), kind, ...reason3 ? { reason: reason3.slice(0, RECORDING_LIMITS.reason) } : {} });
67150
+ this.saveNow(state);
67104
67151
  }
67105
67152
  end(id3, now = Date.now()) {
67106
67153
  const state = this.active.get(id3);
67107
67154
  if (!state) return;
67108
67155
  state.meta.endedAt = now;
67109
- this.save(state.meta);
67110
- this.active.delete(id3);
67156
+ this.saveNow(state);
67157
+ this.forget(id3);
67111
67158
  }
67112
67159
  list() {
67113
67160
  return fs47.readdirSync(this.root).filter((id3) => BROWSER_ID.test(id3)).flatMap((id3) => {
@@ -67121,7 +67168,17 @@ var init_browser_recordings = __esm({
67121
67168
  index(id3) {
67122
67169
  const dir = this.dir(id3);
67123
67170
  try {
67124
- return { meta: JSON.parse(fs47.readFileSync(path109.join(dir, "meta.json"), "utf8")), frames: fs47.readFileSync(path109.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) };
67171
+ return {
67172
+ meta: JSON.parse(fs47.readFileSync(path109.join(dir, "meta.json"), "utf8")),
67173
+ // A crash during an append leaves a torn last line; the complete rows before it still play.
67174
+ frames: fs47.readFileSync(path109.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).flatMap((line) => {
67175
+ try {
67176
+ return [JSON.parse(line)];
67177
+ } catch {
67178
+ return [];
67179
+ }
67180
+ })
67181
+ };
67125
67182
  } catch {
67126
67183
  throw new BridgeError(404, "Recording not found.");
67127
67184
  }
@@ -67146,6 +67203,12 @@ var init_browser_recordings = __esm({
67146
67203
  /** Recover archives left open by a Hook crash before accepting new producers. */
67147
67204
  recover(now = Date.now()) {
67148
67205
  for (const meta3 of this.list()) if (meta3.endedAt === null && !this.active.has(meta3.id)) {
67206
+ try {
67207
+ const frames = this.index(meta3.id).frames, final = frames.at(-1);
67208
+ meta3.frames = frames.length;
67209
+ meta3.bytes = final ? final.offset + final.length : 0;
67210
+ } catch {
67211
+ }
67149
67212
  meta3.endedAt = now;
67150
67213
  this.save(meta3);
67151
67214
  }
@@ -67156,7 +67219,7 @@ var init_browser_recordings = __esm({
67156
67219
  let total = [...sizes.values()].reduce((a, b) => a + b, 0);
67157
67220
  for (const meta3 of all.reverse()) {
67158
67221
  if (now - meta3.startedAt >= 864e5 || total > budget) {
67159
- this.active.delete(meta3.id);
67222
+ this.forget(meta3.id);
67160
67223
  this.remove(meta3.id);
67161
67224
  total -= sizes.get(meta3.id) ?? 0;
67162
67225
  }
@@ -67171,13 +67234,14 @@ import { EventEmitter as EventEmitter2 } from "node:events";
67171
67234
  import * as fs48 from "node:fs/promises";
67172
67235
  import { createServer as createServer2, connect as connect3 } from "node:net";
67173
67236
  import path110 from "node:path";
67174
- var MAX_INPUT_BACKLOG, BrowserRegistry;
67237
+ var MAX_PAGES, MAX_INPUT_BACKLOG, BrowserRegistry;
67175
67238
  var init_browser_registry = __esm({
67176
67239
  "src/bridge/browser-registry.ts"() {
67177
67240
  "use strict";
67178
67241
  init_browser_protocol();
67179
67242
  init_browser_socket();
67180
67243
  init_browser_recordings();
67244
+ MAX_PAGES = 200;
67181
67245
  MAX_INPUT_BACKLOG = 1024 * 1024;
67182
67246
  BrowserRegistry = class extends EventEmitter2 {
67183
67247
  constructor(root) {
@@ -67220,6 +67284,11 @@ var init_browser_registry = __esm({
67220
67284
  let page = browser.pages.find((page2) => page2.id === p.pageId);
67221
67285
  if (page && !page.live) throw new Error("Closed page");
67222
67286
  if (!page) {
67287
+ while (browser.pages.length >= MAX_PAGES) {
67288
+ const closed = browser.pages.findIndex((page2) => !page2.live);
67289
+ if (closed < 0) throw new Error("Too many pages");
67290
+ browser.pages.splice(closed, 1);
67291
+ }
67223
67292
  page = { id: p.pageId, url: p.url, title: p.title, width: p.width, height: p.height, live: true };
67224
67293
  browser.pages.push(page);
67225
67294
  }
@@ -72493,8 +72562,20 @@ var init_push = __esm({
72493
72562
  devices = [];
72494
72563
  sender;
72495
72564
  devicesFile = path122.join(bridgeRoot(), "push-devices.json");
72565
+ /** Loading, registering, forgetting and dropping a gone phone each read or
72566
+ * write the list and its file; one at a time, so an older write never lands
72567
+ * over a newer one and a load never brings back what was just forgotten. */
72568
+ changes = Promise.resolve();
72569
+ change(work) {
72570
+ const next = this.changes.then(work, work);
72571
+ this.changes = next.catch(() => {
72572
+ });
72573
+ return next;
72574
+ }
72496
72575
  async start() {
72497
- this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
72576
+ await this.change(async () => {
72577
+ this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
72578
+ });
72498
72579
  const configFile = process.env.PHREN_APNS_CONFIG || path122.join(bridgeRoot(), "apns.json");
72499
72580
  const config4 = await secureJSON(configFile, configSchema3);
72500
72581
  if (!config4) return;
@@ -72520,16 +72601,31 @@ var init_push = __esm({
72520
72601
  };
72521
72602
  }
72522
72603
  async register(value2) {
72523
- this.devices = upsertPushDevice(this.devices, value2);
72524
- await atomic(this.devicesFile, JSON.stringify(this.devices));
72604
+ await this.change(async () => {
72605
+ this.devices = upsertPushDevice(this.devices, value2);
72606
+ await atomic(this.devicesFile, JSON.stringify(this.devices));
72607
+ });
72608
+ }
72609
+ /** Drop every registration; returns how many went. Registrations carry no
72610
+ * SSH key, so removing a phone cannot pick out its own: all go, and the
72611
+ * phones still paired register again the next time Phren renews (hourly, on open). */
72612
+ async forgetAll() {
72613
+ return this.change(async () => {
72614
+ const removed = this.devices.length;
72615
+ this.devices = [];
72616
+ await atomic(this.devicesFile, JSON.stringify(this.devices));
72617
+ return removed;
72618
+ });
72525
72619
  }
72526
72620
  /** One phone: the relay when it registered through one, otherwise direct. */
72527
72621
  async send(device, payload, headers) {
72528
72622
  if (device.relay) {
72529
72623
  const result = await sendThroughRelay(device.relay, payload, headers);
72530
72624
  if (result === "gone") {
72531
- this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
72532
- await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => {
72625
+ await this.change(async () => {
72626
+ this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
72627
+ await atomic(this.devicesFile, JSON.stringify(this.devices));
72628
+ }).catch(() => {
72533
72629
  });
72534
72630
  }
72535
72631
  return result === "sent";
@@ -90110,8 +90206,12 @@ function createRouteHandler(ctx) {
90110
90206
  } else if (url2.pathname === "/v1/sets/link") {
90111
90207
  result = await linkSetMember(data, request10);
90112
90208
  } else if (url2.pathname === "/v1/push/register") {
90209
+ if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner's phone registers for notifications.");
90113
90210
  await agentHooks.push.register(data);
90114
90211
  result = { ok: true, configured: agentHooks.push.status.configured };
90212
+ } else if (url2.pathname === "/v1/push/forget") {
90213
+ if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner removes notification registrations.");
90214
+ result = { ok: true, removed: await agentHooks.push.forgetAll() };
90115
90215
  } else if (url2.pathname === "/v1/sudo/answer") {
90116
90216
  if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
90117
90217
  let parsed;
@@ -92864,7 +92964,7 @@ async function main() {
92864
92964
  return askpass2(args[1]);
92865
92965
  }
92866
92966
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
92867
- return runBridge2(args, "0.3.75");
92967
+ return runBridge2(args, "0.3.77");
92868
92968
  }
92869
92969
  main().then((code) => {
92870
92970
  process.exitCode = code;
@@ -145,6 +145,11 @@ export const REGISTRY = [
145
145
  { name: "ask", usage: 'phren browser ask "<reason>" [--browser <id>] [--timeout <s>]', summary: "Wait for owner help (900 s default); Ctrl-C cancels" },
146
146
  ],
147
147
  run: async (args) => { const { runBrowser } = await import("./bridge/browser-env.js"); return runBrowser(args); } },
148
+ {
149
+ name: "unpair", topic: "setup", usage: "phren unpair [<number> | SHA256:<fingerprint> | --all | --notifications]",
150
+ summary: "List the phones paired with this computer, or remove one, end its open connections and stop its notifications",
151
+ run: async (args) => { const { runUnpair } = await import("./bridge/unpair.js"); return runUnpair(args); },
152
+ },
148
153
  {
149
154
  name: "pair", topic: "setup", usage: "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|->",
150
155
  summary: "Connect your phone with a pairing QR code, or authorize a scoped key for gitboy (gitboy-read: project memory; gitboy-write: save findings)",
@@ -69,7 +69,7 @@ export const BUILTIN_MODULES = [
69
69
  tools: [],
70
70
  cliCommands: [
71
71
  "bridge", "bridge install", "bridge update", "bridge uninstall", "bridge rollback", "bridge status",
72
- "browser", "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair",
72
+ "browser", "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair", "unpair",
73
73
  "bridge fanouts archive", "bridge accounts", "bridge askpass", "canary", "computers", "computers mcp", "usage", "sudo",
74
74
  ],
75
75
  agentHooks: [
@@ -90,7 +90,7 @@ export const BUILTIN_MODULES = [
90
90
  "/v1/subagents", "/v1/subagents/transcript", "/v1/subagents/messages", "/v1/sessions/move", "/v1/sessions/moves", "/v1/sessions/move/computers", "/v1/sessions/move/availability", "/v1/sessions/move/intent", "/v1/sessions/move/launch", "/v1/dispatch/relocation", "/v1/dispatch/arrival",
91
91
  ]),
92
92
  ...routes("POST", [
93
- "/v1/push/register", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
93
+ "/v1/push/register", "/v1/push/forget", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
94
94
  "/v1/workspaces/launch", "/v1/workspaces/create", "/v1/workspaces/focus", "/v1/workspaces/rename",
95
95
  "/v1/workspaces/close", "/v1/sessions/rename", "/v1/sessions/seen", "/v1/sessions/move", "/v1/accounts/claude/add", "/v1/accounts/claude/settings", "/v1/accounts/allowed-pools", "/v1/sessions/move/abort", "/v1/sessions/move/launch", "/v1/prompt", "/v1/prompt/status", "/v1/prompt/after-turn", "/v1/prompt/after-turn/list", "/v1/prompt/after-turn/edit", "/v1/prompt/after-turn/cancel", "/v1/prompt/queue", "/v1/model", "/v1/settings", "/v1/agents/permission-mode", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
96
96
  "/v1/approvals/answer", "/v1/questions/answer", "/v1/subagents/resume", "/v1/subagents/archive-finished", "/v1/canary",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.75",
3
+ "version": "0.3.77",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {