@phren/cli 0.3.72 → 0.3.73
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.
- package/dist/bridge/agent-hooks.js +11 -1
- package/dist/bridge/browser-env.d.ts +1 -1
- package/dist/bridge/browser-env.js +34 -10
- package/dist/bridge/browser-watch.d.ts +12 -0
- package/dist/bridge/browser-watch.js +83 -0
- package/dist/bridge/claude-account-setup.js +3 -1
- package/dist/bridge/claude-accounts.d.ts +5 -1
- package/dist/bridge/claude-accounts.js +36 -6
- package/dist/bridge/codex-servers.d.ts +2 -0
- package/dist/bridge/codex-servers.js +1 -1
- package/dist/bridge/command.js +24 -5
- package/dist/bridge/dispatch-clone.d.ts +33 -0
- package/dist/bridge/dispatch-clone.js +176 -0
- package/dist/bridge/dispatch-command.d.ts +14 -0
- package/dist/bridge/dispatch-command.js +98 -13
- package/dist/bridge/dispatch-idempotency.d.ts +85 -0
- package/dist/bridge/dispatch-idempotency.js +235 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -0
- package/dist/bridge/dispatch-returns.js +131 -1
- package/dist/bridge/dispatch-wait.d.ts +32 -0
- package/dist/bridge/dispatch-wait.js +177 -0
- package/dist/bridge/dispatch.d.ts +68 -2
- package/dist/bridge/dispatch.js +839 -25
- package/dist/bridge/fanouts.js +20 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/git-credential.d.ts +44 -0
- package/dist/bridge/git-credential.js +113 -0
- package/dist/bridge/git-host-auth.d.ts +9 -1
- package/dist/bridge/git-host-auth.js +18 -5
- package/dist/bridge/git-host-gitboy.js +8 -1
- package/dist/bridge/git-hosts.d.ts +12 -1
- package/dist/bridge/git-publish.js +3 -2
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +29 -3
- package/dist/bridge/install.d.ts +1 -1
- package/dist/bridge/install.js +8 -4
- package/dist/bridge/launch-worktree.d.ts +2 -0
- package/dist/bridge/launch-worktree.js +5 -1
- package/dist/bridge/protocol.d.ts +7 -0
- package/dist/bridge/schedule-watch.js +13 -2
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +251 -145
- package/dist/bridge/server-routes.js +18 -2
- package/dist/bridge/server.js +12 -1
- package/dist/bridge/status-line-fast.d.ts +9 -0
- package/dist/bridge/status-line-fast.js +56 -0
- package/dist/bridge/terminal-herdr.d.ts +5 -1
- package/dist/bridge/terminal-herdr.js +65 -1
- package/dist/bridge/terminal-tmux.d.ts +2 -0
- package/dist/bridge/terminal-tmux.js +27 -6
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.js +192 -112
- package/dist/bridge/transcript-preview.d.ts +2 -1
- package/dist/bridge/transcript-preview.js +85 -3
- package/dist/bridge/transcripts.js +17 -11
- package/dist/bridge/turn-records.js +16 -4
- package/dist/bridge/usage.d.ts +7 -1
- package/dist/bridge/usage.js +47 -31
- package/dist/bridge/worker-close.d.ts +15 -0
- package/dist/bridge/worker-close.js +304 -3
- package/dist/bridge/worker-identity.d.ts +51 -0
- package/dist/bridge/worker-identity.js +289 -0
- package/dist/bridge-hook.mjs +20857 -18606
- package/dist/cli/browser-hint.d.ts +2 -0
- package/dist/cli/browser-hint.js +21 -0
- package/dist/cli/hooks-context.d.ts +2 -2
- package/dist/cli/hooks-context.js +3 -3
- package/dist/cli/hooks.js +20 -11
- package/dist/cli-registry.js +5 -3
- package/dist/modules/registry.js +1 -1
- package/package.json +1 -1
|
@@ -55,6 +55,23 @@ async function claudeChildModel(file) {
|
|
|
55
55
|
* too: Git routes must fail explicitly when a checkout disappears, never
|
|
56
56
|
* substitute the parent repository. */
|
|
57
57
|
export async function claudeChildCheckout(file) {
|
|
58
|
+
// A child's first rows never change and its meta file rarely does; the tree asks for every child each time.
|
|
59
|
+
const [child, metaInfo] = await Promise.all([stat(file), stat(file.slice(0, -".jsonl".length) + ".meta.json").catch(() => undefined)]);
|
|
60
|
+
const stamp = `${child.dev}:${child.ino}:${metaInfo ? `${metaInfo.ino}:${metaInfo.size}:${metaInfo.mtimeMs}` : "-"}`;
|
|
61
|
+
const cached = claudeCheckoutCache.get(file);
|
|
62
|
+
if (cached?.stamp === stamp)
|
|
63
|
+
return cached.checkout;
|
|
64
|
+
const checkout = await readClaudeChildCheckout(file);
|
|
65
|
+
if (checkout.cwd) {
|
|
66
|
+
claudeCheckoutCache.delete(file);
|
|
67
|
+
claudeCheckoutCache.set(file, { stamp, checkout });
|
|
68
|
+
while (claudeCheckoutCache.size > 1024)
|
|
69
|
+
claudeCheckoutCache.delete(claudeCheckoutCache.keys().next().value);
|
|
70
|
+
}
|
|
71
|
+
return checkout;
|
|
72
|
+
}
|
|
73
|
+
const claudeCheckoutCache = new Map();
|
|
74
|
+
async function readClaudeChildCheckout(file) {
|
|
58
75
|
const meta = await readFile(file.slice(0, -".jsonl".length) + ".meta.json", "utf8").then(v => object(JSON.parse(v))).catch(() => ({}));
|
|
59
76
|
let cwd = typeof meta.worktreePath === "string" && path.isAbsolute(meta.worktreePath) ? meta.worktreePath : undefined;
|
|
60
77
|
let branch = typeof meta.worktreeBranch === "string" && meta.worktreeBranch ? meta.worktreeBranch.slice(0, 200) : undefined;
|
|
@@ -108,7 +125,8 @@ export async function claudeChildAgents(file, session) {
|
|
|
108
125
|
const rows = cached?.signature.startsWith(`${parent}:`) && cached.rows ? cached.rows : await claudeParentRows(file);
|
|
109
126
|
return claudeChildRelations(file, session, signature, rows, stop);
|
|
110
127
|
}
|
|
111
|
-
|
|
128
|
+
const claudeParentParses = new Map();
|
|
129
|
+
function newParentParse(identity) {
|
|
112
130
|
const launches = new Map();
|
|
113
131
|
const stops = new Map();
|
|
114
132
|
// A background skill (`/code-review` run as `@code-review`) is announced in
|
|
@@ -125,122 +143,170 @@ async function claudeParentRows(file) {
|
|
|
125
143
|
// Agent calls by tool_use id: the parent waits on a foreground one until its tool_result; a background one
|
|
126
144
|
// waits here for its launch result, which names its agent (or, when it names none, stays here).
|
|
127
145
|
const foreground = new Map(), background = new Map(), unidentified = new Map();
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
146
|
+
return { identity, offset: 0, stops, background, rows: { launches, skills, workflows, teammates, foreground, unidentified } };
|
|
147
|
+
}
|
|
148
|
+
async function claudeParentRows(file) {
|
|
149
|
+
// Reads of one file take turns, so no row is applied twice.
|
|
150
|
+
while (claudeParentParses.get(file)?.reading)
|
|
151
|
+
await claudeParentParses.get(file).reading;
|
|
152
|
+
const metadata = await stat(file), identity = `${metadata.dev}:${metadata.ino}`;
|
|
153
|
+
let parse = claudeParentParses.get(file);
|
|
154
|
+
if (parse?.reading)
|
|
155
|
+
return claudeParentRows(file);
|
|
156
|
+
// Replaced or rewritten (shorter than what was read): read from the start.
|
|
157
|
+
if (!parse || parse.identity !== identity || metadata.size < parse.offset)
|
|
158
|
+
parse = newParentParse(identity);
|
|
159
|
+
claudeParentParses.delete(file);
|
|
160
|
+
claudeParentParses.set(file, parse);
|
|
161
|
+
while (claudeParentParses.size > 64)
|
|
162
|
+
claudeParentParses.delete(claudeParentParses.keys().next().value);
|
|
163
|
+
if (metadata.size > parse.offset) {
|
|
164
|
+
const reading = readParentRows(file, parse, metadata.size);
|
|
165
|
+
parse.reading = reading.catch(() => undefined).finally(() => { parse.reading = undefined; });
|
|
166
|
+
await reading;
|
|
167
|
+
}
|
|
168
|
+
return copyRows(parse.rows);
|
|
169
|
+
}
|
|
170
|
+
/** Applies every whole row in [offset, size). A last row with no newline yet counts once it parses; a
|
|
171
|
+
* part-written one is left for the next read. */
|
|
172
|
+
async function readParentRows(file, parse, size) {
|
|
173
|
+
let carry = Buffer.alloc(0);
|
|
174
|
+
for await (const chunk of createReadStream(file, { start: parse.offset, end: size - 1 })) {
|
|
175
|
+
let data = carry.length ? Buffer.concat([carry, chunk]) : chunk, from = 0;
|
|
176
|
+
for (let at = data.indexOf(10); at !== -1; at = data.indexOf(10, from)) {
|
|
177
|
+
const end = at > from && data[at - 1] === 13 ? at - 1 : at;
|
|
178
|
+
applyParentRow(parse, data.toString("utf8", from, end));
|
|
179
|
+
parse.offset += at + 1 - from;
|
|
180
|
+
from = at + 1;
|
|
181
|
+
}
|
|
182
|
+
carry = data.subarray(from);
|
|
183
|
+
}
|
|
184
|
+
if (!carry.length)
|
|
185
|
+
return;
|
|
186
|
+
const line = carry.toString("utf8");
|
|
187
|
+
try {
|
|
188
|
+
JSON.parse(line);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
applyParentRow(parse, line);
|
|
194
|
+
parse.offset += carry.length;
|
|
195
|
+
}
|
|
196
|
+
function applyParentRow(parse, line) {
|
|
197
|
+
const { stops, background } = parse, { launches, skills, workflows, teammates, foreground, unidentified } = parse.rows;
|
|
198
|
+
try {
|
|
199
|
+
const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
|
|
200
|
+
const blocks = objects(object(raw.message).content);
|
|
201
|
+
const status = String(result.status ?? "");
|
|
202
|
+
// The agent id under the key Claude Code uses, or the one an older or newer version does.
|
|
203
|
+
const agentId = String([result.agentId, result.agent_id, result.taskType === "local_workflow" ? undefined : result.taskId, result.task_id]
|
|
204
|
+
.find(value => typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value)) ?? "");
|
|
205
|
+
// A launch that runs on: async by its own word, or by any status that is not an end.
|
|
206
|
+
const launched = result.taskType !== "local_workflow" && !/^(completed|failed|error|killed|cancell?ed|stopped|done)$/.test(status)
|
|
207
|
+
&& (result.isAsync === true || /^(async_)?(launched|running|started|queued|pending|spawned)$/.test(status));
|
|
208
|
+
const resultCall = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
|
|
209
|
+
if (launched && agentId && resultCall) {
|
|
210
|
+
launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId: resultCall, state: "running" });
|
|
211
|
+
}
|
|
212
|
+
else if (launched && resultCall && !agentId && background.has(resultCall)) {
|
|
213
|
+
const call = background.get(resultCall);
|
|
214
|
+
// Timed from the call itself: its agent can start before the launch result is stamped.
|
|
215
|
+
unidentified.set(resultCall, { path: String(result.description || call?.path || "Agent").slice(0, 200), callId: resultCall, prompt: call?.prompt ?? "",
|
|
216
|
+
...(call?.at ? { at: call.at } : typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) });
|
|
217
|
+
}
|
|
218
|
+
// SendMessage to a finished agent resumes it until its next final notification.
|
|
219
|
+
const resumed = typeof result.resumedAgentId === "string" ? launches.get(result.resumedAgentId) : undefined;
|
|
220
|
+
if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message)) {
|
|
221
|
+
resumed.state = "running";
|
|
222
|
+
if (typeof raw.timestamp === "string")
|
|
223
|
+
resumed.resumedAt = raw.timestamp;
|
|
224
|
+
}
|
|
225
|
+
if (result.taskType === "local_workflow" && status === "async_launched" && typeof result.taskId === "string"
|
|
226
|
+
&& typeof result.runId === "string" && /^wf_[A-Za-z0-9-]{1,64}$/.test(result.runId)) {
|
|
227
|
+
const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
|
|
228
|
+
workflows.set(result.taskId, { runId: result.runId, name: String(result.workflowName || "Workflow").slice(0, 200), callId, state: "running" });
|
|
229
|
+
}
|
|
230
|
+
if (raw.type === "system" && typeof raw.content === "string" && raw.content.includes("<forked-skill-launch>")) {
|
|
231
|
+
const launch = object(JSON.parse(/<forked-skill-launch>([\s\S]*?)<\/forked-skill-launch>/.exec(raw.content)?.[1] ?? "{}"));
|
|
232
|
+
const id = String(launch.agentId ?? "");
|
|
233
|
+
if (/^[A-Za-z0-9._-]{1,128}$/.test(id)) {
|
|
234
|
+
launches.set(id, { path: String(launch.description || (launch.skillName ? `/${launch.skillName}` : "Skill")).slice(0, 200), callId: `skill:${id}`, state: "running" });
|
|
235
|
+
skills.add(id);
|
|
161
236
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
if (
|
|
166
|
-
|
|
167
|
-
|
|
237
|
+
}
|
|
238
|
+
if (raw.type === "assistant") {
|
|
239
|
+
for (const block of blocks) {
|
|
240
|
+
if (block.type !== "tool_use")
|
|
241
|
+
continue;
|
|
242
|
+
if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
|
|
243
|
+
stops.set(block.id, String(object(block.input).task_id));
|
|
168
244
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if (block.name !== "Agent" && block.name !== "Task")
|
|
178
|
-
continue;
|
|
179
|
-
const input = object(block.input), name = String(input.name ?? "");
|
|
180
|
-
if (typeof block.id !== "string")
|
|
181
|
-
continue;
|
|
182
|
-
if (block.name === "Agent" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
|
|
183
|
-
teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
|
|
184
|
-
continue;
|
|
185
|
-
}
|
|
186
|
-
const call = { path: String(input.description || input.subagent_type || "Agent").slice(0, 200), callId: block.id.slice(0, 200),
|
|
187
|
-
prompt: typeof input.prompt === "string" ? input.prompt : "", ...(typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) };
|
|
188
|
-
(input.run_in_background === true ? background : foreground).set(call.callId, call);
|
|
245
|
+
if (block.name !== "Agent" && block.name !== "Task")
|
|
246
|
+
continue;
|
|
247
|
+
const input = object(block.input), name = String(input.name ?? "");
|
|
248
|
+
if (typeof block.id !== "string")
|
|
249
|
+
continue;
|
|
250
|
+
if (block.name === "Agent" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
|
|
251
|
+
teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
|
|
252
|
+
continue;
|
|
189
253
|
}
|
|
254
|
+
const call = { path: String(input.description || input.subagent_type || "Agent").slice(0, 200), callId: block.id.slice(0, 200),
|
|
255
|
+
prompt: typeof input.prompt === "string" ? input.prompt : "", ...(typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) };
|
|
256
|
+
(input.run_in_background === true ? background : foreground).set(call.callId, call);
|
|
190
257
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
// A stop request alone proves nothing. Its successful, matching result
|
|
200
|
-
// ends the child even when no later task notification is recorded.
|
|
201
|
-
if (raw.type === "user") {
|
|
202
|
-
for (const block of blocks) {
|
|
203
|
-
if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
|
|
204
|
-
continue;
|
|
205
|
-
const task = stops.get(block.tool_use_id);
|
|
206
|
-
if (!task)
|
|
207
|
-
continue;
|
|
208
|
-
stops.delete(block.tool_use_id);
|
|
209
|
-
const previous = launches.get(task) ?? workflows.get(task);
|
|
210
|
-
if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
|
|
211
|
-
&& /^Successfully stopped task\b/i.test(result.message))
|
|
212
|
-
previous.state = "completed";
|
|
213
|
-
}
|
|
258
|
+
}
|
|
259
|
+
// A call's result ends the parent's wait on it: the foreground agent finished, failed or was interrupted.
|
|
260
|
+
if (raw.type === "user")
|
|
261
|
+
for (const block of blocks) {
|
|
262
|
+
if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
|
|
263
|
+
continue;
|
|
264
|
+
foreground.delete(block.tool_use_id);
|
|
265
|
+
background.delete(block.tool_use_id);
|
|
214
266
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
267
|
+
// A stop request alone proves nothing. Its successful, matching result
|
|
268
|
+
// ends the child even when no later task notification is recorded.
|
|
269
|
+
if (raw.type === "user") {
|
|
270
|
+
for (const block of blocks) {
|
|
271
|
+
if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
|
|
272
|
+
continue;
|
|
273
|
+
const task = stops.get(block.tool_use_id);
|
|
274
|
+
if (!task)
|
|
275
|
+
continue;
|
|
276
|
+
stops.delete(block.tool_use_id);
|
|
277
|
+
const previous = launches.get(task) ?? workflows.get(task);
|
|
278
|
+
if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
|
|
279
|
+
&& /^Successfully stopped task\b/i.test(result.message))
|
|
280
|
+
previous.state = "completed";
|
|
228
281
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
282
|
+
}
|
|
283
|
+
const content = typeof raw.content === "string" ? raw.content : typeof object(raw.message).content === "string" ? String(object(raw.message).content) : "";
|
|
284
|
+
const attachment = object(raw.attachment);
|
|
285
|
+
const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
|
|
286
|
+
...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
|
|
287
|
+
raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
|
|
288
|
+
for (const notice of notices) {
|
|
289
|
+
for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
|
|
290
|
+
const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
|
|
291
|
+
// Terminal notifications end only the child named in that envelope.
|
|
292
|
+
const previous = child && (launches.get(child) ?? workflows.get(child));
|
|
293
|
+
if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
|
|
294
|
+
previous.state = "completed";
|
|
239
295
|
}
|
|
240
296
|
}
|
|
241
|
-
|
|
297
|
+
// One row can carry several messages (a shutdown approval and the
|
|
298
|
+
// system's termination notice together). Idle, an approved shutdown
|
|
299
|
+
// and termination end a teammate; anything else it says wakes it.
|
|
300
|
+
for (const match of content.includes("<teammate-message") ? content.matchAll(/<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"[^>]*>([\s\S]*?)<\/teammate-message>/g) : []) {
|
|
301
|
+
const [, from, body] = match;
|
|
302
|
+
const type = /"type":"([a-z_]+)"/.exec(body)?.[1];
|
|
303
|
+
const ended = from === "system" && type === "teammate_terminated" ? /"message":"([A-Za-z0-9][A-Za-z0-9_-]{0,63}) has shut down/.exec(body)?.[1] : undefined;
|
|
304
|
+
const teammate = teammates.get(ended ?? from);
|
|
305
|
+
if (teammate)
|
|
306
|
+
teammate.state = ended || type === "idle_notification" || type === "shutdown_approved" ? "completed" : "running";
|
|
307
|
+
}
|
|
242
308
|
}
|
|
243
|
-
|
|
309
|
+
catch { /* Ignore unrelated/malformed rows. */ }
|
|
244
310
|
}
|
|
245
311
|
async function claudeChildRelations(file, session, signature, rows, stop) {
|
|
246
312
|
// Kept as the parent wrote them: what follows marks finished children.
|
|
@@ -510,24 +576,38 @@ async function claudeWorkflowAgents(root, session, workflow, quietEnds = true, n
|
|
|
510
576
|
}
|
|
511
577
|
return relations;
|
|
512
578
|
}
|
|
579
|
+
/** Answers from a child's first row, which Claude Code never rewrites: kept per file while it is the same file. */
|
|
580
|
+
const claudeBelongsCache = new Map();
|
|
513
581
|
async function claudeChildBelongsTo(file, parent, agentId) {
|
|
514
|
-
|
|
582
|
+
const info = await stat(file), identity = `${info.dev}:${info.ino}`, key = `${file}\0${parent}\0${agentId}`;
|
|
583
|
+
const cached = claudeBelongsCache.get(key);
|
|
584
|
+
if (cached?.identity === identity)
|
|
585
|
+
return cached.belongs;
|
|
586
|
+
let bytes = Buffer.alloc(0), whole = false;
|
|
515
587
|
for await (const chunk of createReadStream(file, { start: 0, end: 1_048_575 })) {
|
|
516
588
|
bytes = Buffer.concat([bytes, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
|
|
517
589
|
const newline = bytes.indexOf(0x0a);
|
|
518
590
|
if (newline >= 0) {
|
|
519
591
|
bytes = bytes.subarray(0, newline);
|
|
592
|
+
whole = true;
|
|
520
593
|
break;
|
|
521
594
|
}
|
|
522
595
|
}
|
|
596
|
+
let belongs = false;
|
|
523
597
|
try {
|
|
524
598
|
const raw = object(JSON.parse(bytes.toString("utf8")));
|
|
525
|
-
|
|
599
|
+
belongs = (raw.isSidechain === true && raw.sessionId === parent && raw.agentId === agentId)
|
|
526
600
|
|| (raw.type === "fork-context-ref" && raw.parentSessionId === parent && raw.agentId === agentId);
|
|
527
601
|
}
|
|
528
|
-
catch {
|
|
529
|
-
|
|
602
|
+
catch { /* Not a row yet, or not one of this parent's. */ }
|
|
603
|
+
// A first row still being written is read again next time.
|
|
604
|
+
if (whole) {
|
|
605
|
+
claudeBelongsCache.delete(key);
|
|
606
|
+
claudeBelongsCache.set(key, { identity, belongs });
|
|
607
|
+
while (claudeBelongsCache.size > 1024)
|
|
608
|
+
claudeBelongsCache.delete(claudeBelongsCache.keys().next().value);
|
|
530
609
|
}
|
|
610
|
+
return belongs;
|
|
531
611
|
}
|
|
532
612
|
// `effort` rides on each assistant row (Claude Code 2.1): with `message.model`
|
|
533
613
|
// it is what the phone's model chip shows as in effect. `permissionMode` on a
|
|
@@ -116,7 +116,8 @@ export declare class TranscriptPreviewStream {
|
|
|
116
116
|
constructor(target: Target, pane?: () => Promise<string>, delta?: (file?: string) => Promise<TranscriptPreview | null>);
|
|
117
117
|
observe(entries: Entry[], reset?: boolean): void;
|
|
118
118
|
/** Whether pane text is a reply block that already landed: its words agree with the block's as far as
|
|
119
|
-
* both go (drawsLanded),
|
|
119
|
+
* both go (drawsLanded), or a long paragraph is still on screen after the block's opening scrolled away.
|
|
120
|
+
* A block still drawing the same opening as a landed one waits until the two part. */
|
|
120
121
|
private hasLanded;
|
|
121
122
|
/** Seed a reconnect from a classified owner row in the verified transcript. */
|
|
122
123
|
seedTurn(turnStartedAt: string, prompt: string): void;
|
|
@@ -17,7 +17,9 @@ const MAX_PREVIEW_BYTES = MAX_TEXT * 6 + 1_024;
|
|
|
17
17
|
* unless `inTurn` (the turn already landed an entry, so the screen is its own
|
|
18
18
|
* output and the prompt scrolled off above it). */
|
|
19
19
|
export function claudePanePreview(rendered, prompt, previous = "", inTurn = false) {
|
|
20
|
-
const screen = rendered.split("\n");
|
|
20
|
+
const screen = claudeReplyRegion(rendered.split("\n"));
|
|
21
|
+
if (!screen)
|
|
22
|
+
return "";
|
|
21
23
|
const raw = screen.map(stripTerminal);
|
|
22
24
|
// What the phone shows: the line with Claude's bold as Markdown. Detection
|
|
23
25
|
// below reads the plain line.
|
|
@@ -323,6 +325,84 @@ export function readPreviewPane(target) {
|
|
|
323
325
|
}
|
|
324
326
|
// An SGR sequence (captured) or any other control sequence stripTerminal removes.
|
|
325
327
|
const PANE_CONTROL = /\x1b\[([0-?]*)[ -/]*([@-~])|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\r/g;
|
|
328
|
+
/** Separate a styled sidebar before classifying rows or measuring wraps. Claude's diff
|
|
329
|
+
* panel has no enclosing box: bold paths and dim/italic instructions start at a fixed
|
|
330
|
+
* column, with padding between them and the reply. Two rows establish that column;
|
|
331
|
+
* crop every row there, including unstyled wraps and rows with no intervening space.
|
|
332
|
+
* An isolated region cannot establish a safe boundary, so that read stays silent. */
|
|
333
|
+
function claudeReplyRegion(screen) {
|
|
334
|
+
const columns = new Map();
|
|
335
|
+
const rows = screen.map(line => {
|
|
336
|
+
const styles = new Map();
|
|
337
|
+
const runs = [];
|
|
338
|
+
let plain = "", last = 0, inkStyle = "";
|
|
339
|
+
const take = (end) => {
|
|
340
|
+
const text = line.slice(last, end);
|
|
341
|
+
if (!text)
|
|
342
|
+
return;
|
|
343
|
+
runs.push({ raw: last, plain: plain.length, text });
|
|
344
|
+
if (text.trim()) {
|
|
345
|
+
const style = [...styles].sort(([a], [b]) => a - b).map(([key, value]) => `${key}:${value}`).join(";");
|
|
346
|
+
const before = plain + text.slice(0, text.length - text.trimStart().length);
|
|
347
|
+
if (before.length >= 20 && / {4,}$/.test(before) && style && style !== inkStyle) {
|
|
348
|
+
columns.set(before.length, (columns.get(before.length) ?? 0) + 1);
|
|
349
|
+
}
|
|
350
|
+
inkStyle = style;
|
|
351
|
+
}
|
|
352
|
+
plain += text;
|
|
353
|
+
};
|
|
354
|
+
for (const match of line.matchAll(PANE_CONTROL)) {
|
|
355
|
+
take(match.index);
|
|
356
|
+
last = match.index + match[0].length;
|
|
357
|
+
if (match[2] !== "m")
|
|
358
|
+
continue;
|
|
359
|
+
const params = (match[1] || "0").split(/[;:]/).map(value => Number(value || 0));
|
|
360
|
+
for (let i = 0; i < params.length; i++) {
|
|
361
|
+
const code = params[i];
|
|
362
|
+
if (code === 0)
|
|
363
|
+
styles.clear();
|
|
364
|
+
else if (code === 22) {
|
|
365
|
+
styles.delete(1);
|
|
366
|
+
styles.delete(2);
|
|
367
|
+
}
|
|
368
|
+
else if ([23, 24, 27, 29].includes(code))
|
|
369
|
+
styles.delete(code - 20);
|
|
370
|
+
else if (code === 39 || code === 49)
|
|
371
|
+
styles.delete(code - 1);
|
|
372
|
+
else if (code === 38 || code === 48 || code === 58) {
|
|
373
|
+
const size = params[i + 1] === 5 ? 2 : params[i + 1] === 2 ? 4 : 0;
|
|
374
|
+
styles.set(code, params.slice(i + 1, i + size + 1).join(":"));
|
|
375
|
+
i += size;
|
|
376
|
+
}
|
|
377
|
+
else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97))
|
|
378
|
+
styles.set(38, String(code));
|
|
379
|
+
else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
|
|
380
|
+
styles.set(48, String(code));
|
|
381
|
+
else
|
|
382
|
+
styles.set(code, "");
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
take(line.length);
|
|
386
|
+
return { line, runs };
|
|
387
|
+
});
|
|
388
|
+
// Without usable styles/padding, a known diff-panel notice is still evidence
|
|
389
|
+
// that this read cannot safely be interpreted as a single text region.
|
|
390
|
+
const panelNotice = screen.some(line => /New file not yet staged\.|Run `?git add :\/.*to see line counts\./.test(stripTerminal(line)));
|
|
391
|
+
if (!columns.size)
|
|
392
|
+
return panelNotice ? undefined : screen;
|
|
393
|
+
const repeated = [...columns].filter(([, count]) => count >= 2).map(([column]) => column);
|
|
394
|
+
if (!repeated.length)
|
|
395
|
+
return undefined;
|
|
396
|
+
const column = Math.min(...repeated);
|
|
397
|
+
// Offsets above count UTF-16 units. Wide glyphs and combining marks make that
|
|
398
|
+
// an unsafe terminal column; do not guess a crop in those reads.
|
|
399
|
+
if (rows.some(({ line }) => /[\t\p{Mark}\u1100-\u11ff\u2e80-\ua4cf\uac00-\ud7a3\ud800-\udfff\uf900-\ufaff\ufe00-\ufe6f\uff00-\uffef]/u.test(stripTerminal(line).slice(0, column))))
|
|
400
|
+
return undefined;
|
|
401
|
+
return rows.map(({ line, runs }) => {
|
|
402
|
+
const run = runs.find(run => run.plain + run.text.length > column);
|
|
403
|
+
return run ? line.slice(0, run.raw + Math.max(0, column - run.plain)) + "\x1b[0m" : line;
|
|
404
|
+
});
|
|
405
|
+
}
|
|
326
406
|
/**
|
|
327
407
|
* One pane line as Markdown bold. Claude draws a reply's **bold** with SGR 1
|
|
328
408
|
* and drops the asterisks, so a plain read loses it and the phone's preview
|
|
@@ -654,12 +734,14 @@ export class TranscriptPreviewStream {
|
|
|
654
734
|
}
|
|
655
735
|
}
|
|
656
736
|
/** Whether pane text is a reply block that already landed: its words agree with the block's as far as
|
|
657
|
-
* both go (drawsLanded),
|
|
737
|
+
* both go (drawsLanded), or a long paragraph is still on screen after the block's opening scrolled away.
|
|
738
|
+
* A block still drawing the same opening as a landed one waits until the two part. */
|
|
658
739
|
hasLanded(text) {
|
|
659
740
|
const words = previewWords(text);
|
|
660
741
|
return !words || [...this.landedTexts].some(landed =>
|
|
661
742
|
// A short block ("Let me check.") is not a longer one that starts with its words.
|
|
662
|
-
|
|
743
|
+
(words.length >= LANDED_MATCH_CHARS && landed.includes(words))
|
|
744
|
+
|| !(landed.length < LANDED_MATCH_CHARS && words.length > landed.length) && drawsLanded(words, landed));
|
|
663
745
|
}
|
|
664
746
|
/** Seed a reconnect from a classified owner row in the verified transcript. */
|
|
665
747
|
seedTurn(turnStartedAt, prompt) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { claudeQuestionResolutions, projectClaudeQuestionResolutions } from "./claude-question-lifecycle.js";
|
|
2
|
-
import { readdir, realpath
|
|
2
|
+
import { readdir, realpath } from "node:fs/promises";
|
|
3
|
+
import { lstatSync } from "node:fs";
|
|
3
4
|
import { createHash } from "node:crypto";
|
|
4
5
|
import { homedir } from "node:os";
|
|
5
6
|
import { codexHome } from "../home-paths.js";
|
|
@@ -159,19 +160,24 @@ async function findPatternMatches(root, pattern) {
|
|
|
159
160
|
const last = index === segments.length - 1;
|
|
160
161
|
if (!segment.includes("*") && !segment.includes("?")) {
|
|
161
162
|
const next = path.join(dir, segment);
|
|
163
|
+
// A Claude session is looked for in every project folder, and nearly all
|
|
164
|
+
// miss: a throwing lstat built an error for each one, the Hook's top cost.
|
|
165
|
+
let info;
|
|
162
166
|
try {
|
|
163
|
-
|
|
164
|
-
if (last) {
|
|
165
|
-
// glob returns a symlink to a file here too; the caller's realpath
|
|
166
|
-
// check is what rejects one pointing outside the provider folder.
|
|
167
|
-
if (info.isFile() || info.isSymbolicLink())
|
|
168
|
-
matches.push(next);
|
|
169
|
-
}
|
|
170
|
-
else if (info.isDirectory()) {
|
|
171
|
-
await walk(next, index + 1);
|
|
172
|
-
}
|
|
167
|
+
info = lstatSync(next, { throwIfNoEntry: false });
|
|
173
168
|
}
|
|
174
169
|
catch { /* no match */ }
|
|
170
|
+
if (!info)
|
|
171
|
+
return;
|
|
172
|
+
if (last) {
|
|
173
|
+
// glob returns a symlink to a file here too; the caller's realpath
|
|
174
|
+
// check is what rejects one pointing outside the provider folder.
|
|
175
|
+
if (info.isFile() || info.isSymbolicLink())
|
|
176
|
+
matches.push(next);
|
|
177
|
+
}
|
|
178
|
+
else if (info.isDirectory()) {
|
|
179
|
+
await walk(next, index + 1);
|
|
180
|
+
}
|
|
175
181
|
return;
|
|
176
182
|
}
|
|
177
183
|
let entries;
|
|
@@ -174,13 +174,18 @@ export function backgroundLeft(count, stoppedAt, finishedTasks = []) {
|
|
|
174
174
|
const stopped = Date.parse(stoppedAt);
|
|
175
175
|
return Math.max(0, count - finishedTasks.filter(at => Date.parse(at) >= stopped).length);
|
|
176
176
|
}
|
|
177
|
-
async function readRecord(file) {
|
|
177
|
+
async function readRecord(file, cache) {
|
|
178
178
|
try {
|
|
179
179
|
const info = await lstat(file);
|
|
180
180
|
if (!info.isFile() || info.size > MAX_RECORD_BYTES)
|
|
181
181
|
return undefined;
|
|
182
|
+
const stamp = `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}`, cached = cache?.get(file);
|
|
183
|
+
if (cached?.stamp === stamp)
|
|
184
|
+
return cached.record;
|
|
182
185
|
const parsed = turnRecordSchema.safeParse(JSON.parse(await readFile(file, "utf8")));
|
|
183
|
-
|
|
186
|
+
const record = parsed.success ? parsed.data : undefined;
|
|
187
|
+
cache?.set(file, { stamp, record });
|
|
188
|
+
return record;
|
|
184
189
|
}
|
|
185
190
|
catch {
|
|
186
191
|
return undefined;
|
|
@@ -206,6 +211,9 @@ export function readTurn(server, pane) {
|
|
|
206
211
|
}
|
|
207
212
|
const STOP_TASKS_CACHE_MS = 2_000;
|
|
208
213
|
let stopTasksCache;
|
|
214
|
+
/** Every pane's record, parsed, while its file is unchanged: the scan below runs every two seconds over
|
|
215
|
+
* hundreds of records, nearly all of them closed panes'. */
|
|
216
|
+
const stopRecordCache = new Map();
|
|
209
217
|
/** The background tasks the latest Stop of conversation `session` listed, from whichever pane's record
|
|
210
218
|
* holds it (the child tree knows the conversation, not its pane); undefined when no Stop listed any. */
|
|
211
219
|
export async function latestStopTasks(source, session) {
|
|
@@ -216,10 +224,11 @@ export async function latestStopTasks(source, session) {
|
|
|
216
224
|
// with the old process) outdates the list a closed pane's record still holds.
|
|
217
225
|
// Panes are read in name order, and a record written in the same millisecond as another wins only when
|
|
218
226
|
// its last event came after its own Stop (the pane that went on), so a tie never depends on directory order.
|
|
219
|
-
const newest = new Map();
|
|
227
|
+
const newest = new Map(), seen = new Set();
|
|
220
228
|
for (const server of (await readdir(root).catch(() => [])).sort()) {
|
|
221
229
|
for (const name of (await readdir(path.join(root, server)).catch(() => [])).filter(name => name.endsWith(".json")).sort()) {
|
|
222
|
-
|
|
230
|
+
seen.add(path.join(root, server, name));
|
|
231
|
+
const record = await readRecord(path.join(root, server, name), stopRecordCache);
|
|
223
232
|
if (!record)
|
|
224
233
|
continue;
|
|
225
234
|
const key = `${record.source}\0${record.session}`, previous = newest.get(key);
|
|
@@ -228,6 +237,9 @@ export async function latestStopTasks(source, session) {
|
|
|
228
237
|
newest.set(key, record);
|
|
229
238
|
}
|
|
230
239
|
}
|
|
240
|
+
for (const file of stopRecordCache.keys())
|
|
241
|
+
if (!seen.has(file))
|
|
242
|
+
stopRecordCache.delete(file);
|
|
231
243
|
const found = new Map();
|
|
232
244
|
for (const [key, record] of newest)
|
|
233
245
|
if (record.stop?.tasks)
|
package/dist/bridge/usage.d.ts
CHANGED
|
@@ -241,6 +241,12 @@ export declare class AccountUsageReader {
|
|
|
241
241
|
private claude;
|
|
242
242
|
private snapshotClaude;
|
|
243
243
|
}
|
|
244
|
-
/** Wrap
|
|
244
|
+
/** Wrap the owner's status line, preserving its input, output and options. A status line already wrapped,
|
|
245
|
+
* by any node or Hook folder and any number of times over, is unwrapped to the owner's first, so one
|
|
246
|
+
* refresh never runs a chain of wrappers. */
|
|
245
247
|
export declare function usageStatusLine(current: unknown, program: string, remove: boolean): unknown;
|
|
248
|
+
/** One status line report from Claude Code running in `configDir`: its normalized windows into that
|
|
249
|
+
* home's usage file and its session's cost into the home's ledger. Never session content. */
|
|
250
|
+
export declare function recordClaudeStatusLine(payload: unknown, configDir: string | undefined, now?: number): Promise<void>;
|
|
251
|
+
/** `bridge-hook.mjs usage-statusline`: the status line a version before the forwarder installed. */
|
|
246
252
|
export declare function captureClaudeUsage(original: string): Promise<void>;
|