@phren/cli 0.3.11 → 0.3.13

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 (182) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  4. package/dist/bridge/agent-hook-stores.js +5 -0
  5. package/dist/bridge/agent-hooks.d.ts +162 -5
  6. package/dist/bridge/agent-hooks.js +682 -49
  7. package/dist/bridge/approval-summary.d.ts +16 -0
  8. package/dist/bridge/approval-summary.js +133 -0
  9. package/dist/bridge/authority-command.d.ts +20 -0
  10. package/dist/bridge/authority-command.js +120 -0
  11. package/dist/bridge/authority.d.ts +223 -0
  12. package/dist/bridge/authority.js +231 -0
  13. package/dist/bridge/claude-account-setup.d.ts +14 -0
  14. package/dist/bridge/claude-account-setup.js +69 -0
  15. package/dist/bridge/claude-accounts.d.ts +49 -0
  16. package/dist/bridge/claude-accounts.js +195 -0
  17. package/dist/bridge/code-routes.js +2 -2
  18. package/dist/bridge/codex-app-server.d.ts +144 -0
  19. package/dist/bridge/codex-app-server.js +319 -0
  20. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  21. package/dist/bridge/codex-auth-refresh.js +71 -0
  22. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  23. package/dist/bridge/codex-hook-trust.js +237 -0
  24. package/dist/bridge/codex-question-reply.d.ts +16 -0
  25. package/dist/bridge/codex-question-reply.js +57 -0
  26. package/dist/bridge/codex-review-mode.d.ts +10 -0
  27. package/dist/bridge/codex-review-mode.js +74 -0
  28. package/dist/bridge/codex-servers.d.ts +217 -0
  29. package/dist/bridge/codex-servers.js +636 -0
  30. package/dist/bridge/command.js +97 -4
  31. package/dist/bridge/computer-identity.d.ts +75 -0
  32. package/dist/bridge/computer-identity.js +166 -0
  33. package/dist/bridge/conductor-group.d.ts +91 -8
  34. package/dist/bridge/conductor-group.js +105 -9
  35. package/dist/bridge/conductor-role.d.ts +94 -0
  36. package/dist/bridge/conductor-role.js +176 -0
  37. package/dist/bridge/conductor-sets.d.ts +20 -0
  38. package/dist/bridge/conductor-sets.js +59 -0
  39. package/dist/bridge/dispatch-command.d.ts +3 -0
  40. package/dist/bridge/dispatch-command.js +82 -12
  41. package/dist/bridge/dispatch-returns.d.ts +128 -19
  42. package/dist/bridge/dispatch-returns.js +371 -54
  43. package/dist/bridge/dispatch.d.ts +128 -3
  44. package/dist/bridge/dispatch.js +303 -42
  45. package/dist/bridge/fanouts.d.ts +7 -1
  46. package/dist/bridge/fanouts.js +39 -4
  47. package/dist/bridge/folder-trust.d.ts +56 -0
  48. package/dist/bridge/folder-trust.js +195 -0
  49. package/dist/bridge/grants.d.ts +22 -1
  50. package/dist/bridge/grants.js +57 -9
  51. package/dist/bridge/hand-off-queue.d.ts +74 -0
  52. package/dist/bridge/hand-off-queue.js +235 -0
  53. package/dist/bridge/hand-off.d.ts +30 -10
  54. package/dist/bridge/hand-off.js +79 -46
  55. package/dist/bridge/harness-status.d.ts +11 -0
  56. package/dist/bridge/harness-status.js +32 -0
  57. package/dist/bridge/harnesses.d.ts +39 -0
  58. package/dist/bridge/harnesses.js +65 -0
  59. package/dist/bridge/health.d.ts +2 -0
  60. package/dist/bridge/health.js +1 -1
  61. package/dist/bridge/herdr.d.ts +11 -2
  62. package/dist/bridge/herdr.js +98 -23
  63. package/dist/bridge/hook-fast.d.ts +4 -0
  64. package/dist/bridge/hook-fast.js +68 -0
  65. package/dist/bridge/install.d.ts +16 -1
  66. package/dist/bridge/install.js +102 -21
  67. package/dist/bridge/launch-brief.d.ts +96 -0
  68. package/dist/bridge/launch-brief.js +164 -0
  69. package/dist/bridge/model-switch.d.ts +3 -0
  70. package/dist/bridge/model-switch.js +17 -1
  71. package/dist/bridge/models.d.ts +8 -4
  72. package/dist/bridge/models.js +24 -8
  73. package/dist/bridge/mux-wire.d.ts +9 -0
  74. package/dist/bridge/mux-wire.js +19 -0
  75. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  76. package/dist/bridge/opencode-pane-server.js +332 -0
  77. package/dist/bridge/opencode-panes.d.ts +111 -0
  78. package/dist/bridge/opencode-panes.js +295 -0
  79. package/dist/bridge/pane-accounts.d.ts +8 -0
  80. package/dist/bridge/pane-accounts.js +46 -0
  81. package/dist/bridge/pane-status.d.ts +12 -0
  82. package/dist/bridge/pane-status.js +50 -1
  83. package/dist/bridge/prompt-startup.d.ts +5 -0
  84. package/dist/bridge/prompt-startup.js +24 -0
  85. package/dist/bridge/protocol.d.ts +5 -0
  86. package/dist/bridge/protocol.js +4 -0
  87. package/dist/bridge/push.d.ts +11 -4
  88. package/dist/bridge/push.js +27 -4
  89. package/dist/bridge/questions.d.ts +37 -2
  90. package/dist/bridge/questions.js +158 -15
  91. package/dist/bridge/resources.d.ts +9 -3
  92. package/dist/bridge/resources.js +24 -8
  93. package/dist/bridge/schedule-format.d.ts +2 -0
  94. package/dist/bridge/schedule-format.js +3 -0
  95. package/dist/bridge/schedule-launch.d.ts +2 -1
  96. package/dist/bridge/schedule-launch.js +27 -53
  97. package/dist/bridge/schedule-watch.d.ts +24 -1
  98. package/dist/bridge/schedule-watch.js +89 -2
  99. package/dist/bridge/server-launch.d.ts +22 -5
  100. package/dist/bridge/server-launch.js +238 -32
  101. package/dist/bridge/server-overview.d.ts +10 -3
  102. package/dist/bridge/server-overview.js +32 -15
  103. package/dist/bridge/server-pane-routes.d.ts +3 -0
  104. package/dist/bridge/server-pane-routes.js +150 -18
  105. package/dist/bridge/server-routes.d.ts +11 -0
  106. package/dist/bridge/server-routes.js +214 -36
  107. package/dist/bridge/server-stream.d.ts +2 -0
  108. package/dist/bridge/server-stream.js +22 -8
  109. package/dist/bridge/server.d.ts +6 -1
  110. package/dist/bridge/server.js +58 -13
  111. package/dist/bridge/session-activity.d.ts +93 -0
  112. package/dist/bridge/session-activity.js +139 -0
  113. package/dist/bridge/session-rename.d.ts +48 -0
  114. package/dist/bridge/session-rename.js +190 -0
  115. package/dist/bridge/session-servers.js +2 -2
  116. package/dist/bridge/settings-switch.d.ts +60 -0
  117. package/dist/bridge/settings-switch.js +287 -0
  118. package/dist/bridge/speech-voice.d.ts +55 -0
  119. package/dist/bridge/speech-voice.js +132 -0
  120. package/dist/bridge/speech.d.ts +70 -11
  121. package/dist/bridge/speech.js +169 -41
  122. package/dist/bridge/stalls.d.ts +22 -0
  123. package/dist/bridge/stalls.js +57 -0
  124. package/dist/bridge/sudo.d.ts +209 -0
  125. package/dist/bridge/sudo.js +501 -0
  126. package/dist/bridge/terminal-herdr.js +9 -3
  127. package/dist/bridge/terminal-tmux.d.ts +15 -3
  128. package/dist/bridge/terminal-tmux.js +103 -13
  129. package/dist/bridge/terminal.d.ts +27 -4
  130. package/dist/bridge/terminal.js +8 -1
  131. package/dist/bridge/transcript-claude.d.ts +4 -0
  132. package/dist/bridge/transcript-claude.js +186 -16
  133. package/dist/bridge/transcript-codex.d.ts +0 -2
  134. package/dist/bridge/transcript-codex.js +29 -4
  135. package/dist/bridge/transcript-preview.d.ts +1 -0
  136. package/dist/bridge/transcript-preview.js +24 -4
  137. package/dist/bridge/transcripts.d.ts +15 -2
  138. package/dist/bridge/transcripts.js +47 -16
  139. package/dist/bridge/turn-records.d.ts +85 -0
  140. package/dist/bridge/turn-records.js +143 -0
  141. package/dist/bridge/uploads.d.ts +3 -0
  142. package/dist/bridge/uploads.js +14 -0
  143. package/dist/bridge/usage.d.ts +56 -10
  144. package/dist/bridge/usage.js +190 -45
  145. package/dist/bridge-hook.mjs +27975 -20636
  146. package/dist/cli/claude-unmanaged.d.ts +12 -0
  147. package/dist/cli/claude-unmanaged.js +105 -0
  148. package/dist/cli/schedules.js +2 -1
  149. package/dist/cli/session-start.js +10 -1
  150. package/dist/cli/session-stop.js +9 -1
  151. package/dist/cli-registry.js +31 -6
  152. package/dist/data/task-receipts.d.ts +19 -0
  153. package/dist/data/task-receipts.js +68 -0
  154. package/dist/data/tasks.js +4 -1
  155. package/dist/generated/memory-ui-graph.browser.js +63 -63
  156. package/dist/graph-core/model.js +24 -3
  157. package/dist/graph-core/types.d.ts +4 -1
  158. package/dist/graph-core/types.js +1 -0
  159. package/dist/init/init-preset.js +7 -3
  160. package/dist/init/init-uninstall.js +2 -11
  161. package/dist/init/teardown.d.ts +3 -0
  162. package/dist/init/teardown.js +47 -0
  163. package/dist/link/context.js +21 -9
  164. package/dist/mcp/plugin-mode.js +1 -1
  165. package/dist/memory-ui-graph.runtime.js +63 -63
  166. package/dist/modules/code-package.d.ts +1 -0
  167. package/dist/modules/code-package.js +36 -7
  168. package/dist/modules/registry.js +17 -16
  169. package/dist/profile-store.d.ts +6 -0
  170. package/dist/profile-store.js +25 -1
  171. package/dist/shell/graph/glyphs.js +4 -0
  172. package/dist/shell/graph/graph-view.js +2 -0
  173. package/dist/status.js +7 -1
  174. package/dist/sync/task-claim.js +3 -2
  175. package/dist/task/lifecycle.js +25 -4
  176. package/dist/test-global-setup.js +5 -0
  177. package/dist/tools/dispatch.js +52 -4
  178. package/dist/tools/tasks.js +10 -1
  179. package/package.json +1 -1
  180. package/plugins/opencode/phren-transcript.js +87 -4
  181. package/starter/global/AGENTS.md +4 -0
  182. package/starter/global/skills/conductor/SKILL.md +51 -4
@@ -0,0 +1,231 @@
1
+ import { tryFileLock } from "../governance/locks.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import { lstat, mkdir, readFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { dump, load } from "js-yaml";
6
+ import { z } from "zod";
7
+ import { atomic, BridgeError, bridgeRoot, PERMISSION_MODES } from "./protocol.js";
8
+ /**
9
+ * The owner's release authority policy: per project, which release-type
10
+ * actions a conductor may send a worker to do on its own (`go`) and which need
11
+ * the owner's word each time (`ask`). It only restricts: nothing here lifts a
12
+ * worker's own permission checks. See docs/authority.md.
13
+ */
14
+ export const RELEASE_ACTIONS = ["merge", "publish", "deploy", "app-store", "github-admin"];
15
+ export const releaseAction = z.enum(RELEASE_ACTIONS);
16
+ const verdict = z.enum(["go", "ask"]);
17
+ const projectSlug = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/);
18
+ const writer = z.enum(["phone", "cli"]);
19
+ export const projectEntrySchema = z.object({
20
+ default: verdict.optional().describe("go or ask for the release actions `actions` does not list; go when omitted."),
21
+ actions: z.object({
22
+ merge: verdict.optional(), publish: verdict.optional(), deploy: verdict.optional(),
23
+ "app-store": verdict.optional(), "github-admin": verdict.optional(),
24
+ }).strict().optional(),
25
+ maxPermissionMode: z.enum(PERMISSION_MODES).optional()
26
+ .describe("Highest permission mode an agent may start a worker in here; auto-edits when omitted and any action is ask."),
27
+ note: z.string().min(1).max(300).refine(value => !/[\x00-\x1f\x7f]/.test(value)).optional(),
28
+ }).strict();
29
+ const fileSchema = z.object({
30
+ projects: z.record(projectSlug, projectEntrySchema).refine(value => Object.keys(value).length <= 256, "At most 256 projects."),
31
+ updatedAt: z.string().datetime({ offset: true }).optional(),
32
+ updatedBy: writer.optional(),
33
+ }).strict();
34
+ /** Used until the owner first writes the policy: hub and safety are ask-first,
35
+ * and Mina is go for App Store work (the owner's word, 2026-09-29). */
36
+ export const DEFAULT_AUTHORITY = { projects: {
37
+ hub: { default: "ask" },
38
+ safety: { default: "ask" },
39
+ mina: { actions: { "app-store": "go" }, note: "Owner authorized App Store work on 2026-09-29." },
40
+ } };
41
+ /** The permission ceiling of a project with any ask-first action that names none. */
42
+ export const ASK_FIRST_PERMISSION_MODE = "auto-edits";
43
+ const authorityFile = (root = bridgeRoot()) => path.join(root, "authority.yaml");
44
+ const confirmationsFile = (root = bridgeRoot()) => path.join(root, "authority-confirmations.json");
45
+ async function privateFile(file, name) {
46
+ const info = await lstat(file).catch(() => undefined);
47
+ if (!info)
48
+ return false;
49
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 65_536 || (info.mode & 0o077)) {
50
+ throw new BridgeError(409, `${name} must be a private regular file (0600), at most 64 KiB.`);
51
+ }
52
+ return true;
53
+ }
54
+ /** js-yaml reads an unquoted timestamp as a Date; the schema takes strings. */
55
+ function normalize(raw) {
56
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
57
+ return raw;
58
+ const file = { ...raw };
59
+ if (file.updatedAt instanceof Date)
60
+ file.updatedAt = file.updatedAt.toISOString();
61
+ return file;
62
+ }
63
+ /** The saved policy, or the built-in defaults when the owner has written none.
64
+ * A file that is not private or does not parse is an error, never "no policy". */
65
+ export async function readAuthority(root = bridgeRoot()) {
66
+ const file = authorityFile(root);
67
+ if (!await privateFile(file, "authority.yaml"))
68
+ return { ...structuredClone(DEFAULT_AUTHORITY), source: "defaults" };
69
+ const parsed = fileSchema.safeParse(normalize(load(await readFile(file, "utf8")) ?? { projects: {} }));
70
+ if (!parsed.success)
71
+ throw new BridgeError(409, "authority.yaml does not match the release authority schema. Fix it with `phren authority set` or remove the broken entry.");
72
+ return { ...parsed.data, source: "file" };
73
+ }
74
+ export function projectAuthority(policy, project) {
75
+ const entry = Object.hasOwn(policy.projects, project) ? policy.projects[project] : undefined;
76
+ const verdictOf = (action) => entry?.actions?.[action] ?? entry?.default ?? "go";
77
+ const go = RELEASE_ACTIONS.filter(action => verdictOf(action) === "go");
78
+ const ask = RELEASE_ACTIONS.filter(action => verdictOf(action) === "ask");
79
+ const maxPermissionMode = entry?.maxPermissionMode ?? (ask.length ? ASK_FIRST_PERMISSION_MODE : undefined);
80
+ const parts = [
81
+ ...(!entry ? ["no release restrictions listed"] : []),
82
+ ...(entry && go.length ? [`go for ${go.join(", ")}`] : []),
83
+ ...(ask.length ? [`ask-first for ${ask.join(", ")}`] : []),
84
+ ...(maxPermissionMode ? [`dispatched workers start at most in ${maxPermissionMode}`] : []),
85
+ ];
86
+ const line = `Release authority for ${project} (owner policy): ${parts.join("; ")}.${entry?.note ? ` Note: ${entry.note}` : ""}`;
87
+ return { project, listed: !!entry, go, ask, ...(maxPermissionMode ? { maxPermissionMode } : {}), ...(entry?.note ? { note: entry.note } : {}), line };
88
+ }
89
+ /** The lower of two permission ceilings; undefined is no ceiling. */
90
+ export function lowerMode(a, b) {
91
+ if (!a || !b)
92
+ return a ?? b;
93
+ return PERMISSION_MODES.indexOf(a) <= PERMISSION_MODES.indexOf(b) ? a : b;
94
+ }
95
+ const mutations = new Map();
96
+ /** One change at a time in this process, and a file lock across processes. */
97
+ async function mutate(file, action) {
98
+ const key = path.resolve(file);
99
+ const previous = mutations.get(key) ?? Promise.resolve();
100
+ const pending = previous.catch(() => { }).then(async () => {
101
+ await mkdir(path.dirname(key), { recursive: true, mode: 0o700 });
102
+ const release = tryFileLock(key);
103
+ if (!release)
104
+ throw new BridgeError(409, "The release authority policy is being updated. Try again.");
105
+ try {
106
+ return await action();
107
+ }
108
+ finally {
109
+ release();
110
+ }
111
+ });
112
+ mutations.set(key, pending);
113
+ try {
114
+ return await pending;
115
+ }
116
+ finally {
117
+ if (mutations.get(key) === pending)
118
+ mutations.delete(key);
119
+ }
120
+ }
121
+ async function writeAuthority(root, projects, by) {
122
+ const sorted = Object.fromEntries(Object.entries(projects).sort(([a], [b]) => a.localeCompare(b)));
123
+ const file = fileSchema.parse({ projects: sorted, updatedAt: new Date().toISOString(), updatedBy: by });
124
+ await atomic(authorityFile(root), dump(file, { lineWidth: 120 }));
125
+ }
126
+ export const setAuthoritySchema = projectEntrySchema.extend({ project: projectSlug }).strict();
127
+ /** Replace one project's entry. The first write saves the defaults with it. */
128
+ export async function setProjectAuthority(input, by, root = bridgeRoot()) {
129
+ const { project, ...entry } = setAuthoritySchema.parse(input);
130
+ return mutate(authorityFile(root), async () => {
131
+ const { projects } = await readAuthority(root);
132
+ const next = { ...projects, [project]: entry };
133
+ await writeAuthority(root, next, by);
134
+ return projectAuthority({ projects: next }, project);
135
+ });
136
+ }
137
+ /** Drop one project's entry, which makes it go for everything. */
138
+ export async function clearProjectAuthority(input, by, root = bridgeRoot()) {
139
+ const { project } = z.object({ project: projectSlug }).strict().parse(input);
140
+ return mutate(authorityFile(root), async () => {
141
+ const { projects } = await readAuthority(root);
142
+ if (!Object.hasOwn(projects, project))
143
+ throw new BridgeError(404, `The release authority policy does not list ${project}.`);
144
+ const { [project]: _removed, ...rest } = projects;
145
+ await writeAuthority(root, rest, by);
146
+ return projectAuthority({ projects: rest }, project);
147
+ });
148
+ }
149
+ const confirmationSchema = z.object({
150
+ id: z.string().uuid(), project: projectSlug, actions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length),
151
+ confirmedAt: z.string().datetime(), expiresAt: z.string().datetime(), by: writer,
152
+ }).strict();
153
+ const confirmationsListSchema = z.array(confirmationSchema).max(32);
154
+ export const confirmInputSchema = z.object({
155
+ project: projectSlug,
156
+ actions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length),
157
+ minutes: z.number().int().min(1).max(24 * 60).optional().describe("How long the confirmation waits to be used; 30 when omitted."),
158
+ }).strict();
159
+ export const DEFAULT_CONFIRMATION_MINUTES = 30;
160
+ async function readConfirmations(root, now) {
161
+ const file = confirmationsFile(root);
162
+ if (!await privateFile(file, "authority-confirmations.json"))
163
+ return [];
164
+ const parsed = confirmationsListSchema.safeParse(JSON.parse(await readFile(file, "utf8")));
165
+ // A damaged list confirms nothing: the owner confirms again.
166
+ if (!parsed.success)
167
+ return [];
168
+ return parsed.data.filter(item => Date.parse(item.expiresAt) > now);
169
+ }
170
+ /** Confirmations still waiting to be used. */
171
+ export async function listConfirmations(root = bridgeRoot()) {
172
+ return readConfirmations(root, Date.now());
173
+ }
174
+ /** The owner's word for one agent dispatch of these release actions to this project. */
175
+ export async function confirmAuthority(input, by, root = bridgeRoot()) {
176
+ const data = confirmInputSchema.parse(input);
177
+ return mutate(confirmationsFile(root), async () => {
178
+ const now = Date.now();
179
+ const existing = await readConfirmations(root, now);
180
+ if (existing.length >= 32)
181
+ throw new BridgeError(409, "32 release confirmations are already waiting. Let some expire first.");
182
+ const confirmation = { id: randomUUID(), project: data.project, actions: [...new Set(data.actions)],
183
+ confirmedAt: new Date(now).toISOString(), expiresAt: new Date(now + (data.minutes ?? DEFAULT_CONFIRMATION_MINUTES) * 60_000).toISOString(), by };
184
+ await atomic(confirmationsFile(root), [...existing, confirmation]);
185
+ return confirmation;
186
+ });
187
+ }
188
+ /** Use up the oldest confirmation that covers every one of `actions` for
189
+ * `project`, or return undefined when none does. */
190
+ export async function consumeConfirmation(project, actions, root = bridgeRoot()) {
191
+ return mutate(confirmationsFile(root), async () => {
192
+ const now = Date.now();
193
+ const existing = await readConfirmations(root, now);
194
+ const index = existing.findIndex(item => item.project === project && actions.every(action => item.actions.includes(action)));
195
+ if (index < 0)
196
+ return undefined;
197
+ const [used] = existing.splice(index, 1);
198
+ await atomic(confirmationsFile(root), existing);
199
+ return used;
200
+ });
201
+ }
202
+ /**
203
+ * What the policy asks of an agent's dispatch: refuse a mode above the
204
+ * project's ceiling (lowered further by `grantCeiling`), start one that named
205
+ * no mode at that ceiling, and refuse an ask-first release action the owner
206
+ * has not confirmed. Only an agent's call is checked; the owner's never is.
207
+ * The confirmation is used up only when everything else passed.
208
+ */
209
+ export async function checkAgentDispatch(data, grantCeiling, root = bridgeRoot()) {
210
+ const authority = projectAuthority(await readAuthority(root), data.project);
211
+ const ceiling = authority.maxPermissionMode ? lowerMode(authority.maxPermissionMode, grantCeiling) : undefined;
212
+ let permissionMode;
213
+ if (ceiling) {
214
+ if (data.harness === "opencode") {
215
+ throw new BridgeError(403, `${data.project} caps dispatched workers at ${ceiling}, and OpenCode takes its permissions from its own config. Dispatch Claude or Codex, or ask the owner to dispatch it.`);
216
+ }
217
+ if (data.permissionMode && PERMISSION_MODES.indexOf(data.permissionMode) > PERMISSION_MODES.indexOf(ceiling)) {
218
+ throw new BridgeError(403, `The release authority policy caps agent-dispatched workers for ${data.project} at ${ceiling}. Ask for ${ceiling} or lower, or ask the owner to dispatch it.`);
219
+ }
220
+ if (!data.permissionMode)
221
+ permissionMode = ceiling;
222
+ }
223
+ const needed = [...new Set(data.releaseActions ?? [])].filter(action => authority.ask.includes(action));
224
+ if (!needed.length)
225
+ return { ...(permissionMode ? { permissionMode } : {}), authority };
226
+ const confirmation = await consumeConfirmation(data.project, needed, root);
227
+ if (!confirmation) {
228
+ throw new BridgeError(403, `${data.project} is ask-first for ${needed.join(", ")}. Ask the owner; they confirm it on the phone or with \`phren authority confirm ${data.project} ${needed.join(",")}\`, or dispatch it themselves.`);
229
+ }
230
+ return { ...(permissionMode ? { permissionMode } : {}), authority, confirmation };
231
+ }
@@ -0,0 +1,14 @@
1
+ /** Entries of the default home every account shares by symlink. */
2
+ export declare const SHARED_ENTRIES: string[];
3
+ /** Refresh every extra home's mcpServers from the default home. Returns the ids that changed. */
4
+ export declare function syncAccountMcpServers(env?: NodeJS.ProcessEnv): Promise<string[]>;
5
+ export interface AddedAccount {
6
+ id: string;
7
+ dir: string;
8
+ linked: string[];
9
+ created: boolean;
10
+ }
11
+ export declare function addClaudeAccount(slug: string, opts?: {
12
+ label?: string;
13
+ env?: NodeJS.ProcessEnv;
14
+ }): Promise<AddedAccount>;
@@ -0,0 +1,69 @@
1
+ // `phren bridge accounts add`: a new Claude home that shares the default home's setup.
2
+ import { chmod, lstat, mkdir, readFile, symlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { homeDir } from "../home-paths.js";
5
+ import { claudeHome, claudeHomes, DEFAULT_ACCOUNT, isAccountSlug, setAccountLabel } from "./claude-accounts.js";
6
+ import { atomic } from "./protocol.js";
7
+ /** Entries of the default home every account shares by symlink. */
8
+ export const SHARED_ENTRIES = ["settings.json", "CLAUDE.md", "skills", "agents", "commands", "plugins"];
9
+ const exists = (file) => lstat(file).then(() => true, () => false);
10
+ async function readObject(file) {
11
+ try {
12
+ const value = JSON.parse(await readFile(file, "utf8"));
13
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ async function mcpServersOf(file) {
20
+ const servers = (await readObject(file))?.mcpServers;
21
+ return servers && typeof servers === "object" && !Array.isArray(servers) ? servers : {};
22
+ }
23
+ /** Write the default home's user-scope mcpServers into one home's .claude.json; the default's entries win by name. */
24
+ async function mergeMcpServers(file, servers) {
25
+ const present = await exists(file);
26
+ const existing = present ? await readObject(file) : {};
27
+ if (!existing)
28
+ return false; // Unreadable or not an object: leave the owner's file alone.
29
+ const current = existing.mcpServers && typeof existing.mcpServers === "object" && !Array.isArray(existing.mcpServers) ? existing.mcpServers : {};
30
+ const merged = { ...current, ...servers };
31
+ if (present && JSON.stringify(merged) === JSON.stringify(current))
32
+ return false;
33
+ await atomic(file, JSON.stringify({ ...existing, mcpServers: merged }, null, 2) + "\n", 0o600);
34
+ return true;
35
+ }
36
+ /** Refresh every extra home's mcpServers from the default home. Returns the ids that changed. */
37
+ export async function syncAccountMcpServers(env = process.env) {
38
+ const homes = claudeHomes(env);
39
+ const servers = await mcpServersOf(homes[0].configFile);
40
+ const changed = [];
41
+ for (const home of homes.slice(1))
42
+ if (await mergeMcpServers(home.configFile, servers))
43
+ changed.push(home.id);
44
+ return changed;
45
+ }
46
+ export async function addClaudeAccount(slug, opts = {}) {
47
+ const env = opts.env ?? process.env;
48
+ if (slug === DEFAULT_ACCOUNT || !isAccountSlug(slug))
49
+ throw new Error(`"${slug}" is not an account name: use 1 to 32 lowercase letters, digits and dashes, and not "default".`);
50
+ const source = claudeHome(DEFAULT_ACCOUNT, env);
51
+ const dir = path.join(homeDir(env), `.claude-${slug}`);
52
+ if (dir === source.dir)
53
+ throw new Error(`~/.claude-${slug} is the default Claude home.`);
54
+ const created = !(await exists(dir));
55
+ await mkdir(dir, { recursive: true, mode: 0o700 });
56
+ await chmod(dir, 0o700); // An existing home keeps its login: tighten it too.
57
+ const linked = [];
58
+ for (const name of SHARED_ENTRIES) {
59
+ const target = path.join(source.dir, name), link = path.join(dir, name);
60
+ if (!(await exists(target)) || await exists(link))
61
+ continue;
62
+ await symlink(target, link);
63
+ linked.push(name);
64
+ }
65
+ await mergeMcpServers(path.join(dir, ".claude.json"), await mcpServersOf(source.configFile));
66
+ if (opts.label)
67
+ await setAccountLabel(slug, opts.label);
68
+ return { id: slug, dir, linked, created };
69
+ }
@@ -0,0 +1,49 @@
1
+ export declare const DEFAULT_ACCOUNT = "default";
2
+ export interface ClaudeHome {
3
+ /** "default", or the slug of ~/.claude-<slug>. */
4
+ id: string;
5
+ /** The config directory (CLAUDE_CONFIG_DIR for non-default homes). */
6
+ dir: string;
7
+ /** Where Claude Code keeps this home's .claude.json. */
8
+ configFile: string;
9
+ isDefault: boolean;
10
+ }
11
+ /** What rows, usage and receipts carry to name an account. */
12
+ export interface AccountRef {
13
+ id: string;
14
+ label: string;
15
+ key: string;
16
+ email?: string;
17
+ }
18
+ export declare function isAccountSlug(value: string): boolean;
19
+ /** Every Claude home on this computer, default first, then by slug. */
20
+ export declare function claudeHomes(env?: NodeJS.ProcessEnv): ClaudeHome[];
21
+ export declare function claudeHome(id: string | undefined, env?: NodeJS.ProcessEnv): ClaudeHome | undefined;
22
+ /** The home a transcript or other file lives in, by longest matching directory. */
23
+ export declare function claudeHomeOfPath(file: string, env?: NodeJS.ProcessEnv): ClaudeHome | undefined;
24
+ /** Environment a launch into this home needs; empty for the default home. */
25
+ export declare function claudeLaunchEnv(home: ClaudeHome): Record<string, string>;
26
+ /** The config home a running Claude process uses, from its CLAUDE_CONFIG_DIR. */
27
+ export declare function claudeHomeOfEnv(value: string | undefined, env?: NodeJS.ProcessEnv): ClaudeHome | undefined;
28
+ export declare const accountsFile: () => string;
29
+ export declare function accountLabel(id: string, labels?: Record<string, string>): string;
30
+ export declare function setAccountLabel(id: string, label: string): Promise<void>;
31
+ /** Stable across computers for one subscription; home-scoped when unknown. */
32
+ export declare function claudeAccountKey(home: ClaudeHome): string;
33
+ /** The login's email, so the phone can name a card merged across computers. Usage rows only. */
34
+ export declare function claudeAccountEmail(home: ClaudeHome): string | undefined;
35
+ export declare function claudeAccountRef(home: ClaudeHome, labels?: Record<string, string>): AccountRef;
36
+ export declare const CODEX_ACCOUNT: AccountRef;
37
+ /** Only for tests. */
38
+ export declare function clearAccountCaches(): void;
39
+ /** `unknown`: Claude gave no answer (timeout, crash, unparseable), which must not block a launch. */
40
+ export interface AuthStatus {
41
+ signedIn: boolean;
42
+ unknown?: boolean;
43
+ plan?: string;
44
+ reason?: string;
45
+ }
46
+ /** Parse `claude auth status --json`. Never keeps anything but the state and plan. */
47
+ export declare function parseAuthStatus(output: string): AuthStatus;
48
+ export type AuthRunner = (home: ClaudeHome) => Promise<string>;
49
+ export declare function claudeAuthStatus(home: ClaudeHome, run?: AuthRunner, now?: number): Promise<AuthStatus>;
@@ -0,0 +1,195 @@
1
+ // Claude accounts on this computer: one Claude config home per account.
2
+ // ~/.claude is the "default" account and is launched without CLAUDE_CONFIG_DIR,
3
+ // so its keychain item and ~/.claude.json stay where Claude Code put them.
4
+ // Every ~/.claude-<slug> holding a .claude.json is another account. See docs/accounts.md.
5
+ import { createHash } from "node:crypto";
6
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
7
+ import { mkdir, readFile } from "node:fs/promises";
8
+ import { spawn } from "node:child_process";
9
+ import path from "node:path";
10
+ import { dump, load } from "js-yaml";
11
+ import { claudeConfigDir, homeDir } from "../home-paths.js";
12
+ import { atomic, bridgeRoot } from "./protocol.js";
13
+ export const DEFAULT_ACCOUNT = "default";
14
+ const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
15
+ export function isAccountSlug(value) { return value === DEFAULT_ACCOUNT || SLUG.test(value); }
16
+ function defaultHome(env) {
17
+ const configured = Boolean(env.CLAUDE_CONFIG_DIR?.trim());
18
+ const dir = claudeConfigDir(env);
19
+ // Claude keeps .claude.json inside CLAUDE_CONFIG_DIR when set, else beside ~/.claude.
20
+ return { id: DEFAULT_ACCOUNT, dir, configFile: path.join(configured ? dir : homeDir(env), ".claude.json"), isDefault: true };
21
+ }
22
+ /** Every Claude home on this computer, default first, then by slug. */
23
+ export function claudeHomes(env = process.env) {
24
+ const homes = [defaultHome(env)];
25
+ const home = homeDir(env);
26
+ let names = [];
27
+ try {
28
+ names = readdirSync(home);
29
+ }
30
+ catch {
31
+ return homes;
32
+ }
33
+ for (const name of names.sort()) {
34
+ if (!name.startsWith(".claude-"))
35
+ continue;
36
+ const id = name.slice(".claude-".length);
37
+ if (!SLUG.test(id) || id === DEFAULT_ACCOUNT)
38
+ continue;
39
+ const dir = path.join(home, name);
40
+ if (dir === homes[0].dir)
41
+ continue;
42
+ try {
43
+ if (!statSync(dir).isDirectory() || !existsSync(path.join(dir, ".claude.json")))
44
+ continue;
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ homes.push({ id, dir, configFile: path.join(dir, ".claude.json"), isDefault: false });
50
+ }
51
+ return homes;
52
+ }
53
+ export function claudeHome(id, env = process.env) {
54
+ const wanted = id?.trim() || DEFAULT_ACCOUNT;
55
+ return claudeHomes(env).find(home => home.id === wanted);
56
+ }
57
+ /** The home a transcript or other file lives in, by longest matching directory. */
58
+ export function claudeHomeOfPath(file, env = process.env) {
59
+ const resolved = path.resolve(file);
60
+ return claudeHomes(env)
61
+ .filter(home => resolved.startsWith(home.dir + path.sep))
62
+ .sort((a, b) => b.dir.length - a.dir.length)[0];
63
+ }
64
+ /** Environment a launch into this home needs; empty for the default home. */
65
+ export function claudeLaunchEnv(home) {
66
+ return home.isDefault ? {} : { CLAUDE_CONFIG_DIR: home.dir };
67
+ }
68
+ /** The config home a running Claude process uses, from its CLAUDE_CONFIG_DIR. */
69
+ export function claudeHomeOfEnv(value, env = process.env) {
70
+ if (!value?.trim())
71
+ return claudeHome(DEFAULT_ACCOUNT, env);
72
+ const dir = path.resolve(value.trim());
73
+ return claudeHomes(env).find(home => home.dir === dir);
74
+ }
75
+ // ── labels (<bridge>/accounts.yaml) ─────────────────────────────────────────
76
+ export const accountsFile = () => path.join(bridgeRoot(), "accounts.yaml");
77
+ function readLabels() {
78
+ try {
79
+ const parsed = load(readFileSync(accountsFile(), "utf8"));
80
+ const claude = parsed && typeof parsed === "object" ? parsed.claude : undefined;
81
+ if (!claude || typeof claude !== "object")
82
+ return {};
83
+ return Object.fromEntries(Object.entries(claude)
84
+ .filter(([id, label]) => isAccountSlug(id) && typeof label === "string" && label.trim().length > 0 && label.length <= 40)
85
+ .map(([id, label]) => [id, label.trim()]));
86
+ }
87
+ catch {
88
+ return {};
89
+ }
90
+ }
91
+ export function accountLabel(id, labels = readLabels()) {
92
+ if (labels[id])
93
+ return labels[id];
94
+ if (id === DEFAULT_ACCOUNT)
95
+ return "Claude";
96
+ return id.split("-").filter(Boolean).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
97
+ }
98
+ export async function setAccountLabel(id, label) {
99
+ if (!isAccountSlug(id))
100
+ throw new Error(`"${id}" is not an account name: use lowercase letters, digits and dashes.`);
101
+ const clean = label.trim();
102
+ if (!clean || clean.length > 40 || /[\u0000-\u001f]/.test(clean))
103
+ throw new Error("A label is 1 to 40 printable characters.");
104
+ let parsed = {};
105
+ try {
106
+ const raw = load(await readFile(accountsFile(), "utf8"));
107
+ if (raw && typeof raw === "object")
108
+ parsed = raw;
109
+ }
110
+ catch { /* First label. */ }
111
+ const claude = parsed.claude && typeof parsed.claude === "object" ? parsed.claude : {};
112
+ parsed.claude = { ...claude, [id]: clean };
113
+ await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 });
114
+ await atomic(accountsFile(), dump(parsed), 0o600);
115
+ }
116
+ // ── identity (.claude.json oauthAccount, no tokens) ─────────────────────────
117
+ const identityCache = new Map();
118
+ function oauthIdentity(configFile) {
119
+ try {
120
+ const stat = statSync(configFile);
121
+ if (!stat.isFile() || stat.size > 16_777_216)
122
+ return {};
123
+ const cached = identityCache.get(configFile);
124
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size)
125
+ return cached;
126
+ const config = JSON.parse(readFileSync(configFile, "utf8"));
127
+ const account = config.oauthAccount && typeof config.oauthAccount === "object" ? config.oauthAccount : {};
128
+ const uuid = typeof account.accountUuid === "string" && account.accountUuid ? account.accountUuid : undefined;
129
+ const email = typeof account.emailAddress === "string" && /^[^\s@]{1,64}@[^\s@]{1,190}$/.test(account.emailAddress) ? account.emailAddress : undefined;
130
+ const value = { mtimeMs: stat.mtimeMs, size: stat.size, uuid, email };
131
+ identityCache.set(configFile, value);
132
+ return value;
133
+ }
134
+ catch {
135
+ return {};
136
+ }
137
+ }
138
+ /** Stable across computers for one subscription; home-scoped when unknown. */
139
+ export function claudeAccountKey(home) {
140
+ const { uuid } = oauthIdentity(home.configFile);
141
+ return uuid ? "claude:" + createHash("sha256").update(uuid).digest("hex").slice(0, 12) : `claude:home:${home.id}`;
142
+ }
143
+ /** The login's email, so the phone can name a card merged across computers. Usage rows only. */
144
+ export function claudeAccountEmail(home) { return oauthIdentity(home.configFile).email; }
145
+ export function claudeAccountRef(home, labels = readLabels()) {
146
+ return { id: home.id, label: accountLabel(home.id, labels), key: claudeAccountKey(home) };
147
+ }
148
+ export const CODEX_ACCOUNT = { id: DEFAULT_ACCOUNT, label: "Codex", key: "codex" };
149
+ /** Only for tests. */
150
+ export function clearAccountCaches() { identityCache.clear(); authCache.clear(); }
151
+ const AUTH_CACHE_MS = 5 * 60_000;
152
+ const AUTH_TIMEOUT_MS = 10_000;
153
+ const SIGNED_OUT_CACHE_MS = 30_000;
154
+ const authCache = new Map();
155
+ /** Parse `claude auth status --json`. Never keeps anything but the state and plan. */
156
+ export function parseAuthStatus(output) {
157
+ try {
158
+ const value = JSON.parse(output);
159
+ if (value.loggedIn !== true)
160
+ return { signedIn: false, reason: "Not signed in" };
161
+ const plan = typeof value.subscriptionType === "string" && /^[a-z0-9_-]{1,32}$/i.test(value.subscriptionType) ? value.subscriptionType : undefined;
162
+ return { signedIn: true, ...(plan ? { plan } : {}) };
163
+ }
164
+ catch {
165
+ return { signedIn: false, unknown: true, reason: "Claude did not report its sign-in state" };
166
+ }
167
+ }
168
+ const runAuthStatus = home => new Promise(resolve => {
169
+ let out = "", done = false;
170
+ const child = spawn("claude", ["auth", "status", "--json"], {
171
+ cwd: homeDir(), stdio: ["ignore", "pipe", "ignore"],
172
+ env: { ...process.env, ...claudeLaunchEnv(home), NO_COLOR: "1" },
173
+ });
174
+ const finish = () => { if (!done) {
175
+ done = true;
176
+ clearTimeout(timer);
177
+ resolve(out);
178
+ } };
179
+ const timer = setTimeout(() => { child.kill("SIGKILL"); finish(); }, AUTH_TIMEOUT_MS);
180
+ child.stdout.on("data", (chunk) => { if (out.length < 16_384)
181
+ out += chunk.toString(); });
182
+ child.on("error", finish);
183
+ child.on("close", finish);
184
+ });
185
+ export function claudeAuthStatus(home, run = runAuthStatus, now = Date.now()) {
186
+ const cached = authCache.get(home.dir);
187
+ if (cached && now - cached.at < (cached.signedIn === false ? SIGNED_OUT_CACHE_MS : AUTH_CACHE_MS))
188
+ return cached.value;
189
+ const entry = { at: now, value: Promise.resolve({ signedIn: false }) };
190
+ // A signed-out answer is kept briefly so a fresh /login shows up within half a minute.
191
+ entry.value = run(home).then(parseAuthStatus, () => ({ signedIn: false, unknown: true, reason: "Claude did not report its sign-in state" }))
192
+ .then(status => { entry.signedIn = status.unknown ? false : status.signedIn; return status; });
193
+ authCache.set(home.dir, entry);
194
+ return entry.value;
195
+ }
@@ -5,7 +5,7 @@ import { resolveAllStores } from "../store-registry.js";
5
5
  import { git } from "./projects.js";
6
6
  import { z } from "zod";
7
7
  import { getProjectDirs } from "../shared.js";
8
- import { CODE_PACKAGE_HINT, loadCodePackage } from "../modules/code-package.js";
8
+ import { codePackageHint, loadCodePackage } from "../modules/code-package.js";
9
9
  const indexProject = async (store, ...args) => (await requireCodePackage(store)).indexProject(store, ...args);
10
10
  import { isValidProjectName } from "../utils-paths.js";
11
11
  import { errorMessage } from "../utils.js";
@@ -14,7 +14,7 @@ import { BridgeError, bridgeRoot } from "./protocol.js";
14
14
  export async function requireCodePackage(store) {
15
15
  const code = await loadCodePackage(store);
16
16
  if (!code)
17
- throw new BridgeError(503, CODE_PACKAGE_HINT);
17
+ throw new BridgeError(503, codePackageHint(store));
18
18
  return code;
19
19
  }
20
20
  /** Resolve only registered stores. Phone IDs are repository names; no client