@phren/cli 0.3.18 → 0.3.20
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.d.ts +16 -1
- package/dist/bridge/agent-hooks.js +56 -4
- package/dist/bridge/changes.d.ts +4 -0
- package/dist/bridge/changes.js +25 -2
- package/dist/bridge/command.js +24 -6
- package/dist/bridge/dispatch-returns.d.ts +11 -0
- package/dist/bridge/dispatch-returns.js +47 -7
- package/dist/bridge/dispatch.d.ts +19 -0
- package/dist/bridge/dispatch.js +164 -5
- package/dist/bridge/harnesses.d.ts +1 -1
- package/dist/bridge/harnesses.js +9 -2
- package/dist/bridge/health.d.ts +3 -2
- package/dist/bridge/health.js +4 -3
- package/dist/bridge/hook-fast.d.ts +13 -1
- package/dist/bridge/hook-fast.js +17 -2
- package/dist/bridge/models.d.ts +11 -1
- package/dist/bridge/models.js +47 -2
- package/dist/bridge/server-launch.d.ts +20 -0
- package/dist/bridge/server-launch.js +77 -3
- package/dist/bridge/server-routes.d.ts +4 -0
- package/dist/bridge/server-routes.js +2 -2
- package/dist/bridge/server.js +6 -1
- package/dist/bridge/speech-live.d.ts +45 -0
- package/dist/bridge/speech-live.js +413 -0
- package/dist/bridge/speech-transcribe.d.ts +5 -2
- package/dist/bridge/speech-transcribe.js +8 -5
- package/dist/bridge/speech-voice.d.ts +22 -1
- package/dist/bridge/speech-voice.js +20 -2
- package/dist/bridge/speech.d.ts +24 -4
- package/dist/bridge/speech.js +115 -14
- package/dist/bridge/stalls.d.ts +9 -2
- package/dist/bridge/stalls.js +20 -4
- package/dist/bridge/terminal-herdr.d.ts +7 -0
- package/dist/bridge/terminal-herdr.js +81 -7
- package/dist/bridge/terminal-tmux.js +2 -2
- package/dist/bridge/terminal.d.ts +3 -0
- package/dist/bridge/terminal.js +1 -0
- package/dist/bridge/transcript-preview.d.ts +11 -1
- package/dist/bridge/transcript-preview.js +37 -11
- package/dist/bridge/transcripts.d.ts +2 -1
- package/dist/bridge/transcripts.js +7 -3
- package/dist/bridge/transport.js +4 -3
- package/dist/bridge/turn-records.d.ts +6 -3
- package/dist/bridge/turn-records.js +9 -4
- package/dist/bridge/usage.d.ts +1 -1
- package/dist/bridge/usage.js +4 -3
- package/dist/bridge/worker-close.js +2 -1
- package/dist/bridge/worker-unfinished.d.ts +37 -0
- package/dist/bridge/worker-unfinished.js +145 -0
- package/dist/bridge-hook.mjs +2171 -1230
- package/dist/cli-registry.js +2 -1
- package/dist/modules/registry.js +2 -2
- package/package.json +1 -1
|
@@ -5,6 +5,8 @@ import { readPaneText } from "./pane-text.js";
|
|
|
5
5
|
import { object, objects } from "./protocol.js";
|
|
6
6
|
import { withTranscriptIndex } from "./transcript-index.js";
|
|
7
7
|
import { stripTerminal } from "../terminal-text.js";
|
|
8
|
+
/** Harnesses whose preview text is the reply's own Markdown, from their deltas. */
|
|
9
|
+
const STREAMED_SOURCES = new Set(["codex", "opencode", "phren"]);
|
|
8
10
|
export const PREVIEW_INTERVAL_MS = 500;
|
|
9
11
|
const MAX_TEXT = 32_768;
|
|
10
12
|
// A JSON-escaped UTF-16 code unit takes at most six bytes, plus metadata.
|
|
@@ -351,7 +353,9 @@ export async function readDeltaPreview(target, file, rollout) {
|
|
|
351
353
|
if (target.source === "codex")
|
|
352
354
|
return await codexThreadPreview(target.session)
|
|
353
355
|
?? (file && rollout ? await rollout.read(file).catch(() => null) : null);
|
|
354
|
-
|
|
356
|
+
// OpenCode's plugin and phren's agent write the same sidecar beside their
|
|
357
|
+
// event log (packages/agent/src/session/preview.ts).
|
|
358
|
+
if ((target.source !== "opencode" && target.source !== "phren") || !file)
|
|
355
359
|
return null;
|
|
356
360
|
try {
|
|
357
361
|
const handle = await open(file + ".preview.json", constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
@@ -402,7 +406,9 @@ export class TranscriptPreviewStream {
|
|
|
402
406
|
current = null;
|
|
403
407
|
observedLine = -1;
|
|
404
408
|
wasWorking = false;
|
|
405
|
-
|
|
409
|
+
/** Replies that already landed as entries: a sidecar or thread a tick
|
|
410
|
+
* behind them must not bring the same text back as a preview. */
|
|
411
|
+
completed = new Set();
|
|
406
412
|
rollout = new CodexRolloutPreview();
|
|
407
413
|
constructor(target, pane = () => readPreviewPane(target), delta = file => readDeltaPreview(target, file, this.rollout)) {
|
|
408
414
|
this.target = target;
|
|
@@ -416,7 +422,7 @@ export class TranscriptPreviewStream {
|
|
|
416
422
|
this.landed = false;
|
|
417
423
|
this.ended = false;
|
|
418
424
|
this.wasWorking = false;
|
|
419
|
-
this.
|
|
425
|
+
this.completed.clear();
|
|
420
426
|
}
|
|
421
427
|
for (const { raw, line } of entries) {
|
|
422
428
|
if (line <= this.observedLine)
|
|
@@ -428,25 +434,40 @@ export class TranscriptPreviewStream {
|
|
|
428
434
|
const payload = object(raw.payload);
|
|
429
435
|
if (raw.type === "event_msg" && payload.type === "task_started") {
|
|
430
436
|
this.ended = false;
|
|
431
|
-
this.
|
|
437
|
+
this.completed.clear();
|
|
432
438
|
}
|
|
433
439
|
else if (raw.type === "response_item" && payload.type === "message" && payload.role === "user" && !raw.phrenQueued) {
|
|
434
440
|
this.ended = false;
|
|
435
|
-
this.
|
|
441
|
+
this.completed.clear();
|
|
436
442
|
}
|
|
437
443
|
else if (raw.type === "response_item" && payload.type === "message" && payload.role === "assistant") {
|
|
438
444
|
const text = (typeof payload.content === "string" ? payload.content
|
|
439
445
|
: objects(payload.content).map(block => typeof block.text === "string" ? block.text : "").join("\n")).trim();
|
|
440
446
|
if (text) {
|
|
441
|
-
this.
|
|
442
|
-
if (this.
|
|
443
|
-
this.
|
|
447
|
+
this.completed.add(text);
|
|
448
|
+
if (this.completed.size > 32)
|
|
449
|
+
this.completed.delete(this.completed.values().next().value);
|
|
444
450
|
}
|
|
445
451
|
}
|
|
446
452
|
else if (raw.type === "event_msg" && ["task_complete", "task_completed", "turn_aborted", "task_aborted"].includes(String(payload.type)))
|
|
447
453
|
this.ended = true;
|
|
448
454
|
continue;
|
|
449
455
|
}
|
|
456
|
+
if (this.target.source === "phren") {
|
|
457
|
+
const data = object(raw.data), message = object(data.message);
|
|
458
|
+
if (raw.type === "user/message")
|
|
459
|
+
this.completed.clear();
|
|
460
|
+
else if (raw.type === "assistant/message") {
|
|
461
|
+
const text = (typeof message.content === "string" ? message.content
|
|
462
|
+
: objects(message.content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join("\n")).trim();
|
|
463
|
+
if (text) {
|
|
464
|
+
this.completed.add(text);
|
|
465
|
+
if (this.completed.size > 32)
|
|
466
|
+
this.completed.delete(this.completed.values().next().value);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
450
471
|
if (this.target.source === "copilot") {
|
|
451
472
|
// A prompt starts the turn; idle or abort ends it (Copilot writes a
|
|
452
473
|
// turn_start/turn_end pair per model call, not per prompt).
|
|
@@ -497,14 +518,14 @@ export class TranscriptPreviewStream {
|
|
|
497
518
|
let next = null;
|
|
498
519
|
if (status === "working") {
|
|
499
520
|
this.wasWorking = true;
|
|
500
|
-
if (
|
|
521
|
+
if (STREAMED_SOURCES.has(this.target.source)) {
|
|
501
522
|
// These harnesses own a delta source. Never scrape their pane, even
|
|
502
523
|
// when the source is temporarily empty or unavailable.
|
|
503
524
|
if (!this.ended)
|
|
504
525
|
next = await this.delta(file);
|
|
505
|
-
if (this.target.source
|
|
526
|
+
if (this.target.source !== "opencode" && next) {
|
|
506
527
|
const text = next.text.trim();
|
|
507
|
-
if (text && [...this.
|
|
528
|
+
if (text && [...this.completed].some(completed => completed.startsWith(text)))
|
|
508
529
|
next = null;
|
|
509
530
|
}
|
|
510
531
|
}
|
|
@@ -552,6 +573,11 @@ export class TranscriptPreviewStream {
|
|
|
552
573
|
return undefined;
|
|
553
574
|
if ((next || !previewChanged) && sentAt - this.lastSent < PREVIEW_INTERVAL_MS)
|
|
554
575
|
return undefined;
|
|
576
|
+
if (next && STREAMED_SOURCES.has(this.target.source)) {
|
|
577
|
+
const before = this.current?.turnStartedAt === next.turnStartedAt ? this.current.text : "";
|
|
578
|
+
next = { turnStartedAt: next.turnStartedAt, text: next.text,
|
|
579
|
+
delta: before && next.text.startsWith(before) ? next.text.slice(before.length) : next.text, streamed: true };
|
|
580
|
+
}
|
|
555
581
|
this.current = next;
|
|
556
582
|
this.sentActivity = activity;
|
|
557
583
|
if (next || activityChanged)
|
|
@@ -60,7 +60,8 @@ export declare function childAgent(tree: ChildAgentRelation[], id: string): Loca
|
|
|
60
60
|
* teammates, workflow agents and fan-out jobs a finished turn still waits on. */
|
|
61
61
|
export declare function runningChildAgents(tree: ChildAgentRelation[]): ChildAgentRelation[];
|
|
62
62
|
/**
|
|
63
|
-
* The phren store whose `.
|
|
63
|
+
* The phren store whose `.sessions` holds phren-agent event logs (and
|
|
64
|
+
* `.runtime/sessions` OpenCode's plugin logs).
|
|
64
65
|
* `PHREN_PATH` or the shared `~/.phren` root — the two resolutions the CLI's
|
|
65
66
|
* `findPhrenPath` makes without a working directory, which a service has none
|
|
66
67
|
* of. Kept inline rather than importing phren-paths: that module drags in
|
|
@@ -99,7 +99,8 @@ function toolOutputReferences(output) {
|
|
|
99
99
|
return Array.isArray(result.content) ? { ...result, content: imageReferences(result.content) } : output;
|
|
100
100
|
}
|
|
101
101
|
/**
|
|
102
|
-
* The phren store whose `.
|
|
102
|
+
* The phren store whose `.sessions` holds phren-agent event logs (and
|
|
103
|
+
* `.runtime/sessions` OpenCode's plugin logs).
|
|
103
104
|
* `PHREN_PATH` or the shared `~/.phren` root — the two resolutions the CLI's
|
|
104
105
|
* `findPhrenPath` makes without a working directory, which a service has none
|
|
105
106
|
* of. Kept inline rather than importing phren-paths: that module drags in
|
|
@@ -211,8 +212,11 @@ export async function transcriptPath(source, session, account) {
|
|
|
211
212
|
throw new BridgeError(400, "Invalid conversation identity.");
|
|
212
213
|
const bases = source === "codex" ? [{ base: path.join(codexHome(), "sessions") }]
|
|
213
214
|
: source === "claude" ? claudeHomes().map(home => ({ id: home.id, base: path.join(home.dir, "projects") }))
|
|
214
|
-
|
|
215
|
-
|
|
215
|
+
// phren-agent keeps its event logs in the store's `.sessions` (the CLI's
|
|
216
|
+
// sessionsDir); OpenCode's plugin writes under `.runtime/sessions`.
|
|
217
|
+
: source === "phren" ? [{ base: path.join(phrenStoreRoot(), ".sessions") }, { base: path.join(phrenStoreRoot(), ".runtime", "sessions") }]
|
|
218
|
+
: source === "opencode" ? [{ base: path.join(phrenStoreRoot(), ".runtime", "sessions") }]
|
|
219
|
+
: [{ base: path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state") }];
|
|
216
220
|
const pattern = source === "codex" ? `*/*/*/rollout-*-${session}.jsonl` : source === "claude" ? `*/${session}.jsonl`
|
|
217
221
|
: source === "phren" ? `session-${session}.events.jsonl` : source === "opencode" ? `opencode-${session}.events.jsonl` : `${session}/events.jsonl`;
|
|
218
222
|
const found = [];
|
package/dist/bridge/transport.js
CHANGED
|
@@ -107,7 +107,7 @@ export async function dispatch(command) {
|
|
|
107
107
|
}
|
|
108
108
|
// Without Herdr: a login shell, or one agent, in a validated project folder
|
|
109
109
|
// on the SSH PTY itself. Nothing persists after the phone disconnects.
|
|
110
|
-
const shell = /^phren-hook v1 shell ([A-Za-z0-9_-]{1,8192})(?: (codex|claude|copilot|opencode))?$/.exec(command);
|
|
110
|
+
const shell = /^phren-hook v1 shell ([A-Za-z0-9_-]{1,8192})(?: (codex|claude|copilot|opencode|phren))?$/.exec(command);
|
|
111
111
|
if (shell && shell[0] === command) {
|
|
112
112
|
requireHook();
|
|
113
113
|
const raw = decodeShellDirectory(shell[1]);
|
|
@@ -117,8 +117,9 @@ export async function dispatch(command) {
|
|
|
117
117
|
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
118
118
|
throw new Error("Request an SSH terminal first.");
|
|
119
119
|
const login = process.env.SHELL && path.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
|
|
120
|
-
|
|
121
|
-
|
|
120
|
+
// phren's own agent is the `phren agent` subcommand, in its interactive TUI.
|
|
121
|
+
const [file, args] = shell[2] === "phren" ? ["phren", ["agent", "-i"]] : shell[2] ? [shell[2], []] : [login, ["-l"]];
|
|
122
|
+
await attach(file, args, { cwd, env: shellEnvironment() }, shell[2] === "phren" ? "phren agent exited." : shell[2] ? `${shell[2]} exited.` : "The shell exited.");
|
|
122
123
|
return;
|
|
123
124
|
}
|
|
124
125
|
const terminal = /^phren-hook v1 terminal ([A-Za-z0-9_.-]{1,100})$/.exec(command);
|
|
@@ -18,16 +18,17 @@ declare const turnRecordSchema: z.ZodObject<{
|
|
|
18
18
|
prompt: z.ZodOptional<z.ZodObject<{
|
|
19
19
|
seq: z.ZodNumber;
|
|
20
20
|
at: z.ZodString;
|
|
21
|
-
}, z.core.$
|
|
21
|
+
}, z.core.$strip>>;
|
|
22
22
|
stop: z.ZodOptional<z.ZodObject<{
|
|
23
23
|
seq: z.ZodNumber;
|
|
24
24
|
at: z.ZodString;
|
|
25
25
|
background: z.ZodOptional<z.ZodNumber>;
|
|
26
26
|
reply: z.ZodOptional<z.ZodString>;
|
|
27
27
|
truncated: z.ZodOptional<z.ZodBoolean>;
|
|
28
|
-
|
|
28
|
+
cwd: z.ZodOptional<z.ZodString>;
|
|
29
|
+
}, z.core.$strip>>;
|
|
29
30
|
at: z.ZodString;
|
|
30
|
-
}, z.core.$
|
|
31
|
+
}, z.core.$strip>;
|
|
31
32
|
export type TurnRecord = z.infer<typeof turnRecordSchema>;
|
|
32
33
|
export interface TurnEvent {
|
|
33
34
|
event: string;
|
|
@@ -40,6 +41,8 @@ export interface TurnEvent {
|
|
|
40
41
|
background?: number;
|
|
41
42
|
/** Stop only: the harness's last assistant message, when it reports one. */
|
|
42
43
|
reply?: string;
|
|
44
|
+
/** Stop only: the agent's working directory, as its hook payload names it. */
|
|
45
|
+
cwd?: string;
|
|
43
46
|
at?: number;
|
|
44
47
|
}
|
|
45
48
|
export declare const turnPath: (server: string, pane: string) => string;
|
|
@@ -24,7 +24,9 @@ import { atomicInPrivateDir, bridgeRoot, provider, serverName, sessionId } from
|
|
|
24
24
|
/** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
|
|
25
25
|
export const TURN_REPLY_LIMIT = 4000;
|
|
26
26
|
const MAX_RECORD_BYTES = 16_384;
|
|
27
|
-
|
|
27
|
+
// Not strict: a field a newer Hook adds (as `stop.cwd` was) is dropped on
|
|
28
|
+
// read here, never a reason to throw the pane's record away.
|
|
29
|
+
const stamp = z.object({ seq: z.number().int().min(0), at: z.string().datetime() });
|
|
28
30
|
const turnRecordSchema = z.object({
|
|
29
31
|
terminal: z.string().min(1).max(200), source: provider, session: sessionId,
|
|
30
32
|
/** Climbs with every recorded event, so prompt and stop are ordered without trusting the clock. */
|
|
@@ -37,9 +39,11 @@ const turnRecordSchema = z.object({
|
|
|
37
39
|
/** Background tasks (shells, subagents, monitors) the harness still ran when the turn stopped. */
|
|
38
40
|
background: z.number().int().min(0).max(999).optional(),
|
|
39
41
|
reply: z.string().max(TURN_REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
|
|
40
|
-
|
|
42
|
+
/** The agent's working directory when the turn stopped: where its uncommitted work would be. */
|
|
43
|
+
cwd: z.string().max(4096).optional(),
|
|
44
|
+
}).optional(),
|
|
41
45
|
at: z.string().datetime(),
|
|
42
|
-
})
|
|
46
|
+
});
|
|
43
47
|
export const turnPath = (server, pane) => path.join(bridgeRoot(), "turns", encodeURIComponent(serverName.parse(server)), encodeURIComponent(pane) + ".json");
|
|
44
48
|
/** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
|
|
45
49
|
export function truncateUtf8(value, limit = TURN_REPLY_LIMIT) {
|
|
@@ -70,7 +74,8 @@ export function nextTurn(previous, event) {
|
|
|
70
74
|
else {
|
|
71
75
|
const reply = event.reply?.trim() ? truncateUtf8(event.reply.trim()) : undefined;
|
|
72
76
|
record.stop = { seq: record.seq, at, ...(event.background !== undefined ? { background: Math.min(999, Math.max(0, Math.floor(event.background))) } : {}),
|
|
73
|
-
...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {})
|
|
77
|
+
...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}),
|
|
78
|
+
...(event.cwd && path.isAbsolute(event.cwd) && event.cwd.length <= 4096 ? { cwd: event.cwd } : {}) };
|
|
74
79
|
}
|
|
75
80
|
return record;
|
|
76
81
|
}
|
package/dist/bridge/usage.d.ts
CHANGED
|
@@ -87,7 +87,7 @@ export declare function fetchOpenRouterUsage(key: string, fetchImpl?: typeof fet
|
|
|
87
87
|
/** ElevenLabs' subscription: characters used this billing period against the plan's limit. */
|
|
88
88
|
export declare function elevenLabsUsage(value: unknown, now?: Date): AccountUsage;
|
|
89
89
|
/** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
|
|
90
|
-
export declare function fetchElevenLabsUsage(key: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
|
|
90
|
+
export declare function fetchElevenLabsUsage(key: string, fetchImpl?: typeof fetch, now?: Date, origin?: string): Promise<AccountUsage>;
|
|
91
91
|
/** Claude Code's documented status-line payload: rate_limits carries the
|
|
92
92
|
* five_hour and seven_day windows (the 5h/7d unified limits) and, when the
|
|
93
93
|
* build emits them, per-model keys such as seven_day_fable. Every window
|
package/dist/bridge/usage.js
CHANGED
|
@@ -10,6 +10,7 @@ import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
|
10
10
|
import { stripTerminal } from "../terminal-text.js";
|
|
11
11
|
import { codexExecutable } from "./codex-binary.js";
|
|
12
12
|
import { readSpeechKey } from "./speech-key.js";
|
|
13
|
+
import { resolveSpeechRegion, SPEECH_REGIONS } from "./speech-voice.js";
|
|
13
14
|
import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
|
|
14
15
|
import { planName, subscriptionDate } from "./subscription.js";
|
|
15
16
|
const exec = promisify(execFile);
|
|
@@ -352,11 +353,11 @@ export function elevenLabsUsage(value, now = new Date()) {
|
|
|
352
353
|
return { source: "elevenlabs", ...metadata, windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
|
|
353
354
|
}
|
|
354
355
|
/** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
|
|
355
|
-
export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date()) {
|
|
356
|
+
export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date(), origin = SPEECH_REGIONS.global) {
|
|
356
357
|
const controller = new AbortController();
|
|
357
358
|
const timer = setTimeout(() => controller.abort(), 8_000);
|
|
358
359
|
try {
|
|
359
|
-
const response = await fetchImpl(
|
|
360
|
+
const response = await fetchImpl(`${origin}/v1/user/subscription`, {
|
|
360
361
|
headers: { "xi-api-key": key, accept: "application/json" },
|
|
361
362
|
redirect: "error",
|
|
362
363
|
signal: controller.signal,
|
|
@@ -377,7 +378,7 @@ async function liveElevenLabsUsage(now) {
|
|
|
377
378
|
if (!key)
|
|
378
379
|
return undefined;
|
|
379
380
|
try {
|
|
380
|
-
return await fetchElevenLabsUsage(key, fetch, now);
|
|
381
|
+
return await fetchElevenLabsUsage(key, fetch, now, (await resolveSpeechRegion()).origin);
|
|
381
382
|
}
|
|
382
383
|
catch {
|
|
383
384
|
return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "Could not read ElevenLabs usage. Check this computer's ElevenLabs key." };
|
|
@@ -51,7 +51,8 @@ export async function closeFinishedWorker(input, queue) {
|
|
|
51
51
|
return { ok: true, closed: false };
|
|
52
52
|
const seen = (await workerStates({ targets: [{ ...data.target, dispatch: data.dispatch }] })).workers[0];
|
|
53
53
|
const turn = workerTurnKey(seen);
|
|
54
|
-
|
|
54
|
+
// A turn that stopped mid-task, or whose checkout could not be read, keeps its pane.
|
|
55
|
+
if (!seen.completed || seen.background || seen.error || seen.unfinished || seen.unchecked || turn !== data.turn)
|
|
55
56
|
return { ok: true, closed: false };
|
|
56
57
|
// One final fresh binding before the terminal mutation.
|
|
57
58
|
const current = await validateTarget(data.target, false, true);
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** The reply's closing sentence when it announces a next step ("Let me…",
|
|
2
|
+
* "I'll…", "Now running…"), else undefined. */
|
|
3
|
+
export declare function announcedNextStep(reply: string | undefined): string | undefined;
|
|
4
|
+
/** A checkout git could not read in time (or at all): its work is unknown,
|
|
5
|
+
* so a turn there is never closed on the strength of it. */
|
|
6
|
+
export declare const UNKNOWN = "unknown";
|
|
7
|
+
export type Uncommitted = number | typeof UNKNOWN | undefined;
|
|
8
|
+
/** Tracked files with uncommitted changes (staged or not) in the checkout at
|
|
9
|
+
* `directory`. Untracked files are left out: a main checkout often holds the
|
|
10
|
+
* owner's own (worktree folders, scratch files) and they are not the worker's.
|
|
11
|
+
* Undefined when it is not a repository; UNKNOWN when git does not answer in
|
|
12
|
+
* time or fails otherwise. */
|
|
13
|
+
export declare function uncommittedFiles(directory: string, timeoutMs?: number): Promise<Uncommitted>;
|
|
14
|
+
/** `uncommittedFiles` for the returns loop, which asks about a finished
|
|
15
|
+
* worker on every poll (15 s) for as long as its receipt is watched: a read
|
|
16
|
+
* under a minute old answers. An UNKNOWN read is not kept, so the next poll
|
|
17
|
+
* (and the close recheck) asks git again. */
|
|
18
|
+
export declare function recentUncommitted(directory: string, now?: number, read?: (directory: string) => Promise<Uncommitted>): Promise<Uncommitted>;
|
|
19
|
+
/** The checkout `directory` is in: the nearest folder holding `.git` (a
|
|
20
|
+
* linked worktree's is a file), or undefined outside any. */
|
|
21
|
+
export declare function checkoutRoot(directory: string): Promise<string | undefined>;
|
|
22
|
+
/** Whether any of `folders` (other panes' working folders) is in the same
|
|
23
|
+
* checkout as `directory`. Uncommitted files there may be the owner's or a
|
|
24
|
+
* sibling worker's, so they say nothing about this worker. */
|
|
25
|
+
export declare function sharedCheckout(directory: string, folders: readonly unknown[]): Promise<boolean>;
|
|
26
|
+
/** Why a turn that ended is not done: it announced a next step, or it left
|
|
27
|
+
* uncommitted work with no PR reported or named in the reply (`unfinished`). `unchecked` when its
|
|
28
|
+
* checkout could not be read: the turn may be done, but it is not safe to
|
|
29
|
+
* close. Empty when it reads as done. */
|
|
30
|
+
export declare function unfinishedTurn(input: {
|
|
31
|
+
reply?: string;
|
|
32
|
+
prs?: readonly unknown[];
|
|
33
|
+
directory?: string;
|
|
34
|
+
}, uncommitted?: (directory: string) => Promise<Uncommitted>): Promise<{
|
|
35
|
+
unfinished?: string;
|
|
36
|
+
unchecked?: true;
|
|
37
|
+
}>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { lstat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { nonInteractiveGitEnv } from "../utils-helpers.js";
|
|
6
|
+
import { countGit } from "./metrics.js";
|
|
7
|
+
/**
|
|
8
|
+
* A worker whose turn ended is not always done. OpenCode in particular ends a
|
|
9
|
+
* turn on a line like "The worktree lacks node_modules. Let me install
|
|
10
|
+
* dependencies." with nothing run after it (hook-permission-mode, 2026-09-30:
|
|
11
|
+
* returned done, its pane closed, 9 files of uncommitted work left behind).
|
|
12
|
+
* Dispatch returns report such a turn as needs-you, never done, so its pane
|
|
13
|
+
* is not closed and the dispatcher nudges it on.
|
|
14
|
+
*/
|
|
15
|
+
const exec = promisify(execFile);
|
|
16
|
+
/** A closing sentence that announces work the turn never did: "Let me…",
|
|
17
|
+
* "I'll…", "I need to…", or "Now" with a working verb. Anything else, and
|
|
18
|
+
* whatever follows the subject in HANDOVER or a sentence waiting on something
|
|
19
|
+
* (CONDITIONAL), reads as finished: a done worker that says "I'll wait for
|
|
20
|
+
* your review" must not read as needs-you. "Let me know…" is a sign-off. */
|
|
21
|
+
const NEXT_STEP = /^(?:(?:ok(?:ay)?|alright|now|next|then|first|great|good)\b[,.!:]?\s+)*(?:let me(?! know)|let's|let us|i'll|i will|i'm going to|i am going to|i need to|i'm now|i am now|now i)\s+(.*)$/i;
|
|
22
|
+
const NOW_DOING = /^now,?\s+(?:adding|applying|building|checking|cleaning|committing|compiling|creating|debugging|editing|fixing|generating|implementing|installing|investigating|launching|looking|moving|opening|patching|pushing|reading|rebuilding|refactoring|removing|rerunning|re-running|running|searching|setting|starting|testing|trying|updating|verifying|wiring|working|writing)\b/i;
|
|
23
|
+
/** What a finished worker says it does next: wait, leave it to the owner, stop, be around. */
|
|
24
|
+
const HANDOVER = /^(?:just\s+)?(?:wait|await|leave|stop|hold|pause|be|hand|defer|stand|end|wrap|let you|keep an eye|check back|merge|ship|land|release|discuss|review|done|finished|ready)\b/i;
|
|
25
|
+
const CONDITIONAL = /\b(?:once|when|whenever|after|as soon as|if|until|unless)\b/i;
|
|
26
|
+
/** The last prose line of a reply: blank lines and fenced code are skipped, so
|
|
27
|
+
* "Let me run:" before a closing code block is still the closing sentence. */
|
|
28
|
+
function lastProseLine(reply) {
|
|
29
|
+
let fenced = false, last;
|
|
30
|
+
for (const raw of reply.replace(/\r/g, "").split("\n")) {
|
|
31
|
+
const line = raw.trim();
|
|
32
|
+
if (/^(?:```|~~~)/.test(line)) {
|
|
33
|
+
fenced = !fenced;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (!fenced && line)
|
|
37
|
+
last = line;
|
|
38
|
+
}
|
|
39
|
+
return last;
|
|
40
|
+
}
|
|
41
|
+
/** The reply's closing sentence when it announces a next step ("Let me…",
|
|
42
|
+
* "I'll…", "Now running…"), else undefined. */
|
|
43
|
+
export function announcedNextStep(reply) {
|
|
44
|
+
const line = reply ? lastProseLine(reply) : undefined;
|
|
45
|
+
if (!line)
|
|
46
|
+
return undefined;
|
|
47
|
+
const plain = line.replace(/^(?:[-*+>]|\d+[.)])\s+/, "").replace(/[*_`#]+/g, "").replace(/[\u2018\u2019]/g, "'").trim();
|
|
48
|
+
const last = plain.split(/(?<=[.!?\u2026])\s+/).filter(Boolean).at(-1)?.trim();
|
|
49
|
+
if (!last || CONDITIONAL.test(last))
|
|
50
|
+
return undefined;
|
|
51
|
+
const step = NEXT_STEP.exec(last);
|
|
52
|
+
const announced = step ? !HANDOVER.test(step[1]) : NOW_DOING.test(last);
|
|
53
|
+
return announced ? last.slice(0, 160) : undefined;
|
|
54
|
+
}
|
|
55
|
+
/** A checkout git could not read in time (or at all): its work is unknown,
|
|
56
|
+
* so a turn there is never closed on the strength of it. */
|
|
57
|
+
export const UNKNOWN = "unknown";
|
|
58
|
+
/** Tracked files with uncommitted changes (staged or not) in the checkout at
|
|
59
|
+
* `directory`. Untracked files are left out: a main checkout often holds the
|
|
60
|
+
* owner's own (worktree folders, scratch files) and they are not the worker's.
|
|
61
|
+
* Undefined when it is not a repository; UNKNOWN when git does not answer in
|
|
62
|
+
* time or fails otherwise. */
|
|
63
|
+
export async function uncommittedFiles(directory, timeoutMs = 3000) {
|
|
64
|
+
if (!path.isAbsolute(directory))
|
|
65
|
+
return undefined;
|
|
66
|
+
countGit("worker-unfinished");
|
|
67
|
+
try {
|
|
68
|
+
const { stdout } = await exec("git", ["-C", directory, "--no-pager", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "--untracked-files=no", "-z"], {
|
|
69
|
+
timeout: timeoutMs, maxBuffer: 1_048_576, env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" }),
|
|
70
|
+
});
|
|
71
|
+
// -z: renames carry their source as a second entry with no status.
|
|
72
|
+
return stdout.split("\0").filter(entry => /^[ MADRCTU?!]{2} /.test(entry)).length;
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
const failed = error;
|
|
76
|
+
// Exit 128 naming no repository (or no such folder) is a plain answer, not a slow one.
|
|
77
|
+
if (failed.code === 128 && !failed.killed && /not a git repository|cannot change to/i.test(String(failed.stderr ?? "")))
|
|
78
|
+
return undefined;
|
|
79
|
+
return UNKNOWN;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const recent = new Map();
|
|
83
|
+
/** `uncommittedFiles` for the returns loop, which asks about a finished
|
|
84
|
+
* worker on every poll (15 s) for as long as its receipt is watched: a read
|
|
85
|
+
* under a minute old answers. An UNKNOWN read is not kept, so the next poll
|
|
86
|
+
* (and the close recheck) asks git again. */
|
|
87
|
+
export function recentUncommitted(directory, now = Date.now(), read = uncommittedFiles) {
|
|
88
|
+
const hit = recent.get(directory);
|
|
89
|
+
if (hit && now - hit.at < 60_000)
|
|
90
|
+
return hit.files;
|
|
91
|
+
const files = read(directory).catch(() => UNKNOWN);
|
|
92
|
+
recent.delete(directory);
|
|
93
|
+
recent.set(directory, { at: now, files });
|
|
94
|
+
while (recent.size > 256)
|
|
95
|
+
recent.delete(recent.keys().next().value);
|
|
96
|
+
void files.then(value => { if (value === UNKNOWN && recent.get(directory)?.files === files)
|
|
97
|
+
recent.delete(directory); });
|
|
98
|
+
return files;
|
|
99
|
+
}
|
|
100
|
+
/** The checkout `directory` is in: the nearest folder holding `.git` (a
|
|
101
|
+
* linked worktree's is a file), or undefined outside any. */
|
|
102
|
+
export async function checkoutRoot(directory) {
|
|
103
|
+
if (!path.isAbsolute(directory))
|
|
104
|
+
return undefined;
|
|
105
|
+
let folder = path.resolve(directory);
|
|
106
|
+
for (let depth = 0; depth < 64; depth++) {
|
|
107
|
+
if (await lstat(path.join(folder, ".git")).then(() => true, () => false))
|
|
108
|
+
return folder;
|
|
109
|
+
const parent = path.dirname(folder);
|
|
110
|
+
if (parent === folder)
|
|
111
|
+
return undefined;
|
|
112
|
+
folder = parent;
|
|
113
|
+
}
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
/** Whether any of `folders` (other panes' working folders) is in the same
|
|
117
|
+
* checkout as `directory`. Uncommitted files there may be the owner's or a
|
|
118
|
+
* sibling worker's, so they say nothing about this worker. */
|
|
119
|
+
export async function sharedCheckout(directory, folders) {
|
|
120
|
+
const root = await checkoutRoot(directory);
|
|
121
|
+
if (!root)
|
|
122
|
+
return false;
|
|
123
|
+
const others = [...new Set(folders.filter((folder) => typeof folder === "string" && path.isAbsolute(folder)))].slice(0, 64);
|
|
124
|
+
for (const folder of others)
|
|
125
|
+
if (folder.startsWith(root) && await checkoutRoot(folder) === root)
|
|
126
|
+
return true;
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
/** A pull request the reply itself names: a GitHub PR link or "PR #12". */
|
|
130
|
+
const PR_NAMED = /\/pull\/\d+|\bPR\s*#\d+/i;
|
|
131
|
+
/** Why a turn that ended is not done: it announced a next step, or it left
|
|
132
|
+
* uncommitted work with no PR reported or named in the reply (`unfinished`). `unchecked` when its
|
|
133
|
+
* checkout could not be read: the turn may be done, but it is not safe to
|
|
134
|
+
* close. Empty when it reads as done. */
|
|
135
|
+
export async function unfinishedTurn(input, uncommitted) {
|
|
136
|
+
const step = announcedNextStep(input.reply);
|
|
137
|
+
if (step)
|
|
138
|
+
return { unfinished: `Stopped mid-task: ${step}` };
|
|
139
|
+
if (input.prs?.length || PR_NAMED.test(input.reply ?? "") || !input.directory || !uncommitted)
|
|
140
|
+
return {};
|
|
141
|
+
const files = await uncommitted(input.directory).catch(() => UNKNOWN);
|
|
142
|
+
if (files === UNKNOWN)
|
|
143
|
+
return { unchecked: true };
|
|
144
|
+
return files ? { unfinished: `Stopped with ${files} uncommitted file${files === 1 ? "" : "s"} and no PR.` } : {};
|
|
145
|
+
}
|