@phren/cli 0.3.11 → 0.3.12

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 (168) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanouts.d.ts +7 -1
  42. package/dist/bridge/fanouts.js +39 -4
  43. package/dist/bridge/folder-trust.d.ts +56 -0
  44. package/dist/bridge/folder-trust.js +195 -0
  45. package/dist/bridge/grants.d.ts +22 -1
  46. package/dist/bridge/grants.js +57 -9
  47. package/dist/bridge/hand-off.d.ts +21 -9
  48. package/dist/bridge/hand-off.js +58 -45
  49. package/dist/bridge/harness-status.d.ts +11 -0
  50. package/dist/bridge/harness-status.js +32 -0
  51. package/dist/bridge/harnesses.d.ts +39 -0
  52. package/dist/bridge/harnesses.js +65 -0
  53. package/dist/bridge/health.d.ts +2 -0
  54. package/dist/bridge/health.js +1 -1
  55. package/dist/bridge/herdr.d.ts +11 -2
  56. package/dist/bridge/herdr.js +98 -23
  57. package/dist/bridge/hook-fast.d.ts +4 -0
  58. package/dist/bridge/hook-fast.js +68 -0
  59. package/dist/bridge/install.d.ts +16 -1
  60. package/dist/bridge/install.js +88 -21
  61. package/dist/bridge/launch-brief.d.ts +96 -0
  62. package/dist/bridge/launch-brief.js +164 -0
  63. package/dist/bridge/model-switch.d.ts +3 -0
  64. package/dist/bridge/model-switch.js +17 -1
  65. package/dist/bridge/models.d.ts +8 -4
  66. package/dist/bridge/models.js +24 -8
  67. package/dist/bridge/mux-wire.d.ts +9 -0
  68. package/dist/bridge/mux-wire.js +19 -0
  69. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  70. package/dist/bridge/opencode-pane-server.js +332 -0
  71. package/dist/bridge/opencode-panes.d.ts +111 -0
  72. package/dist/bridge/opencode-panes.js +295 -0
  73. package/dist/bridge/pane-accounts.d.ts +8 -0
  74. package/dist/bridge/pane-accounts.js +46 -0
  75. package/dist/bridge/prompt-startup.d.ts +5 -0
  76. package/dist/bridge/prompt-startup.js +24 -0
  77. package/dist/bridge/protocol.d.ts +5 -0
  78. package/dist/bridge/protocol.js +4 -0
  79. package/dist/bridge/push.d.ts +5 -4
  80. package/dist/bridge/push.js +6 -4
  81. package/dist/bridge/questions.d.ts +37 -2
  82. package/dist/bridge/questions.js +158 -15
  83. package/dist/bridge/resources.d.ts +9 -3
  84. package/dist/bridge/resources.js +24 -8
  85. package/dist/bridge/schedule-format.d.ts +2 -0
  86. package/dist/bridge/schedule-format.js +3 -0
  87. package/dist/bridge/schedule-launch.d.ts +2 -1
  88. package/dist/bridge/schedule-launch.js +23 -53
  89. package/dist/bridge/schedule-watch.d.ts +10 -1
  90. package/dist/bridge/schedule-watch.js +54 -2
  91. package/dist/bridge/server-launch.d.ts +22 -5
  92. package/dist/bridge/server-launch.js +225 -29
  93. package/dist/bridge/server-overview.d.ts +3 -3
  94. package/dist/bridge/server-overview.js +22 -14
  95. package/dist/bridge/server-pane-routes.d.ts +2 -0
  96. package/dist/bridge/server-pane-routes.js +145 -15
  97. package/dist/bridge/server-routes.d.ts +7 -0
  98. package/dist/bridge/server-routes.js +163 -35
  99. package/dist/bridge/server-stream.d.ts +2 -0
  100. package/dist/bridge/server-stream.js +22 -8
  101. package/dist/bridge/server.d.ts +6 -1
  102. package/dist/bridge/server.js +44 -12
  103. package/dist/bridge/session-activity.d.ts +81 -0
  104. package/dist/bridge/session-activity.js +117 -0
  105. package/dist/bridge/session-rename.d.ts +48 -0
  106. package/dist/bridge/session-rename.js +190 -0
  107. package/dist/bridge/session-servers.js +2 -2
  108. package/dist/bridge/settings-switch.d.ts +60 -0
  109. package/dist/bridge/settings-switch.js +287 -0
  110. package/dist/bridge/speech-voice.d.ts +55 -0
  111. package/dist/bridge/speech-voice.js +132 -0
  112. package/dist/bridge/speech.d.ts +70 -11
  113. package/dist/bridge/speech.js +169 -41
  114. package/dist/bridge/terminal-herdr.js +9 -3
  115. package/dist/bridge/terminal-tmux.d.ts +3 -3
  116. package/dist/bridge/terminal-tmux.js +24 -9
  117. package/dist/bridge/terminal.d.ts +27 -4
  118. package/dist/bridge/terminal.js +8 -1
  119. package/dist/bridge/transcript-claude.js +57 -12
  120. package/dist/bridge/transcript-codex.d.ts +0 -2
  121. package/dist/bridge/transcript-codex.js +29 -4
  122. package/dist/bridge/transcript-preview.d.ts +1 -0
  123. package/dist/bridge/transcript-preview.js +24 -4
  124. package/dist/bridge/transcripts.d.ts +15 -2
  125. package/dist/bridge/transcripts.js +47 -16
  126. package/dist/bridge/turn-records.d.ts +85 -0
  127. package/dist/bridge/turn-records.js +143 -0
  128. package/dist/bridge/uploads.d.ts +3 -0
  129. package/dist/bridge/uploads.js +14 -0
  130. package/dist/bridge/usage.d.ts +39 -10
  131. package/dist/bridge/usage.js +155 -44
  132. package/dist/bridge-hook.mjs +19169 -13176
  133. package/dist/cli/claude-unmanaged.d.ts +12 -0
  134. package/dist/cli/claude-unmanaged.js +105 -0
  135. package/dist/cli/schedules.js +2 -1
  136. package/dist/cli/session-start.js +10 -1
  137. package/dist/cli/session-stop.js +9 -1
  138. package/dist/cli-registry.js +24 -5
  139. package/dist/data/task-receipts.d.ts +19 -0
  140. package/dist/data/task-receipts.js +68 -0
  141. package/dist/data/tasks.js +4 -1
  142. package/dist/generated/memory-ui-graph.browser.js +63 -63
  143. package/dist/graph-core/model.js +24 -3
  144. package/dist/graph-core/types.d.ts +4 -1
  145. package/dist/graph-core/types.js +1 -0
  146. package/dist/init/init-preset.js +7 -3
  147. package/dist/init/init-uninstall.js +2 -11
  148. package/dist/init/teardown.d.ts +3 -0
  149. package/dist/init/teardown.js +47 -0
  150. package/dist/link/context.js +21 -9
  151. package/dist/mcp/plugin-mode.js +1 -1
  152. package/dist/memory-ui-graph.runtime.js +63 -63
  153. package/dist/modules/code-package.d.ts +1 -0
  154. package/dist/modules/code-package.js +36 -7
  155. package/dist/modules/registry.js +14 -13
  156. package/dist/profile-store.d.ts +6 -0
  157. package/dist/profile-store.js +25 -1
  158. package/dist/shell/graph/glyphs.js +4 -0
  159. package/dist/shell/graph/graph-view.js +2 -0
  160. package/dist/status.js +7 -1
  161. package/dist/sync/task-claim.js +3 -2
  162. package/dist/task/lifecycle.js +25 -4
  163. package/dist/test-global-setup.js +5 -0
  164. package/dist/tools/dispatch.js +35 -2
  165. package/dist/tools/tasks.js +10 -1
  166. package/package.json +1 -1
  167. package/plugins/opencode/phren-transcript.js +87 -4
  168. package/starter/global/skills/conductor/SKILL.md +17 -2
@@ -27,6 +27,8 @@ export declare const manifestSchema: z.ZodObject<{
27
27
  worktree: z.ZodString;
28
28
  model: z.ZodOptional<z.ZodString>;
29
29
  eventLog: z.ZodString;
30
+ nativeTranscript: z.ZodOptional<z.ZodString>;
31
+ unmanagedPid: z.ZodOptional<z.ZodNumber>;
30
32
  createdAt: z.ZodString;
31
33
  startedAt: z.ZodString;
32
34
  updatedAt: z.ZodString;
@@ -60,9 +62,11 @@ export interface FanoutChild {
60
62
  cwd: string;
61
63
  path: string;
62
64
  callId: string;
63
- state: "running" | "completed" | "failed";
65
+ state: "running" | "completed" | "failed" | "gone";
64
66
  /** `blocked: <type> <pattern>` when the plugin refused a permission. */
65
67
  reason?: string;
68
+ /** Actual launch time from a validated manifest; queued jobs omit it. */
69
+ startedAt?: string;
66
70
  finishedAt?: string;
67
71
  transcript: string;
68
72
  fanout: {
@@ -75,6 +79,7 @@ export declare function fanoutRoot(env?: NodeJS.ProcessEnv): string;
75
79
  /** Bind public worker identities to the canonical store as well as their parent. */
76
80
  export declare function fanoutChildID(root: string, manifest: FanoutManifest): string;
77
81
  export declare function containedFanoutRoot(env: NodeJS.ProcessEnv): Promise<string | undefined>;
82
+ export declare function nativeClaudeTranscript(candidate: string, session: string): Promise<string | undefined>;
78
83
  /** Read only manifests explicitly bound to the already validated parent. */
79
84
  export declare function fanoutChildren(parentProvider: Provider, parentSession: string, env?: NodeJS.ProcessEnv, parentComputer?: string): Promise<FanoutChild[]>;
80
85
  /** Every fan-out job's worktree with its task label and harness, whatever
@@ -107,6 +112,7 @@ export declare function blockedFanouts(env?: NodeJS.ProcessEnv): Promise<Blocked
107
112
  export declare function fanoutAsking(job: unknown, session: string, env?: NodeJS.ProcessEnv): Promise<{
108
113
  id: string;
109
114
  label: string;
115
+ worktree: string;
110
116
  parent: NonNullable<FanoutManifest["parent"]>;
111
117
  } | undefined>;
112
118
  export interface FanoutArchiveResult {
@@ -7,6 +7,7 @@ import { promisify } from "node:util";
7
7
  import { z } from "zod";
8
8
  import { object, sessionId } from "./protocol.js";
9
9
  import { countGit } from "./metrics.js";
10
+ import { claudeHomes } from "./claude-accounts.js";
10
11
  import { readOpencodeRequest } from "./opencode-approvals.js";
11
12
  const MAX_MANIFEST_BYTES = 64 * 1024;
12
13
  const MAX_EVENT_LOG_BYTES = 64 * 1024 * 1024;
@@ -37,6 +38,8 @@ export const manifestSchema = z.object({
37
38
  worktree: z.string().min(1).max(4096).refine(path.isAbsolute),
38
39
  model: z.string().min(1).max(200).optional(),
39
40
  eventLog: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/),
41
+ nativeTranscript: z.string().min(1).max(4096).refine(path.isAbsolute).optional(),
42
+ unmanagedPid: z.number().int().positive().optional(),
40
43
  createdAt: timestamp,
41
44
  startedAt: timestamp,
42
45
  updatedAt: timestamp,
@@ -47,6 +50,10 @@ export const manifestSchema = z.object({
47
50
  resumes: sessionId.optional(),
48
51
  schedule: z.object({ id: z.string().regex(/^[a-f0-9]{8}$/), project: z.string().min(1).max(200) }).optional(),
49
52
  }).strict().superRefine((manifest, ctx) => {
53
+ if (manifest.nativeTranscript && (manifest.provider !== "claude" || !manifest.unmanagedPid || !manifest.session))
54
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["nativeTranscript"], message: "A native transcript needs an unmanaged Claude process." });
55
+ if (manifest.unmanagedPid && !manifest.nativeTranscript)
56
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["unmanagedPid"], message: "An unmanaged process needs a native transcript." });
50
57
  // OpenCode sessions are `ses_…`; Codex and Claude sessions are UUIDs.
51
58
  // A provider cannot claim another provider's identity shape.
52
59
  if (manifest.session === undefined)
@@ -127,6 +134,28 @@ async function regularContainedFile(root, candidate, maxBytes) {
127
134
  return;
128
135
  }
129
136
  }
137
+ export async function nativeClaudeTranscript(candidate, session) {
138
+ if (path.basename(candidate) !== `${session}.jsonl`)
139
+ return;
140
+ for (const home of claudeHomes()) {
141
+ const resolvedRoot = await realpath(path.join(home.dir, "projects")).catch(() => undefined);
142
+ if (!resolvedRoot)
143
+ continue;
144
+ const file = await regularContainedFile(resolvedRoot, candidate, MAX_EVENT_LOG_BYTES);
145
+ if (file)
146
+ return file;
147
+ }
148
+ return undefined;
149
+ }
150
+ function pidGone(pid) {
151
+ try {
152
+ process.kill(pid, 0);
153
+ return false;
154
+ }
155
+ catch (error) {
156
+ return error.code === "ESRCH";
157
+ }
158
+ }
130
159
  async function readBlocked(jobRoot) {
131
160
  const file = await regularContainedFile(jobRoot, path.join(jobRoot, "blocked.json"), MAX_BLOCKED_BYTES);
132
161
  if (file) {
@@ -201,7 +230,10 @@ export async function fanoutChildren(parentProvider, parentSession, env = proces
201
230
  const jobRoot = await realpath(directory);
202
231
  if (!jobRoot.startsWith(root + path.sep))
203
232
  continue;
204
- const transcript = await regularContainedFile(jobRoot, path.join(jobRoot, manifest.eventLog), MAX_EVENT_LOG_BYTES);
233
+ const transcript = manifest.nativeTranscript && manifest.session
234
+ ? await nativeClaudeTranscript(manifest.nativeTranscript, manifest.session)
235
+ ?? await regularContainedFile(jobRoot, path.join(jobRoot, manifest.eventLog), MAX_EVENT_LOG_BYTES)
236
+ : await regularContainedFile(jobRoot, path.join(jobRoot, manifest.eventLog), MAX_EVENT_LOG_BYTES);
205
237
  if (!transcript)
206
238
  continue;
207
239
  const worktree = await worktreeDetails(manifest.worktree);
@@ -212,13 +244,16 @@ export async function fanoutChildren(parentProvider, parentSession, env = proces
212
244
  // A running worker waiting on the phone's answer to a permission ask.
213
245
  const asking = !blocked && manifest.status === "running" && manifest.provider === "opencode" && manifest.session
214
246
  ? await readOpencodeRequest(manifest.session, storeRoot(env)) : undefined;
247
+ const gone = manifest.status === "running" && manifest.unmanagedPid !== undefined && pidGone(manifest.unmanagedPid);
215
248
  const finishedAt = manifest.finishedAt ?? blocked?.at
249
+ ?? (gone ? manifest.updatedAt : undefined)
216
250
  ?? (ARCHIVED_STATUSES.has(manifest.status)
217
251
  ? (await stat(path.join(jobRoot, "exit.txt")).catch(() => undefined))?.mtime.toISOString() ?? manifest.updatedAt : undefined);
218
252
  children.push({ id, provider: manifest.provider, session: manifest.session, model: manifest.model, ...worktree, cwd: manifest.worktree,
219
253
  path: manifest.taskLabel, callId: `fanout:${id}`,
220
- state: blocked || manifest.status === "failed" || manifest.status === "cancelled" ? "failed" : ["queued", "running"].includes(manifest.status) ? "running" : "completed",
221
- ...(blocked ? { reason: blockedReason(blocked) } : asking ? { reason: `needs-you: ${String(asking.message ?? asking.type)}`.slice(0, 500) } : {}), ...(finishedAt ? { finishedAt } : {}), transcript,
254
+ state: blocked || manifest.status === "failed" || manifest.status === "cancelled" ? "failed" : gone ? "gone" : ["queued", "running"].includes(manifest.status) ? "running" : "completed",
255
+ ...(blocked ? { reason: blockedReason(blocked) } : gone ? { reason: "gone: worker process exited" } : asking ? { reason: `needs-you: ${String(asking.message ?? asking.type)}`.slice(0, 500) } : {}),
256
+ ...(manifest.status === "queued" ? {} : { startedAt: manifest.startedAt }), ...(finishedAt ? { finishedAt } : {}), transcript,
222
257
  fanout: { resumable: manifest.session !== undefined }, children: [] });
223
258
  }
224
259
  catch { /* Torn, old, or untrusted manifests do not become child agents. */ }
@@ -296,7 +331,7 @@ export async function fanoutAsking(job, session, env = process.env) {
296
331
  const manifest = manifestSchema.parse(JSON.parse(await readFile(file, "utf8")));
297
332
  if (manifest.id !== job || manifest.provider !== "opencode" || manifest.session !== session || manifest.status !== "running" || !manifest.parent)
298
333
  return undefined;
299
- return { id: manifest.id, label: manifest.taskLabel, parent: manifest.parent };
334
+ return { id: manifest.id, label: manifest.taskLabel, worktree: manifest.worktree, parent: manifest.parent };
300
335
  }
301
336
  catch {
302
337
  return undefined;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Marking a folder the Hook chose as trusted, so a Claude or Codex launched
3
+ * there starts without its folder-trust screen. Claude's default on that
4
+ * screen is "No, exit", so a dispatched worker would otherwise sit there
5
+ * until the owner answers it (the brief is never sent; see dispatch.ts).
6
+ *
7
+ * Only callers that picked the folder themselves use this: a dispatched or
8
+ * scheduled project's resolved source folder and a worktree the Hook just
9
+ * created. Never a parent, never a folder the phone typed in. Each harness
10
+ * gets exactly one key for exactly that path:
11
+ *
12
+ * - Claude: `projects[<dir>].hasTrustDialogAccepted = true` in its global
13
+ * config (`$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json`; a
14
+ * legacy `<config dir>/.config.json` wins when it exists). Claude checks
15
+ * that key for the working folder and each parent up to its git root.
16
+ * - Codex: `[projects."<dir>"]` `trust_level = "trusted"` in
17
+ * `$CODEX_HOME/config.toml`, the table Codex itself writes on "Yes".
18
+ *
19
+ * Both were checked against Claude Code 2.1.280 and codex-cli 0.155.1.
20
+ * `PHREN_PRETRUST=off` turns all of it off.
21
+ */
22
+ export type TrustHarness = "claude" | "codex";
23
+ export type TrustResult = "trusted" | "already" | "skipped";
24
+ export declare function pretrustEnabled(env?: NodeJS.ProcessEnv): boolean;
25
+ /** Claude Code's global config file, resolved the way Claude resolves it. */
26
+ export declare function claudeGlobalConfigFile(env?: NodeJS.ProcessEnv): Promise<string>;
27
+ /**
28
+ * The `projects` key Claude reads for `dir`: the normalized path, with
29
+ * forward slashes on Windows (`C:/Users/me/repo`). Claude 2.1.280 builds
30
+ * every lookup and write key this way (`normalize`, then
31
+ * `replaceAll("\\", "/")` when the platform is Windows) and looks the key up
32
+ * exactly, so a backslash key is never read there.
33
+ */
34
+ export declare function claudeProjectKey(dir: string, platform?: NodeJS.Platform): string;
35
+ /**
36
+ * Sets `projects[dir].hasTrustDialogAccepted` and nothing else. Claude
37
+ * rewrites this file all the time, so the write happens under Claude's own
38
+ * lock, from a fresh read, and is retried when the file changed between the
39
+ * read and the rename. A missing or unparsable file is left alone: that is
40
+ * a Claude that has not finished its own first run, which needs the owner.
41
+ */
42
+ export declare function ensureClaudeFolderTrusted(dir: string, env?: NodeJS.ProcessEnv): Promise<TrustResult>;
43
+ /** The config text with `[projects."<dir>"]` trusted, or undefined when it already is. */
44
+ export declare function codexTrustedText(text: string, dir: string): string | undefined;
45
+ /**
46
+ * Adds or flips the one `trust_level` line for `dir` in Codex's
47
+ * `config.toml`, appending the table when it is absent. The rest of the
48
+ * file is kept byte for byte. An unreadable config is left untouched.
49
+ */
50
+ export declare function ensureCodexDirTrusted(dir: string, env?: NodeJS.ProcessEnv): Promise<TrustResult>;
51
+ /**
52
+ * Trusts `dir` for `harness` before a launch, when the harness has a trust
53
+ * screen and pre-trust is on. Never throws: a failure is logged and the
54
+ * launch goes on to meet the screen, which dispatch then reports.
55
+ */
56
+ export declare function pretrustFolder(harness: string, dir: string, why: string, env?: NodeJS.ProcessEnv): Promise<TrustResult>;
@@ -0,0 +1,195 @@
1
+ import { lstat, mkdir, readFile, realpath, rmdir, stat, utimes } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { claudeConfigDir, codexHome, homeDir } from "../home-paths.js";
4
+ import { logger } from "../logger.js";
5
+ import { atomic } from "./protocol.js";
6
+ export function pretrustEnabled(env = process.env) {
7
+ return !/^(off|0|false|no)$/i.test(env.PHREN_PRETRUST?.trim() ?? "");
8
+ }
9
+ /** Claude Code's global config file, resolved the way Claude resolves it. */
10
+ export async function claudeGlobalConfigFile(env = process.env) {
11
+ const legacy = path.join(claudeConfigDir(env), ".config.json");
12
+ if (await stat(legacy).then(info => info.isFile(), () => false))
13
+ return legacy;
14
+ const configured = env.CLAUDE_CONFIG_DIR?.trim();
15
+ return path.join(configured ? path.resolve(configured) : homeDir(env), ".claude.json");
16
+ }
17
+ /**
18
+ * The `projects` key Claude reads for `dir`: the normalized path, with
19
+ * forward slashes on Windows (`C:/Users/me/repo`). Claude 2.1.280 builds
20
+ * every lookup and write key this way (`normalize`, then
21
+ * `replaceAll("\\", "/")` when the platform is Windows) and looks the key up
22
+ * exactly, so a backslash key is never read there.
23
+ */
24
+ export function claudeProjectKey(dir, platform = process.platform) {
25
+ return platform === "win32" ? path.win32.normalize(dir).replaceAll("\\", "/") : path.posix.normalize(dir);
26
+ }
27
+ /** Claude takes `<file>.lock` (a proper-lockfile directory) around each config write; so does this. */
28
+ const LOCK_WAIT_MS = 3_000, LOCK_STALE_MS = 10_000;
29
+ async function withClaudeLock(file, work) {
30
+ const lock = `${file}.lock`, deadline = Date.now() + LOCK_WAIT_MS;
31
+ for (;;) {
32
+ try {
33
+ await mkdir(lock);
34
+ break;
35
+ }
36
+ catch (error) {
37
+ if (error.code !== "EEXIST")
38
+ throw error;
39
+ const held = await stat(lock).catch(() => undefined);
40
+ // A lock nobody refreshed for LOCK_STALE_MS belongs to a process that
41
+ // died holding it; proper-lockfile takes it over the same way.
42
+ if (held && Date.now() - held.mtimeMs > LOCK_STALE_MS) {
43
+ await rmdir(lock).catch(() => undefined);
44
+ continue;
45
+ }
46
+ if (Date.now() >= deadline)
47
+ throw new Error(`${path.basename(lock)} is held by another process`);
48
+ await new Promise(resolve => setTimeout(resolve, 50));
49
+ }
50
+ }
51
+ try {
52
+ return await work();
53
+ }
54
+ finally {
55
+ await utimes(lock, new Date(), new Date()).catch(() => undefined);
56
+ await rmdir(lock).catch(() => undefined);
57
+ }
58
+ }
59
+ /**
60
+ * Sets `projects[dir].hasTrustDialogAccepted` and nothing else. Claude
61
+ * rewrites this file all the time, so the write happens under Claude's own
62
+ * lock, from a fresh read, and is retried when the file changed between the
63
+ * read and the rename. A missing or unparsable file is left alone: that is
64
+ * a Claude that has not finished its own first run, which needs the owner.
65
+ */
66
+ export async function ensureClaudeFolderTrusted(dir, env = process.env) {
67
+ const configured = await claudeGlobalConfigFile(env);
68
+ // Write through a symlinked config to its target, never over the link.
69
+ const file = await realpath(configured).catch(() => configured);
70
+ const key = claudeProjectKey(dir);
71
+ return withClaudeLock(file, async () => {
72
+ for (let attempt = 0; attempt < 3; attempt++) {
73
+ const before = await stat(file).catch(error => {
74
+ if (error.code === "ENOENT")
75
+ return undefined;
76
+ throw error;
77
+ });
78
+ if (!before)
79
+ return "skipped";
80
+ const text = await readFile(file, "utf8");
81
+ const config = JSON.parse(text);
82
+ if (!config || typeof config !== "object" || Array.isArray(config))
83
+ throw new Error(`${path.basename(file)} is not a JSON object`);
84
+ const record = config;
85
+ const projects = record.projects && typeof record.projects === "object" && !Array.isArray(record.projects)
86
+ ? record.projects : {};
87
+ const current = projects[key];
88
+ const entry = current && typeof current === "object" && !Array.isArray(current) ? current : {};
89
+ if (entry.hasTrustDialogAccepted === true)
90
+ return "already";
91
+ const next = { ...record, projects: { ...projects, [key]: { ...entry, hasTrustDialogAccepted: true } } };
92
+ const now = await stat(file);
93
+ if (now.mtimeMs !== before.mtimeMs || now.size !== before.size)
94
+ continue;
95
+ await atomic(file, JSON.stringify(next, null, 2), before.mode & 0o777);
96
+ return "trusted";
97
+ }
98
+ throw new Error(`${path.basename(file)} kept changing while it was being updated`);
99
+ });
100
+ }
101
+ function tomlQuote(value) {
102
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
103
+ }
104
+ /** The config text with `[projects."<dir>"]` trusted, or undefined when it already is. */
105
+ export function codexTrustedText(text, dir) {
106
+ const header = `[projects.${tomlQuote(dir)}]`;
107
+ const trustLine = 'trust_level = "trusted"';
108
+ const at = text.indexOf(header);
109
+ if (at < 0) {
110
+ const separator = text && !text.endsWith("\n") ? "\n\n" : text ? "\n" : "";
111
+ return text + `${separator}${header}\n${trustLine}\n`;
112
+ }
113
+ const bodyStart = at + header.length;
114
+ const rest = text.slice(bodyStart);
115
+ const nextTable = rest.search(/^\s*\[/m);
116
+ const section = nextTable >= 0 ? rest.slice(0, nextTable) : rest;
117
+ if (/^[ \t]*trust_level\s*=\s*"trusted"/m.test(section))
118
+ return undefined;
119
+ const existing = /^[ \t]*trust_level\s*=.*$/m.exec(section);
120
+ if (existing) {
121
+ const replaced = section.replace(existing[0], existing[0].match(/^[ \t]*/)[0] + trustLine);
122
+ return text.slice(0, bodyStart) + replaced + rest.slice(section.length);
123
+ }
124
+ const startsWithNewline = section.startsWith("\n") || section.startsWith("\r\n");
125
+ // The table exists without the key: it goes on its own line under the header.
126
+ return text.slice(0, bodyStart) + "\n" + trustLine + (startsWithNewline ? section : "\n" + section) + rest.slice(section.length);
127
+ }
128
+ /**
129
+ * Adds or flips the one `trust_level` line for `dir` in Codex's
130
+ * `config.toml`, appending the table when it is absent. The rest of the
131
+ * file is kept byte for byte. An unreadable config is left untouched.
132
+ */
133
+ export async function ensureCodexDirTrusted(dir, env = process.env) {
134
+ const directory = codexHome(env);
135
+ const configured = path.join(directory, "config.toml");
136
+ const file = await realpath(configured).catch(() => configured);
137
+ for (let attempt = 0; attempt < 3; attempt++) {
138
+ let text = "";
139
+ try {
140
+ text = await readFile(file, "utf8");
141
+ }
142
+ catch (error) {
143
+ if (error.code !== "ENOENT")
144
+ throw error;
145
+ }
146
+ const next = codexTrustedText(text, dir);
147
+ if (next === undefined)
148
+ return "already";
149
+ await mkdir(directory, { recursive: true, mode: 0o700 });
150
+ const metadata = await lstat(file).catch(() => undefined);
151
+ // Codex may have rewritten the file meanwhile; start over from its text.
152
+ if (await readFile(file, "utf8").catch(() => "") !== text)
153
+ continue;
154
+ await atomic(file, next, metadata ? metadata.mode & 0o777 : 0o600);
155
+ return "trusted";
156
+ }
157
+ throw new Error("config.toml kept changing while it was being updated");
158
+ }
159
+ /**
160
+ * Trusts `dir` for `harness` before a launch, when the harness has a trust
161
+ * screen and pre-trust is on. Never throws: a failure is logged and the
162
+ * launch goes on to meet the screen, which dispatch then reports.
163
+ */
164
+ export async function pretrustFolder(harness, dir, why, env = process.env) {
165
+ if (harness !== "claude" && harness !== "codex")
166
+ return "skipped";
167
+ if (!pretrustEnabled(env))
168
+ return "skipped";
169
+ if (!path.isAbsolute(dir))
170
+ return "skipped";
171
+ const name = harness === "claude" ? "Claude" : "Codex";
172
+ // The same folder by the path the Hook was given and by its real path: the
173
+ // harness keys trust by whichever one its working directory reports.
174
+ const real = await realpath(dir).catch(() => undefined);
175
+ if (!real || !(await stat(real).then(info => info.isDirectory(), () => false)))
176
+ return "skipped";
177
+ let outcome = "already";
178
+ for (const folder of [...new Set([dir, real])]) {
179
+ try {
180
+ const result = harness === "claude" ? await ensureClaudeFolderTrusted(folder, env) : await ensureCodexDirTrusted(folder, env);
181
+ if (result === "trusted")
182
+ logger.info("launch", `Marked ${folder} trusted for ${name} (${why}).`);
183
+ else if (result === "skipped")
184
+ logger.warn("launch", `Did not mark ${folder} trusted for ${name}: its config file does not exist yet.`);
185
+ if (result === "trusted" || (result === "skipped" && outcome === "already"))
186
+ outcome = result;
187
+ }
188
+ catch (error) {
189
+ logger.warn("launch", `Could not mark ${folder} trusted for ${name} (${why}): ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`);
190
+ if (outcome === "already")
191
+ outcome = "skipped";
192
+ }
193
+ }
194
+ return outcome;
195
+ }
@@ -1,4 +1,6 @@
1
1
  import { z } from "zod";
2
+ import { type PermissionMode } from "./protocol.js";
3
+ import { type Computer } from "./computer-identity.js";
2
4
  declare const grantAction: z.ZodEnum<{
3
5
  dispatch: "dispatch";
4
6
  hand_off: "hand_off";
@@ -11,6 +13,12 @@ export declare const grantSchema: z.ZodObject<{
11
13
  }>>;
12
14
  computers: z.ZodOptional<z.ZodArray<z.ZodString>>;
13
15
  until: z.ZodOptional<z.ZodString>;
16
+ maxPermissionMode: z.ZodOptional<z.ZodEnum<{
17
+ auto: "auto";
18
+ "auto-edits": "auto-edits";
19
+ "full-access": "full-access";
20
+ supervised: "supervised";
21
+ }>>;
14
22
  }, z.core.$strict>;
15
23
  export type Grant = z.infer<typeof grantSchema>;
16
24
  export declare function listGrants(root?: string): Promise<Grant[]>;
@@ -18,11 +26,24 @@ export interface GrantQuery {
18
26
  action: z.infer<typeof grantAction>;
19
27
  project?: string;
20
28
  computer?: string;
29
+ /** The computers this Hook knows, so a grant naming any alias of `computer` matches. */
30
+ computers?: readonly Computer[];
21
31
  }
22
- /** Most specific matching grant wins. A computers-restricted grant never
32
+ /** Most specific matching grant wins. A grant's computers may be any name the
33
+ * destination answers to (see `computer-identity.ts`). A computers-restricted grant never
23
34
  * covers an unresolved destination: `anywhere` may pick a peer outside the
24
35
  * list, and a local hand-off never goes to one of them. */
25
36
  export declare function matchGrant(grants: Grant[], query: GrantQuery, now?: number): Grant | undefined;
37
+ /** matchGrant over the stored grants; the known computers are read once, and
38
+ * only when a grant restricts computers. */
39
+ export declare function findGrant(query: Omit<GrantQuery, "computers">, root?: string): Promise<Grant | undefined>;
40
+ /** Grants as listed to people: computers by canonical name. The file is left as written. */
41
+ export declare function listNamedGrants(root?: string): Promise<Grant[]>;
42
+ /** The highest permission mode an agent may ask for under a grant. Without a
43
+ * grant, or with one that names no ceiling, that is auto: full-access needs a
44
+ * grant that says so. */
45
+ export declare const DEFAULT_MAX_PERMISSION_MODE: PermissionMode;
46
+ export declare function permissionModeAllowed(mode: PermissionMode, grant: Grant | undefined): boolean;
26
47
  export declare function grantLabel(grant: Grant): string;
27
48
  export declare function addGrant(input: unknown, root?: string): Promise<Grant>;
28
49
  /** Write a grant from an approval card answer: already listed is success. */
@@ -3,7 +3,8 @@ import { lstat, mkdir, readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { dump, load } from "js-yaml";
5
5
  import { z } from "zod";
6
- import { atomic, BridgeError, bridgeRoot, computerName } from "./protocol.js";
6
+ import { atomic, BridgeError, bridgeRoot, computerName, PERMISSION_MODES } from "./protocol.js";
7
+ import { readComputers, resolveComputer } from "./computer-identity.js";
7
8
  const grantAction = z.enum(["dispatch", "hand_off"]);
8
9
  const grantScope = z.union([
9
10
  z.literal("global"),
@@ -14,6 +15,7 @@ export const grantSchema = z.object({
14
15
  actions: z.array(grantAction).min(1).max(2).describe("Which conductor actions this grant covers."),
15
16
  computers: z.array(computerName).min(1).max(32).optional().describe("Named verified peers; omitted means any."),
16
17
  until: z.string().datetime({ offset: true }).optional().describe("Expiry timestamp; omitted means until revoked."),
18
+ maxPermissionMode: z.enum(PERMISSION_MODES).optional().describe("Highest permission mode an agent may start a dispatched worker in; omitted means auto (never full-access)."),
17
19
  }).strict();
18
20
  const grantFile = (root = bridgeRoot()) => path.join(root, "conductor.yaml");
19
21
  const fileSchema = z.object({ grants: z.array(grantSchema).max(64) }).strict();
@@ -64,11 +66,19 @@ async function writeGrants(root, grants) {
64
66
  await mkdir(root, { recursive: true, mode: 0o700 });
65
67
  await atomic(file, dump({ grants }, { lineWidth: 120 }));
66
68
  }
69
+ /** A grant's computer list names `computer` itself or another name of the same computer. */
70
+ function namesComputer(list, computer, known) {
71
+ if (list.includes(computer))
72
+ return true;
73
+ const row = known && resolveComputer(known, computer);
74
+ return !!row && list.some(name => resolveComputer(known, name) === row);
75
+ }
67
76
  /** Project scope beats global; a named computer list beats any. */
68
77
  function specificity(grant) {
69
78
  return (grant.scope === "global" ? 0 : 2) + (grant.computers ? 1 : 0);
70
79
  }
71
- /** Most specific matching grant wins. A computers-restricted grant never
80
+ /** Most specific matching grant wins. A grant's computers may be any name the
81
+ * destination answers to (see `computer-identity.ts`). A computers-restricted grant never
72
82
  * covers an unresolved destination: `anywhere` may pick a peer outside the
73
83
  * list, and a local hand-off never goes to one of them. */
74
84
  export function matchGrant(grants, query, now = Date.now()) {
@@ -82,12 +92,42 @@ export function matchGrant(grants, query, now = Date.now()) {
82
92
  if (query.project !== slug)
83
93
  return false;
84
94
  }
85
- if (grant.computers && (!query.computer || query.computer === "anywhere" || !grant.computers.includes(query.computer)))
95
+ if (grant.computers && (!query.computer || query.computer === "anywhere" || !namesComputer(grant.computers, query.computer, query.computers)))
86
96
  return false;
87
97
  return true;
88
98
  });
89
99
  return matches.sort((a, b) => specificity(b) - specificity(a))[0];
90
100
  }
101
+ /** matchGrant over the stored grants; the known computers are read once, and
102
+ * only when a grant restricts computers. */
103
+ export async function findGrant(query, root = bridgeRoot()) {
104
+ const grants = await listGrants(root);
105
+ const restricted = query.computer && query.computer !== "anywhere" && grants.some(grant => grant.computers);
106
+ return matchGrant(grants, { ...query, ...(restricted ? { computers: (await readComputers({ root, trusted: true })).computers } : {}) });
107
+ }
108
+ /** The grant with each computer named by its canonical name; unknown names stay. */
109
+ function nameComputers(grant, known) {
110
+ if (!grant.computers)
111
+ return grant;
112
+ return { ...grant, computers: [...new Set(grant.computers.map(name => resolveComputer(known, name)?.name ?? name))] };
113
+ }
114
+ async function knownFor(root, grants) {
115
+ return grants.some(grant => grant.computers) ? (await readComputers({ root, trusted: true })).computers : [];
116
+ }
117
+ /** Grants as listed to people: computers by canonical name. The file is left as written. */
118
+ export async function listNamedGrants(root = bridgeRoot()) {
119
+ const grants = await listGrants(root);
120
+ const known = await knownFor(root, grants);
121
+ return grants.map(grant => nameComputers(grant, known));
122
+ }
123
+ /** The highest permission mode an agent may ask for under a grant. Without a
124
+ * grant, or with one that names no ceiling, that is auto: full-access needs a
125
+ * grant that says so. */
126
+ export const DEFAULT_MAX_PERMISSION_MODE = "auto";
127
+ export function permissionModeAllowed(mode, grant) {
128
+ const ceiling = grant?.maxPermissionMode ?? DEFAULT_MAX_PERMISSION_MODE;
129
+ return PERMISSION_MODES.indexOf(mode) <= PERMISSION_MODES.indexOf(ceiling);
130
+ }
91
131
  export function grantLabel(grant) {
92
132
  return grant.scope;
93
133
  }
@@ -117,9 +157,11 @@ async function mutateGrants(root, action) {
117
157
  }
118
158
  export async function addGrant(input, root = bridgeRoot()) {
119
159
  return mutateGrants(root, async () => {
120
- const grant = grantSchema.parse(input);
160
+ const parsed = grantSchema.parse(input);
121
161
  const existing = await listGrants(root);
122
- if (existing.some(item => canonicalGrant(item) === canonicalGrant(grant))) {
162
+ const known = await knownFor(root, [parsed, ...existing]);
163
+ const grant = nameComputers(parsed, known);
164
+ if (existing.some(item => canonicalGrant(nameComputers(item, known)) === canonicalGrant(grant))) {
123
165
  throw new BridgeError(409, "That grant is already listed.");
124
166
  }
125
167
  if (existing.length >= 64)
@@ -134,9 +176,11 @@ function canonicalGrant(grant) {
134
176
  /** Write a grant from an approval card answer: already listed is success. */
135
177
  export async function ensureGrant(input, root = bridgeRoot()) {
136
178
  return mutateGrants(root, async () => {
137
- const grant = grantSchema.parse(input);
179
+ const parsed = grantSchema.parse(input);
138
180
  const existing = await listGrants(root);
139
- if (existing.some(item => canonicalGrant(item) === canonicalGrant(grant)))
181
+ const known = await knownFor(root, [parsed, ...existing]);
182
+ const grant = nameComputers(parsed, known);
183
+ if (existing.some(item => canonicalGrant(nameComputers(item, known)) === canonicalGrant(grant)))
140
184
  return grant;
141
185
  if (existing.length >= 64)
142
186
  throw new BridgeError(409, "conductor.yaml already holds 64 grants.");
@@ -157,6 +201,10 @@ export async function removeGrant(input, root = bridgeRoot()) {
157
201
  const existing = await listGrants(root);
158
202
  if (!existing.length)
159
203
  throw new BridgeError(404, "There are no conductor grants to remove.");
204
+ // The list shows canonical names, so compare that way, not by the raw text.
205
+ const known = await knownFor(root, [body, body.expected ?? {}, ...existing]);
206
+ const named = (grant) => nameComputers(grant, known);
207
+ const wanted = body.computers && named({ scope: "global", actions: ["dispatch"], computers: body.computers }).computers;
160
208
  let index = body.index;
161
209
  if (index === undefined) {
162
210
  // Scope names the row; the optional fields refine it. They never invent a
@@ -164,14 +212,14 @@ export async function removeGrant(input, root = bridgeRoot()) {
164
212
  const sameSet = (a, b) => a.length === b.length && [...a].sort().join() === [...b].sort().join();
165
213
  index = existing.findIndex(grant => grant.scope === body.scope
166
214
  && (body.actions === undefined || sameSet(grant.actions, body.actions))
167
- && (body.computers === undefined || (grant.computers !== undefined && sameSet(grant.computers, body.computers)))
215
+ && (wanted === undefined || (grant.computers !== undefined && sameSet(named(grant).computers, wanted)))
168
216
  && (body.until === undefined || grant.until === body.until));
169
217
  if (index < 0)
170
218
  throw new BridgeError(404, "No conductor grant matches that scope.");
171
219
  }
172
220
  if (index >= existing.length)
173
221
  throw new BridgeError(404, "No conductor grant has that index.");
174
- if (body.expected && canonicalGrant(existing[index]) !== canonicalGrant(body.expected)) {
222
+ if (body.expected && canonicalGrant(named(existing[index])) !== canonicalGrant(named(body.expected))) {
175
223
  throw new BridgeError(409, "The grants list changed. Refresh it before revoking this grant.");
176
224
  }
177
225
  const [removed] = existing.splice(index, 1);
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { type Target } from "./protocol.js";
3
+ import { computerLabel, type PeerFacts } from "./computer-identity.js";
4
+ export { computerLabel };
3
5
  export declare const handOffSchema: z.ZodObject<{
4
6
  computer: z.ZodOptional<z.ZodString>;
5
7
  target: z.ZodOptional<z.ZodObject<{
@@ -18,13 +20,21 @@ export declare const handOffSchema: z.ZodObject<{
18
20
  }, z.core.$strip>>;
19
21
  session: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodString]>>;
20
22
  project: z.ZodOptional<z.ZodString>;
23
+ account: z.ZodOptional<z.ZodString>;
21
24
  text: z.ZodString;
22
25
  }, z.core.$strict>;
23
26
  export type HandOffInput = z.infer<typeof handOffSchema>;
24
- export declare function handOff(input: unknown): Promise<{
27
+ /** `deliveryId` names this one message on the receiving Hook, which then types
28
+ * it at most once however often it is sent (the Hook's own callers retry;
29
+ * the MCP tool does not take one). */
30
+ export declare function handOff(input: unknown, options?: {
31
+ deliveryId?: string;
32
+ }): Promise<{
25
33
  ok: boolean;
26
34
  delivered: boolean;
27
35
  target: Target;
36
+ deliveryUncertain?: boolean;
37
+ unsubmitted?: boolean;
28
38
  label?: string;
29
39
  granted?: string;
30
40
  }>;
@@ -41,13 +51,13 @@ export interface LiveSession {
41
51
  branch?: string;
42
52
  model?: string;
43
53
  target?: Target;
54
+ /** Claude account id, when the Hook knows it; absent means the default account or an unknown one. */
55
+ account?: string;
44
56
  /** Seconds since the tab last changed, when the Hook has seen it change. */
45
57
  idleFor?: number;
58
+ /** Set when the main turn ended and this many background tasks keep the session `working`. */
59
+ backgroundTasks?: number;
46
60
  }
47
- /** A computer name's first DNS label, lowercased: `Desk`, `desk.local` and
48
- * `Desk.example.net` are one computer. DHCP and Bonjour add domains to the
49
- * same machine's name, so full names do not identify a computer. */
50
- export declare function computerLabel(name: string): string;
51
61
  /** A registered computer this Hook cannot see, with the other names the store
52
62
  * registers it under. */
53
63
  export interface NotLinkedComputer {
@@ -55,10 +65,12 @@ export interface NotLinkedComputer {
55
65
  aliases?: string[];
56
66
  }
57
67
  /** Computers the store registers (machines.yaml) that this Hook has no
58
- * verified connection to, so their sessions cannot be listed from here.
59
- * Names are compared by first label against this computer's names and each
60
- * peer's name, address and aliases; names sharing a label collapse into one
61
- * entry. */
68
+ * verified connection to, so their sessions cannot be listed from here: the
69
+ * unlinked rows of `foldComputers`, which folds names by first label and by
70
+ * shared profile into the computers it can see. */
71
+ export declare function notLinkedFrom(store: string | null, here: string, peers: readonly PeerFacts[]): NotLinkedComputer[];
72
+ /** As `notLinkedFrom` for a flat list of names the linked computers answer
73
+ * to, each standing for its own computer. */
62
74
  export declare function notLinkedComputers(store: string | null, here: string, linked: readonly string[]): NotLinkedComputer[];
63
75
  export interface LiveSessions {
64
76
  sessions: LiveSession[];