@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
@@ -188,7 +188,7 @@ export class CodexServers {
188
188
  await mkdir(codexServersRoot(), { recursive: true, mode: 0o700 });
189
189
  await mkdir(directory, { recursive: true, mode: 0o700 });
190
190
  const spawnOptions = { socketPath: socket, cwd: options.cwd, detached: true, logFile: path.join(directory, "server.log"),
191
- config: serverConfig(), replaceEnv: true, env: serverEnvironment(process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) };
191
+ config: serverConfig(), replaceEnv: true, env: serverEnvironment(options.envExact ? {} : process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) };
192
192
  const scope = this.deps.scope?.(serverId);
193
193
  const handle = await (scope
194
194
  // No systemd-run, or no user manager to ask: the server runs in the
@@ -10,6 +10,7 @@ import { object, provider, socketPath } from "./protocol.js";
10
10
  import { apnsSetupSteps } from "./push.js";
11
11
  import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
12
12
  import { gitHostsFile, listHostTokens, writeHostToken } from "./git-host-auth.js";
13
+ import { gitCredentialCommand } from "./git-credential.js";
13
14
  import { hostInfo, PROVIDERS } from "./git-hosts.js";
14
15
  import { clearSpeechModel, clearSpeechVoice, DEFAULT_SPEECH_MODEL, FALLBACK_SPEECH_MODEL, resolveSpeechModel, resolveSpeechRegion, resolveSpeechVoice, SPEECH_REGIONS, speechModelId, speechRegion, speechVoiceFile, voiceId, writeSpeechModel, writeSpeechRegion, writeSpeechVoice } from "./speech-voice.js";
15
16
  import { AccountUsageReader, captureClaudeUsage } from "./usage.js";
@@ -149,6 +150,17 @@ export async function runBridge(args, version) {
149
150
  console.log(`Stored the ElevenLabs key in ${speechKeyFile()} (mode 600).`);
150
151
  break;
151
152
  }
153
+ case "git-credential": {
154
+ // Git runs this helper with get/store/erase. Only get answers, and only
155
+ // from the Hook's stored gitboy token; store and erase do nothing.
156
+ let request = "";
157
+ for await (const chunk of process.stdin)
158
+ request += chunk;
159
+ const output = await gitCredentialCommand(args[1], request);
160
+ if (output)
161
+ process.stdout.write(output);
162
+ break;
163
+ }
152
164
  case "git-host": {
153
165
  // Tokens for GitLab and gitboy, which the Hook reads over HTTP; GitHub keeps gh's sign-in.
154
166
  const [, action = "list", domain, kind] = args;
@@ -159,7 +171,7 @@ export async function runBridge(args, version) {
159
171
  if (!hosts.length)
160
172
  console.log("No GitLab or gitboy tokens stored. Add one with phren bridge git-host set <domain> gitlab|gitboy.");
161
173
  for (const host of hosts)
162
- console.log(`${host.domain} ${host.kind}${host.user ? ` @${host.user}` : ""}`);
174
+ console.log(`${host.domain} ${host.kind}${host.agent ? " agent token" : ""}${host.user ? ` @${host.user}` : ""}`);
163
175
  }
164
176
  else if (action === "set" && domain && (kind === "gitlab" || kind === "gitboy") && args.length === 4) {
165
177
  // The token comes from stdin, never argv, so it stays out of ps and shell history.
@@ -167,9 +179,16 @@ export async function runBridge(args, version) {
167
179
  if (!token)
168
180
  throw new Error("No token given.");
169
181
  const host = hostInfo(kind, { domain: domain.toLowerCase(), webUrl: null, remote: null, source: "none" });
170
- const { user } = await PROVIDERS[kind].whoami(process.cwd(), host, token);
171
- await writeHostToken(domain, kind, token, user || undefined);
172
- console.log(`Connected ${domain} (${kind})${user ? ` as @${user}` : ""}. Stored in ${gitHostsFile()} (mode 600).`);
182
+ const identity = await PROVIDERS[kind].whoami(process.cwd(), host, token);
183
+ const user = identity.user;
184
+ const agent = identity.agent ?? identity.agent_token;
185
+ await writeHostToken(domain, kind, token, user || undefined, undefined, !!agent);
186
+ if (agent) {
187
+ const expires = agent.expires_at ? `, expires ${agent.expires_at.slice(0, 10)}` : "";
188
+ console.log(`Connected ${domain} (gitboy agent token as @${user}${expires}). Stored in ${gitHostsFile()} (mode 600).`);
189
+ }
190
+ else
191
+ console.log(`Connected ${domain} (${kind})${user ? ` as @${user}` : ""}. Stored in ${gitHostsFile()} (mode 600).`);
173
192
  }
174
193
  else if (action === "remove" && domain && args.length === 3) {
175
194
  await writeHostToken(domain, "gitlab", "");
@@ -308,7 +327,7 @@ export async function runBridge(args, version) {
308
327
  console.error(`warning: ${push.warning}`);
309
328
  break;
310
329
  }
311
- default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|speech-key set|speech-voice|speech-model|speech-region>");
330
+ default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|git-credential|speech-key set|speech-voice|speech-model|speech-region>");
312
331
  }
313
332
  return 0;
314
333
  }
@@ -1,3 +1,4 @@
1
+ import type { IncomingMessage } from "node:http";
1
2
  import { type LinkResult, linkComputer } from "./link.js";
2
3
  import { type Json } from "./protocol.js";
3
4
  /** The Hook routes for linked computer sets (docs/conductor-sets.md). */
@@ -27,5 +28,5 @@ export declare function nameSet(data: Json): Promise<Json>;
27
28
  /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
28
29
  * on the computer whose set lists `name` as indirect or one-way, over this
29
30
  * computer's own ssh login, one link at a time. */
30
- export declare function linkSetMember(data: Json, link?: typeof linkComputer): Promise<LinkResult>;
31
+ export declare function linkSetMember(data: Json, request: Pick<IncomingMessage, "headers">, link?: typeof linkComputer): Promise<LinkResult>;
31
32
  export {};
@@ -7,6 +7,7 @@ import { listsCaller } from "./health.js";
7
7
  import { linkComputer } from "./link.js";
8
8
  import { optionalHookPeers, peerRequest } from "./peers.js";
9
9
  import { BridgeError, object } from "./protocol.js";
10
+ import { ownerRequest } from "./request-origin.js";
10
11
  import { localConductor } from "./server-launch.js";
11
12
  const callerSchema = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() });
12
13
  /** `GET /v1/conductor`: this computer's live conductor and what a peer needs
@@ -89,8 +90,8 @@ let linking;
89
90
  /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
90
91
  * on the computer whose set lists `name` as indirect or one-way, over this
91
92
  * computer's own ssh login, one link at a time. */
92
- export async function linkSetMember(data, link = linkComputer) {
93
- if (data && typeof data === "object" && "origin" in data)
93
+ export async function linkSetMember(data, request, link = linkComputer) {
94
+ if (!ownerRequest(request, data))
94
95
  throw new BridgeError(403, "Only the owner links computers, from the phone or `phren bridge link` in their own terminal.");
95
96
  const { name } = linkInput.parse(data);
96
97
  if (linking)
@@ -3,3 +3,7 @@
3
3
  export declare const DIALOG_READ_MS: number;
4
4
  export declare const DIALOG_CONFIRM_MS = 300;
5
5
  export declare function confirmDialogRead<T>(read: () => Promise<T>, current: () => boolean): Promise<T | undefined>;
6
+ /** A live composer or working hint after all dialog cues proves closure.
7
+ * Call only after ruling out a currently readable dialog. A failed parse alone
8
+ * says nothing: clipped and half-drawn screens remain unknown. */
9
+ export declare function dialogHasClosed(screen: string): boolean;
@@ -1,3 +1,5 @@
1
+ import { stripTerminal } from "../terminal-text.js";
2
+ import { claudeFooterMode } from "./claude-footer-mode.js";
1
3
  import { intervalFromEnv } from "./limits.js";
2
4
  /** Discovery is frequent by default; an owner can still cap polling explicitly.
3
5
  * Confirmation has its own small, fixed budget, independent of that cap. */
@@ -18,3 +20,25 @@ export async function confirmDialogRead(read, current) {
18
20
  clearTimeout(timer);
19
21
  }
20
22
  }
23
+ /** A live composer or working hint after all dialog cues proves closure.
24
+ * Call only after ruling out a currently readable dialog. A failed parse alone
25
+ * says nothing: clipped and half-drawn screens remain unknown. */
26
+ export function dialogHasClosed(screen) {
27
+ const lines = stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
28
+ const composer = (line) => /^[❯›](?!\s*\d+[.)])(?:\s|$)/.test(line);
29
+ const chrome = (line) => /^[─━═]+$/.test(line) || claudeFooterMode(line) !== undefined
30
+ || /^(?:[←→?].*(?:agents|shortcuts)|(?:gpt-|GPT-|claude-|Claude ).*)/i.test(line);
31
+ const liveTail = (index) => lines.slice(index + 1).every(line => composer(line) || chrome(line));
32
+ let cue = -1;
33
+ for (let index = 0; index < lines.length; index++) {
34
+ 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]))
35
+ cue = index;
36
+ }
37
+ for (let index = lines.length - 1; index > cue; index--) {
38
+ if (/\besc to interrupt\b/i.test(lines[index]) && liveTail(index))
39
+ return true;
40
+ if (index >= lines.length - 3 && composer(lines[index]) && liveTail(index))
41
+ return true;
42
+ }
43
+ return false;
44
+ }
@@ -0,0 +1,33 @@
1
+ /** A keyed dispatch's isolated checkout. The clone and its managed global
2
+ * config are outside the user's checkout and are removed with the dispatch. */
3
+ export interface DispatchClonePaths {
4
+ cloneDir: string;
5
+ gitConfigFile: string;
6
+ agentTokenFile: string;
7
+ /** The wrapper's PID/start-time record, beside the clone. */
8
+ workerFile?: string;
9
+ }
10
+ export declare function dispatchClonePaths(dispatchId: string): DispatchClonePaths;
11
+ /** Canonical path inside the managed clone root, or a refusal. */
12
+ export declare function assertManagedClonePath(candidate: string): Promise<string>;
13
+ export interface DispatchClone extends DispatchClonePaths {
14
+ /** Where the agent starts: the same folder inside the clone as the project folder in its repository. */
15
+ cwd: string;
16
+ path: string;
17
+ branch: string;
18
+ discard(): Promise<void>;
19
+ }
20
+ /** Only the keys a keyed worker may inherit: no user URL-specific overrides. */
21
+ export declare function writeManagedConfig(file: string, domain: string, checkout: string): Promise<void>;
22
+ /** The start folder inside the clone, refusing a symlink or a path that escapes it. */
23
+ export declare function cloneStartDirectory(cloneDir: string, root: string, checkout: string): Promise<string>;
24
+ /** A fresh clone with only our managed global config, never the user's checkout config. */
25
+ export declare function createDispatchClone(checkout: string, request: {
26
+ branch: string;
27
+ dispatchId: string;
28
+ paths?: DispatchClonePaths;
29
+ }): Promise<DispatchClone>;
30
+ /** Remove a dispatch's clone, managed config and token file; only paths this Hook made. */
31
+ export declare function removeDispatchClone(paths: Partial<DispatchClonePaths> | undefined): Promise<void>;
32
+ /** Keep the clone (recoverable work) but remove the token and managed config immediately. */
33
+ export declare function removeDispatchSecrets(paths: Partial<DispatchClonePaths> | undefined): Promise<void>;
@@ -0,0 +1,176 @@
1
+ import { execFile } from "node:child_process";
2
+ import { chmod, lstat, mkdir, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { nonInteractiveGitEnv } from "../utils-helpers.js";
6
+ import { countGit } from "./metrics.js";
7
+ import { gitRoot } from "./projects.js";
8
+ import { EMPTY_TREE } from "./launch-worktree.js";
9
+ import { credentialFreeRemote, keyedExplicitEnv, removeAgentTokenFile } from "./git-credential.js";
10
+ import { detectHost } from "./git-hosts.js";
11
+ import { BridgeError, bridgeRoot } from "./protocol.js";
12
+ import { workerFilePath } from "./worker-identity.js";
13
+ export function dispatchClonePaths(dispatchId) {
14
+ const root = path.join(bridgeRoot(), "clones");
15
+ const cloneDir = path.join(root, dispatchId);
16
+ return {
17
+ cloneDir,
18
+ gitConfigFile: path.join(root, `${dispatchId}.gitconfig`),
19
+ agentTokenFile: path.join(cloneDir, ".git", "phren-agent-token"),
20
+ workerFile: workerFilePath(dispatchId),
21
+ };
22
+ }
23
+ const managedRoot = () => path.join(bridgeRoot(), "clones");
24
+ async function canonicalManagedRoot() {
25
+ const root = managedRoot();
26
+ await mkdir(root, { recursive: true, mode: 0o700 });
27
+ return realpath(root);
28
+ }
29
+ /** Canonical path inside the managed clone root, or a refusal. */
30
+ export async function assertManagedClonePath(candidate) {
31
+ const root = await canonicalManagedRoot();
32
+ const resolved = await realpath(candidate).catch(() => path.resolve(candidate));
33
+ const rel = path.relative(root, resolved);
34
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) {
35
+ throw new BridgeError(403, "The keyed clone path is outside Phren's managed clone folder.");
36
+ }
37
+ return resolved;
38
+ }
39
+ const exec = promisify(execFile);
40
+ async function git(args, env = nonInteractiveGitEnv(process.env)) {
41
+ countGit("dispatch-clone");
42
+ return (await exec("git", args, { timeout: 120_000, maxBuffer: 1_048_576, env })).stdout;
43
+ }
44
+ function configValue(value) {
45
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
46
+ }
47
+ async function userValue(checkout, key) {
48
+ try {
49
+ return (await git(["-C", checkout, "config", "--get", key])).trim() || undefined;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ /** Only the keys a keyed worker may inherit: no user URL-specific overrides. */
56
+ export async function writeManagedConfig(file, domain, checkout) {
57
+ await assertManagedClonePath(file);
58
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
59
+ const lines = [
60
+ "[credential]",
61
+ "\thelper =",
62
+ `[credential "https://${domain}"]`,
63
+ "\thelper = !phren bridge git-credential",
64
+ "\tuseHttpPath = false",
65
+ "[core]",
66
+ "\tsshCommand = false",
67
+ "\thooksPath = /dev/null",
68
+ ];
69
+ const name = await userValue(checkout, "user.name");
70
+ const email = await userValue(checkout, "user.email");
71
+ if (name || email) {
72
+ lines.push("[user]");
73
+ if (name)
74
+ lines.push(`\tname = ${configValue(name)}`);
75
+ if (email)
76
+ lines.push(`\temail = ${configValue(email)}`);
77
+ }
78
+ await writeFile(file, `${lines.join("\n")}\n`, { mode: 0o600, flag: "wx" });
79
+ await chmod(file, 0o600);
80
+ }
81
+ /** The start folder inside the clone, refusing a symlink or a path that escapes it. */
82
+ export async function cloneStartDirectory(cloneDir, root, checkout) {
83
+ const clone = await realpath(cloneDir);
84
+ const inside = path.relative(root, await realpath(checkout));
85
+ if (!inside || inside.startsWith("..") || path.isAbsolute(inside))
86
+ return clone;
87
+ const candidate = path.join(clone, inside);
88
+ const info = await lstat(candidate).catch(() => undefined);
89
+ if (!info)
90
+ return clone;
91
+ if (!info.isDirectory() || info.isSymbolicLink())
92
+ throw new BridgeError(409, "The project folder in the keyed clone is a symlink or not a directory.");
93
+ const real = await realpath(candidate);
94
+ const rel = path.relative(clone, real);
95
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel))
96
+ throw new BridgeError(403, "The project folder in the keyed clone points outside it.");
97
+ return real;
98
+ }
99
+ /** A fresh clone with only our managed global config, never the user's checkout config. */
100
+ export async function createDispatchClone(checkout, request) {
101
+ const root = await gitRoot(checkout);
102
+ if (!root)
103
+ throw new BridgeError(409, "This folder is not a Git repository, so it cannot be cloned for a keyed dispatch.");
104
+ const host = await detectHost(checkout, request.branch);
105
+ if (host.kind !== "gitboy" || !host.domain)
106
+ throw new BridgeError(409, "A keyed worktree dispatch needs a gitboy checkout.");
107
+ const url = credentialFreeRemote(host);
108
+ const paths = request.paths ?? dispatchClonePaths(request.dispatchId);
109
+ await assertManagedClonePath(paths.cloneDir);
110
+ await assertManagedClonePath(paths.gitConfigFile);
111
+ await assertManagedClonePath(paths.agentTokenFile);
112
+ if (await stat(paths.cloneDir).then(() => true, () => false))
113
+ throw new BridgeError(409, "This dispatch's clone folder already exists.");
114
+ await mkdir(path.dirname(paths.cloneDir), { recursive: true, mode: 0o700 });
115
+ await writeManagedConfig(paths.gitConfigFile, host.domain, checkout);
116
+ const env = keyedExplicitEnv(process.env, {
117
+ GIT_CONFIG_GLOBAL: paths.gitConfigFile,
118
+ GIT_CONFIG_NOSYSTEM: "1",
119
+ GIT_TERMINAL_PROMPT: "0",
120
+ GIT_ASKPASS: "false",
121
+ SSH_ASKPASS: "false",
122
+ });
123
+ try {
124
+ await git(["-c", "core.hooksPath=/dev/null", "clone", "--no-checkout", "--reference-if-able", root, "--dissociate", url, paths.cloneDir], env);
125
+ await git(["-C", paths.cloneDir, "-c", "core.hooksPath=/dev/null", `--attr-source=${EMPTY_TREE}`, "checkout", "-b", request.branch], env);
126
+ }
127
+ catch (error) {
128
+ await rm(paths.cloneDir, { recursive: true, force: true }).catch(() => undefined);
129
+ await unlink(paths.gitConfigFile).catch(() => undefined);
130
+ const detail = error instanceof Error && "stderr" in error ? String(error.stderr ?? "").trim().split("\n").at(-1) : "";
131
+ throw new BridgeError(409, `Git could not create the keyed clone${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
132
+ }
133
+ const clone = await realpath(paths.cloneDir);
134
+ const cwd = await cloneStartDirectory(clone, root, checkout);
135
+ return {
136
+ ...paths,
137
+ cwd,
138
+ path: clone,
139
+ branch: request.branch,
140
+ async discard() {
141
+ await removeDispatchClone(paths);
142
+ },
143
+ };
144
+ }
145
+ /** Remove a dispatch's clone, managed config and token file; only paths this Hook made. */
146
+ export async function removeDispatchClone(paths) {
147
+ if (!paths)
148
+ return;
149
+ const remove = async (candidate, removeOne) => {
150
+ if (!candidate)
151
+ return;
152
+ try {
153
+ await removeOne(await assertManagedClonePath(candidate));
154
+ }
155
+ catch { /* outside the managed root: never touch it */ }
156
+ };
157
+ await remove(paths.cloneDir, canonical => rm(canonical, { recursive: true, force: true }));
158
+ await remove(paths.gitConfigFile, canonical => unlink(canonical));
159
+ await remove(paths.agentTokenFile, canonical => removeAgentTokenFile(canonical));
160
+ await remove(paths.workerFile, canonical => unlink(canonical));
161
+ }
162
+ /** Keep the clone (recoverable work) but remove the token and managed config immediately. */
163
+ export async function removeDispatchSecrets(paths) {
164
+ if (!paths)
165
+ return;
166
+ const remove = async (candidate, removeOne) => {
167
+ if (!candidate)
168
+ return;
169
+ try {
170
+ await removeOne(await assertManagedClonePath(candidate));
171
+ }
172
+ catch { /* outside the managed root: never touch it */ }
173
+ };
174
+ await remove(paths.gitConfigFile, canonical => unlink(canonical));
175
+ await remove(paths.agentTokenFile, canonical => removeAgentTokenFile(canonical));
176
+ }
@@ -1,5 +1,19 @@
1
+ import type { Readable } from "node:stream";
2
+ import { type DispatchInput } from "./dispatch.js";
1
3
  import { type Json } from "./protocol.js";
2
4
  export declare function runDispatch(args: string[]): Promise<number>;
5
+ /** The brief limit shared with dispatchSchema. */
6
+ export declare const PROMPT_LIMIT = 32768;
7
+ /** A brief from a file, or stdin for `-`. The text never goes through argv. */
8
+ export declare function readPromptFile(file: string, stdin?: Readable): Promise<string>;
9
+ /** The dispatch form's argv, prompt file/stdin and defaults, without reaching a Hook. */
10
+ export declare function dispatchInputFromArgs(args: string[], stdin?: Readable): Promise<DispatchInput>;
11
+ /** Exactly one of a dispatch id and an idempotency key, for `dispatch close`. */
12
+ export declare function closeRequestFromArgs(args: string[]): {
13
+ dispatch: string;
14
+ } | {
15
+ idempotencyKey: string;
16
+ };
3
17
  export declare function runHandOff(args: string[]): Promise<number>;
4
18
  /** `phren move`: a live session, named by its session id or its pane id (`wC9:p1`), to another agent, through its computer's Hook (session-move.ts). */
5
19
  export declare function runMove(args: string[]): Promise<number>;
@@ -1,8 +1,13 @@
1
1
  import { ownerInboxSchema } from "./owner-inbox.js";
2
2
  import { prsSchema } from "./return-contract.js";
3
+ import { createReadStream } from "node:fs";
4
+ import { stat } from "node:fs/promises";
5
+ import { StringDecoder } from "node:string_decoder";
3
6
  import { parseArgs } from "node:util";
4
7
  import { hookRequest } from "./client.js";
5
- import { dispatchSchema } from "./dispatch.js";
8
+ import { DISPATCH_PROMPT_LIMIT, dispatchSchema } from "./dispatch.js";
9
+ import { idempotencyKeySchema } from "./dispatch-idempotency.js";
10
+ import { waitForDispatch } from "./dispatch-wait.js";
6
11
  import { handOff, moveSession } from "./hand-off.js";
7
12
  import { terminalPaneFromEnv } from "./terminal.js";
8
13
  import { dispatchIdFromEnv } from "./launch-brief.js";
@@ -67,16 +72,86 @@ export async function runDispatch(args) {
67
72
  console.log(JSON.stringify(await listLiveSessions(), null, 2));
68
73
  return 0;
69
74
  }
75
+ if (args[0] === "wait") {
76
+ const { values, positionals } = parseArgs({ args: args.slice(1), allowPositionals: true, options: {
77
+ timeout: { type: "string" }, json: { type: "boolean" }, follow: { type: "boolean" },
78
+ } });
79
+ if (positionals.length !== 1)
80
+ throw new Error("Usage: phren dispatch wait <dispatch-id> [--timeout <seconds>] [--json] [--follow]");
81
+ const seconds = values.timeout === undefined ? undefined : Number(values.timeout);
82
+ if (seconds !== undefined && (!Number.isFinite(seconds) || seconds < 0))
83
+ throw new Error("--timeout is a non-negative number of seconds.");
84
+ return waitForDispatch(positionals[0], { timeoutMs: seconds === undefined ? undefined : seconds * 1000 });
85
+ }
86
+ if (args[0] === "close") {
87
+ const result = await hookRequest("/v1/dispatch/cancel", closeRequestFromArgs(args.slice(1)));
88
+ console.log(JSON.stringify({ ...(typeof result.dispatch === "string" ? { dispatch: result.dispatch } : {}), closed: result.closed === true,
89
+ ...(result.pending === true ? { pending: true } : {}) }, null, 2));
90
+ return result.pending === true ? 1 : 0;
91
+ }
92
+ const input = await dispatchInputFromArgs(args);
93
+ // Run inside an agent's pane, the dispatch remembers that pane for return notices.
94
+ const origin = await terminalPaneFromEnv();
95
+ const result = await hookRequest("/v1/dispatch", { ...input, ...(origin ? { origin } : {}) }, undefined, 180_000);
96
+ console.log(JSON.stringify(result, null, 2));
97
+ return result.ok === true || result.existing === true ? 0 : 1;
98
+ }
99
+ const DISPATCH_USAGE = "Usage: phren dispatch <computer|anywhere|local> <project> --prompt <brief> | --prompt-file <path|-> [--harness codex|claude|opencode|copilot] [--label <label>] [--idempotency-key <key>] [--worktree [--branch <name>]] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]";
100
+ /** The brief limit shared with dispatchSchema. */
101
+ export const PROMPT_LIMIT = DISPATCH_PROMPT_LIMIT;
102
+ /** A brief from a file, or stdin for `-`. The text never goes through argv. */
103
+ export async function readPromptFile(file, stdin = process.stdin) {
104
+ if (file !== "-") {
105
+ const info = await stat(file);
106
+ if (info.size > PROMPT_LIMIT)
107
+ throw new Error(`Worker brief is too large: ${info.size} bytes; the limit is ${PROMPT_LIMIT} characters.`);
108
+ }
109
+ const stream = file === "-" ? stdin : createReadStream(file);
110
+ const decoder = new StringDecoder("utf8");
111
+ let prompt = "";
112
+ try {
113
+ for await (const chunk of stream) {
114
+ prompt += decoder.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
115
+ if (prompt.length > PROMPT_LIMIT) {
116
+ throw new Error(`Worker brief is too large: more than ${PROMPT_LIMIT} characters.`);
117
+ }
118
+ }
119
+ prompt += decoder.end();
120
+ }
121
+ finally {
122
+ if (file !== "-")
123
+ stream.destroy();
124
+ }
125
+ if (prompt.length > PROMPT_LIMIT)
126
+ throw new Error(`Worker brief is too large: ${prompt.length} characters; the limit is ${PROMPT_LIMIT}.`);
127
+ return prompt;
128
+ }
129
+ /** The dispatch form's argv, prompt file/stdin and defaults, without reaching a Hook. */
130
+ export async function dispatchInputFromArgs(args, stdin = process.stdin) {
70
131
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
71
132
  "keep-open": { type: "boolean" },
72
- harness: { type: "string", default: "codex" }, model: { type: "string" }, effort: { type: "string" }, account: { type: "string" }, "permission-mode": { type: "string" }, prompt: { type: "string" }, label: { type: "string" },
133
+ harness: { type: "string", default: "codex" }, model: { type: "string" }, effort: { type: "string" }, account: { type: "string" }, "permission-mode": { type: "string" },
134
+ prompt: { type: "string" }, "prompt-file": { type: "string" }, label: { type: "string" }, "idempotency-key": { type: "string" },
135
+ worktree: { type: "boolean" }, branch: { type: "string" },
73
136
  "parent-provider": { type: "string" }, "parent-session": { type: "string" }, "parent-computer": { type: "string" },
74
137
  "parent-server": { type: "string" }, "parent-workspace": { type: "string" }, "parent-tab": { type: "string" }, "parent-pane": { type: "string" },
75
138
  } });
76
139
  if (positionals.length !== 2)
77
- throw new Error("Usage: phren dispatch <computer|anywhere> <project> --label <label> --prompt <brief> [--harness codex|claude|opencode|copilot] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]");
140
+ throw new Error(DISPATCH_USAGE);
141
+ const [computer, project] = positionals;
142
+ const promptFile = values["prompt-file"];
143
+ if ((values.prompt === undefined) === (promptFile === undefined))
144
+ throw new Error("Give exactly one of --prompt and --prompt-file.");
145
+ const prompt = promptFile !== undefined ? await readPromptFile(promptFile, stdin) : values.prompt;
146
+ const key = values["idempotency-key"];
147
+ if (key !== undefined && !idempotencyKeySchema.safeParse(key).success) {
148
+ throw new Error(idempotencyKeySchema.safeParse(key).error.issues[0]?.message ?? "Invalid idempotency key.");
149
+ }
150
+ const label = values.label ?? (computer === "local" ? (key ? key.slice(0, 60) : "gitboy agent") : undefined);
151
+ if (values.branch !== undefined && !values.worktree)
152
+ throw new Error("--branch needs --worktree.");
78
153
  const parentValues = ["parent-provider", "parent-session", "parent-computer", "parent-server", "parent-workspace", "parent-tab", "parent-pane"];
79
- const hasParent = parentValues.some(key => values[key] !== undefined);
154
+ const hasParent = parentValues.some(name => values[name] !== undefined);
80
155
  const parent = hasParent ? {
81
156
  provider: values["parent-provider"], session: values["parent-session"], computer: values["parent-computer"],
82
157
  } : undefined;
@@ -84,21 +159,31 @@ export async function runDispatch(args) {
84
159
  server: values["parent-server"], workspace: values["parent-workspace"], tab: values["parent-tab"], pane: values["parent-pane"],
85
160
  source: values["parent-provider"], session: values["parent-session"],
86
161
  } : undefined;
87
- const { "permission-mode": permissionMode, "keep-open": keepOpen, ...rest } = values;
88
- const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([key]) => !key.startsWith("parent-"))), ...(permissionMode !== undefined ? { permissionMode } : {}), ...(keepOpen ? { closeOnFinish: false } : {}) };
89
- const parsed = dispatchSchema.safeParse({ computer: positionals[0], project: positionals[1], ...ordinary,
162
+ const { "permission-mode": permissionMode, "keep-open": keepOpen, prompt: _prompt, "prompt-file": _promptFile, "idempotency-key": _key, worktree, branch, ...rest } = values;
163
+ const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([name]) => !name.startsWith("parent-"))),
164
+ ...(permissionMode !== undefined ? { permissionMode } : {}), ...(keepOpen ? { closeOnFinish: false } : {}),
165
+ ...(worktree ? { worktree: true } : {}), ...(branch !== undefined ? { branch } : {}), ...(key !== undefined ? { idempotencyKey: key } : {}) };
166
+ const parsed = dispatchSchema.safeParse({ computer, project, prompt, ...(label !== undefined ? { label } : {}), ...ordinary,
90
167
  ...(parent ? { parent, parentTarget } : {}) });
91
168
  if (!parsed.success) {
92
169
  // Name the flag, not a schema path: a missing --label or --prompt is the usual slip.
93
170
  const flag = (path) => path.length ? (["computer", "project"].includes(String(path[0])) ? `<${String(path[0])}>` : `--${String(path[0]).replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`) : "input";
94
171
  throw new Error(`phren dispatch: ${parsed.error.issues.map(issue => `${flag(issue.path)} ${issue.code === "invalid_type" && /received undefined/.test(issue.message) ? "is required" : issue.message}`).join("; ")}. Run phren dispatch for usage.`);
95
172
  }
96
- const input = parsed.data;
97
- // Run inside an agent's pane, the dispatch remembers that pane for return notices.
98
- const origin = await terminalPaneFromEnv();
99
- const result = await hookRequest("/v1/dispatch", { ...input, ...(origin ? { origin } : {}) }, undefined, 180_000);
100
- console.log(JSON.stringify(result, null, 2));
101
- return result.ok === true ? 0 : 1;
173
+ return parsed.data;
174
+ }
175
+ /** Exactly one of a dispatch id and an idempotency key, for `dispatch close`. */
176
+ export function closeRequestFromArgs(args) {
177
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { "idempotency-key": { type: "string" } } });
178
+ const key = values["idempotency-key"];
179
+ const id = positionals[0];
180
+ if (positionals.length > 1 || (id === undefined) === (key === undefined)) {
181
+ throw new Error("Usage: phren dispatch close <dispatch-id> | phren dispatch close --idempotency-key <key>");
182
+ }
183
+ if (key !== undefined && !idempotencyKeySchema.safeParse(key).success) {
184
+ throw new Error(idempotencyKeySchema.safeParse(key).error.issues[0]?.message ?? "Invalid idempotency key.");
185
+ }
186
+ return key !== undefined ? { idempotencyKey: key } : { dispatch: id };
102
187
  }
103
188
  export async function runHandOff(args) {
104
189
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
@@ -0,0 +1,85 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Idempotency keys for local dispatches (`phren dispatch local ... --idempotency-key`).
4
+ * A reservation is written to a temp file and published with `link`, which is
5
+ * atomic and fails with EEXIST: an empty or half-written file is never a
6
+ * reservation another caller can reclaim. Every update or delete checks the
7
+ * owner nonce. The per-key mutex is in-process because only the Hook server
8
+ * process mutates key records; the CLI reaches it through Hook routes.
9
+ */
10
+ export declare const IDEMPOTENCY_TTL_MS: number;
11
+ /** A reservation that has not reached "launched" is interrupted after this. */
12
+ export declare const LAUNCH_INTERRUPTED_MS: number;
13
+ export declare const idempotencyKeySchema: z.ZodString;
14
+ declare const phaseSchema: z.ZodEnum<{
15
+ failed: "failed";
16
+ launched: "launched";
17
+ launching: "launching";
18
+ reserved: "reserved";
19
+ }>;
20
+ declare const recordSchema: z.ZodObject<{
21
+ key: z.ZodString;
22
+ dispatchId: z.ZodString;
23
+ owner: z.ZodString;
24
+ createdAt: z.ZodString;
25
+ phase: z.ZodEnum<{
26
+ failed: "failed";
27
+ launched: "launched";
28
+ launching: "launching";
29
+ reserved: "reserved";
30
+ }>;
31
+ project: z.ZodOptional<z.ZodString>;
32
+ harness: z.ZodOptional<z.ZodString>;
33
+ label: z.ZodOptional<z.ZodString>;
34
+ computer: z.ZodOptional<z.ZodString>;
35
+ cloneDir: z.ZodOptional<z.ZodString>;
36
+ gitConfigFile: z.ZodOptional<z.ZodString>;
37
+ agentTokenFile: z.ZodOptional<z.ZodString>;
38
+ workerFile: z.ZodOptional<z.ZodString>;
39
+ startingToken: z.ZodOptional<z.ZodString>;
40
+ cancelRequestedAt: z.ZodOptional<z.ZodString>;
41
+ }, z.core.$strict>;
42
+ export type IdempotencyRecord = z.infer<typeof recordSchema>;
43
+ export type IdempotencyPhase = z.infer<typeof phaseSchema>;
44
+ export declare const idempotencyKeyFile: (key: string) => string;
45
+ /** Called by the Hook server before it handles dispatches. */
46
+ export declare function markHookServerProcess(): void;
47
+ /** Delete lock and reclaim files left by an older Hook or a crash. */
48
+ export declare function cleanupIdempotencyLocks(): Promise<void>;
49
+ export type KeyReservation = {
50
+ reserved: true;
51
+ record: IdempotencyRecord;
52
+ } | {
53
+ reserved: false;
54
+ record: IdempotencyRecord;
55
+ };
56
+ export interface KeySeed {
57
+ project?: string;
58
+ harness?: string;
59
+ label?: string;
60
+ computer?: string;
61
+ cloneDir?: string;
62
+ gitConfigFile?: string;
63
+ agentTokenFile?: string;
64
+ workerFile?: string;
65
+ startingToken?: string;
66
+ }
67
+ /** Reserve `key` for this caller, with its dispatch id, atomically. */
68
+ export declare function reserveIdempotencyKey(key: string, dispatchId: string, owner: string, seed?: KeySeed, now?: number): Promise<KeyReservation>;
69
+ /** Move the reservation's phase. False when this caller no longer owns it. */
70
+ export declare function updateIdempotencyPhase(key: string, owner: string, phase: IdempotencyPhase): Promise<boolean>;
71
+ /** Run under the key's in-process mutex, with the current reservation record. */
72
+ export declare function withIdempotencyKeyLock<T>(key: string, run: (record: IdempotencyRecord | undefined, save: (record: IdempotencyRecord) => Promise<void>) => Promise<T>): Promise<T>;
73
+ /** Record a cancellation on the reservation itself, under its mutex, before any receipt exists. */
74
+ export declare function requestIdempotencyCancel(key: string, now?: number): Promise<IdempotencyRecord | undefined>;
75
+ /** Release a reservation this caller owns and never launched. */
76
+ export declare function releaseIdempotencyKey(key: string, owner: string): Promise<boolean>;
77
+ /** The live record for a key, or undefined when there is none or it expired. */
78
+ export declare function findIdempotencyKey(key: string): Promise<IdempotencyRecord | undefined>;
79
+ /** Every live reservation, for reconciliation on Hook start. */
80
+ export declare function listIdempotencyRecords(): Promise<IdempotencyRecord[]>;
81
+ /** Wait for the reserving caller to name its dispatch. Undefined when the key disappears or the wait runs out. */
82
+ export declare function waitForIdempotencyKey(key: string, timeoutMs?: number): Promise<IdempotencyRecord | undefined>;
83
+ /** A branch slug for a key: `agent/<key-slug>` or `agent/<dispatch id>` when there is no key. */
84
+ export declare function worktreeBranchFor(key: string | undefined, dispatchId: string): string;
85
+ export {};