@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
@@ -9,6 +9,8 @@ import { paneIdentity, validateTarget } from "./herdr.js";
9
9
  import { transcriptPath } from "./transcripts.js";
10
10
  import { codexExecutable } from "./codex-binary.js";
11
11
  import { withTranscriptIndex } from "./transcript-index.js";
12
+ import { formatQuestionReply, parseQuestionReply } from "./codex-question-reply.js";
13
+ import { IMAGE_NAME, sessionUpload } from "./uploads.js";
12
14
  const exec = promisify(execFile);
13
15
  const text = z.string().trim().min(1).max(4000).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
14
16
  const question = z.object({ title: text, options: z.array(text).max(12).nullable().optional() });
@@ -48,7 +50,8 @@ export function deliveredQuestion(raw) {
48
50
  return;
49
51
  }
50
52
  }
51
- export function questionReply(questions, answers) {
53
+ /** The phone's answer to each question: one option it chose or its typed text. */
54
+ function answerValues(questions, answers) {
52
55
  const parsed = z.array(z.object({ optionIndexes: z.array(z.number().int().nonnegative()).max(1), text: z.string().max(4000).optional() })).parse(answers);
53
56
  if (parsed.length !== questions.length)
54
57
  throw new BridgeError(400, "Answer every question.");
@@ -59,8 +62,17 @@ export function questionReply(questions, answers) {
59
62
  const value = typed || options[answer.optionIndexes[0]];
60
63
  if (!value || !text.safeParse(value).success)
61
64
  throw new BridgeError(400, "Choose an available answer.");
62
- return q.title.split("\n").map(line => `> ${line}`).join("\n") + "\n\n" + value;
63
- }).join("\n\n");
65
+ return value;
66
+ });
67
+ }
68
+ export function questionReply(questions, answers) {
69
+ const values = answerValues(questions, answers);
70
+ return questions.map((q, index) => q.title.split("\n").map(line => `> ${line}`).join("\n") + "\n\n" + values[index]).join("\n\n");
71
+ }
72
+ /** The same answers as Codex's own TUI sends them into the running turn. */
73
+ export function asyncQuestionReply(id, questions, answers) {
74
+ const values = answerValues(questions, answers);
75
+ return formatQuestionReply(id, questions.map((q, index) => ({ question: q.title, answer: values[index] })));
64
76
  }
65
77
  const answersQuestions = (reply, questions) => questions.every(q => {
66
78
  const quote = q.title.split("\n").map(line => `> ${line}`).join("\n") + "\n\n";
@@ -69,7 +81,7 @@ const answersQuestions = (reply, questions) => questions.every(q => {
69
81
  });
70
82
  export async function pendingAsyncQuestions(file, targetID) {
71
83
  return withTranscriptIndex(file, async (handle, index) => {
72
- const replies = [], acknowledged = new Set(), resolved = new Set(), seen = new Set(), pending = [];
84
+ const replies = [], replied = new Set(), acknowledged = new Set(), resolved = new Set(), seen = new Set(), pending = [];
73
85
  let bytes = 0;
74
86
  for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - 10_000))) {
75
87
  // An incomplete scan is not evidence that no questions remain. Status
@@ -89,8 +101,14 @@ export async function pendingAsyncQuestions(file, targetID) {
89
101
  if (raw.type !== "response_item" && !delivered)
90
102
  continue;
91
103
  const p = object(raw.payload), id = delivered ? delivered.id : typeof p.call_id === "string" ? p.call_id : "";
92
- if (p.type === "message" && p.role === "user")
93
- replies.push(objects(p.content).map(b => typeof b.text === "string" ? b.text : "").join("\n"));
104
+ if (p.type === "message" && p.role === "user") {
105
+ const reply = objects(p.content).map(b => typeof b.text === "string" ? b.text : "").join("\n");
106
+ replies.push(reply);
107
+ // Codex's own answer (its TUI, or the Hook for a pane on its app-server) names the question.
108
+ for (const entry of parseQuestionReply(reply) ?? [])
109
+ if (entry.id)
110
+ replied.add(entry.id);
111
+ }
94
112
  if (id && ["function_call_output", "custom_tool_call_output"].includes(String(p.type)) && !resolved.has(id) && !acknowledged.has(id)) {
95
113
  try {
96
114
  if (object(JSON.parse(String(p.output))).accepted === true)
@@ -109,7 +127,7 @@ export async function pendingAsyncQuestions(file, targetID) {
109
127
  const questions = asyncQuestion(raw, id);
110
128
  // Codex 0.155 records one question twice under the same id: the
111
129
  // request_user_input_async call and the AgentMessage delivered async.
112
- if (questions && !seen.has(id) && !replies.some(reply => answersQuestions(reply, questions))) {
130
+ if (questions && !seen.has(id) && !replied.has(id) && !replies.some(reply => answersQuestions(reply, questions))) {
113
131
  pending.push({ id, questions });
114
132
  if (pending.length >= 64)
115
133
  throw new BridgeError(413, "Too many pending questions to verify.");
@@ -130,18 +148,100 @@ export async function pendingAsyncQuestion(file, id) {
130
148
  throw new BridgeError(409, "This question is no longer pending. Refresh the conversation.");
131
149
  return pending.questions;
132
150
  }
151
+ /** Files the phone attached to an answer, named the way the phone names them
152
+ * under a chat message it sends with attachments. */
153
+ export const attachedFiles = (paths) => paths.length ? `Attached files on this computer:\n${paths.join("\n")}` : "";
154
+ const withAttachments = (answer, paths) => paths.length ? `${answer}\n\n${attachedFiles(paths)}` : answer;
155
+ /** The phone's attachments for an answer: at most eight of this conversation's uploads. */
156
+ export async function answerAttachments(session, data) {
157
+ const requested = z.array(z.string().max(4096)).max(8).optional().parse(data.attachments) ?? [];
158
+ return Promise.all(requested.map(file => sessionUpload(session, file)));
159
+ }
160
+ const requestKey = (requestId) => `request:${JSON.stringify(requestId)}`;
161
+ const choose = (label, options, typed) => {
162
+ if (!typed && !options.includes(label))
163
+ throw new BridgeError(400, "Choose one of the offered answers.");
164
+ return label;
165
+ };
166
+ /** `item/tool/requestUserInput` (the synchronous tool) and a form MCP
167
+ * elicitation whose fields are all single values. Secret inputs, URL
168
+ * elicitations and multi-select fields stay in the pane. */
169
+ export function serverQuestion(request) {
170
+ const params = request.params;
171
+ if (request.method === "item/tool/requestUserInput") {
172
+ const asked = objects(params.questions);
173
+ if (!asked.length || asked.some(q => q.isSecret === true || typeof q.id !== "string" || typeof q.question !== "string"))
174
+ return undefined;
175
+ const parsed = questionSet.safeParse(asked.map(q => ({ title: q.question,
176
+ options: objects(q.options).map(option => option.label).filter((label) => typeof label === "string") })));
177
+ if (!parsed.success)
178
+ return undefined;
179
+ const questions = parsed.data.map(q => ({ ...q, options: q.options?.length ? q.options : undefined }));
180
+ return { questions, attachments: true, result: values => ({ answers: Object.fromEntries(asked.map((q, index) => [String(q.id),
181
+ { answers: [choose(values[index], questions[index].options ?? [], q.isOther === true || !questions[index].options)] }])) }) };
182
+ }
183
+ if (request.method !== "mcpServer/elicitation/request" || !["form", "openai/form", "openaiForm"].includes(String(params.mode)))
184
+ return undefined;
185
+ const message = typeof params.message === "string" ? params.message.trim() : "";
186
+ const fields = Object.entries(object(object(params.requestedSchema).properties));
187
+ if (!message || !fields.length || fields.length > 8)
188
+ return undefined;
189
+ const shaped = [];
190
+ for (const [key, raw] of fields) {
191
+ const field = object(raw), label = [field.title, field.description].find((value) => typeof value === "string" && !!value.trim())?.trim() ?? key;
192
+ if (field.type === "boolean") {
193
+ shaped.push({ key, title: label, options: ["Yes", "No"], value: answer => choose(answer, ["Yes", "No"], false) === "Yes" });
194
+ continue;
195
+ }
196
+ if (field.type === "number" || field.type === "integer") {
197
+ shaped.push({ key, title: label, value: answer => {
198
+ const number = Number(answer.trim());
199
+ if (!answer.trim() || !Number.isFinite(number) || (field.type === "integer" && !Number.isInteger(number)))
200
+ throw new BridgeError(400, `Answer "${label}" with a number.`);
201
+ return number;
202
+ } });
203
+ continue;
204
+ }
205
+ if (field.type !== "string")
206
+ return undefined;
207
+ const titled = objects(field.oneOf).filter(option => typeof option.const === "string" && typeof option.title === "string");
208
+ const plain = Array.isArray(field.enum) ? field.enum.filter((value) => typeof value === "string") : [];
209
+ const names = Array.isArray(field.enumNames) ? field.enumNames : [];
210
+ const pairs = titled.length ? titled.map(option => [String(option.title), String(option.const)])
211
+ : plain.map((value, index) => [typeof names[index] === "string" ? String(names[index]) : value, value]);
212
+ if (pairs.length) {
213
+ const options = pairs.map(([title]) => title);
214
+ shaped.push({ key, title: label, options, value: answer => pairs[options.indexOf(choose(answer, options, false))][1] });
215
+ }
216
+ else
217
+ shaped.push({ key, title: label, value: answer => answer });
218
+ }
219
+ // The server's message heads the first question; one field reads as the message itself.
220
+ const titles = shaped.map((field, index) => shaped.length === 1 ? (field.title === field.key ? message : `${message}\n\n${field.title}`)
221
+ : index === 0 ? `${message}\n\n${field.title}` : field.title);
222
+ const parsed = questionSet.safeParse(shaped.map((field, index) => ({ title: titles[index], ...(field.options ? { options: field.options } : {}) })));
223
+ if (!parsed.success)
224
+ return undefined;
225
+ return { questions: parsed.data, attachments: false, result: values => ({ action: "accept", content: Object.fromEntries(shaped.map((field, index) => [field.key, field.value(values[index])])) }) };
226
+ }
133
227
  export class CodexQuestions {
134
228
  configured;
229
+ served;
135
230
  snapshots = new Map();
136
231
  failedSnapshots = new Map();
137
232
  inboxAvailable = false;
138
233
  /** Feature discovery must never delay permission/status frames. */
139
234
  get available() { void this.supported(); return this.inboxAvailable; }
140
235
  probe;
141
- /** No executable: the real `codex` on PATH, past phren's session wrapper. */
142
- constructor(configured) {
236
+ /** No executable: the real `codex` on PATH, past phren's session wrapper.
237
+ * `served` answers panes on the Hook's own app-server over that server. */
238
+ constructor(configured, served) {
143
239
  this.configured = configured;
240
+ this.served = served;
144
241
  }
242
+ /** Whether the phone can answer this pane's questions: a pane on the Hook's
243
+ * own app-server always can; any other needs `codex queue`. */
244
+ availableFor(target) { return target.source === "codex" && (!!this.served?.forTarget(target) || this.available); }
145
245
  get executable() { return this.configured ?? codexExecutable(); }
146
246
  supported() {
147
247
  if (!this.probe || Date.now() - this.probe.at > 300_000)
@@ -153,6 +253,14 @@ export class CodexQuestions {
153
253
  async pending(target) {
154
254
  if (target.source !== "codex")
155
255
  return [];
256
+ const entry = this.served?.forTarget(target);
257
+ const parked = entry ? this.served.questions(entry).flatMap(request => {
258
+ const shown = serverQuestion(request);
259
+ return shown ? [{ toolUseId: requestKey(request.requestId), isAsync: true, submitted: false, questions: asPrompt(shown.questions) }] : [];
260
+ }) : [];
261
+ return [...parked, ...await this.transcriptPending(target)];
262
+ }
263
+ async transcriptPending(target) {
156
264
  if (Date.now() - (this.failedSnapshots.get(target.session) ?? 0) < 5000)
157
265
  throw new BridgeError(503, "Pending question history is unavailable.");
158
266
  const file = await transcriptPath("codex", target.session);
@@ -174,17 +282,44 @@ export class CodexQuestions {
174
282
  return Promise.all((pending ?? []).map(async (p) => {
175
283
  const key = createHash("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
176
284
  const submitted = await readFile(path.join(bridgeRoot(), "question-replies", key), "utf8").then(value => value === "submitted").catch(() => false);
177
- return { toolUseId: p.id, isAsync: true, submitted, questions: p.questions.map(q => ({ question: q.title,
178
- options: (q.options ?? []).map(label => ({ label })), ...(!q.options?.length ? { kind: "text" } : {}) })) };
285
+ return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
179
286
  })).then(prompts => prompts.filter(p => !p.submitted));
180
287
  }
181
288
  async answer(target, data) {
182
- if (target.source !== "codex" || !await this.supported())
289
+ const id = z.string().min(1).max(512).parse(data.toolUseId);
290
+ const entry = target.source === "codex" ? this.served?.forTarget(target) : undefined;
291
+ if (entry && id.startsWith("request:")) {
292
+ // A question parked on the Hook's own app-server: the answer is the
293
+ // reply to that request, exactly once, from whichever client is first.
294
+ const request = this.served.questions(entry).find(candidate => requestKey(candidate.requestId) === id);
295
+ const shown = request && serverQuestion(request);
296
+ if (!request || !shown)
297
+ throw new BridgeError(409, "This question is no longer pending. Refresh the conversation.");
298
+ const files = await answerAttachments(target.session, data);
299
+ if (files.length && !shown.attachments)
300
+ throw new BridgeError(400, "This question takes no attachments.");
301
+ const result = shown.result(answerValues(shown.questions, data.answers));
302
+ // Files ride on the last answer, the way a chat message carries them.
303
+ const answers = object(result.answers), last = Object.keys(answers).at(-1);
304
+ if (files.length && last) {
305
+ const values = object(answers[last]).answers;
306
+ answers[last] = { answers: [...values.slice(0, -1), withAttachments(values.at(-1) ?? "", files)] };
307
+ }
308
+ if (!this.served.answerQuestion(entry, request.requestId, result))
309
+ throw new BridgeError(409, "This question is no longer pending. Refresh the conversation.");
310
+ return;
311
+ }
312
+ if (target.source !== "codex" || (!entry && !await this.supported()))
183
313
  throw new BridgeError(409, "This connection needs the question answered in the terminal.");
184
314
  z.string().uuid().parse(target.session);
185
- const id = z.string().min(1).max(512).parse(data.toolUseId);
186
315
  const questions = await pendingAsyncQuestion(await transcriptPath("codex", target.session), id);
187
- const reply = questionReply(questions, data.answers);
316
+ const files = await answerAttachments(target.session, data);
317
+ // A pane on the Hook's app-server gets the answer in its running turn, as
318
+ // Codex's TUI sends it; `codex queue` would hold it until the turn ends.
319
+ // Attached pictures go in as images, and every file is named below.
320
+ const reply = entry ? asyncQuestionReply(id, questions, data.answers) : withAttachments(questionReply(questions, data.answers), files);
321
+ const extra = entry && files.length ? [{ type: "text", text: attachedFiles(files), text_elements: [] },
322
+ ...files.filter(file => IMAGE_NAME.test(file)).map(file => ({ type: "localImage", path: file }))] : [];
188
323
  const pane = await validateTarget(target);
189
324
  if (await paneIdentity(target.server, pane, true) !== target.session)
190
325
  throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
@@ -202,7 +337,10 @@ export class CodexQuestions {
202
337
  await receipt.close();
203
338
  try {
204
339
  // Explicit UUID, no session-name lookup, no shell, no terminal keystrokes.
205
- await exec(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8000, maxBuffer: 65_536 });
340
+ if (entry)
341
+ await this.served.steer(entry, reply, extra);
342
+ else
343
+ await exec(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8000, maxBuffer: 65_536 });
206
344
  await writeFile(receiptPath, "submitted", { mode: 0o600 });
207
345
  }
208
346
  catch {
@@ -210,3 +348,8 @@ export class CodexQuestions {
210
348
  }
211
349
  }
212
350
  }
351
+ /** Questions in the phone's pending-question shape: labelled options, or a
352
+ * typed answer when there are none. */
353
+ function asPrompt(questions) {
354
+ return questions.map(q => ({ question: q.title, options: (q.options ?? []).map(label => ({ label })), ...(!q.options?.length ? { kind: "text" } : {}) }));
355
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * This computer's live resources for `GET /v1/resources`, the overview
3
+ * stream's `resources` frames and the memory-free `phren computers` surface:
4
+ * load against cores, memory, free disk on the home volume, battery, uptime
5
+ * and the heavy jobs (simulators, emulators, xcodebuild, Gradle, agent
6
+ * workers) with the pane that started them where one did; any other program
7
+ * holding half a core or more across its processes shows as `busy`. macOS reads
8
+ * sysctl, pmset and ps; Linux reads /proc, /sys and ps. Nothing here needs a
9
+ * permission the Hook does not already have.
10
+ */
11
+ export declare const RESOURCES_MAX_AGE_MS: number;
12
+ /** Below this much free disk, or above twice the cores in load, a computer is stressed. */
13
+ export declare const LOW_DISK_BYTES: number;
14
+ export type HeavyKind = "simulator" | "emulator" | "xcodebuild" | "gradle" | "java" | "codex" | "opencode" | "claude" | "busy";
15
+ export interface PaneRef {
16
+ server: string;
17
+ workspace?: string;
18
+ pane: string;
19
+ agent?: string;
20
+ label?: string;
21
+ }
22
+ export interface HeavyProcess {
23
+ kind: HeavyKind;
24
+ name: string;
25
+ pid: number;
26
+ /** OS processes, including helpers; never a count of agents or working sessions. */
27
+ processes: number;
28
+ cpuPercent: number;
29
+ memoryBytes: number;
30
+ /** Why this process group is listed; resource use does not establish session activity. */
31
+ resourceReason?: "cpu" | "memory" | "tracked";
32
+ pane?: PaneRef;
33
+ }
34
+ export interface ComputerResources {
35
+ collectedAt: string;
36
+ platform: string;
37
+ uptimeSeconds: number;
38
+ cpu: {
39
+ cores: number;
40
+ load1: number;
41
+ load5: number;
42
+ load15: number;
43
+ loadPerCore: number;
44
+ };
45
+ memory: {
46
+ totalBytes: number;
47
+ availablePercent?: number;
48
+ pressure?: "normal" | "warn" | "critical";
49
+ swapUsedBytes?: number;
50
+ };
51
+ disk?: {
52
+ path: string;
53
+ totalBytes: number;
54
+ freeBytes: number;
55
+ };
56
+ battery?: {
57
+ percent: number;
58
+ charging: boolean;
59
+ onAC: boolean;
60
+ };
61
+ heavy: HeavyProcess[];
62
+ /** 0 idle to 1 saturated, per resource and overall (the highest), so every client fills its gauge the same way. */
63
+ pressure: {
64
+ cpu: number;
65
+ memory: number;
66
+ disk: number;
67
+ overall: number;
68
+ };
69
+ level: "ok" | "busy" | "stressed";
70
+ warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
71
+ }
72
+ export interface ProcessRow {
73
+ pid: number;
74
+ ppid: number;
75
+ cpu: number;
76
+ rssKB: number;
77
+ command: string;
78
+ args: string;
79
+ }
80
+ /** `ps -axo pid=,ppid=,pcpu=,rss=,comm=` paired with the `args=` listing by pid. */
81
+ export declare function parsePs(stats: string, args: string): ProcessRow[];
82
+ /** What kind of heavy job a process is, if any. */
83
+ export declare function heavyKind(row: ProcessRow): {
84
+ kind: HeavyKind;
85
+ name: string;
86
+ } | undefined;
87
+ /**
88
+ * The heavy jobs in a process table. Every process counts toward its nearest
89
+ * heavy ancestor-or-self, so a Codex worker running xcodebuild shows both,
90
+ * each with only its own share. Any other program shows as `busy` when its
91
+ * processes together hold half a core. Known programs below both a core's
92
+ * tenth and 200 MiB are left out, including simulators and emulators.
93
+ * A memory-only row can be an idle session or helper; it is not evidence of
94
+ * agent activity. Counts include OS helpers, not just the named executable.
95
+ * On Linux, ps pcpu is a process lifetime average, so these cutoffs can miss
96
+ * daemons that spike briefly.
97
+ */
98
+ export declare function heavyProcesses(rows: ProcessRow[], owners?: Map<number, PaneRef>, limit?: number): HeavyProcess[];
99
+ /** `pmset -g batt`: "Now drawing from 'AC Power'" then " -InternalBattery-0 (id=…) 87%; charging; …". */
100
+ export declare function parsePmset(output: string): ComputerResources["battery"];
101
+ /** `sysctl vm.swapusage`: "total = 2048.00M used = 798.50M free = …". */
102
+ export declare function parseSwap(output: string): number | undefined;
103
+ /** /proc/meminfo: MemTotal, MemAvailable and swap, in kB. */
104
+ export declare function parseMeminfo(text: string): ComputerResources["memory"];
105
+ /** Gauge fill and warnings from the numbers. */
106
+ export declare function assess(value: Omit<ComputerResources, "pressure" | "level" | "warnings">): Pick<ComputerResources, "pressure" | "level" | "warnings">;
107
+ /** Every pid a Herdr or tmux pane holds (its shell and foreground), for naming a job's pane. */
108
+ export declare function paneOwners(): Promise<Map<number, PaneRef>>;
109
+ export interface ResourceDeps {
110
+ platform: NodeJS.Platform;
111
+ now: () => number;
112
+ home: () => string;
113
+ processes: () => Promise<ProcessRow[]>;
114
+ owners: () => Promise<Map<number, PaneRef>>;
115
+ }
116
+ export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
117
+ /** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
118
+ export declare class ResourceMonitor {
119
+ private maxAgeMs;
120
+ private cached?;
121
+ private pending?;
122
+ private readonly deps;
123
+ constructor(deps?: Partial<ResourceDeps>, maxAgeMs?: number);
124
+ read(): Promise<ComputerResources>;
125
+ }