@phren/cli 0.3.43 → 0.3.45
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/dispatch-command.js +7 -0
- package/dist/bridge/pane-status.d.ts +2 -0
- package/dist/bridge/pane-status.js +5 -1
- package/dist/bridge/schedule-format.d.ts +6 -4
- package/dist/bridge/schedule-format.js +14 -6
- package/dist/bridge/schedule-launch.d.ts +16 -6
- package/dist/bridge/schedule-launch.js +78 -32
- package/dist/bridge/schedule-problems.d.ts +13 -0
- package/dist/bridge/schedule-problems.js +39 -0
- package/dist/bridge/schedules.d.ts +7 -0
- package/dist/bridge/schedules.js +23 -3
- package/dist/bridge/server-routes.js +9 -2
- package/dist/bridge/session-activity.d.ts +10 -0
- package/dist/bridge/session-activity.js +25 -0
- package/dist/bridge/worker-close.d.ts +5 -0
- package/dist/bridge/worker-close.js +16 -0
- package/dist/bridge-hook.mjs +10091 -9960
- package/dist/cli/schedules.js +14 -1
- package/dist/cli-registry.js +2 -1
- package/dist/link/link.js +6 -1
- package/dist/modules/registry.js +1 -1
- package/package.json +1 -1
|
@@ -18,6 +18,13 @@ export async function runDispatch(args) {
|
|
|
18
18
|
console.log(JSON.stringify(await hookRequest("/v1/dispatch/report", { origin, prs: prsSchema.parse(JSON.parse(values.prs)), ...(dispatch ? { dispatch } : {}) }), null, 2));
|
|
19
19
|
return 0;
|
|
20
20
|
}
|
|
21
|
+
if (args.length === 1 && args[0] === "close-self") {
|
|
22
|
+
const origin = await terminalPaneFromEnv();
|
|
23
|
+
if (!origin)
|
|
24
|
+
throw new Error("phren dispatch close-self runs inside the agent's own terminal pane.");
|
|
25
|
+
console.log(JSON.stringify(await hookRequest("/v1/dispatch/close-self", { origin }), null, 2));
|
|
26
|
+
return 0;
|
|
27
|
+
}
|
|
21
28
|
if (args.length === 1 && args[0] === "status") {
|
|
22
29
|
console.log(JSON.stringify(await hookRequest("/v1/dispatch"), null, 2));
|
|
23
30
|
return 0;
|
|
@@ -16,6 +16,8 @@ export declare function paneStatus(server: string, pane: string, terminal: strin
|
|
|
16
16
|
status: string;
|
|
17
17
|
seq: number;
|
|
18
18
|
} | undefined>;
|
|
19
|
+
/** Claude's optional "Teach auto mode about your environment?" dialog. */
|
|
20
|
+
export declare function claudeTeachAutoModeDialog(screen: string): boolean;
|
|
19
21
|
/** Whether `screen` (a pane's visible lines, with or without colors) shows a
|
|
20
22
|
* dialog waiting for `agent`'s owner. Stricter than the readers that answer
|
|
21
23
|
* a dialog, because it runs while the agent is still writing: Claude's and
|
|
@@ -90,6 +90,10 @@ export async function paneStatus(server, pane, terminal) {
|
|
|
90
90
|
return undefined;
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
+
/** Claude's optional "Teach auto mode about your environment?" dialog. */
|
|
94
|
+
export function claudeTeachAutoModeDialog(screen) {
|
|
95
|
+
return /Teach auto mode about your environment/i.test(stripTerminal(screen));
|
|
96
|
+
}
|
|
93
97
|
/** Whether `screen` (a pane's visible lines, with or without colors) shows a
|
|
94
98
|
* dialog waiting for `agent`'s owner. Stricter than the readers that answer
|
|
95
99
|
* a dialog, because it runs while the agent is still writing: Claude's and
|
|
@@ -101,7 +105,7 @@ export function screenDialog(agent, screen) {
|
|
|
101
105
|
return !!opencodePermissionDialog(screen);
|
|
102
106
|
if (agent === "codex" || agent === "copilot")
|
|
103
107
|
return !!visibleTerminalChoice(text);
|
|
104
|
-
if (agent === "claude" && claudeQuestionDialog(text))
|
|
108
|
+
if (agent === "claude" && (claudeQuestionDialog(text) || claudeTeachAutoModeDialog(text)))
|
|
105
109
|
return true;
|
|
106
110
|
return /Esc to cancel/i.test(text) && !!numberedDialog(text);
|
|
107
111
|
}
|
|
@@ -83,8 +83,8 @@ export interface ScheduleLaunchContext {
|
|
|
83
83
|
projectDir: string;
|
|
84
84
|
cwd: string;
|
|
85
85
|
runId: string;
|
|
86
|
-
/** With `session: reuse`, the
|
|
87
|
-
reuse?: ScheduleLaunchRecord;
|
|
86
|
+
/** With `session: reuse`, the panes this target's earlier runs used, newest first: the newest still open is continued. */
|
|
87
|
+
reuse?: ScheduleLaunchRecord[];
|
|
88
88
|
blockedStartup?: (promptText: string) => void | Promise<void>;
|
|
89
89
|
}
|
|
90
90
|
export type ScheduleLauncher = ((context: ScheduleLaunchContext) => Promise<ScheduleLaunchResult>) & {
|
|
@@ -103,6 +103,8 @@ export interface ScheduleStatus extends Schedule {
|
|
|
103
103
|
running: boolean;
|
|
104
104
|
/** Whether this computer owns the schedule: it runs it and answers Run now. */
|
|
105
105
|
owned: boolean;
|
|
106
|
+
/** Why this schedule can never fire, when something is wrong with its computer or source paths. */
|
|
107
|
+
problems?: string[];
|
|
106
108
|
}
|
|
107
109
|
interface ScheduleDocument {
|
|
108
110
|
document: Record<string, unknown>;
|
|
@@ -123,8 +125,8 @@ export declare function latestScheduleBatch(runs: ScheduleRun[]): {
|
|
|
123
125
|
lastRun: ScheduleRun | undefined;
|
|
124
126
|
lastRuns: ScheduleRun[];
|
|
125
127
|
};
|
|
126
|
-
/** The
|
|
127
|
-
export declare function
|
|
128
|
+
/** The distinct Herdr panes a target's runs used, newest first, which `session: reuse` continues (the newest still open) and tidies (the older finished ones). */
|
|
129
|
+
export declare function reusableLaunches(runs: readonly ScheduleRun[]): ScheduleLaunchRecord[];
|
|
128
130
|
export declare function readScheduleRuns(file: string): Promise<ScheduleRun[]>;
|
|
129
131
|
export declare function writeScheduleRuns(file: string, runs: ScheduleRun[]): Promise<void>;
|
|
130
132
|
export declare function newScheduleId(existing: Iterable<string>): string;
|
|
@@ -255,14 +255,22 @@ export function latestScheduleBatch(runs) {
|
|
|
255
255
|
: lastRuns.map(run => run.finishedAt).filter((time) => Boolean(time)).sort().at(-1);
|
|
256
256
|
return { lastRun: { ...representative, finishedAt }, lastRuns };
|
|
257
257
|
}
|
|
258
|
-
/**
|
|
259
|
-
|
|
260
|
-
|
|
258
|
+
/** Max panes of one schedule `session: reuse` looks through, and tidies. */
|
|
259
|
+
const REUSE_PANES = 8;
|
|
260
|
+
/** The distinct Herdr panes a target's runs used, newest first, which `session: reuse` continues (the newest still open) and tidies (the older finished ones). */
|
|
261
|
+
export function reusableLaunches(runs) {
|
|
262
|
+
const seen = new Set(), found = [];
|
|
263
|
+
for (let index = runs.length - 1; index >= 0 && found.length < REUSE_PANES; index--) {
|
|
261
264
|
const launch = runs[index].launch;
|
|
262
|
-
if (launch.mode
|
|
263
|
-
|
|
265
|
+
if (launch.mode !== "herdr" || !launch.server || !launch.workspaceId || !launch.tabId || !launch.paneId)
|
|
266
|
+
continue;
|
|
267
|
+
const key = [launch.server, launch.workspaceId, launch.tabId, launch.paneId].join("\0");
|
|
268
|
+
if (seen.has(key))
|
|
269
|
+
continue;
|
|
270
|
+
seen.add(key);
|
|
271
|
+
found.push(launch);
|
|
264
272
|
}
|
|
265
|
-
return
|
|
273
|
+
return found;
|
|
266
274
|
}
|
|
267
275
|
export async function readScheduleRuns(file) {
|
|
268
276
|
let text;
|
|
@@ -9,15 +9,25 @@ export interface ContinueEnv {
|
|
|
9
9
|
panes?: (server: string) => Promise<Json[]>;
|
|
10
10
|
transcriptStamp?: typeof realTranscriptStamp;
|
|
11
11
|
watch?: typeof watchHerdrRun;
|
|
12
|
+
/** The conversation a pane runs, for a record that never learned its id. */
|
|
13
|
+
identity?: (server: string, pane: Json) => Promise<string | undefined>;
|
|
14
|
+
/** The pane's visible lines, to see a dialog that would swallow the prompt. */
|
|
15
|
+
screen?: (server: string, pane: string) => Promise<string>;
|
|
16
|
+
keys?: (server: string, pane: string, keys: string[]) => Promise<void>;
|
|
17
|
+
/** Closes a finished pane of this schedule once a newer one has taken the firing. */
|
|
18
|
+
close?: (server: string, pane: Json) => Promise<void>;
|
|
12
19
|
}
|
|
13
20
|
/**
|
|
14
|
-
* `session: reuse`: types the prompt into the session
|
|
15
|
-
*
|
|
16
|
-
* rather than given a second prompt
|
|
17
|
-
*
|
|
18
|
-
*
|
|
21
|
+
* `session: reuse`: types the prompt into the newest session of this schedule
|
|
22
|
+
* whose pane still runs its harness (`previous`, newest first). A busy newest
|
|
23
|
+
* session is skipped rather than given a second prompt; a pane whose prompt
|
|
24
|
+
* cannot be delivered (a dialog that will not dismiss, a refused delivery)
|
|
25
|
+
* passes the firing to the next older one. Once a pane has taken the firing,
|
|
26
|
+
* the schedule's older finished panes are closed. Undefined when no session is
|
|
27
|
+
* left (the panes closed, their agents exited, their conversations were
|
|
28
|
+
* replaced), so the caller starts a new one, which the next firing continues.
|
|
19
29
|
*/
|
|
20
|
-
export declare function continueSession(context: ScheduleLaunchContext, previous: ScheduleLaunchRecord, deliver: ScheduleDeliver, signal: AbortSignal, env?: ContinueEnv): Promise<ScheduleLaunchResult | undefined>;
|
|
30
|
+
export declare function continueSession(context: ScheduleLaunchContext, previous: ScheduleLaunchRecord[], deliver: ScheduleDeliver, signal: AbortSignal, env?: ContinueEnv): Promise<ScheduleLaunchResult | undefined>;
|
|
21
31
|
/**
|
|
22
32
|
* The outcome of a run a previous Hook process launched and never saw finish
|
|
23
33
|
* (a restart or crash mid-run). A Herdr pane is followed again to its real
|
|
@@ -13,6 +13,7 @@ import { agentNotReady, terminalProvider } from "./terminal.js";
|
|
|
13
13
|
import { atomicInPrivateDir, BridgeError, object, objects } from "./protocol.js";
|
|
14
14
|
import { defaultPhrenPath } from "../shared.js";
|
|
15
15
|
import { realTranscriptStamp, watchHerdrRun } from "./schedule-watch.js";
|
|
16
|
+
import { claudeTeachAutoModeDialog } from "./pane-status.js";
|
|
16
17
|
/** Starting a scheduled run: in a Herdr pane when a server is live, otherwise
|
|
17
18
|
* as a headless job under the fan-out root. */
|
|
18
19
|
const CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
|
|
@@ -38,45 +39,90 @@ function busyReason(status) {
|
|
|
38
39
|
const state = status === "blocked" || status === "waiting" ? "is waiting for you" : status === "working" || status === "starting" ? "is still working" : `is ${status || "busy"}`;
|
|
39
40
|
return `The session this schedule continues ${state}, so this firing was skipped.`;
|
|
40
41
|
}
|
|
42
|
+
const finishedPane = (pane) => pane.agent_status === "idle" || pane.agent_status === "done";
|
|
43
|
+
/** Claude's optional "Teach auto mode about your environment?" dialog takes a typed prompt as an answer. */
|
|
44
|
+
async function dismissAutoModeDialog(server, pane, env) {
|
|
45
|
+
const screen = env.screen ?? ((name, id) => terminalProvider().readScreen(name, id, { scope: "pane", source: "visible", lines: 120, stripAnsi: true, timeoutMs: 1000 }));
|
|
46
|
+
const keys = env.keys ?? ((name, id, pressed) => terminalProvider().sendKeys(name, id, pressed));
|
|
47
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
48
|
+
const shown = await screen(server, pane).then(text => claudeTeachAutoModeDialog(text), () => false);
|
|
49
|
+
if (!shown)
|
|
50
|
+
return true;
|
|
51
|
+
await keys(server, pane, ["esc"]).catch(() => undefined);
|
|
52
|
+
await new Promise(resolve => setTimeout(resolve, 300));
|
|
53
|
+
}
|
|
54
|
+
return !await screen(server, pane).then(text => claudeTeachAutoModeDialog(text), () => false);
|
|
55
|
+
}
|
|
41
56
|
/**
|
|
42
|
-
* `session: reuse`: types the prompt into the session
|
|
43
|
-
*
|
|
44
|
-
* rather than given a second prompt
|
|
45
|
-
*
|
|
46
|
-
*
|
|
57
|
+
* `session: reuse`: types the prompt into the newest session of this schedule
|
|
58
|
+
* whose pane still runs its harness (`previous`, newest first). A busy newest
|
|
59
|
+
* session is skipped rather than given a second prompt; a pane whose prompt
|
|
60
|
+
* cannot be delivered (a dialog that will not dismiss, a refused delivery)
|
|
61
|
+
* passes the firing to the next older one. Once a pane has taken the firing,
|
|
62
|
+
* the schedule's older finished panes are closed. Undefined when no session is
|
|
63
|
+
* left (the panes closed, their agents exited, their conversations were
|
|
64
|
+
* replaced), so the caller starts a new one, which the next firing continues.
|
|
47
65
|
*/
|
|
48
66
|
export async function continueSession(context, previous, deliver, signal, env = {}) {
|
|
49
|
-
const
|
|
50
|
-
if (!server || !workspaceId || !tabId || !paneId || !sessionId)
|
|
51
|
-
return undefined;
|
|
67
|
+
const source = context.schedule.harness;
|
|
52
68
|
const panes = env.panes ?? (async (name) => objects((await snapshot(name)).panes));
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
result = await deliver({ server, workspace: workspaceId, tab: tabId, pane: paneId, source, session: sessionId }, context.schedule.prompt, `schedule-${context.runId.replaceAll("-", "")}`);
|
|
64
|
-
}
|
|
65
|
-
catch (error) {
|
|
66
|
-
// The pane or its conversation went away between the look and the send.
|
|
67
|
-
if (error instanceof BridgeError && (error.status === 404 || error.status === 409))
|
|
68
|
-
return undefined;
|
|
69
|
-
throw error;
|
|
69
|
+
const looked = new Map(), live = [];
|
|
70
|
+
for (const record of previous) {
|
|
71
|
+
const { server, workspaceId, tabId, paneId } = record;
|
|
72
|
+
if (!server || !workspaceId || !tabId || !paneId)
|
|
73
|
+
continue;
|
|
74
|
+
if (!looked.has(server))
|
|
75
|
+
looked.set(server, await panes(server).catch(() => []));
|
|
76
|
+
const pane = findPane({ panes: looked.get(server) }, { workspace: workspaceId, tab: tabId, pane: paneId, source });
|
|
77
|
+
if (pane)
|
|
78
|
+
live.push({ record, pane });
|
|
70
79
|
}
|
|
71
|
-
if (
|
|
80
|
+
if (!live.length)
|
|
72
81
|
return undefined;
|
|
73
|
-
|
|
74
|
-
|
|
82
|
+
const recordOf = (item, sessionId) => ({ mode: "herdr", server: item.record.server, workspaceId: item.record.workspaceId, tabId: item.record.tabId, paneId: item.record.paneId, ...(sessionId ? { sessionId } : {}), reused: true });
|
|
83
|
+
const newest = live[0];
|
|
84
|
+
if (!finishedPane(newest.pane))
|
|
85
|
+
return { launch: recordOf(newest, newest.record.sessionId), skipped: busyReason(String(newest.pane.agent_status ?? "")) };
|
|
86
|
+
for (const item of live) {
|
|
87
|
+
if (!finishedPane(item.pane))
|
|
88
|
+
continue;
|
|
89
|
+
const { server, workspaceId, tabId, paneId } = item.record;
|
|
90
|
+
const sessionId = item.record.sessionId ?? await (env.identity ?? ((name, pane) => paneIdentity(name, pane)))(server, item.pane).catch(() => undefined);
|
|
91
|
+
if (!sessionId)
|
|
92
|
+
continue;
|
|
93
|
+
if (source === "claude" && !await dismissAutoModeDialog(server, paneId, env))
|
|
94
|
+
continue;
|
|
95
|
+
const transcript = await (env.transcriptStamp ?? realTranscriptStamp)(source, sessionId).catch(() => undefined);
|
|
96
|
+
let result;
|
|
97
|
+
try {
|
|
98
|
+
result = await deliver({ server, workspace: workspaceId, tab: tabId, pane: paneId, source, session: sessionId }, context.schedule.prompt, `schedule-${context.runId.replaceAll("-", "")}`);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
// The pane or its conversation went away between the look and the send.
|
|
102
|
+
if (error instanceof BridgeError && (error.status === 404 || error.status === 409))
|
|
103
|
+
continue;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
if (result.state === "failed")
|
|
107
|
+
continue;
|
|
108
|
+
if (result.delivered !== true && result.queued !== true) {
|
|
109
|
+
throw new Error(`The prompt to the session this schedule continues was not confirmed${typeof result.error === "string" ? `: ${result.error}` : "."}`);
|
|
110
|
+
}
|
|
111
|
+
// A Claude /clear in the same terminal moves the delivery to the new conversation.
|
|
112
|
+
const session = typeof object(result.target).session === "string" ? String(object(result.target).session) : sessionId;
|
|
113
|
+
const close = env.close ?? closeFinishedPane;
|
|
114
|
+
for (const other of live)
|
|
115
|
+
if (other !== item && finishedPane(other.pane))
|
|
116
|
+
await close(String(other.record.server), other.pane).catch(() => undefined);
|
|
117
|
+
return { launch: recordOf(item, session),
|
|
118
|
+
completion: (env.watch ?? watchHerdrRun)(server, { workspaceId, tabId, paneId }, signal, { source, startedAt: Date.now(), sessionId: session, continued: { transcript } }) };
|
|
75
119
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
async function closeFinishedPane(server, pane) {
|
|
123
|
+
const { markPaneClosed } = await import("./worker-close.js");
|
|
124
|
+
await markPaneClosed(server, pane).catch(() => undefined);
|
|
125
|
+
await terminalProvider().closePane(server, String(pane.pane_id));
|
|
80
126
|
}
|
|
81
127
|
/**
|
|
82
128
|
* The outcome of a run a previous Hook process launched and never saw finish
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Schedule } from "./schedule-format.js";
|
|
2
|
+
/**
|
|
3
|
+
* Why a schedule can never fire, so a list or the app says it instead of the
|
|
4
|
+
* schedule sitting silent: a computer the store does not know (no Hook answers
|
|
5
|
+
* to the name), or, on the computer that owns it, a target project with no
|
|
6
|
+
* source directory or one that is gone. `locate` finds a checkout the Hook
|
|
7
|
+
* discovered; only the owning computer can know its own paths.
|
|
8
|
+
*/
|
|
9
|
+
export declare function scheduleProblems(schedule: Schedule, project: string, options: {
|
|
10
|
+
store: string;
|
|
11
|
+
owned: boolean;
|
|
12
|
+
locate?: (project: string) => Promise<string | undefined>;
|
|
13
|
+
}): Promise<string[]>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { getProjectSourcePath } from "../project-config.js";
|
|
4
|
+
import { listMachines } from "../profile-store.js";
|
|
5
|
+
import { getProjectDirs } from "../shared.js";
|
|
6
|
+
import { canonicalComputer } from "./schedule-format.js";
|
|
7
|
+
/**
|
|
8
|
+
* Why a schedule can never fire, so a list or the app says it instead of the
|
|
9
|
+
* schedule sitting silent: a computer the store does not know (no Hook answers
|
|
10
|
+
* to the name), or, on the computer that owns it, a target project with no
|
|
11
|
+
* source directory or one that is gone. `locate` finds a checkout the Hook
|
|
12
|
+
* discovered; only the owning computer can know its own paths.
|
|
13
|
+
*/
|
|
14
|
+
export async function scheduleProblems(schedule, project, options) {
|
|
15
|
+
const problems = [];
|
|
16
|
+
const machines = listMachines(options.store);
|
|
17
|
+
if (!options.owned && machines.ok && !Object.keys(machines.data).some(name => canonicalComputer(name) === canonicalComputer(schedule.computer))) {
|
|
18
|
+
problems.push(`Computer "${schedule.computer}" is not a machine in this store, so no Hook will run this schedule.`);
|
|
19
|
+
}
|
|
20
|
+
if (!options.owned)
|
|
21
|
+
return problems;
|
|
22
|
+
for (const name of schedule.projects ?? [project]) {
|
|
23
|
+
const directory = getProjectDirs(options.store).find(candidate => path.basename(candidate).toLowerCase() === name.toLowerCase());
|
|
24
|
+
if (!directory) {
|
|
25
|
+
problems.push(`Project "${name}" is not in this store.`);
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const target = path.basename(directory);
|
|
29
|
+
const source = getProjectSourcePath(options.store, target) ?? await options.locate?.(target);
|
|
30
|
+
if (!source) {
|
|
31
|
+
if (schedule.projects)
|
|
32
|
+
problems.push(`No source directory for project "${target}" on this computer.`);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (!await stat(source).then(info => info.isDirectory()).catch(() => false))
|
|
36
|
+
problems.push(`Source directory for project "${target}" is unavailable: ${source}`);
|
|
37
|
+
}
|
|
38
|
+
return problems;
|
|
39
|
+
}
|
|
@@ -13,6 +13,7 @@ export declare class Scheduler {
|
|
|
13
13
|
private readonly locateProject;
|
|
14
14
|
private readonly push?;
|
|
15
15
|
private readonly log;
|
|
16
|
+
private readonly revisionWaitMs;
|
|
16
17
|
private serial;
|
|
17
18
|
private ticking;
|
|
18
19
|
private readonly dispatching;
|
|
@@ -32,6 +33,8 @@ export declare class Scheduler {
|
|
|
32
33
|
locateProject?: (project: string) => Promise<string | undefined>;
|
|
33
34
|
push?: SchedulePushSender;
|
|
34
35
|
log?: (message: string) => void;
|
|
36
|
+
/** How long Run now waits for the store to catch up with the revision the app saw (default 30 s). */
|
|
37
|
+
revisionWaitMs?: number;
|
|
35
38
|
});
|
|
36
39
|
private projectDirectories;
|
|
37
40
|
private projectDirectory;
|
|
@@ -48,6 +51,10 @@ export declare class Scheduler {
|
|
|
48
51
|
limit?: number;
|
|
49
52
|
}): Promise<ScheduleRun[]>;
|
|
50
53
|
launchNow(projectName: string, id: string, onlyIfDue?: boolean, expectedUpdatedAt?: string): Promise<ScheduleRun[]>;
|
|
54
|
+
/** An edit made on another computer reaches this one with the store's sync. A Run now right after it waits for the
|
|
55
|
+
* schedule to arrive (or catch up) rather than failing; a copy newer than the app's, or none after the wait, is
|
|
56
|
+
* left to `prepareAndLaunch`'s revision check. */
|
|
57
|
+
private awaitRevision;
|
|
51
58
|
private prepareAndLaunch;
|
|
52
59
|
private updateRun;
|
|
53
60
|
private finishRun;
|
package/dist/bridge/schedules.js
CHANGED
|
@@ -3,9 +3,10 @@ import { stat } from "node:fs/promises";
|
|
|
3
3
|
import { localNames, stableComputerName } from "./computer-names.js";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { BridgeError } from "./protocol.js";
|
|
6
|
+
import { scheduleProblems } from "./schedule-problems.js";
|
|
6
7
|
import { getProjectSourcePath } from "../project-config.js";
|
|
7
8
|
import { getProjectDirs } from "../shared.js";
|
|
8
|
-
import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns,
|
|
9
|
+
import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunches, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
|
|
9
10
|
export * from "./schedule-format.js";
|
|
10
11
|
export * from "./schedule-launch.js";
|
|
11
12
|
export * from "./schedule-watch.js";
|
|
@@ -20,6 +21,7 @@ export class Scheduler {
|
|
|
20
21
|
locateProject;
|
|
21
22
|
push;
|
|
22
23
|
log;
|
|
24
|
+
revisionWaitMs;
|
|
23
25
|
serial = Promise.resolve();
|
|
24
26
|
ticking = false;
|
|
25
27
|
dispatching = new Set();
|
|
@@ -29,6 +31,7 @@ export class Scheduler {
|
|
|
29
31
|
/** When the scheduler last looked for due work; a health read shows it. */
|
|
30
32
|
lastTickAt;
|
|
31
33
|
constructor(options) {
|
|
34
|
+
this.revisionWaitMs = options.revisionWaitMs ?? 30_000;
|
|
32
35
|
this.now = options.now;
|
|
33
36
|
this.store = options.store;
|
|
34
37
|
this.launch = options.launch;
|
|
@@ -84,7 +87,8 @@ export class Scheduler {
|
|
|
84
87
|
const running = matching.some(run => runningStatuses.has(run.status));
|
|
85
88
|
const due = this.owns(schedule, names) ? nextRun(schedule, last) : null;
|
|
86
89
|
const owned = this.owns(schedule, names);
|
|
87
|
-
|
|
90
|
+
const problems = await scheduleProblems(schedule, project, { store: this.store, owned, locate: this.locateProject });
|
|
91
|
+
result.push({ ...schedule, project, lastRuns, owned, ...(problems.length ? { problems } : {}), nextRun: due?.toISOString() ?? null,
|
|
88
92
|
lastRun: last ? { startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}), status: last.status,
|
|
89
93
|
...(last.batchId ? { batchId: last.batchId, scheduleProject: last.scheduleProject } : {}),
|
|
90
94
|
...(last.reason ? { reason: last.reason } : {}),
|
|
@@ -105,12 +109,28 @@ export class Scheduler {
|
|
|
105
109
|
throw new BridgeError(409, "This schedule is already launching.");
|
|
106
110
|
this.dispatching.add(key);
|
|
107
111
|
try {
|
|
112
|
+
if (expectedUpdatedAt !== undefined)
|
|
113
|
+
await this.awaitRevision(projectName, id, expectedUpdatedAt);
|
|
108
114
|
return await this.prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt);
|
|
109
115
|
}
|
|
110
116
|
finally {
|
|
111
117
|
this.dispatching.delete(key);
|
|
112
118
|
}
|
|
113
119
|
}
|
|
120
|
+
/** An edit made on another computer reaches this one with the store's sync. A Run now right after it waits for the
|
|
121
|
+
* schedule to arrive (or catch up) rather than failing; a copy newer than the app's, or none after the wait, is
|
|
122
|
+
* left to `prepareAndLaunch`'s revision check. */
|
|
123
|
+
async awaitRevision(projectName, id, expectedUpdatedAt) {
|
|
124
|
+
const expected = Date.parse(expectedUpdatedAt), deadline = Date.now() + this.revisionWaitMs;
|
|
125
|
+
for (;;) {
|
|
126
|
+
const found = await readScheduleDocument(this.projectDirectory(projectName)).then(file => file.schedules.find(item => item.id === id), () => undefined);
|
|
127
|
+
if (found && Date.parse(found.updatedAt) >= expected)
|
|
128
|
+
return;
|
|
129
|
+
if (Date.now() >= deadline)
|
|
130
|
+
return;
|
|
131
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(1_000, Math.max(10, this.revisionWaitMs / 10))));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
114
134
|
async prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt) {
|
|
115
135
|
const prepared = await this.exclusive(async () => {
|
|
116
136
|
const projectDir = this.projectDirectory(projectName), project = path.basename(projectDir);
|
|
@@ -145,7 +165,7 @@ export class Scheduler {
|
|
|
145
165
|
}
|
|
146
166
|
const batchId = randomUUID(), startedAt = this.now().toISOString();
|
|
147
167
|
const children = targets.map(target => ({ ...target,
|
|
148
|
-
...(schedule.session === "reuse" ? { reuse:
|
|
168
|
+
...(schedule.session === "reuse" ? { reuse: reusableLaunches(matching.filter(run => run.project === target.project)) } : {}), run: {
|
|
149
169
|
id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
|
|
150
170
|
startedAt, status: "launched", launch: { mode: "headless" },
|
|
151
171
|
} }));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { listMoves, readMove } from "./session-move.js";
|
|
2
2
|
import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
|
|
3
3
|
import { ownerInboxView } from "./owner-inbox-view.js";
|
|
4
|
-
import { closeFinishedWorker } from "./worker-close.js";
|
|
4
|
+
import { closeFinishedWorker, closeOwnPane } from "./worker-close.js";
|
|
5
5
|
import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js";
|
|
6
6
|
import { sessionStalls } from "./stalls.js";
|
|
7
7
|
import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
|
|
@@ -29,7 +29,7 @@ import { resolveFilePath } from "./file-resolve.js";
|
|
|
29
29
|
import { storeRoute } from "./memory-store.js";
|
|
30
30
|
import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding, tasksForBranch, completeProjectTask } from "./project-memory.js";
|
|
31
31
|
import { PROJECT_GIT_ROUTE, projectGit } from "./project-git.js";
|
|
32
|
-
import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
|
|
32
|
+
import { liveBackground, markBackground, paneRecord, recordTitle, replyExcerpt } from "./session-activity.js";
|
|
33
33
|
import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
|
|
34
34
|
import { locateProject } from "./locate.js";
|
|
35
35
|
import { gitStatus } from "./git.js";
|
|
@@ -210,6 +210,10 @@ export function workspacesReader(ctx) {
|
|
|
210
210
|
return;
|
|
211
211
|
Object.assign(tab, stall);
|
|
212
212
|
tab.title = title;
|
|
213
|
+
// What a finished turn said last; a row still working (background work) has no last word yet.
|
|
214
|
+
const reply = tab.agentStatus === "working" ? undefined : replyExcerpt(record);
|
|
215
|
+
if (reply)
|
|
216
|
+
tab.lastReply = reply;
|
|
213
217
|
}));
|
|
214
218
|
// Separate bounded queues: a stalled git/model/step read cannot prevent
|
|
215
219
|
// the child tree from reaching the phone. Apply each answer as it arrives.
|
|
@@ -795,6 +799,9 @@ export function createRouteHandler(ctx) {
|
|
|
795
799
|
else if (url.pathname === "/v1/dispatch/close") {
|
|
796
800
|
result = await closeFinishedWorker(data, ctx.handOffs);
|
|
797
801
|
}
|
|
802
|
+
else if (url.pathname === "/v1/dispatch/close-self") {
|
|
803
|
+
result = await closeOwnPane(data);
|
|
804
|
+
}
|
|
798
805
|
else if (url.pathname === "/v1/hand-off") {
|
|
799
806
|
result = await ctx.handOffs.enqueue(data);
|
|
800
807
|
}
|
|
@@ -72,6 +72,16 @@ export declare function liveBackground(record: TurnRecord | undefined, readFinal
|
|
|
72
72
|
* sits on a tab with a live turn.
|
|
73
73
|
*/
|
|
74
74
|
export declare function markBackground(tab: Json, count: number | undefined): void;
|
|
75
|
+
/** How much of a turn's last reply a session row carries. */
|
|
76
|
+
export declare const REPLY_EXCERPT_CHARS = 240;
|
|
77
|
+
/**
|
|
78
|
+
* The ended turn's last reply as one short line for a session row
|
|
79
|
+
* (`lastReply`): what the agent said before it stopped, so a waiting row can
|
|
80
|
+
* say what it waits for. Markdown emphasis, headings and code fences are
|
|
81
|
+
* dropped and whitespace collapsed. Undefined while a turn runs (its prompt
|
|
82
|
+
* is newer than the Stop) or when the Stop carried no reply.
|
|
83
|
+
*/
|
|
84
|
+
export declare function replyExcerpt(record: TurnRecord | undefined): string | undefined;
|
|
75
85
|
/** A tab or workspace label worth showing as a name: not empty, not Herdr's bare numbering, not an id. */
|
|
76
86
|
export declare function meaningfulLabel(value: unknown): string | undefined;
|
|
77
87
|
/** A terminal title without the spinner or status glyphs around it, nor the
|
|
@@ -122,6 +122,31 @@ export function markBackground(tab, count) {
|
|
|
122
122
|
else if (typeof tab.backgroundTasks === "number")
|
|
123
123
|
tab.backgroundTasks = Math.max(tab.backgroundTasks, count);
|
|
124
124
|
}
|
|
125
|
+
/** How much of a turn's last reply a session row carries. */
|
|
126
|
+
export const REPLY_EXCERPT_CHARS = 240;
|
|
127
|
+
/**
|
|
128
|
+
* The ended turn's last reply as one short line for a session row
|
|
129
|
+
* (`lastReply`): what the agent said before it stopped, so a waiting row can
|
|
130
|
+
* say what it waits for. Markdown emphasis, headings and code fences are
|
|
131
|
+
* dropped and whitespace collapsed. Undefined while a turn runs (its prompt
|
|
132
|
+
* is newer than the Stop) or when the Stop carried no reply.
|
|
133
|
+
*/
|
|
134
|
+
export function replyExcerpt(record) {
|
|
135
|
+
if (!record)
|
|
136
|
+
return undefined;
|
|
137
|
+
const phase = turnPhase(record);
|
|
138
|
+
if (phase.phase !== "ended" || !phase.reply)
|
|
139
|
+
return undefined;
|
|
140
|
+
const line = phase.reply
|
|
141
|
+
.replace(/```[\s\S]*?(```|$)/g, " ")
|
|
142
|
+
.replace(/(^|\n)\s*(#{1,6}|>|[-*+]|\d+\.)\s+/g, "$1")
|
|
143
|
+
.replace(/(\*\*|__|\*|`)/g, "")
|
|
144
|
+
.replace(/\s+/g, " ")
|
|
145
|
+
.trim();
|
|
146
|
+
if (!line)
|
|
147
|
+
return undefined;
|
|
148
|
+
return line.length > REPLY_EXCERPT_CHARS ? `${line.slice(0, REPLY_EXCERPT_CHARS - 1).trimEnd()}…` : line;
|
|
149
|
+
}
|
|
125
150
|
/** A tab or workspace label worth showing as a name: not empty, not Herdr's bare numbering, not an id. */
|
|
126
151
|
export function meaningfulLabel(value) {
|
|
127
152
|
if (typeof value !== "string")
|
|
@@ -7,4 +7,9 @@ export declare function markPaneClosed(server: string, pane: Json): Promise<void
|
|
|
7
7
|
/** Called on the worker's computer only after the sender read the done return.
|
|
8
8
|
* Recheck this exact ended turn and skip any new work, background work or inbox. */
|
|
9
9
|
export declare function closeFinishedWorker(input: unknown, queue?: HandOffQueue): Promise<Json>;
|
|
10
|
+
/** An agent closing the pane it runs in, once its work is committed and reported:
|
|
11
|
+
* the sanctioned form of `herdr pane close`, which an agent's auto mode refuses.
|
|
12
|
+
* Only the caller's own pane (named by its terminal variables) is ever closed, and
|
|
13
|
+
* after the reply, so the agent's `phren` call still returns. */
|
|
14
|
+
export declare function closeOwnPane(input: unknown, delayMs?: number): Promise<Json>;
|
|
10
15
|
export {};
|
|
@@ -6,6 +6,7 @@ import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, startingTarg
|
|
|
6
6
|
import { validateTarget, paneChatState } from "./herdr.js";
|
|
7
7
|
import { terminalProvider } from "./terminal.js";
|
|
8
8
|
import { paneTurn, workerStates, workerTurnKey } from "./dispatch-returns.js";
|
|
9
|
+
import { originPaneSchema } from "./dispatch.js";
|
|
9
10
|
const closedTargetSchema = z.union([targetSchema, startingTargetSchema]);
|
|
10
11
|
const file = (target) => path.join(bridgeRoot(), "closed-workers", `${createHash("sha256").update(JSON.stringify([target.server, target.workspace, target.tab, target.pane, target.source, "session" in target ? target.session : target.startingToken])).digest("hex")}.json`);
|
|
11
12
|
export async function markWorkerClosed(target, terminal) {
|
|
@@ -77,3 +78,18 @@ export async function closeFinishedWorker(input, queue) {
|
|
|
77
78
|
}
|
|
78
79
|
return { ok: true, closed: true };
|
|
79
80
|
}
|
|
81
|
+
/** An agent closing the pane it runs in, once its work is committed and reported:
|
|
82
|
+
* the sanctioned form of `herdr pane close`, which an agent's auto mode refuses.
|
|
83
|
+
* Only the caller's own pane (named by its terminal variables) is ever closed, and
|
|
84
|
+
* after the reply, so the agent's `phren` call still returns. */
|
|
85
|
+
export async function closeOwnPane(input, delayMs = 500) {
|
|
86
|
+
const data = z.object({ origin: originPaneSchema }).strict().parse(input);
|
|
87
|
+
const { snapshot, findPane } = await import("./herdr.js");
|
|
88
|
+
const pane = findPane(await snapshot(data.origin.server), data.origin);
|
|
89
|
+
if (!pane)
|
|
90
|
+
return { ok: true, closed: false, reason: "The pane is already gone." };
|
|
91
|
+
await markPaneClosed(data.origin.server, pane);
|
|
92
|
+
const timer = setTimeout(() => { void terminalProvider().closePane(data.origin.server, data.origin.pane).catch(() => undefined); }, delayMs);
|
|
93
|
+
timer.unref();
|
|
94
|
+
return { ok: true, closed: true, pane: data.origin.pane };
|
|
95
|
+
}
|