@phren/cli 0.3.10 → 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 (184) 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/fanout-messages.js +2 -2
  42. package/dist/bridge/fanouts.d.ts +7 -1
  43. package/dist/bridge/fanouts.js +40 -5
  44. package/dist/bridge/folder-trust.d.ts +56 -0
  45. package/dist/bridge/folder-trust.js +195 -0
  46. package/dist/bridge/grants.d.ts +22 -1
  47. package/dist/bridge/grants.js +57 -9
  48. package/dist/bridge/hand-off.d.ts +21 -9
  49. package/dist/bridge/hand-off.js +58 -45
  50. package/dist/bridge/harness-status.d.ts +11 -0
  51. package/dist/bridge/harness-status.js +32 -0
  52. package/dist/bridge/harnesses.d.ts +39 -0
  53. package/dist/bridge/harnesses.js +65 -0
  54. package/dist/bridge/health.d.ts +2 -0
  55. package/dist/bridge/health.js +1 -1
  56. package/dist/bridge/herdr.d.ts +11 -2
  57. package/dist/bridge/herdr.js +98 -23
  58. package/dist/bridge/hook-fast.d.ts +4 -0
  59. package/dist/bridge/hook-fast.js +68 -0
  60. package/dist/bridge/install.d.ts +16 -1
  61. package/dist/bridge/install.js +88 -21
  62. package/dist/bridge/launch-brief.d.ts +96 -0
  63. package/dist/bridge/launch-brief.js +164 -0
  64. package/dist/bridge/model-switch.d.ts +3 -0
  65. package/dist/bridge/model-switch.js +17 -1
  66. package/dist/bridge/models.d.ts +8 -4
  67. package/dist/bridge/models.js +24 -8
  68. package/dist/bridge/mux-wire.d.ts +9 -0
  69. package/dist/bridge/mux-wire.js +19 -0
  70. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  71. package/dist/bridge/opencode-pane-server.js +332 -0
  72. package/dist/bridge/opencode-panes.d.ts +111 -0
  73. package/dist/bridge/opencode-panes.js +295 -0
  74. package/dist/bridge/pane-accounts.d.ts +8 -0
  75. package/dist/bridge/pane-accounts.js +46 -0
  76. package/dist/bridge/prompt-startup.d.ts +5 -0
  77. package/dist/bridge/prompt-startup.js +24 -0
  78. package/dist/bridge/protocol.d.ts +5 -0
  79. package/dist/bridge/protocol.js +4 -0
  80. package/dist/bridge/push.d.ts +5 -4
  81. package/dist/bridge/push.js +6 -4
  82. package/dist/bridge/questions.d.ts +37 -2
  83. package/dist/bridge/questions.js +158 -15
  84. package/dist/bridge/resources.d.ts +125 -0
  85. package/dist/bridge/resources.js +314 -0
  86. package/dist/bridge/schedule-format.d.ts +2 -0
  87. package/dist/bridge/schedule-format.js +3 -0
  88. package/dist/bridge/schedule-launch.d.ts +2 -1
  89. package/dist/bridge/schedule-launch.js +23 -53
  90. package/dist/bridge/schedule-watch.d.ts +10 -1
  91. package/dist/bridge/schedule-watch.js +54 -2
  92. package/dist/bridge/server-launch.d.ts +22 -5
  93. package/dist/bridge/server-launch.js +225 -29
  94. package/dist/bridge/server-overview.d.ts +8 -2
  95. package/dist/bridge/server-overview.js +26 -5
  96. package/dist/bridge/server-pane-routes.d.ts +2 -0
  97. package/dist/bridge/server-pane-routes.js +145 -15
  98. package/dist/bridge/server-routes.d.ts +11 -1
  99. package/dist/bridge/server-routes.js +195 -36
  100. package/dist/bridge/server-stream.d.ts +2 -0
  101. package/dist/bridge/server-stream.js +22 -8
  102. package/dist/bridge/server.d.ts +6 -1
  103. package/dist/bridge/server.js +47 -12
  104. package/dist/bridge/session-activity.d.ts +81 -0
  105. package/dist/bridge/session-activity.js +117 -0
  106. package/dist/bridge/session-rename.d.ts +48 -0
  107. package/dist/bridge/session-rename.js +190 -0
  108. package/dist/bridge/session-servers.js +2 -2
  109. package/dist/bridge/settings-switch.d.ts +60 -0
  110. package/dist/bridge/settings-switch.js +287 -0
  111. package/dist/bridge/speech-voice.d.ts +55 -0
  112. package/dist/bridge/speech-voice.js +132 -0
  113. package/dist/bridge/speech.d.ts +70 -11
  114. package/dist/bridge/speech.js +169 -41
  115. package/dist/bridge/terminal-herdr.js +9 -3
  116. package/dist/bridge/terminal-tmux.d.ts +3 -3
  117. package/dist/bridge/terminal-tmux.js +24 -9
  118. package/dist/bridge/terminal.d.ts +27 -4
  119. package/dist/bridge/terminal.js +8 -1
  120. package/dist/bridge/transcript-claude.js +62 -12
  121. package/dist/bridge/transcript-codex.d.ts +0 -2
  122. package/dist/bridge/transcript-codex.js +29 -4
  123. package/dist/bridge/transcript-preview.d.ts +1 -0
  124. package/dist/bridge/transcript-preview.js +24 -4
  125. package/dist/bridge/transcripts.d.ts +15 -2
  126. package/dist/bridge/transcripts.js +47 -16
  127. package/dist/bridge/turn-records.d.ts +85 -0
  128. package/dist/bridge/turn-records.js +143 -0
  129. package/dist/bridge/uploads.d.ts +3 -0
  130. package/dist/bridge/uploads.js +14 -0
  131. package/dist/bridge/usage.d.ts +73 -28
  132. package/dist/bridge/usage.js +313 -340
  133. package/dist/bridge-hook.mjs +24624 -18450
  134. package/dist/cli/claude-unmanaged.d.ts +12 -0
  135. package/dist/cli/claude-unmanaged.js +105 -0
  136. package/dist/cli/schedules.js +2 -1
  137. package/dist/cli/session-start.js +10 -1
  138. package/dist/cli/session-stop.js +9 -1
  139. package/dist/cli-registry.d.ts +2 -0
  140. package/dist/cli-registry.js +37 -5
  141. package/dist/computers/command.d.ts +6 -0
  142. package/dist/computers/command.js +152 -0
  143. package/dist/computers/mcp.d.ts +1 -0
  144. package/dist/computers/mcp.js +97 -0
  145. package/dist/computers/read.d.ts +85 -0
  146. package/dist/computers/read.js +177 -0
  147. package/dist/data/task-receipts.d.ts +19 -0
  148. package/dist/data/task-receipts.js +68 -0
  149. package/dist/data/tasks.js +4 -1
  150. package/dist/entrypoint.js +10 -0
  151. package/dist/fanout/adapters/claude.js +15 -2
  152. package/dist/fanout/adapters/types.d.ts +6 -0
  153. package/dist/fanout/launcher.d.ts +5 -1
  154. package/dist/fanout/launcher.js +34 -3
  155. package/dist/fanout/picker.js +3 -2
  156. package/dist/fanout/usage.js +1 -1
  157. package/dist/generated/memory-ui-graph.browser.js +63 -63
  158. package/dist/graph-core/model.js +24 -3
  159. package/dist/graph-core/types.d.ts +4 -1
  160. package/dist/graph-core/types.js +1 -0
  161. package/dist/init/init-preset.js +7 -3
  162. package/dist/init/init-uninstall.js +2 -11
  163. package/dist/init/teardown.d.ts +3 -0
  164. package/dist/init/teardown.js +47 -0
  165. package/dist/link/context.js +21 -9
  166. package/dist/mcp/plugin-mode.js +1 -1
  167. package/dist/memory-ui-graph.runtime.js +63 -63
  168. package/dist/modules/code-package.d.ts +1 -0
  169. package/dist/modules/code-package.js +36 -7
  170. package/dist/modules/registry.js +14 -13
  171. package/dist/profile-store.d.ts +6 -0
  172. package/dist/profile-store.js +25 -1
  173. package/dist/shell/graph/glyphs.js +4 -0
  174. package/dist/shell/graph/graph-view.js +2 -0
  175. package/dist/status.js +7 -1
  176. package/dist/sync/task-claim.js +3 -2
  177. package/dist/task/lifecycle.js +25 -4
  178. package/dist/test-global-setup.js +5 -0
  179. package/dist/tools/dispatch.js +35 -2
  180. package/dist/tools/tasks.js +10 -1
  181. package/package.json +1 -1
  182. package/plugins/opencode/phren-transcript.js +87 -4
  183. package/starter/global/skills/conductor/SKILL.md +17 -2
  184. package/starter/global/skills/fanout/SKILL.md +3 -0
@@ -2,18 +2,23 @@ import { z } from "zod";
2
2
  import { computerName } from "./computers.js";
3
3
  import { hookRequest } from "./client.js";
4
4
  import { projectName } from "./dispatch.js";
5
- import { grantLabel, listGrants, matchGrant } from "./grants.js";
5
+ import { isAccountSlug } from "./claude-accounts.js";
6
+ import { grantLabel, findGrant } from "./grants.js";
6
7
  import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
7
8
  import { BridgeError, errorCode, object, objects, sessionId, targetSchema } from "./protocol.js";
8
9
  import { findPhrenPath } from "../phren-paths.js";
9
10
  import { listMachines } from "../profile-store.js";
10
11
  import { localNames } from "./computer-names.js";
12
+ import { computerLabel, foldComputers, linkedComputer } from "./computer-identity.js";
13
+ export { computerLabel };
11
14
  const promptText = z.string().min(1).max(32768).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value));
12
15
  export const handOffSchema = z.object({
13
16
  computer: computerName.optional().describe("Enrolled computer name. Omit for this computer."),
14
17
  target: targetSchema.optional().describe("Complete live target for the existing session."),
15
18
  session: sessionId.optional().describe("Session id to resolve through the Hook workspace overview."),
16
19
  project: projectName.optional().describe("Project slug this hand-off belongs to, for conductor grant matching."),
20
+ account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
21
+ .describe("Claude account id the session must run under (default, or a slug). A session of another account is refused; a row without an account counts as default."),
17
22
  text: promptText.describe("Prompt to deliver to the existing session, at most 32768 characters."),
18
23
  }).strict().superRefine((value, context) => {
19
24
  if ((value.target === undefined) === (value.session === undefined))
@@ -25,6 +30,8 @@ function labelOf(group, tab) {
25
30
  const folder = typeof tab.cwd === "string" && tab.role !== "conductor" ? tab.cwd.split("/").filter(Boolean).at(-1) : undefined;
26
31
  return folder || (typeof group.label === "string" && group.label ? group.label : undefined);
27
32
  }
33
+ /** The account id an overview row runs under; a row without one is the default account. */
34
+ const accountOf = (tab) => typeof object(tab.account).id === "string" ? String(object(tab.account).id) : "default";
28
35
  async function findInOverview(request, match, server) {
29
36
  const route = server ? `/v1/workspaces?server=${encodeURIComponent(server)}` : "/v1/workspaces";
30
37
  const overview = await request(route);
@@ -32,41 +39,63 @@ async function findInOverview(request, match, server) {
32
39
  for (const tab of objects(group.children)) {
33
40
  const parsed = targetSchema.safeParse(tab.target);
34
41
  if (parsed.success && match(parsed.data))
35
- return { target: parsed.data, label: labelOf(group, tab) };
42
+ return { target: parsed.data, label: labelOf(group, tab), account: accountOf(tab) };
36
43
  }
37
44
  return undefined;
38
45
  }
39
- async function targetFromOverview(request, session, server) {
46
+ async function targetFromOverview(request, session, server, account) {
40
47
  const found = await findInOverview(request, target => target.session === session, server);
41
48
  if (!found)
42
49
  throw new BridgeError(404, "No live session with that id appears in the workspace overview.");
50
+ if (account && found.account !== account)
51
+ throw new BridgeError(409, `That session runs under account ${found.account}, not ${account}.`, { code: "account_mismatch" });
43
52
  return found;
44
53
  }
45
- export async function handOff(input) {
54
+ /** `deliveryId` names this one message on the receiving Hook, which then types
55
+ * it at most once however often it is sent (the Hook's own callers retry;
56
+ * the MCP tool does not take one). */
57
+ export async function handOff(input, options = {}) {
46
58
  const data = handOffSchema.parse(input);
47
59
  let request;
48
60
  let peer;
49
61
  if (data.computer === undefined)
50
62
  request = (route, body) => hookRequest(route, body);
51
63
  else {
52
- peer = (await hookPeers()).find(candidate => candidate.name === data.computer);
53
- if (!peer)
54
- throw new BridgeError(404, "Unknown computer. Add its verified connection to hooks.yaml.");
55
- request = (route, body) => peerRequest(peer, route, body);
64
+ // No hooks.yaml only matters when the name turns out to be another computer.
65
+ let peersError;
66
+ const peers = await hookPeers().catch(error => { peersError = error; return []; });
67
+ // An alias or hostname (`Mac`, `Desk.local`) names the same computer as its hooks.yaml name.
68
+ const named = peers.some(candidate => candidate.name === data.computer) ? undefined : await linkedComputer(data.computer).catch(() => undefined);
69
+ if (named && "local" in named)
70
+ request = (route, body) => hookRequest(route, body);
71
+ else {
72
+ if (peersError)
73
+ throw peersError;
74
+ const found = peers.find(candidate => candidate.name === (named && "peer" in named ? named.peer : data.computer));
75
+ if (!found)
76
+ throw new BridgeError(404, "Unknown computer. Add its verified connection to hooks.yaml.");
77
+ peer = found;
78
+ request = (route, body) => peerRequest(found, route, body);
79
+ }
56
80
  }
57
- const resolved = data.target ? undefined : await targetFromOverview(request, data.session, peer?.server);
81
+ const resolved = data.target ? undefined : await targetFromOverview(request, data.session, peer?.server, data.account);
58
82
  const target = data.target ?? resolved.target;
59
83
  if (peer && target.server !== peer.server)
60
84
  throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
61
- const grant = matchGrant(await listGrants(), { action: "hand_off", project: data.project, computer: data.computer });
62
- const result = await request("/v1/prompt", { target, text: data.text });
63
- const delivered = result.ok === true && result.deliveryUncertain !== true;
85
+ const grant = await findGrant({ action: "hand_off", project: data.project, computer: data.computer });
86
+ const result = await request("/v1/prompt", { target, text: data.text, ...(options.deliveryId ? { deliveryId: options.deliveryId } : {}) });
87
+ // A bare ok only acknowledges typing. Even an unchanged, busy Codex pane
88
+ // may have kept the text in its composer instead of submitting a turn.
89
+ const delivered = result.ok === true && result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true;
64
90
  // A session id was resolved from the overview already; an explicit target
65
91
  // is looked up once more, best effort, for its label.
66
92
  const label = resolved ? resolved.label
67
93
  : await findInOverview(request, found => found.pane === target.pane && found.session === target.session, peer?.server)
68
94
  .then(found => found?.label, () => undefined);
69
- return { ok: delivered, delivered, target, ...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
95
+ return { ok: delivered, delivered, target,
96
+ ...(!delivered && (result.ok === true || result.deliveryUncertain === true) ? { deliveryUncertain: true } : {}),
97
+ ...(result.unsubmitted === true ? { unsubmitted: true } : {}),
98
+ ...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
70
99
  }
71
100
  function sessionsFrom(overview, computer, local, now = Date.now()) {
72
101
  const sessions = [];
@@ -85,43 +114,29 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
85
114
  // A conductor sits in the store, not a project.
86
115
  sessions.push({ computer, local, project: tab.role === "conductor" ? undefined : text(cwd.split("/").filter(Boolean).at(-1)), label: text(label),
87
116
  title: text(tab.title), agent: tab.agent, status: text(tab.agentStatus), role: text(tab.role),
88
- branch: text(tab.branch), model: text(tab.model), ...(target.success ? { target: target.data } : {}),
117
+ branch: text(tab.branch), model: text(tab.model), ...(typeof object(tab.account).id === "string" ? { account: String(object(tab.account).id) } : {}), ...(target.success ? { target: target.data } : {}),
118
+ ...(typeof tab.backgroundTasks === "number" && tab.backgroundTasks > 0 ? { backgroundTasks: tab.backgroundTasks } : {}),
89
119
  ...(Number.isFinite(changedAt) ? { idleFor: Math.max(0, Math.floor((now - changedAt) / 1000)) } : {}) });
90
120
  }
91
121
  return sessions;
92
122
  }
93
- /** A computer name's first DNS label, lowercased: `Desk`, `desk.local` and
94
- * `Desk.example.net` are one computer. DHCP and Bonjour add domains to the
95
- * same machine's name, so full names do not identify a computer. */
96
- export function computerLabel(name) {
97
- const value = name.trim().toLowerCase();
98
- // An IPv4 address is one name, not a label and a domain.
99
- return /^\d+(\.\d+){3}$/.test(value) ? value : value.split(".")[0] ?? "";
100
- }
101
123
  /** Computers the store registers (machines.yaml) that this Hook has no
102
- * verified connection to, so their sessions cannot be listed from here.
103
- * Names are compared by first label against this computer's names and each
104
- * peer's name, address and aliases; names sharing a label collapse into one
105
- * entry. */
106
- export function notLinkedComputers(store, here, linked) {
124
+ * verified connection to, so their sessions cannot be listed from here: the
125
+ * unlinked rows of `foldComputers`, which folds names by first label and by
126
+ * shared profile into the computers it can see. */
127
+ export function notLinkedFrom(store, here, peers) {
107
128
  if (!store)
108
129
  return [];
109
130
  const machines = listMachines(store);
110
131
  if (!machines.ok)
111
132
  return [];
112
- const known = new Set([here, ...localNames(), ...linked].map(computerLabel).filter(Boolean));
113
- const groups = new Map();
114
- for (const name of Object.keys(machines.data)) {
115
- const label = computerLabel(name);
116
- if (!label || known.has(label))
117
- continue;
118
- groups.set(label, [...(groups.get(label) ?? []), name]);
119
- }
120
- return [...groups.values()].map(names => {
121
- // The shortest name leads (usually the bare label); the rest are aliases.
122
- const [name, ...aliases] = [...names].sort((a, b) => a.length - b.length || a.localeCompare(b));
123
- return aliases.length ? { name, aliases } : { name };
124
- }).sort((a, b) => a.name.localeCompare(b.name));
133
+ return foldComputers({ local: { names: [here, ...localNames()] }, peers, machines: machines.data })
134
+ .filter(row => !row.linked).map(row => row.aliases.length ? { name: row.name, aliases: row.aliases } : { name: row.name });
135
+ }
136
+ /** As `notLinkedFrom` for a flat list of names the linked computers answer
137
+ * to, each standing for its own computer. */
138
+ export function notLinkedComputers(store, here, linked) {
139
+ return notLinkedFrom(store, here, linked.map(name => ({ name, address: name })));
125
140
  }
126
141
  /** Every live agent the conductor could hand work to: this computer's Herdr
127
142
  * overview plus each enrolled computer's, read through its verified Hook.
@@ -134,16 +149,14 @@ export async function listLiveSessions(options = {}) {
134
149
  const unreachable = [];
135
150
  // Names each peer answers to (its hostname, Bonjour name), so a computer
136
151
  // registered under another of its names is not reported as unlinked.
137
- const peerNames = [];
152
+ const peerNames = new Map();
138
153
  await Promise.all(peers.map(async (peer) => {
139
154
  try {
140
155
  const route = peer.server && peer.server !== "default" ? `/v1/workspaces?server=${encodeURIComponent(peer.server)}` : "/v1/workspaces";
141
156
  const [overview, health] = await Promise.all([peerRequest(peer, route), peerRequest(peer, "/v1/health").catch(() => ({}))]);
142
157
  sessions.push(...sessionsFrom(overview, peer.name, false));
143
158
  const computer = object(object(health).computer);
144
- for (const name of [computer.name, ...(Array.isArray(computer.aliases) ? computer.aliases : [])])
145
- if (typeof name === "string")
146
- peerNames.push(name);
159
+ peerNames.set(peer.name, [computer.name, ...(Array.isArray(computer.aliases) ? computer.aliases : [])].filter((name) => typeof name === "string"));
147
160
  }
148
161
  catch (error) {
149
162
  const code = errorCode(error);
@@ -151,6 +164,6 @@ export async function listLiveSessions(options = {}) {
151
164
  }
152
165
  }));
153
166
  const store = options.store !== undefined ? options.store : findPhrenPath();
154
- const notLinked = notLinkedComputers(store, here, [...peers.flatMap(peer => [peer.name, peer.address]), ...peerNames]);
167
+ const notLinked = notLinkedFrom(store, here, peers.map(peer => ({ name: peer.name, address: peer.address, names: peerNames.get(peer.name) })));
155
168
  return { sessions, unreachable, notLinked, enrolled: peers.length, ...(peerError ? { peerError } : {}) };
156
169
  }
@@ -1,5 +1,15 @@
1
1
  /** What phren's OpenCode plugin last recorded for any of `pids`, newest first. */
2
2
  export declare function opencodeProcessStatus(pids: number[], root?: string): Promise<string | undefined>;
3
+ type TurnStamps = {
4
+ session: string;
5
+ at: string;
6
+ busyAt?: string;
7
+ idleAt?: string;
8
+ };
9
+ /** The turn stamps phren's OpenCode plugin last recorded for any of `pids`,
10
+ * newest first: when the session went busy and when it went idle after that.
11
+ * Undefined when no file has them (an older plugin). */
12
+ export declare function opencodeTurnStamps(pids: number[], root?: string): Promise<TurnStamps | undefined>;
3
13
  /** The status a Copilot session log's lines leave the session in; undefined
4
14
  * when none of them says. Copilot writes a turn_start/turn_end pair per model
5
15
  * call, so only the turn that carried the final answer ends the work. */
@@ -10,3 +20,4 @@ export declare function copilotProcessStatus(pids: number[], home?: string): Pro
10
20
  /** The status `agent`'s own records give for a pane running `pids`, for the
11
21
  * harnesses whose lifecycle hooks say nothing about turns. */
12
22
  export declare function harnessStatus(agent: string, pids: number[]): Promise<string | undefined>;
23
+ export {};
@@ -43,6 +43,38 @@ export async function opencodeProcessStatus(pids, root = phrenStoreRoot()) {
43
43
  }
44
44
  return current;
45
45
  }
46
+ /** The turn stamps phren's OpenCode plugin last recorded for any of `pids`,
47
+ * newest first: when the session went busy and when it went idle after that.
48
+ * Undefined when no file has them (an older plugin). */
49
+ export async function opencodeTurnStamps(pids, root = phrenStoreRoot()) {
50
+ const folder = path.join(root, ".runtime", "sessions");
51
+ let current, latest = -Infinity;
52
+ for (const pid of pids.slice(0, 16)) {
53
+ const file = await open(path.join(folder, `opencode-status-${pid}.json`), "r").catch(() => undefined);
54
+ if (!file)
55
+ continue;
56
+ try {
57
+ if ((await file.stat()).size > 4_096)
58
+ continue;
59
+ const value = object(JSON.parse((await file.readFile()).toString("utf8")));
60
+ const at = Date.parse(String(value.at));
61
+ if (typeof value.session !== "string" || !(at > latest))
62
+ continue;
63
+ const busyAt = typeof value.busyAt === "string" ? value.busyAt : undefined, idleAt = typeof value.idleAt === "string" ? value.idleAt : undefined;
64
+ if (!busyAt && !idleAt)
65
+ continue;
66
+ current = { session: value.session, at: String(value.at), ...(busyAt ? { busyAt } : {}), ...(idleAt ? { idleAt } : {}) };
67
+ latest = at;
68
+ }
69
+ catch {
70
+ continue;
71
+ }
72
+ finally {
73
+ await file.close();
74
+ }
75
+ }
76
+ return current;
77
+ }
46
78
  /** The status a Copilot session log's lines leave the session in; undefined
47
79
  * when none of them says. Copilot writes a turn_start/turn_end pair per model
48
80
  * call, so only the turn that carried the final answer ends the work. */
@@ -0,0 +1,39 @@
1
+ import { type AccountRef, type AuthRunner } from "./claude-accounts.js";
2
+ import { type ToolVersion } from "./health.js";
3
+ export type HarnessSource = "claude" | "codex" | "opencode" | "copilot";
4
+ export interface HarnessAccount extends AccountRef {
5
+ signedIn: boolean;
6
+ usable: boolean;
7
+ plan?: string;
8
+ reason?: string;
9
+ }
10
+ export interface HarnessEntry {
11
+ source: HarnessSource;
12
+ installed: boolean;
13
+ version?: string;
14
+ usable: boolean;
15
+ reason?: string;
16
+ accounts?: HarnessAccount[];
17
+ }
18
+ export interface HarnessInventory {
19
+ harnesses: HarnessEntry[];
20
+ }
21
+ export interface HarnessDeps {
22
+ toolVersion?: (tool: string) => Promise<ToolVersion>;
23
+ authRunner?: AuthRunner;
24
+ env?: NodeJS.ProcessEnv;
25
+ }
26
+ export declare function harnessInventory(deps?: HarnessDeps): Promise<HarnessInventory>;
27
+ /** The inventory, or undefined when it is not ready within `ms` (a cold `claude auth status` can take seconds). */
28
+ export declare function harnessInventoryWithin(ms: number, deps?: HarnessDeps): Promise<HarnessInventory | undefined>;
29
+ /** `PHREN_LAUNCH_CHECK=off`: no early launch refusal and no `harnesses` advertised to dispatch (tests, or a misreporting computer). */
30
+ export declare function launchCheckOff(env?: NodeJS.ProcessEnv): boolean;
31
+ export type Availability = {
32
+ ok: true;
33
+ } | {
34
+ ok: false;
35
+ code: "harness_unavailable" | "account_unavailable";
36
+ reason: string;
37
+ };
38
+ /** Whether a launch of `source` (and `accountId`) should work on a computer with this inventory. */
39
+ export declare function hasUsable(inventory: HarnessInventory, source: string, accountId?: string): Availability;
@@ -0,0 +1,65 @@
1
+ // What this computer can launch: each harness's install state and, for Claude and Codex, its accounts.
2
+ // Served as GET /v1/harnesses and as `harnesses` on /v1/dispatch/capacity. See docs/accounts.md.
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { codexHome } from "../home-paths.js";
6
+ import { claudeAccountRef, claudeAuthStatus, claudeHomes, CODEX_ACCOUNT } from "./claude-accounts.js";
7
+ import { toolVersion } from "./health.js";
8
+ const SOURCES = ["claude", "codex", "opencode", "copilot"];
9
+ export async function harnessInventory(deps = {}) {
10
+ const env = deps.env ?? process.env;
11
+ const probe = deps.toolVersion ?? ((tool) => toolVersion(tool));
12
+ const harnesses = await Promise.all(SOURCES.map(async (source) => {
13
+ const found = await probe(source);
14
+ // Only a missing binary is definite; a slow or failing --version (a loaded computer) stays usable.
15
+ if (found.status === "missing")
16
+ return { source, installed: false, usable: false, reason: "Not installed" };
17
+ const base = { source, installed: true, ...(found.version ? { version: found.version } : {}) };
18
+ if (source === "claude") {
19
+ const accounts = await Promise.all(claudeHomes(env).map(async (home) => {
20
+ const auth = await claudeAuthStatus(home, deps.authRunner);
21
+ // An unanswered sign-in check stays usable: only Claude saying "logged out" hides an account.
22
+ const usable = auth.signedIn || auth.unknown === true;
23
+ return { ...claudeAccountRef(home), signedIn: auth.signedIn, usable,
24
+ ...(auth.plan ? { plan: auth.plan } : {}), ...(auth.signedIn ? {} : { reason: auth.reason ?? "Not signed in" }) };
25
+ }));
26
+ const usable = accounts.some(account => account.usable);
27
+ return { ...base, usable, ...(usable ? {} : { reason: "No signed-in Claude account" }), accounts };
28
+ }
29
+ if (source === "codex") {
30
+ const signedIn = existsSync(path.join(codexHome(env), "auth.json"));
31
+ return { ...base, usable: signedIn, ...(signedIn ? {} : { reason: "Not signed in" }),
32
+ accounts: [{ ...CODEX_ACCOUNT, signedIn, usable: signedIn, ...(signedIn ? {} : { reason: "Not signed in" }) }] };
33
+ }
34
+ return { ...base, usable: true };
35
+ }));
36
+ return { harnesses };
37
+ }
38
+ /** The inventory, or undefined when it is not ready within `ms` (a cold `claude auth status` can take seconds). */
39
+ export function harnessInventoryWithin(ms, deps = {}) {
40
+ let timer;
41
+ const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), ms); });
42
+ return Promise.race([harnessInventory(deps).catch(() => undefined), late]).finally(() => clearTimeout(timer));
43
+ }
44
+ /** `PHREN_LAUNCH_CHECK=off`: no early launch refusal and no `harnesses` advertised to dispatch (tests, or a misreporting computer). */
45
+ export function launchCheckOff(env = process.env) {
46
+ return /^(off|0|false|no)$/i.test(env.PHREN_LAUNCH_CHECK?.trim() ?? "");
47
+ }
48
+ /** Whether a launch of `source` (and `accountId`) should work on a computer with this inventory. */
49
+ export function hasUsable(inventory, source, accountId) {
50
+ const entry = inventory.harnesses.find(item => item.source === source);
51
+ if (!entry || !entry.installed)
52
+ return { ok: false, code: "harness_unavailable", reason: entry?.reason ?? "Not installed" };
53
+ if (!entry.accounts) {
54
+ return accountId && accountId !== "default"
55
+ ? { ok: false, code: "account_unavailable", reason: `${source} has no accounts` }
56
+ : entry.usable ? { ok: true } : { ok: false, code: "harness_unavailable", reason: entry.reason ?? "Unavailable" };
57
+ }
58
+ const id = accountId?.trim() || "default";
59
+ const account = entry.accounts.find(item => item.id === id);
60
+ if (!account)
61
+ return { ok: false, code: "account_unavailable", reason: `No ${source} account "${id}"` };
62
+ if (!account.usable)
63
+ return { ok: false, code: "account_unavailable", reason: account.reason ?? "Not signed in" };
64
+ return { ok: true };
65
+ }
@@ -122,6 +122,8 @@ export declare function clearVersionCache(): void;
122
122
  export declare function storeSync(store: string): Promise<StoreSync[]>;
123
123
  /** The newest run in schedule-runs.jsonl, with its schedule's name when the project still has it. */
124
124
  export declare function lastScheduledRun(store: string, runsFile?: string): Promise<LastScheduledRun | null>;
125
+ /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
126
+ export declare function ownHostKey(): Promise<string | undefined>;
125
127
  /** Whether this computer's hooks.yaml lists the caller, by pinned host key or by name. */
126
128
  export declare function listsCaller(caller: {
127
129
  name?: string;
@@ -144,7 +144,7 @@ export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
144
144
  startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}) };
145
145
  }
146
146
  /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
147
- async function ownHostKey() {
147
+ export async function ownHostKey() {
148
148
  try {
149
149
  return publicComputerKey(await readFile("/etc/ssh/ssh_host_ed25519_key.pub", "utf8"));
150
150
  }
@@ -1,3 +1,4 @@
1
+ import type { AccountRef } from "./claude-accounts.js";
1
2
  import { BridgeError, type Json, type Target, type StartingTarget } from "./protocol.js";
2
3
  export declare function herdrRoot(): string;
3
4
  /** Where Herdr's socket for `server` lives. */
@@ -63,9 +64,13 @@ export interface PaneAddress {
63
64
  }
64
65
  /** The snapshot's pane at `address`; with a `source`, only while that agent runs there. */
65
66
  export declare function findPane(s: Json, address: PaneAddress): Json | undefined;
66
- /** A conductor's Herdr name: "conductor", or "conductor-" plus its label. */
67
+ /** A conductor's Herdr name: "conductor", or "conductor-" plus its label. Only
68
+ * a label since the Hook records the role (conductor-role.ts): read to migrate
69
+ * a conductor from before that record, and kept off workers' names. */
67
70
  export declare function isConductorName(name: string | undefined): boolean;
68
- export declare function workspaceSnapshot(s: Json, contextUsedPercent?: ReadonlyMap<Json, number>, approvalPanes?: ReadonlySet<string>, lastChanged?: ReadonlyMap<string, string>): Json;
71
+ /** `conductorPane` is the pane the Hook records as the conductor (null for
72
+ * none); left out, the agent's name decides, as before the record. */
73
+ export declare function workspaceSnapshot(s: Json, contextUsedPercent?: ReadonlyMap<Json, number>, approvalPanes?: ReadonlySet<string>, lastChanged?: ReadonlyMap<string, string>, conductorPane?: string | null): Json;
69
74
  export declare function paneIdentity(server: string, pane: Json, fresh?: boolean): Promise<string | undefined>;
70
75
  /** Copilot CLI changes conversation inside one process (/new, /clear,
71
76
  * /resume) and runs its sessionStart hook only once that conversation's first
@@ -87,6 +92,10 @@ export declare function paneForCodexSession(server: string, session: string, cwd
87
92
  export declare function paneChatState(server: string, pane: Json, options?: {
88
93
  tokenWhenIdentified?: boolean;
89
94
  }): Promise<Json>;
95
+ /** `{ account }` for a Claude pane whose account is known, else nothing. */
96
+ export declare function paneAccountField(server: string, pane: Json): {
97
+ account?: AccountRef;
98
+ };
90
99
  export declare function panes(server: string, workspace: string, tab: string): Promise<Json>;
91
100
  /** The pane a starting target names, if its terminal/process binding still
92
101
  * holds. Status is not checked here: a starting agent's first prompt (folder