@phren/cli 0.3.72 → 0.3.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/bridge/agent-hooks.js +11 -1
  2. package/dist/bridge/browser-env.d.ts +1 -1
  3. package/dist/bridge/browser-env.js +34 -10
  4. package/dist/bridge/browser-watch.d.ts +12 -0
  5. package/dist/bridge/browser-watch.js +83 -0
  6. package/dist/bridge/claude-account-setup.js +3 -1
  7. package/dist/bridge/claude-accounts.d.ts +5 -1
  8. package/dist/bridge/claude-accounts.js +36 -6
  9. package/dist/bridge/claude-question-dialog.d.ts +2 -3
  10. package/dist/bridge/claude-question-dialog.js +129 -46
  11. package/dist/bridge/codex-servers.d.ts +2 -0
  12. package/dist/bridge/codex-servers.js +1 -1
  13. package/dist/bridge/command.js +24 -5
  14. package/dist/bridge/conductor-sets.d.ts +2 -1
  15. package/dist/bridge/conductor-sets.js +3 -2
  16. package/dist/bridge/dialog-observation.d.ts +4 -0
  17. package/dist/bridge/dialog-observation.js +24 -0
  18. package/dist/bridge/dispatch-clone.d.ts +33 -0
  19. package/dist/bridge/dispatch-clone.js +176 -0
  20. package/dist/bridge/dispatch-command.d.ts +14 -0
  21. package/dist/bridge/dispatch-command.js +98 -13
  22. package/dist/bridge/dispatch-idempotency.d.ts +85 -0
  23. package/dist/bridge/dispatch-idempotency.js +235 -0
  24. package/dist/bridge/dispatch-returns.d.ts +6 -0
  25. package/dist/bridge/dispatch-returns.js +131 -1
  26. package/dist/bridge/dispatch-wait.d.ts +32 -0
  27. package/dist/bridge/dispatch-wait.js +177 -0
  28. package/dist/bridge/dispatch.d.ts +68 -2
  29. package/dist/bridge/dispatch.js +839 -25
  30. package/dist/bridge/fanouts.js +20 -3
  31. package/dist/bridge/files.d.ts +1 -1
  32. package/dist/bridge/git-credential.d.ts +44 -0
  33. package/dist/bridge/git-credential.js +113 -0
  34. package/dist/bridge/git-host-auth.d.ts +9 -1
  35. package/dist/bridge/git-host-auth.js +18 -5
  36. package/dist/bridge/git-host-gitboy.js +8 -1
  37. package/dist/bridge/git-hosts.d.ts +12 -1
  38. package/dist/bridge/git-publish.js +3 -2
  39. package/dist/bridge/herdr.d.ts +4 -0
  40. package/dist/bridge/herdr.js +29 -3
  41. package/dist/bridge/install.d.ts +1 -1
  42. package/dist/bridge/install.js +8 -4
  43. package/dist/bridge/launch-worktree.d.ts +2 -0
  44. package/dist/bridge/launch-worktree.js +5 -1
  45. package/dist/bridge/pane-status.js +2 -19
  46. package/dist/bridge/protocol.d.ts +7 -0
  47. package/dist/bridge/schedule-watch.js +13 -2
  48. package/dist/bridge/server-launch.d.ts +2 -0
  49. package/dist/bridge/server-launch.js +251 -145
  50. package/dist/bridge/server-pane-routes.d.ts +1 -1
  51. package/dist/bridge/server-pane-routes.js +12 -9
  52. package/dist/bridge/server-routes.js +26 -8
  53. package/dist/bridge/server.js +12 -1
  54. package/dist/bridge/status-line-fast.d.ts +9 -0
  55. package/dist/bridge/status-line-fast.js +56 -0
  56. package/dist/bridge/terminal-herdr.d.ts +5 -1
  57. package/dist/bridge/terminal-herdr.js +65 -1
  58. package/dist/bridge/terminal-tmux.d.ts +6 -0
  59. package/dist/bridge/terminal-tmux.js +38 -11
  60. package/dist/bridge/terminal.d.ts +5 -1
  61. package/dist/bridge/transcript-claude.d.ts +7 -0
  62. package/dist/bridge/transcript-claude.js +227 -112
  63. package/dist/bridge/transcript-preview.d.ts +2 -1
  64. package/dist/bridge/transcript-preview.js +85 -3
  65. package/dist/bridge/transcripts.js +17 -11
  66. package/dist/bridge/turn-records.js +16 -4
  67. package/dist/bridge/usage.d.ts +7 -1
  68. package/dist/bridge/usage.js +47 -31
  69. package/dist/bridge/worker-close.d.ts +15 -0
  70. package/dist/bridge/worker-close.js +304 -3
  71. package/dist/bridge/worker-identity.d.ts +51 -0
  72. package/dist/bridge/worker-identity.js +289 -0
  73. package/dist/bridge-hook.mjs +22097 -19129
  74. package/dist/cli/browser-hint.d.ts +2 -0
  75. package/dist/cli/browser-hint.js +21 -0
  76. package/dist/cli/hooks-context.d.ts +2 -2
  77. package/dist/cli/hooks-context.js +3 -3
  78. package/dist/cli/hooks.js +20 -11
  79. package/dist/cli-registry.js +5 -3
  80. package/dist/modules/registry.js +1 -1
  81. package/package.json +3 -3
@@ -120,6 +120,9 @@ export async function containedFanoutRoot(env) {
120
120
  }
121
121
  }
122
122
  async function regularContainedFile(root, candidate, maxBytes) {
123
+ return (await containedFileStat(root, candidate, maxBytes))?.resolved;
124
+ }
125
+ async function containedFileStat(root, candidate, maxBytes) {
123
126
  try {
124
127
  const link = await lstat(candidate);
125
128
  if (!link.isFile() || link.isSymbolicLink() || link.size > maxBytes)
@@ -128,12 +131,26 @@ async function regularContainedFile(root, candidate, maxBytes) {
128
131
  if (!resolved.startsWith(root + path.sep))
129
132
  return;
130
133
  const metadata = await stat(resolved);
131
- return metadata.isFile() && metadata.size <= maxBytes ? resolved : undefined;
134
+ return metadata.isFile() && metadata.size <= maxBytes ? { resolved, stamp: `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}` } : undefined;
132
135
  }
133
136
  catch {
134
137
  return;
135
138
  }
136
139
  }
140
+ /** Parsed manifests by file, while unchanged: every conversation's child tree reads every job's manifest
141
+ * to find its own, so parsing them each time cost the Hook per session per overview. */
142
+ const manifestCache = new Map();
143
+ async function readManifest(file) {
144
+ const cached = manifestCache.get(file.resolved);
145
+ if (cached?.stamp === file.stamp)
146
+ return cached.manifest;
147
+ const manifest = manifestSchema.parse(JSON.parse(await readFile(file.resolved, "utf8")));
148
+ manifestCache.delete(file.resolved);
149
+ manifestCache.set(file.resolved, { stamp: file.stamp, manifest });
150
+ while (manifestCache.size > MAX_JOBS * 2)
151
+ manifestCache.delete(manifestCache.keys().next().value);
152
+ return manifest;
153
+ }
137
154
  export async function nativeClaudeTranscript(candidate, session) {
138
155
  if (path.basename(candidate) !== `${session}.jsonl`)
139
156
  return;
@@ -219,11 +236,11 @@ export async function fanoutChildren(parentProvider, parentSession, env = proces
219
236
  const children = [];
220
237
  for (const name of names) {
221
238
  const directory = path.join(root, name);
222
- const manifestFile = await regularContainedFile(root, path.join(directory, "manifest.json"), MAX_MANIFEST_BYTES);
239
+ const manifestFile = await containedFileStat(root, path.join(directory, "manifest.json"), MAX_MANIFEST_BYTES);
223
240
  if (!manifestFile)
224
241
  continue;
225
242
  try {
226
- const manifest = manifestSchema.parse(JSON.parse(await readFile(manifestFile, "utf8")));
243
+ const manifest = await readManifest(manifestFile);
227
244
  if (manifest.id !== name || manifest.parent?.provider !== parentProvider || manifest.parent.session !== parentSession
228
245
  || (manifest.parent.computer !== undefined && parentComputer !== undefined && manifest.parent.computer !== parentComputer))
229
246
  continue;
@@ -1,5 +1,6 @@
1
1
  /** Read-only browsing beneath a root selected and verified by the server. */
2
2
  export declare function browseFiles(root: string, relative: string): Promise<{
3
+ size?: undefined;
3
4
  path: string;
4
5
  kind: string;
5
6
  truncated: boolean;
@@ -8,7 +9,6 @@ export declare function browseFiles(root: string, relative: string): Promise<{
8
9
  path: string;
9
10
  kind: string;
10
11
  }[];
11
- size?: undefined;
12
12
  data?: undefined;
13
13
  } | {
14
14
  truncated?: undefined;
@@ -0,0 +1,44 @@
1
+ import { type GitHost } from "./git-hosts.js";
2
+ /**
3
+ * The gitboy path's credentials. The Hook's stored `gba_` agent token is the
4
+ * only one a keyed dispatch may use: a credential helper in the worktree's own
5
+ * config answers git, and the agent environment carries the same token for the
6
+ * API. The token never enters argv, a remote URL or a log.
7
+ */
8
+ /** Variables a keyed worker may inherit from the Hook's own environment. */
9
+ export declare const KEYED_ENV_ALLOW: readonly ["HOME", "USER", "LOGNAME", "PATH", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR"];
10
+ /**
11
+ * The exact environment for a keyed worker: a small allowlist plus the values
12
+ * this Hook owns. Nothing else from process.env is copied, so no caller or
13
+ * Hook token reaches the harness.
14
+ */
15
+ export declare function keyedExplicitEnv(base?: NodeJS.ProcessEnv, extra?: Record<string, string>): Record<string, string>;
16
+ /** The credential-free HTTPS remote for a gitboy host, or a refusal when owner/repo cannot be derived. */
17
+ export declare function credentialFreeRemote(host: Pick<GitHost, "domain" | "webUrl">): string;
18
+ /** Write the agent token to an exact private file path. */
19
+ export declare function writeAgentTokenFileAt(file: string, token: string): Promise<string>;
20
+ /** Remove a token file this Hook wrote; only the expected file name is ever touched. */
21
+ export declare function removeAgentTokenFile(file: string | undefined): Promise<void>;
22
+ export interface KeyedGitboy {
23
+ env: Record<string, string>;
24
+ tokenFile: string;
25
+ }
26
+ export interface KeyedGitboyOptions {
27
+ /** The exact token file path (the clone's git dir). */
28
+ tokenFile: string;
29
+ /** The managed global config the clone and the agent use. */
30
+ gitConfigFile?: string;
31
+ }
32
+ /**
33
+ * A keyed dispatch in a gitboy checkout uses this computer's stored agent token
34
+ * and fails closed when there is none. The token goes to a 0600 file; the agent
35
+ * gets only GITBOY_TOKEN_FILE (and, for a clone, its managed GIT_CONFIG_GLOBAL).
36
+ */
37
+ export declare function prepareKeyedGitboy(cwd: string, options: KeyedGitboyOptions): Promise<KeyedGitboy | undefined>;
38
+ /** A git credential request for a host with a stored gitboy token, answered for `get` only. */
39
+ export declare function gitCredentialAnswer(request: string): Promise<{
40
+ username: string;
41
+ password: string;
42
+ } | undefined>;
43
+ /** The `phren bridge git-credential` helper: get answers, store and erase do nothing. */
44
+ export declare function gitCredentialCommand(operation: string | undefined, request: string): Promise<string | undefined>;
@@ -0,0 +1,113 @@
1
+ import { mkdir, open, unlink } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { detectHost } from "./git-hosts.js";
4
+ import { resolveAgentToken } from "./git-host-auth.js";
5
+ import { BridgeError } from "./protocol.js";
6
+ /**
7
+ * The gitboy path's credentials. The Hook's stored `gba_` agent token is the
8
+ * only one a keyed dispatch may use: a credential helper in the worktree's own
9
+ * config answers git, and the agent environment carries the same token for the
10
+ * API. The token never enters argv, a remote URL or a log.
11
+ */
12
+ /** Variables a keyed worker may inherit from the Hook's own environment. */
13
+ export const KEYED_ENV_ALLOW = ["HOME", "USER", "LOGNAME", "PATH", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR"];
14
+ const KEYED_ENV_CONFIG_DIRS = ["CODEX_HOME", "CLAUDE_CONFIG_DIR"];
15
+ /**
16
+ * The exact environment for a keyed worker: a small allowlist plus the values
17
+ * this Hook owns. Nothing else from process.env is copied, so no caller or
18
+ * Hook token reaches the harness.
19
+ */
20
+ export function keyedExplicitEnv(base = process.env, extra = {}) {
21
+ const env = {};
22
+ for (const key of [...KEYED_ENV_ALLOW, ...KEYED_ENV_CONFIG_DIRS]) {
23
+ const value = base[key];
24
+ if (typeof value === "string")
25
+ env[key] = value;
26
+ }
27
+ return { ...env, ...extra };
28
+ }
29
+ /** The credential-free HTTPS remote for a gitboy host, or a refusal when owner/repo cannot be derived. */
30
+ export function credentialFreeRemote(host) {
31
+ if (!host.domain || !host.webUrl)
32
+ throw new BridgeError(409, "This gitboy checkout has no owner/repository in its remote URL, so a keyed dispatch cannot use it.");
33
+ let pathname;
34
+ try {
35
+ pathname = new URL(host.webUrl).pathname;
36
+ }
37
+ catch {
38
+ throw new BridgeError(409, "This gitboy checkout's remote URL cannot be parsed.");
39
+ }
40
+ const parts = pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
41
+ if (parts.length !== 2 || !parts[0] || !parts[1])
42
+ throw new BridgeError(409, "This gitboy checkout has no owner/repository in its remote URL, so a keyed dispatch cannot use it.");
43
+ return `https://${host.domain}/${parts[0]}/${parts[1]}.git`;
44
+ }
45
+ /** Write the agent token to an exact private file path. */
46
+ export async function writeAgentTokenFileAt(file, token) {
47
+ if (!path.isAbsolute(file) || path.basename(file) !== "phren-agent-token")
48
+ throw new BridgeError(409, "The agent token file path is not valid.");
49
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
50
+ const handle = await open(file, "wx", 0o600).catch(error => {
51
+ if (error.code === "EEXIST")
52
+ throw new BridgeError(409, "An agent token file already exists in this checkout; close the earlier dispatch first.");
53
+ throw error;
54
+ });
55
+ try {
56
+ await handle.writeFile(token);
57
+ await handle.sync();
58
+ }
59
+ finally {
60
+ await handle.close();
61
+ }
62
+ return file;
63
+ }
64
+ /** Remove a token file this Hook wrote; only the expected file name is ever touched. */
65
+ export async function removeAgentTokenFile(file) {
66
+ if (!file || !path.isAbsolute(file) || path.basename(file) !== "phren-agent-token")
67
+ return;
68
+ await unlink(file).catch(() => undefined);
69
+ }
70
+ /**
71
+ * A keyed dispatch in a gitboy checkout uses this computer's stored agent token
72
+ * and fails closed when there is none. The token goes to a 0600 file; the agent
73
+ * gets only GITBOY_TOKEN_FILE (and, for a clone, its managed GIT_CONFIG_GLOBAL).
74
+ */
75
+ export async function prepareKeyedGitboy(cwd, options) {
76
+ const host = await detectHost(cwd, "");
77
+ // Keyed dispatches exist for gitboy's runner. A checkout Phren can't place
78
+ // on a gitboy host with an agent token is refused, never launched with
79
+ // whatever git credentials the computer happens to have.
80
+ const stored = host.domain ? await resolveAgentToken(host.domain) : undefined;
81
+ if (!host.domain || !stored) {
82
+ const domain = host.domain ?? "this checkout's host";
83
+ throw new BridgeError(409, `No gitboy agent token for ${domain}. Run phren bridge git-host set ${domain} gitboy with a gba_ token.`);
84
+ }
85
+ const tokenFile = await writeAgentTokenFileAt(options.tokenFile, stored.token);
86
+ return {
87
+ env: {
88
+ GITBOY_HOST: host.domain,
89
+ GITBOY_TOKEN_FILE: tokenFile,
90
+ GIT_TERMINAL_PROMPT: "0",
91
+ ...(options.gitConfigFile ? { GIT_CONFIG_GLOBAL: options.gitConfigFile, GIT_CONFIG_NOSYSTEM: "1" } : {}),
92
+ },
93
+ tokenFile,
94
+ };
95
+ }
96
+ /** A git credential request for a host with a stored gitboy token, answered for `get` only. */
97
+ export async function gitCredentialAnswer(request) {
98
+ const protocol = /(?:^|\n)protocol=(.+)/.exec(request)?.[1]?.trim().toLowerCase();
99
+ const host = /(?:^|\n)host=(.+)/.exec(request)?.[1]?.trim().toLowerCase().replace(/\.$/, "").replace(/:\d+$/, "");
100
+ if (protocol !== "https" || !host)
101
+ return undefined;
102
+ const stored = await resolveAgentToken(host);
103
+ if (!stored)
104
+ return undefined;
105
+ return { username: "x-token", password: stored.token };
106
+ }
107
+ /** The `phren bridge git-credential` helper: get answers, store and erase do nothing. */
108
+ export async function gitCredentialCommand(operation, request) {
109
+ if (operation !== "get")
110
+ return undefined;
111
+ const answer = await gitCredentialAnswer(request);
112
+ return answer ? `username=${answer.username}\npassword=${answer.password}\n` : undefined;
113
+ }
@@ -13,22 +13,30 @@ export interface HostToken {
13
13
  token: string;
14
14
  source: TokenSource;
15
15
  user?: string;
16
+ agent?: true;
16
17
  }
17
18
  export declare function gitHostsFile(): string;
18
19
  /** Store (or, with an empty token, forget) one domain's token. */
19
- export declare function writeHostToken(domain: string, kind: TokenHostKind, token: string, user?: string, file?: string): Promise<void>;
20
+ export declare function writeHostToken(domain: string, kind: TokenHostKind, token: string, user?: string, file?: string, agent?: boolean): Promise<void>;
20
21
  export interface TokenLookup {
21
22
  env?: NodeJS.ProcessEnv;
22
23
  file?: string;
23
24
  cli?: boolean;
24
25
  }
25
26
  export declare function resolveHostToken(kind: TokenHostKind, domain: string, options?: TokenLookup): Promise<HostToken | undefined>;
27
+ /**
28
+ * The gitboy agent token for a domain: only a token `phren bridge git-host set`
29
+ * marked `agent: true` and that carries the `gba_` prefix. Keyed dispatches
30
+ * use this and nothing else.
31
+ */
32
+ export declare function resolveAgentToken(domain: string, file?: string): Promise<HostToken | undefined>;
26
33
  /** Each stored domain with its kind and who it signs in as. Never a token. */
27
34
  export declare function listHostTokens(file?: string): Promise<{
28
35
  domain: string;
29
36
  kind: TokenHostKind;
30
37
  user?: string;
31
38
  savedAt?: string;
39
+ agent?: true;
32
40
  }[] | "unsafe">;
33
41
  /** Credential fingerprint only: raw credentials never enter lookup keys.
34
42
  * gh logout/switch-user rewrites hosts.yml even when its token is in a keychain. */
@@ -38,7 +38,7 @@ async function readStore(file = gitHostsFile()) {
38
38
  const token = clean(entry.token);
39
39
  const kind = entry.kind === "gitlab" || entry.kind === "gitboy" ? entry.kind : null;
40
40
  if (token && kind)
41
- hosts[normalDomain(domain)] = { kind, token, ...(clean(entry.user) ? { user: clean(entry.user) } : {}), ...(clean(entry.savedAt) ? { savedAt: clean(entry.savedAt) } : {}) };
41
+ hosts[normalDomain(domain)] = { kind, token, ...(clean(entry.user) ? { user: clean(entry.user) } : {}), ...(clean(entry.savedAt) ? { savedAt: clean(entry.savedAt) } : {}), ...(entry.agent === true ? { agent: true } : {}) };
42
42
  }
43
43
  }
44
44
  return { hosts };
@@ -48,7 +48,7 @@ async function readStore(file = gitHostsFile()) {
48
48
  }
49
49
  }
50
50
  /** Store (or, with an empty token, forget) one domain's token. */
51
- export async function writeHostToken(domain, kind, token, user, file = gitHostsFile()) {
51
+ export async function writeHostToken(domain, kind, token, user, file = gitHostsFile(), agent) {
52
52
  const key = normalDomain(domain);
53
53
  if (!key || /[\s/]/.test(key))
54
54
  throw new Error("That is not a host name.");
@@ -56,7 +56,7 @@ export async function writeHostToken(domain, kind, token, user, file = gitHostsF
56
56
  const hosts = current && current !== "unsafe" ? { ...current.hosts } : {};
57
57
  const value = clean(token);
58
58
  if (value)
59
- hosts[key] = { kind, token: value, ...(user ? { user } : {}), savedAt: new Date().toISOString() };
59
+ hosts[key] = { kind, token: value, ...(user ? { user } : {}), savedAt: new Date().toISOString(), ...(agent ? { agent: true } : {}) };
60
60
  else
61
61
  delete hosts[key];
62
62
  await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
@@ -97,7 +97,7 @@ export async function resolveHostToken(kind, domain, options = {}) {
97
97
  const store = await readStore(options.file);
98
98
  const stored = store && store !== "unsafe" ? store.hosts[key] : undefined;
99
99
  if (stored && stored.kind === kind)
100
- return { token: stored.token, source: "file", ...(stored.user ? { user: stored.user } : {}) };
100
+ return { token: stored.token, source: "file", ...(stored.user ? { user: stored.user } : {}), ...(stored.agent ? { agent: true } : {}) };
101
101
  if (options.cli !== false) {
102
102
  const cli = await fromCli(kind, key);
103
103
  if (cli)
@@ -105,12 +105,25 @@ export async function resolveHostToken(kind, domain, options = {}) {
105
105
  }
106
106
  return undefined;
107
107
  }
108
+ /**
109
+ * The gitboy agent token for a domain: only a token `phren bridge git-host set`
110
+ * marked `agent: true` and that carries the `gba_` prefix. Keyed dispatches
111
+ * use this and nothing else.
112
+ */
113
+ export async function resolveAgentToken(domain, file = gitHostsFile()) {
114
+ const key = normalDomain(domain);
115
+ const store = await readStore(file);
116
+ const stored = store && store !== "unsafe" ? store.hosts[key] : undefined;
117
+ if (!stored || stored.kind !== "gitboy" || stored.agent !== true || !stored.token.startsWith("gba_"))
118
+ return undefined;
119
+ return { token: stored.token, source: "file", agent: true, ...(stored.user ? { user: stored.user } : {}) };
120
+ }
108
121
  /** Each stored domain with its kind and who it signs in as. Never a token. */
109
122
  export async function listHostTokens(file = gitHostsFile()) {
110
123
  const store = await readStore(file);
111
124
  if (store === "unsafe")
112
125
  return "unsafe";
113
- return Object.entries(store?.hosts ?? {}).map(([domain, { kind, user, savedAt }]) => ({ domain, kind, ...(user ? { user } : {}), ...(savedAt ? { savedAt } : {}) }));
126
+ return Object.entries(store?.hosts ?? {}).map(([domain, { kind, user, savedAt, agent }]) => ({ domain, kind, ...(user ? { user } : {}), ...(savedAt ? { savedAt } : {}), ...(agent ? { agent: true } : {}) }));
114
127
  }
115
128
  /** Credential fingerprint only: raw credentials never enter lookup keys.
116
129
  * gh logout/switch-user rewrites hosts.yml even when its token is in a keychain. */
@@ -291,6 +291,13 @@ export const gitboy = {
291
291
  throw new HostApiError("failed", "This repository has no gitboy remote.");
292
292
  const api = checkedApi ?? await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
293
293
  const { json } = await hostJson(`${api}/user`, { token, scheme: "bearer" });
294
- return { user: String(obj(json).username ?? "") };
294
+ const user = obj(json);
295
+ const agent = obj(user.agent_token);
296
+ const identity = {
297
+ ...(typeof agent.name === "string" && agent.name ? { name: agent.name } : {}),
298
+ ...(Array.isArray(agent.repo_ids) ? { repo_ids: agent.repo_ids } : {}),
299
+ ...(typeof agent.expires_at === "string" && agent.expires_at ? { expires_at: agent.expires_at } : {}),
300
+ };
301
+ return { user: String(user.username ?? ""), ...(Object.keys(agent).length ? { agent: identity, agent_token: identity } : {}) };
295
302
  },
296
303
  };
@@ -63,9 +63,20 @@ export interface GitHostProvider {
63
63
  * tool picks it rather than the remote (gh prefers an `upstream` or its `repo set-default`). Without it,
64
64
  * the remote's `webUrl` is that repository. Null when it cannot be told. */
65
65
  repository?(root: string, host: GitHost): Promise<string | null>;
66
- /** Who a token signs in as, for Connect; HTTP hosts only. */
66
+ /** Who a token signs in as, for Connect; HTTP hosts only. A gitboy agent
67
+ * token also reports the agent identity the host attached to it. */
67
68
  whoami?(root: string, host: GitHost, token: string, api?: string): Promise<{
68
69
  user: string;
70
+ agent?: {
71
+ name?: string;
72
+ repo_ids?: unknown[];
73
+ expires_at?: string;
74
+ };
75
+ agent_token?: {
76
+ name?: string;
77
+ repo_ids?: unknown[];
78
+ expires_at?: string;
79
+ };
69
80
  }>;
70
81
  }
71
82
  export type MergeMethod = "merge" | "squash" | "rebase";
@@ -272,8 +272,9 @@ export async function gitHostToken(cwd, data) {
272
272
  try {
273
273
  const identity = await provider.whoami(root, host, token.trim(), api);
274
274
  const user = identity.user.replaceAll(token.trim(), "[redacted]");
275
- await writeHostToken(host.domain, kind, token.trim(), user || undefined);
276
- return { ok: true, domain: host.domain, kind, ...(user ? { user } : {}), host };
275
+ const agent = identity.agent ?? identity.agent_token;
276
+ await writeHostToken(host.domain, kind, token.trim(), user || undefined, undefined, !!agent);
277
+ return { ok: true, domain: host.domain, kind, ...(user ? { user } : {}), ...(agent ? { agent: true } : {}), host };
277
278
  }
278
279
  catch (error) {
279
280
  if (error instanceof HostApiError)
@@ -92,6 +92,10 @@ export declare function opencodePidSession(pids: number[], root?: string): Promi
92
92
  * inside a Codex daemon and so cannot name its pane. Falls back to the only
93
93
  * Codex pane in the callback's folder while that pane shows no conversation. */
94
94
  export declare function paneForCodexSession(server: string, session: string, cwd?: string): Promise<Json | undefined>;
95
+ export declare function seedStartingToken(server: string, pane: Json, token: string): void;
96
+ export declare function paneStartingToken(server: string, pane: Json): string | undefined;
97
+ export declare function clearStartingToken(server: string, pane: Json): void;
98
+ export declare function clearStartingTokenByToken(token: string): void;
95
99
  /** Bind first-send permission to the actual terminal/process, never a cwd or
96
100
  * a guessed conversation. Tokens expire naturally when the Hook/process restarts. */
97
101
  export declare function paneChatState(server: string, pane: Json, options?: {
@@ -1,3 +1,4 @@
1
+ import { paneBrowserWatch } from "./browser-watch.js";
1
2
  import { createHmac, randomBytes } from "node:crypto";
2
3
  import { paneAccount, paneAccountKey, notePaneTranscript } from "./pane-accounts.js";
3
4
  import { execFile } from "node:child_process";
@@ -585,6 +586,29 @@ export async function paneForCodexSession(server, session, cwd) {
585
586
  const startingKey = randomBytes(32);
586
587
  const startingBindings = new Map();
587
588
  const startingPaneKey = (server, pane) => JSON.stringify([server, pane.workspace_id, pane.tab_id, pane.pane_id, pane.terminal_id, pane.agent]);
589
+ const seededPaneKey = (server, pane) => JSON.stringify([server, pane.workspace_id, pane.tab_id, pane.pane_id]);
590
+ /** Tokens supplied by a launch, keyed by pane coordinates, so an ambiguous
591
+ * launch can be resolved by finding the pane that carries its token. */
592
+ const seededStartingTokens = new Map();
593
+ export function seedStartingToken(server, pane, token) {
594
+ if (!/^[a-f0-9]{64}$/.test(token))
595
+ return;
596
+ seededStartingTokens.set(seededPaneKey(server, pane), token);
597
+ const binding = startingBindings.get(startingPaneKey(server, pane));
598
+ if (binding)
599
+ binding.token = token;
600
+ }
601
+ export function paneStartingToken(server, pane) {
602
+ return seededStartingTokens.get(seededPaneKey(server, pane));
603
+ }
604
+ export function clearStartingToken(server, pane) {
605
+ seededStartingTokens.delete(seededPaneKey(server, pane));
606
+ }
607
+ export function clearStartingTokenByToken(token) {
608
+ for (const [key, value] of seededStartingTokens)
609
+ if (value === token)
610
+ seededStartingTokens.delete(key);
611
+ }
588
612
  const startingToken = (process) => createHmac("sha256", startingKey).update(process).update(randomBytes(32)).digest("hex");
589
613
  /** Remember the first identified conversation even when an overview skips the
590
614
  * PID probe. A later conversation in the same process retires its old token. */
@@ -606,13 +630,14 @@ export async function paneChatState(server, pane, options = {}) {
606
630
  return {};
607
631
  const identity = await resolveIdentity(server, pane, false);
608
632
  const sessionId = identity.sessionId;
633
+ const watch = paneBrowserWatch(server, pane, sessionId, identity.pids?.[0] ?? (typeof pane.agent_pid === "number" ? pane.agent_pid : undefined));
609
634
  const key = startingPaneKey(server, pane);
610
635
  if (sessionId)
611
636
  identifyStartingBinding(key, sessionId);
612
637
  // A pane whose conversation is known is not starting, so a caller that
613
638
  // reads only `sessionId` and `starting` (the overview) needs no PIDs.
614
639
  if (sessionId && options.tokenWhenIdentified === false)
615
- return { sessionId };
640
+ return { sessionId, browserWatch: watch };
616
641
  const pids = identity.pids ?? await foregroundPids(server, pane);
617
642
  // The token binds to the agent's own process, the oldest in the pane's
618
643
  // foreground group. Helpers it spawns while starting up (Codex forks
@@ -629,14 +654,15 @@ export async function paneChatState(server, pane, options = {}) {
629
654
  // Lost identity, changed process, or newly ambiguous evidence requires a
630
655
  // new token. Never revive a previous conversation's first-send permission.
631
656
  if (!binding || binding.process !== process || (!sessionId && (!!binding.sessionId || binding.wasStarting !== starting))) {
632
- binding = { process, token: startingToken(process), wasStarting: starting,
657
+ const seeded = seededStartingTokens.get(seededPaneKey(server, pane));
658
+ binding = { process, token: seeded ?? startingToken(process), wasStarting: starting,
633
659
  ...(sessionId ? { sessionId, identifiedAt: Date.now() } : {}) };
634
660
  if (startingBindings.size >= 256)
635
661
  startingBindings.delete(startingBindings.keys().next().value);
636
662
  startingBindings.set(key, binding);
637
663
  }
638
664
  }
639
- return { sessionId, ...(process && binding ? { startingToken: binding.token } : {}), ...(starting ? { starting: true } : {}) };
665
+ return { sessionId, browserWatch: paneBrowserWatch(server, pane, sessionId, pids[0]), ...(process && binding ? { startingToken: binding.token } : {}), ...(starting ? { starting: true } : {}) };
640
666
  }
641
667
  /** `{ account }` for a Claude pane whose account is known, else nothing. */
642
668
  export function paneAccountField(server, pane) {
@@ -69,7 +69,7 @@ interface SettingsEdit {
69
69
  before?: string;
70
70
  after: string;
71
71
  }
72
- export declare function planAgentHooks(program: string, remove?: boolean, modules?: ModuleSnapshot, fastClaude?: boolean): Promise<SettingsEdit[]>;
72
+ export declare function planAgentHooks(program: string, remove?: boolean, modules?: ModuleSnapshot, fastClaude?: boolean, fastStatusLine?: boolean): Promise<SettingsEdit[]>;
73
73
  /** The first line of every plugin copy phren wrote; a copy without it belongs to the user. */
74
74
  export declare const OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
75
75
  /** Whether to (re)write the installed plugin: a missing copy, or one phren wrote that is now out of date. */
@@ -16,6 +16,7 @@ import { bridgeRoot, object, objects, atomic, socketPath } from "./protocol.js";
16
16
  import { herdrRoot } from "./herdr.js";
17
17
  import { health } from "./transport.js";
18
18
  import { FAST_HOOK_SOURCE, fastHookPath } from "./hook-fast.js";
19
+ import { FAST_STATUS_LINE_SOURCE, fastStatusLinePath } from "./status-line-fast.js";
19
20
  import { installAskpass, removeAskpass } from "./sudo.js";
20
21
  import { readStoredVoice, SPEECH_VOICE_ENV, writeSpeechVoice } from "./speech-voice.js";
21
22
  import { carryCodexHookTrust } from "./codex-hook-trust.js";
@@ -304,6 +305,7 @@ export async function install(version, noService = false, force = false) {
304
305
  await mkdir(shimDirectory, { recursive: true, mode: 0o700 });
305
306
  await atomic(path.join(shimDirectory, "phren-playwright.cjs"), typeof BROWSER_SHIM_SOURCE !== "undefined" ? BROWSER_SHIM_SOURCE : await readFile(browserShimPath(), "utf8"), 0o600);
306
307
  await atomic(fastHookPath(destination), FAST_HOOK_SOURCE);
308
+ await atomic(fastStatusLinePath(destination), FAST_STATUS_LINE_SOURCE);
307
309
  const previous = await readFile(path.join(root, "installed.json"), "utf8").then(v => JSON.parse(v)).catch(() => null);
308
310
  const gateway = await detectGateway();
309
311
  await atomic(path.join(root, "dispatch"), gatewayScript(gateway, {
@@ -432,7 +434,9 @@ async function missingFile(operation) {
432
434
  /** Whether the version `current/` points at ships the Claude forwarder; one
433
435
  * from before it does not, and its Claude callbacks run the bundle. */
434
436
  const currentHasFastHook = (root) => access(fastHookPath(path.join(root, "current"))).then(() => true, () => false);
435
- export async function planAgentHooks(program, remove = false, modules, fastClaude = true) {
437
+ /** Whether that version ships the status line forwarder; before it, the status line runs the bundle. */
438
+ const currentHasFastStatusLine = (root) => access(fastStatusLinePath(path.join(root, "current"))).then(() => true, () => false);
439
+ export async function planAgentHooks(program, remove = false, modules, fastClaude = true, fastStatusLine = fastClaude) {
436
440
  const edits = [];
437
441
  // Extra Claude homes (one per account) get the same hooks; a symlinked settings.json shares another home's, so it is skipped.
438
442
  const extraClaude = claudeHomes().slice(1).map(home => ["claude", path.join(home.dir, "settings.json")]);
@@ -497,7 +501,7 @@ export async function planAgentHooks(program, remove = false, modules, fastClaud
497
501
  }
498
502
  config.hooks = hooks;
499
503
  if (source === "claude") {
500
- const statusLine = usageStatusLine(config.statusLine, program, remove || modules?.has("hook") === false);
504
+ const statusLine = usageStatusLine(config.statusLine, fastStatusLine ? fastStatusLinePath(path.dirname(program)) : program, remove || modules?.has("hook") === false);
501
505
  if (statusLine === undefined)
502
506
  delete config.statusLine;
503
507
  else
@@ -586,7 +590,7 @@ export async function rollback() {
586
590
  // forwarder or, from before the forwarder, its bundle.
587
591
  const root = bridgeRoot();
588
592
  const program = path.join(root, "current/bridge-hook.mjs");
589
- const edits = await planAgentHooks(program, false, moduleSnapshot(defaultPhrenPath(), undefined, true), await currentHasFastHook(root));
593
+ const edits = await planAgentHooks(program, false, moduleSnapshot(defaultPhrenPath(), undefined, true), await currentHasFastHook(root), await currentHasFastStatusLine(root));
590
594
  await applyAgentHooks(edits);
591
595
  await carryCodexHookTrust(program, codexHooksBefore(edits));
592
596
  await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version, ...(config.store ? { store: config.store } : {}) }) + "\n");
@@ -610,7 +614,7 @@ export async function reconcileModuleHooks(store, profile) {
610
614
  if (typeof served === "string" && path.resolve(served) !== path.resolve(store))
611
615
  return;
612
616
  const program = path.join(root, "current/bridge-hook.mjs");
613
- const edits = await planAgentHooks(program, false, modules, await currentHasFastHook(root));
617
+ const edits = await planAgentHooks(program, false, modules, await currentHasFastHook(root), await currentHasFastStatusLine(root));
614
618
  await applyAgentHooks(edits);
615
619
  await carryCodexHookTrust(program, codexHooksBefore(edits));
616
620
  await applyOpencodePlugin(!modules.has("hook"));
@@ -17,5 +17,7 @@ export interface LaunchWorktree {
17
17
  /** Removes the worktree and its branch when the launch fails before anything ran there. */
18
18
  discard(): Promise<void>;
19
19
  }
20
+ /** Git's empty tree: an attribute source that cannot name a repository .gitattributes. */
21
+ export declare const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
20
22
  /** Creates the worktree, or refuses with a message the phone shows as is. */
21
23
  export declare function createLaunchWorktree(cwd: string, request: LaunchWorktreeRequest): Promise<LaunchWorktree>;
@@ -28,6 +28,8 @@ export const launchWorktreeSchema = z.object({ branch: worktreeBranch }).strict(
28
28
  export function worktreeFolderName(branch) {
29
29
  return branch.replace(/[/.]+/g, "-").replace(/^-+|-+$/g, "") || "worktree";
30
30
  }
31
+ /** Git's empty tree: an attribute source that cannot name a repository .gitattributes. */
32
+ export const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
31
33
  /** Creates the worktree, or refuses with a message the phone shows as is. */
32
34
  export async function createLaunchWorktree(cwd, request) {
33
35
  const branch = request.branch;
@@ -48,8 +50,10 @@ export async function createLaunchWorktree(cwd, request) {
48
50
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
49
51
  }
50
52
  await mkdir(path.dirname(worktree), { recursive: true });
53
+ // No repository-selected hook or script runs before the agent starts:
54
+ // `git worktree add` would otherwise run the checkout's post-checkout hook.
51
55
  try {
52
- await git(root, "worktree", "add", "-b", branch, worktree, head);
56
+ await git(root, "-c", "core.hooksPath=/dev/null", "worktree", "add", "-b", branch, worktree, head);
53
57
  }
54
58
  catch (error) {
55
59
  const detail = error instanceof Error && "stderr" in error ? String(error.stderr ?? "").trim().split("\n").at(-1) : "";
@@ -23,9 +23,8 @@ import { readFile } from "node:fs/promises";
23
23
  import { stripTerminal } from "../terminal-text.js";
24
24
  import { bindingPath } from "./agent-hook-stores.js";
25
25
  import { claudeQuestionDialog } from "./claude-question-dialog.js";
26
- import { confirmDialogRead, DIALOG_READ_MS } from "./dialog-observation.js";
26
+ import { confirmDialogRead, dialogHasClosed, DIALOG_READ_MS } from "./dialog-observation.js";
27
27
  import { object } from "./protocol.js";
28
- import { claudeFooterMode } from "./claude-footer-mode.js";
29
28
  import { claudePermissionDialog, opencodePermissionDialog, visibleTerminalChoice } from "./terminal-choice.js";
30
29
  const EVENT_STATUS = {
31
30
  SessionStart: "idle", UserPromptSubmit: "working", PreToolUse: "working", PostToolUse: "working",
@@ -120,23 +119,7 @@ export function screenDialog(agent, screen) {
120
119
  export function screenDialogState(agent, screen) {
121
120
  if (screenDialog(agent, screen))
122
121
  return "shown";
123
- const lines = stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
124
- const composer = (line) => /^[❯›](?!\s*\d+[.)])(?:\s|$)/.test(line);
125
- const chrome = (line) => /^[─━═]+$/.test(line) || claudeFooterMode(line) !== undefined
126
- || /^(?:[←→?].*(?:agents|shortcuts)|(?:gpt-|GPT-|claude-|Claude ).*)/i.test(line);
127
- const liveTail = (index) => lines.slice(index + 1).every(line => composer(line) || chrome(line));
128
- let cue = -1;
129
- for (let index = 0; index < lines.length; index++) {
130
- if (/^(?:[>❯›]?\s*\d+[.)]|Do you want|Would you like|Ready to code|Allow\b|Trust\b|Teach auto|△\s*Permission|[☐☒]|.*Esc to cancel)/i.test(lines[index]))
131
- cue = index;
132
- }
133
- for (let index = lines.length - 1; index > cue; index--) {
134
- if (/\besc to interrupt\b/i.test(lines[index]) && liveTail(index))
135
- return "gone";
136
- if (index >= lines.length - 3 && composer(lines[index]) && liveTail(index))
137
- return "gone";
138
- }
139
- return "unknown";
122
+ return dialogHasClosed(screen) ? "gone" : "unknown";
140
123
  }
141
124
  const dialogs = new Map();
142
125
  /** The status of a pane after a look at its screen: blocked while its agent
@@ -44,6 +44,13 @@ export declare const startingTargetSchema: z.ZodObject<{
44
44
  startingToken: z.ZodString;
45
45
  }, z.core.$strip>;
46
46
  export type StartingTarget = z.infer<typeof startingTargetSchema>;
47
+ /** Optional live-session field: environment readiness, not a connected browser.
48
+ * On records a Hook launch or readable socket/session/preload environment;
49
+ * off requires a readable agent environment; unknown includes pending probes. */
50
+ export type BrowserWatch = "on" | "off" | "unknown";
51
+ export interface BrowserWatchField {
52
+ browserWatch?: BrowserWatch;
53
+ }
47
54
  export type Json = Record<string, unknown>;
48
55
  /** The decisions an approval answer may carry. An OpenCode permission ask
49
56
  * accepts both grant scopes; every other provider approves or denies only. */
@@ -297,6 +297,9 @@ function claudeUserText(raw) {
297
297
  return undefined;
298
298
  return blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)).join("\n");
299
299
  }
300
+ /** The last answer per transcript, kept while the file is unchanged: every overview asks for each pane
301
+ * that finished a turn, and parsing a 512 KiB tail each time was a steady cost. */
302
+ const finalTurnCache = new Map();
300
303
  /** The final turn of a conversation, read from the tail of its transcript. */
301
304
  export async function readFinalTurn(source, sessionId) {
302
305
  if (!sessionId)
@@ -308,11 +311,19 @@ export async function readFinalTurn(source, sessionId) {
308
311
  if (!handle)
309
312
  return undefined;
310
313
  try {
311
- const { size } = await handle.stat();
314
+ const { size, dev, ino, mtimeMs } = await handle.stat();
315
+ const key = `${source}\0${file}`, stamp = `${dev}:${ino}:${size}:${mtimeMs}`, cached = finalTurnCache.get(key);
316
+ if (cached?.stamp === stamp)
317
+ return cached.turn;
312
318
  const start = Math.max(0, size - FINAL_TURN_TAIL_BYTES), buffer = Buffer.alloc(size - start);
313
319
  await handle.read(buffer, 0, buffer.length, start);
314
320
  const lines = buffer.toString("utf8").split("\n");
315
- return finalTurnFromLines(start > 0 ? lines.slice(1) : lines, source);
321
+ const turn = finalTurnFromLines(start > 0 ? lines.slice(1) : lines, source);
322
+ finalTurnCache.delete(key);
323
+ finalTurnCache.set(key, { stamp, turn });
324
+ while (finalTurnCache.size > 128)
325
+ finalTurnCache.delete(finalTurnCache.keys().next().value);
326
+ return turn;
316
327
  }
317
328
  catch {
318
329
  return undefined;