@phren/cli 0.3.71 → 0.3.73

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 (164) hide show
  1. package/dist/bridge/agent-hooks.js +11 -1
  2. package/dist/bridge/browser-env.d.ts +5 -0
  3. package/dist/bridge/browser-env.js +110 -0
  4. package/dist/bridge/browser-protocol.d.ts +120 -0
  5. package/dist/bridge/browser-protocol.js +70 -0
  6. package/dist/bridge/browser-recordings.d.ts +63 -0
  7. package/dist/bridge/browser-recordings.js +148 -0
  8. package/dist/bridge/browser-registry.d.ts +64 -0
  9. package/dist/bridge/browser-registry.js +262 -0
  10. package/dist/bridge/browser-routes.d.ts +4 -0
  11. package/dist/bridge/browser-routes.js +39 -0
  12. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  13. package/dist/bridge/browser-socket.d.ts +2 -0
  14. package/dist/bridge/browser-socket.js +10 -0
  15. package/dist/bridge/browser-stream.d.ts +3 -0
  16. package/dist/bridge/browser-stream.js +129 -0
  17. package/dist/bridge/browser-watch.d.ts +12 -0
  18. package/dist/bridge/browser-watch.js +83 -0
  19. package/dist/bridge/claude-account-setup.js +3 -1
  20. package/dist/bridge/claude-accounts.d.ts +5 -1
  21. package/dist/bridge/claude-accounts.js +36 -6
  22. package/dist/bridge/codex-servers.d.ts +2 -0
  23. package/dist/bridge/codex-servers.js +1 -1
  24. package/dist/bridge/command.js +24 -5
  25. package/dist/bridge/dispatch-clone.d.ts +33 -0
  26. package/dist/bridge/dispatch-clone.js +176 -0
  27. package/dist/bridge/dispatch-command.d.ts +14 -0
  28. package/dist/bridge/dispatch-command.js +98 -13
  29. package/dist/bridge/dispatch-idempotency.d.ts +85 -0
  30. package/dist/bridge/dispatch-idempotency.js +235 -0
  31. package/dist/bridge/dispatch-returns.d.ts +6 -0
  32. package/dist/bridge/dispatch-returns.js +131 -1
  33. package/dist/bridge/dispatch-wait.d.ts +32 -0
  34. package/dist/bridge/dispatch-wait.js +177 -0
  35. package/dist/bridge/dispatch.d.ts +78 -2
  36. package/dist/bridge/dispatch.js +841 -25
  37. package/dist/bridge/dream-schedule.d.ts +133 -0
  38. package/dist/bridge/dream-schedule.js +322 -0
  39. package/dist/bridge/fanouts.js +20 -3
  40. package/dist/bridge/files.d.ts +1 -1
  41. package/dist/bridge/git-credential.d.ts +44 -0
  42. package/dist/bridge/git-credential.js +113 -0
  43. package/dist/bridge/git-host-auth.d.ts +9 -1
  44. package/dist/bridge/git-host-auth.js +18 -5
  45. package/dist/bridge/git-host-gitboy.js +8 -1
  46. package/dist/bridge/git-hosts.d.ts +12 -1
  47. package/dist/bridge/git-publish.js +3 -2
  48. package/dist/bridge/herdr.d.ts +4 -0
  49. package/dist/bridge/herdr.js +44 -9
  50. package/dist/bridge/install.d.ts +1 -1
  51. package/dist/bridge/install.js +12 -4
  52. package/dist/bridge/launch-brief.d.ts +11 -0
  53. package/dist/bridge/launch-brief.js +22 -0
  54. package/dist/bridge/launch-worktree.d.ts +2 -0
  55. package/dist/bridge/launch-worktree.js +5 -1
  56. package/dist/bridge/pane-status.js +1 -1
  57. package/dist/bridge/protocol.d.ts +7 -0
  58. package/dist/bridge/schedule-watch.js +13 -2
  59. package/dist/bridge/server-launch.d.ts +2 -0
  60. package/dist/bridge/server-launch.js +251 -145
  61. package/dist/bridge/server-routes.d.ts +3 -0
  62. package/dist/bridge/server-routes.js +33 -17
  63. package/dist/bridge/server-stream.d.ts +4 -0
  64. package/dist/bridge/server-stream.js +24 -5
  65. package/dist/bridge/server.js +35 -4
  66. package/dist/bridge/session-move.d.ts +10 -4
  67. package/dist/bridge/session-move.js +65 -34
  68. package/dist/bridge/simulator-stream.d.ts +2 -0
  69. package/dist/bridge/simulator-stream.js +2 -0
  70. package/dist/bridge/status-line-fast.d.ts +9 -0
  71. package/dist/bridge/status-line-fast.js +56 -0
  72. package/dist/bridge/tab-activity.d.ts +2 -0
  73. package/dist/bridge/tab-activity.js +15 -2
  74. package/dist/bridge/task-routes.d.ts +20 -16
  75. package/dist/bridge/task-routes.js +1 -1
  76. package/dist/bridge/terminal-herdr.d.ts +5 -1
  77. package/dist/bridge/terminal-herdr.js +67 -2
  78. package/dist/bridge/terminal-tmux.d.ts +2 -0
  79. package/dist/bridge/terminal-tmux.js +29 -7
  80. package/dist/bridge/terminal.d.ts +5 -1
  81. package/dist/bridge/transcript-claude.js +192 -112
  82. package/dist/bridge/transcript-preview.d.ts +2 -1
  83. package/dist/bridge/transcript-preview.js +85 -3
  84. package/dist/bridge/transcripts.js +17 -11
  85. package/dist/bridge/turn-records.js +16 -4
  86. package/dist/bridge/usage.d.ts +7 -1
  87. package/dist/bridge/usage.js +47 -31
  88. package/dist/bridge/worker-close.d.ts +15 -0
  89. package/dist/bridge/worker-close.js +304 -3
  90. package/dist/bridge/worker-identity.d.ts +51 -0
  91. package/dist/bridge/worker-identity.js +289 -0
  92. package/dist/bridge/worker-reports.js +15 -3
  93. package/dist/bridge-hook.mjs +39990 -36152
  94. package/dist/capabilities/mcp.js +1 -1
  95. package/dist/cli/browser-hint.d.ts +2 -0
  96. package/dist/cli/browser-hint.js +21 -0
  97. package/dist/cli/config-dreaming.d.ts +7 -0
  98. package/dist/cli/config-dreaming.js +72 -0
  99. package/dist/cli/config.js +6 -0
  100. package/dist/cli/dream.d.ts +59 -0
  101. package/dist/cli/dream.js +315 -0
  102. package/dist/cli/hooks-context.d.ts +2 -2
  103. package/dist/cli/hooks-context.js +3 -3
  104. package/dist/cli/hooks.js +20 -11
  105. package/dist/cli/namespaces-tasks.js +14 -0
  106. package/dist/cli-registry.js +28 -3
  107. package/dist/config/dreaming.d.ts +82 -0
  108. package/dist/config/dreaming.js +195 -0
  109. package/dist/config/resolve.js +11 -0
  110. package/dist/config/schema.d.ts +4 -4
  111. package/dist/config/schema.js +157 -1
  112. package/dist/content/citation-freshness.js +6 -0
  113. package/dist/content/learning.d.ts +1 -0
  114. package/dist/content/learning.js +2 -0
  115. package/dist/data/access.d.ts +1 -1
  116. package/dist/data/access.js +3 -1
  117. package/dist/data/task-contract.d.ts +5 -4
  118. package/dist/data/tasks.d.ts +5 -0
  119. package/dist/data/tasks.js +28 -2
  120. package/dist/dream/apply.d.ts +69 -0
  121. package/dist/dream/apply.js +372 -0
  122. package/dist/dream/budget.d.ts +78 -0
  123. package/dist/dream/budget.js +180 -0
  124. package/dist/dream/collect.d.ts +86 -0
  125. package/dist/dream/collect.js +449 -0
  126. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  127. package/dist/dream/eval/dream-adapter.js +21 -0
  128. package/dist/dream/eval/fixture.d.ts +53 -0
  129. package/dist/dream/eval/fixture.js +172 -0
  130. package/dist/dream/eval/index.d.ts +40 -0
  131. package/dist/dream/eval/index.js +78 -0
  132. package/dist/dream/eval/score.d.ts +34 -0
  133. package/dist/dream/eval/score.js +99 -0
  134. package/dist/dream/eval/scripted-model.d.ts +19 -0
  135. package/dist/dream/eval/scripted-model.js +70 -0
  136. package/dist/dream/pages.d.ts +68 -0
  137. package/dist/dream/pages.js +220 -0
  138. package/dist/dream/privacy.d.ts +3 -0
  139. package/dist/dream/privacy.js +18 -0
  140. package/dist/dream/prompt.d.ts +13 -0
  141. package/dist/dream/prompt.js +84 -0
  142. package/dist/dream/run.d.ts +98 -0
  143. package/dist/dream/run.js +317 -0
  144. package/dist/dream/types.d.ts +74 -0
  145. package/dist/dream/types.js +4 -0
  146. package/dist/finding/lifecycle.d.ts +2 -2
  147. package/dist/finding/lifecycle.js +5 -2
  148. package/dist/finding/versions.d.ts +4 -0
  149. package/dist/finding/versions.js +28 -0
  150. package/dist/index.js +1 -0
  151. package/dist/modules/registry.js +10 -8
  152. package/dist/project-config.d.ts +3 -0
  153. package/dist/task/merge-links.d.ts +38 -0
  154. package/dist/task/merge-links.js +45 -0
  155. package/dist/task/reconcile.d.ts +39 -0
  156. package/dist/task/reconcile.js +201 -0
  157. package/dist/task/report-links.d.ts +10 -0
  158. package/dist/task/report-links.js +47 -0
  159. package/dist/tools/config.js +46 -4
  160. package/dist/tools/dispatch.js +2 -1
  161. package/dist/tools/dream.d.ts +3 -0
  162. package/dist/tools/dream.js +123 -0
  163. package/dist/tools/tasks.js +4 -1
  164. package/package.json +1 -1
@@ -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";
@@ -10,7 +11,7 @@ import { BridgeError, id, object, objects, requestID, serverName, provider, sess
10
11
  import { logger } from "../logger.js";
11
12
  import { recordedSession } from "./agent-hook-stores.js";
12
13
  import { paneRecord, recordTitle } from "./session-activity.js";
13
- import { tabActivityKey } from "./tab-activity.js";
14
+ import { panesByTab, tabActivityKey } from "./tab-activity.js";
14
15
  import { intervalFromEnv } from "./limits.js";
15
16
  import { countHerdr, countIdentity } from "./metrics.js";
16
17
  import { phrenStoreRoot } from "./transcripts.js";
@@ -280,6 +281,15 @@ export function isConductorName(name) {
280
281
  /** `conductorPane` is the pane the Hook records as the conductor (null for
281
282
  * none); left out, the agent's name decides, as before the record. */
282
283
  export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, conductorPane) {
284
+ const grouped = panesByTab(s);
285
+ const tabsByWorkspace = new Map();
286
+ for (const tab of objects(s.tabs)) {
287
+ const tabs = tabsByWorkspace.get(tab.workspace_id);
288
+ if (tabs)
289
+ tabs.push(tab);
290
+ else
291
+ tabsByWorkspace.set(tab.workspace_id, [tab]);
292
+ }
283
293
  const focusedPane = objects(s.panes).find(p => p.pane_id === s.focused_pane_id
284
294
  && p.tab_id === s.focused_tab_id && p.workspace_id === s.focused_workspace_id);
285
295
  const focus = focusedPane && id.safeParse(s.focused_workspace_id).success
@@ -290,9 +300,9 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
290
300
  // Focus identifies a pane to inspect. Its conversation is still resolved and
291
301
  // validated independently through panes(), never inferred from a directory.
292
302
  return { kind: "herdr", focus, groups: objects(s.workspaces).map(w => ({ id: w.workspace_id, label: w.label,
293
- children: objects(s.tabs).filter(t => t.workspace_id === w.workspace_id).map(t => {
294
- const panes = objects(s.panes).filter(p => p.tab_id === t.tab_id && p.workspace_id === t.workspace_id);
295
- const agent = panes.find(p => p.agent);
303
+ children: (tabsByWorkspace.get(w.workspace_id) ?? []).map(t => {
304
+ const panes = grouped.get(tabActivityKey(t.workspace_id, t.tab_id)) ?? [];
305
+ const agents = panes.filter(p => p.agent), agent = agents[0];
296
306
  const activity = lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id));
297
307
  // Herdr's per-pane state_change_seq climbs with every agent status
298
308
  // change; the phone orders "just finished" ahead of "finished an hour ago" by it.
@@ -304,8 +314,8 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
304
314
  lastChangedAt: activity?.lastChangedAt,
305
315
  statusSince: activity?.statusSince,
306
316
  approvalPending: panes.some(p => approvalPanes?.has(String(p.pane_id))) || undefined,
307
- contextUsedPercent: agent && panes.filter(p => p.agent).length === 1 ? contextUsedPercent?.get(agent) : undefined,
308
- agentPaneCount: panes.filter(p => p.agent).length, paneCount: panes.length };
317
+ contextUsedPercent: agent && agents.length === 1 ? contextUsedPercent?.get(agent) : undefined,
318
+ agentPaneCount: agents.length, paneCount: panes.length };
309
319
  }) })) };
310
320
  }
311
321
  /** Only file descriptors held by this pane's foreground processes establish identity.
@@ -576,6 +586,29 @@ export async function paneForCodexSession(server, session, cwd) {
576
586
  const startingKey = randomBytes(32);
577
587
  const startingBindings = new Map();
578
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
+ }
579
612
  const startingToken = (process) => createHmac("sha256", startingKey).update(process).update(randomBytes(32)).digest("hex");
580
613
  /** Remember the first identified conversation even when an overview skips the
581
614
  * PID probe. A later conversation in the same process retires its old token. */
@@ -597,13 +630,14 @@ export async function paneChatState(server, pane, options = {}) {
597
630
  return {};
598
631
  const identity = await resolveIdentity(server, pane, false);
599
632
  const sessionId = identity.sessionId;
633
+ const watch = paneBrowserWatch(server, pane, sessionId, identity.pids?.[0] ?? (typeof pane.agent_pid === "number" ? pane.agent_pid : undefined));
600
634
  const key = startingPaneKey(server, pane);
601
635
  if (sessionId)
602
636
  identifyStartingBinding(key, sessionId);
603
637
  // A pane whose conversation is known is not starting, so a caller that
604
638
  // reads only `sessionId` and `starting` (the overview) needs no PIDs.
605
639
  if (sessionId && options.tokenWhenIdentified === false)
606
- return { sessionId };
640
+ return { sessionId, browserWatch: watch };
607
641
  const pids = identity.pids ?? await foregroundPids(server, pane);
608
642
  // The token binds to the agent's own process, the oldest in the pane's
609
643
  // foreground group. Helpers it spawns while starting up (Codex forks
@@ -620,14 +654,15 @@ export async function paneChatState(server, pane, options = {}) {
620
654
  // Lost identity, changed process, or newly ambiguous evidence requires a
621
655
  // new token. Never revive a previous conversation's first-send permission.
622
656
  if (!binding || binding.process !== process || (!sessionId && (!!binding.sessionId || binding.wasStarting !== starting))) {
623
- binding = { process, token: startingToken(process), wasStarting: starting,
657
+ const seeded = seededStartingTokens.get(seededPaneKey(server, pane));
658
+ binding = { process, token: seeded ?? startingToken(process), wasStarting: starting,
624
659
  ...(sessionId ? { sessionId, identifiedAt: Date.now() } : {}) };
625
660
  if (startingBindings.size >= 256)
626
661
  startingBindings.delete(startingBindings.keys().next().value);
627
662
  startingBindings.set(key, binding);
628
663
  }
629
664
  }
630
- 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 } : {}) };
631
666
  }
632
667
  /** `{ account }` for a Claude pane whose account is known, else nothing. */
633
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. */
@@ -1,3 +1,4 @@
1
+ import { browserShimPath } from "./browser-env.js";
1
2
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
2
3
  import { defaultPhrenPath } from "../shared.js";
3
4
  import { disabledHint } from "../modules/registry.js";
@@ -15,6 +16,7 @@ import { bridgeRoot, object, objects, atomic, socketPath } from "./protocol.js";
15
16
  import { herdrRoot } from "./herdr.js";
16
17
  import { health } from "./transport.js";
17
18
  import { FAST_HOOK_SOURCE, fastHookPath } from "./hook-fast.js";
19
+ import { FAST_STATUS_LINE_SOURCE, fastStatusLinePath } from "./status-line-fast.js";
18
20
  import { installAskpass, removeAskpass } from "./sudo.js";
19
21
  import { readStoredVoice, SPEECH_VOICE_ENV, writeSpeechVoice } from "./speech-voice.js";
20
22
  import { carryCodexHookTrust } from "./codex-hook-trust.js";
@@ -299,7 +301,11 @@ export async function install(version, noService = false, force = false) {
299
301
  const stagedBundle = installedBundle + `.phren-${process.pid}`;
300
302
  await copyFile(bundle, stagedBundle);
301
303
  await rename(stagedBundle, installedBundle);
304
+ const shimDirectory = path.join(destination, "bridge/browser-shim");
305
+ await mkdir(shimDirectory, { recursive: true, mode: 0o700 });
306
+ await atomic(path.join(shimDirectory, "phren-playwright.cjs"), typeof BROWSER_SHIM_SOURCE !== "undefined" ? BROWSER_SHIM_SOURCE : await readFile(browserShimPath(), "utf8"), 0o600);
302
307
  await atomic(fastHookPath(destination), FAST_HOOK_SOURCE);
308
+ await atomic(fastStatusLinePath(destination), FAST_STATUS_LINE_SOURCE);
303
309
  const previous = await readFile(path.join(root, "installed.json"), "utf8").then(v => JSON.parse(v)).catch(() => null);
304
310
  const gateway = await detectGateway();
305
311
  await atomic(path.join(root, "dispatch"), gatewayScript(gateway, {
@@ -428,7 +434,9 @@ async function missingFile(operation) {
428
434
  /** Whether the version `current/` points at ships the Claude forwarder; one
429
435
  * from before it does not, and its Claude callbacks run the bundle. */
430
436
  const currentHasFastHook = (root) => access(fastHookPath(path.join(root, "current"))).then(() => true, () => false);
431
- 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) {
432
440
  const edits = [];
433
441
  // Extra Claude homes (one per account) get the same hooks; a symlinked settings.json shares another home's, so it is skipped.
434
442
  const extraClaude = claudeHomes().slice(1).map(home => ["claude", path.join(home.dir, "settings.json")]);
@@ -493,7 +501,7 @@ export async function planAgentHooks(program, remove = false, modules, fastClaud
493
501
  }
494
502
  config.hooks = hooks;
495
503
  if (source === "claude") {
496
- 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);
497
505
  if (statusLine === undefined)
498
506
  delete config.statusLine;
499
507
  else
@@ -582,7 +590,7 @@ export async function rollback() {
582
590
  // forwarder or, from before the forwarder, its bundle.
583
591
  const root = bridgeRoot();
584
592
  const program = path.join(root, "current/bridge-hook.mjs");
585
- 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));
586
594
  await applyAgentHooks(edits);
587
595
  await carryCodexHookTrust(program, codexHooksBefore(edits));
588
596
  await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version, ...(config.store ? { store: config.store } : {}) }) + "\n");
@@ -606,7 +614,7 @@ export async function reconcileModuleHooks(store, profile) {
606
614
  if (typeof served === "string" && path.resolve(served) !== path.resolve(store))
607
615
  return;
608
616
  const program = path.join(root, "current/bridge-hook.mjs");
609
- const edits = await planAgentHooks(program, false, modules, await currentHasFastHook(root));
617
+ const edits = await planAgentHooks(program, false, modules, await currentHasFastHook(root), await currentHasFastStatusLine(root));
610
618
  await applyAgentHooks(edits);
611
619
  await carryCodexHookTrust(program, codexHooksBefore(edits));
612
620
  await applyOpencodePlugin(!modules.has("hook"));
@@ -20,6 +20,11 @@ import { type Target } from "./protocol.js";
20
20
  export declare const briefId: z.ZodString;
21
21
  export declare const launchBriefSchema: z.ZodObject<{
22
22
  id: z.ZodString;
23
+ task: z.ZodOptional<z.ZodObject<{
24
+ storeId: z.ZodString;
25
+ project: z.ZodString;
26
+ stableId: z.ZodString;
27
+ }, z.core.$strict>>;
23
28
  text: z.ZodString;
24
29
  }, z.core.$strict>;
25
30
  export type LaunchBrief = z.infer<typeof launchBriefSchema>;
@@ -103,3 +108,9 @@ export declare function briefIdInPrompt(prompt: string): string | undefined;
103
108
  /** Records a worker hook's report about its brief. Only the first of each
104
109
  * event counts, and only for a brief this computer wrote. */
105
110
  export declare function recordBriefArrival(id: string, event: string, target: Target, now?: Date): Promise<void>;
111
+ /** Private association carried with the launch, never included in GitHub data. */
112
+ export declare function briefTask(id: string): Promise<{
113
+ storeId: string;
114
+ project: string;
115
+ stableId: string;
116
+ } | undefined>;
@@ -1,3 +1,4 @@
1
+ import { mergeTaskIdentitySchema } from "../task/merge-links.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
3
4
  import path from "node:path";
@@ -23,6 +24,7 @@ import { atomic, BridgeError, bridgeRoot, targetSchema } from "./protocol.js";
23
24
  export const briefId = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/);
24
25
  export const launchBriefSchema = z.object({
25
26
  id: briefId,
27
+ task: mergeTaskIdentitySchema.optional(),
26
28
  text: z.string().min(1).max(32768).refine(value => !!value.trim() && !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)),
27
29
  }).strict();
28
30
  /** The variable a launched agent's hooks read its brief id from. */
@@ -110,6 +112,8 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
110
112
  const named = label ? cleanLabel(label) : "";
111
113
  const fill = async (folder) => {
112
114
  await atomic(path.join(folder, "brief.md"), text);
115
+ if (brief.task)
116
+ await atomic(path.join(folder, "task.json"), JSON.stringify(brief.task));
113
117
  if (named)
114
118
  await atomic(path.join(folder, LABEL_FILE), named);
115
119
  };
@@ -117,6 +121,9 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
117
121
  const existing = async () => {
118
122
  if (await readFile(file, "utf8").catch(() => undefined) !== text)
119
123
  throw new BridgeError(409, "This brief id already belongs to another launch.");
124
+ const task = await readFile(path.join(directory, "task.json"), "utf8").catch(() => undefined);
125
+ if (task !== (brief.task ? JSON.stringify(brief.task) : undefined))
126
+ throw new BridgeError(409, "This brief id belongs to another task.");
120
127
  return file;
121
128
  };
122
129
  if (await stat(directory).catch(() => undefined))
@@ -196,3 +203,18 @@ export function recordBriefArrival(id, event, target, now = new Date()) {
196
203
  arrivals = run.catch(() => undefined);
197
204
  return run;
198
205
  }
206
+ /** Private association carried with the launch, never included in GitHub data. */
207
+ export async function briefTask(id) {
208
+ if (!briefId.safeParse(id).success)
209
+ return undefined;
210
+ try {
211
+ const file = path.join(briefDirectory(id), "task.json");
212
+ const info = await lstat(file);
213
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 1024)
214
+ return undefined;
215
+ return mergeTaskIdentitySchema.parse(JSON.parse(await readFile(file, "utf8")));
216
+ }
217
+ catch {
218
+ return undefined;
219
+ }
220
+ }
@@ -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) : "";
@@ -111,7 +111,7 @@ export function screenDialog(agent, screen) {
111
111
  return !!opencodePermissionDialog(screen);
112
112
  if (agent === "codex" || agent === "copilot")
113
113
  return !!visibleTerminalChoice(text);
114
- if (agent === "claude" && (claudeQuestionDialog(text) || claudeTeachAutoModeDialog(text)))
114
+ if (agent === "claude" && claudeQuestionDialog(text))
115
115
  return true;
116
116
  return !!claudePermissionDialog(text);
117
117
  }
@@ -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;
@@ -1,5 +1,7 @@
1
1
  import { type HarnessInventory } from "./harnesses.js";
2
2
  import { type Json } from "./protocol.js";
3
+ /** Refuse a keyed launch whose resolved arguments would skip approvals or allow everything. */
4
+ export declare function assertKeyedLaunchArgs(kind: string, args: readonly string[]): void;
3
5
  /**
4
6
  * phren agent's quick chat and resume: `mode: "chat"` starts it with no tools
5
7
  * and its memory read up front (`--mode chat`); `resumeSession` continues a