@phren/cli 0.3.67 → 0.3.69
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-hook-callback.js +11 -2
- package/dist/bridge/agent-hooks.d.ts +11 -1
- package/dist/bridge/agent-hooks.js +259 -40
- package/dist/bridge/changes.d.ts +2 -2
- package/dist/bridge/changes.js +11 -9
- package/dist/bridge/checkpoints.d.ts +24 -0
- package/dist/bridge/checkpoints.js +423 -0
- package/dist/bridge/claude-input-state.d.ts +14 -0
- package/dist/bridge/claude-input-state.js +58 -0
- package/dist/bridge/claude-queue.js +5 -2
- package/dist/bridge/claude-suggestion.d.ts +3 -0
- package/dist/bridge/claude-suggestion.js +10 -0
- package/dist/bridge/codex-threads.d.ts +7 -1
- package/dist/bridge/codex-threads.js +185 -56
- package/dist/bridge/conversation-search.d.ts +20 -0
- package/dist/bridge/conversation-search.js +928 -0
- package/dist/bridge/git-watch.d.ts +46 -0
- package/dist/bridge/git-watch.js +351 -0
- package/dist/bridge/git-worktree-remove.d.ts +44 -0
- package/dist/bridge/git-worktree-remove.js +140 -0
- package/dist/bridge/git-worktrees.d.ts +14 -0
- package/dist/bridge/git-worktrees.js +7 -3
- package/dist/bridge/git-write-policy.js +1 -1
- package/dist/bridge/gitboy-webhooks.d.ts +3 -1
- package/dist/bridge/gitboy-webhooks.js +26 -2
- package/dist/bridge/herdr.d.ts +6 -1
- package/dist/bridge/herdr.js +56 -10
- package/dist/bridge/hook-fast.js +13 -1
- package/dist/bridge/input-classification.d.ts +33 -0
- package/dist/bridge/input-classification.js +84 -0
- package/dist/bridge/pane-status.d.ts +3 -3
- package/dist/bridge/pane-status.js +16 -8
- package/dist/bridge/prompt-deliveries.d.ts +30 -4
- package/dist/bridge/prompt-deliveries.js +365 -13
- package/dist/bridge/prompt-identity.d.ts +8 -0
- package/dist/bridge/prompt-identity.js +15 -0
- package/dist/bridge/request-origin.js +2 -1
- package/dist/bridge/schedule-events.d.ts +17 -0
- package/dist/bridge/schedule-events.js +53 -0
- package/dist/bridge/schedule-format.d.ts +22 -2
- package/dist/bridge/schedule-format.js +40 -5
- package/dist/bridge/schedule-update.js +2 -1
- package/dist/bridge/schedule-watch.js +15 -5
- package/dist/bridge/schedules.d.ts +9 -0
- package/dist/bridge/schedules.js +120 -7
- package/dist/bridge/server-pane-routes.d.ts +7 -8
- package/dist/bridge/server-pane-routes.js +186 -82
- package/dist/bridge/server-routes.d.ts +26 -2
- package/dist/bridge/server-routes.js +180 -56
- package/dist/bridge/server-stream.js +66 -15
- package/dist/bridge/server.js +25 -7
- package/dist/bridge/session-activity.d.ts +49 -4
- package/dist/bridge/session-activity.js +47 -0
- package/dist/bridge/session-evidence.d.ts +18 -0
- package/dist/bridge/session-evidence.js +72 -0
- package/dist/bridge/session-seen.d.ts +23 -0
- package/dist/bridge/session-seen.js +69 -0
- package/dist/bridge/tab-activity.d.ts +26 -1
- package/dist/bridge/tab-activity.js +64 -9
- package/dist/bridge/terminal-resolve.d.ts +20 -0
- package/dist/bridge/terminal-resolve.js +145 -0
- package/dist/bridge/terminal-tmux.d.ts +8 -3
- package/dist/bridge/terminal-tmux.js +59 -7
- package/dist/bridge/transcript-claude.d.ts +12 -2
- package/dist/bridge/transcript-claude.js +91 -13
- package/dist/bridge/transcript-index.d.ts +4 -2
- package/dist/bridge/transcript-index.js +6 -5
- package/dist/bridge/transcript-preview.d.ts +16 -1
- package/dist/bridge/transcript-preview.js +171 -27
- package/dist/bridge/transcripts.d.ts +41 -1
- package/dist/bridge/transcripts.js +181 -23
- package/dist/bridge/turn-queue-pane.d.ts +6 -0
- package/dist/bridge/turn-queue-pane.js +30 -0
- package/dist/bridge/turn-queue.d.ts +86 -0
- package/dist/bridge/turn-queue.js +280 -0
- package/dist/bridge/turn-records.d.ts +18 -0
- package/dist/bridge/turn-records.js +77 -5
- package/dist/bridge-hook.mjs +7074 -3173
- package/dist/cli/config-shared.js +2 -1
- package/dist/cli/schedules.js +6 -1
- package/dist/content/secrets.js +1 -1
- package/dist/modules/registry.js +12 -11
- package/package.json +1 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
1
2
|
import type { SchedulePush, SchedulePushResult } from "./push.js";
|
|
2
3
|
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
3
|
-
* the five
|
|
4
|
-
export declare const SCHEDULE_EVERY: readonly ["interval", "daily", "weekly", "once", "cron"];
|
|
4
|
+
* the five time forms evaluated in local time and event triggers, and the run history file. */
|
|
5
|
+
export declare const SCHEDULE_EVERY: readonly ["interval", "daily", "weekly", "once", "cron", "event"];
|
|
5
6
|
export declare const SCHEDULE_HARNESSES: readonly ["claude", "codex", "opencode", "copilot"];
|
|
6
7
|
export declare const SCHEDULE_NOTIFY: readonly ["start", "finish", "failure"];
|
|
7
8
|
export declare const WEEKDAYS: readonly ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
@@ -39,6 +40,12 @@ export interface Schedule {
|
|
|
39
40
|
interval?: string;
|
|
40
41
|
once?: string;
|
|
41
42
|
cron?: string;
|
|
43
|
+
event?: string;
|
|
44
|
+
filters?: {
|
|
45
|
+
path: string;
|
|
46
|
+
equals: string | number | boolean | null;
|
|
47
|
+
}[];
|
|
48
|
+
coalesceSeconds?: number;
|
|
42
49
|
prompt: string;
|
|
43
50
|
createdAt: string;
|
|
44
51
|
updatedAt: string;
|
|
@@ -65,6 +72,13 @@ export interface ScheduleRun {
|
|
|
65
72
|
finishedAt?: string;
|
|
66
73
|
status: ScheduleRunStatus;
|
|
67
74
|
reason?: string;
|
|
75
|
+
trigger?: {
|
|
76
|
+
event: string;
|
|
77
|
+
deliveryId: string;
|
|
78
|
+
};
|
|
79
|
+
outcome?: "accepted" | "ignored" | "duplicate" | "coalesced";
|
|
80
|
+
/** Only referenced scalar fields, capped and credential-redacted. */
|
|
81
|
+
fields?: Record<string, string>;
|
|
68
82
|
blockedStartupPrompt?: string;
|
|
69
83
|
blockNotified?: boolean;
|
|
70
84
|
notified?: boolean;
|
|
@@ -112,6 +126,12 @@ interface ScheduleDocument {
|
|
|
112
126
|
}
|
|
113
127
|
export declare const runningStatuses: Set<"blocked" | "failed" | "finished" | "launched" | "needs-you" | "running" | "skipped">;
|
|
114
128
|
export declare function intervalMilliseconds(value: string): number;
|
|
129
|
+
export declare const eventNameSchema: z.ZodString;
|
|
130
|
+
export declare const payloadPathSchema: z.ZodString;
|
|
131
|
+
export declare const eventFiltersSchema: z.ZodArray<z.ZodObject<{
|
|
132
|
+
path: z.ZodString;
|
|
133
|
+
equals: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>;
|
|
134
|
+
}, z.core.$strict>>;
|
|
115
135
|
export declare function parseSchedule(value: unknown): Schedule;
|
|
116
136
|
export declare function readScheduleDocument(projectDir: string): Promise<ScheduleDocument>;
|
|
117
137
|
/** Synchronous I/O for writers sharing a lock with synchronous store routes. */
|
|
@@ -9,8 +9,8 @@ import { isValidProjectName } from "../utils-paths.js";
|
|
|
9
9
|
import { tryFileLock } from "../governance/locks.js";
|
|
10
10
|
import { isAccountSlug } from "./claude-accounts.js";
|
|
11
11
|
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
12
|
-
* the five
|
|
13
|
-
export const SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
12
|
+
* the five time forms evaluated in local time and event triggers, and the run history file. */
|
|
13
|
+
export const SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron", "event"];
|
|
14
14
|
export const SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
|
|
15
15
|
export const SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
16
16
|
export const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
@@ -48,6 +48,12 @@ export function intervalMilliseconds(value) {
|
|
|
48
48
|
throw new Error("Schedule interval is too large.");
|
|
49
49
|
return milliseconds;
|
|
50
50
|
}
|
|
51
|
+
export const eventNameSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/);
|
|
52
|
+
export const payloadPathSchema = z.string().max(200).regex(/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*|\.\d+)*$/)
|
|
53
|
+
.refine(value => !value.split(".").some(part => ["__proto__", "prototype", "constructor"].includes(part)));
|
|
54
|
+
export const eventFiltersSchema = z.array(z.object({ path: payloadPathSchema,
|
|
55
|
+
equals: z.union([z.string().max(1024), z.number().finite(), z.boolean(), z.null()]),
|
|
56
|
+
}).strict()).max(16);
|
|
51
57
|
export function parseSchedule(value) {
|
|
52
58
|
const raw = object(value);
|
|
53
59
|
const every = z.enum(SCHEDULE_EVERY).parse(raw.every);
|
|
@@ -92,6 +98,13 @@ export function parseSchedule(value) {
|
|
|
92
98
|
schedule.cron = singleLine(200).parse(raw.cron);
|
|
93
99
|
parseCron(schedule.cron);
|
|
94
100
|
}
|
|
101
|
+
if (every === "event") {
|
|
102
|
+
schedule.event = eventNameSchema.parse(raw.event);
|
|
103
|
+
if (raw.filters !== undefined)
|
|
104
|
+
schedule.filters = eventFiltersSchema.parse(raw.filters);
|
|
105
|
+
if (raw.coalesceSeconds !== undefined)
|
|
106
|
+
schedule.coalesceSeconds = z.number().int().min(0).max(86400).parse(raw.coalesceSeconds);
|
|
107
|
+
}
|
|
95
108
|
return schedule;
|
|
96
109
|
}
|
|
97
110
|
export async function readScheduleDocument(projectDir) {
|
|
@@ -121,13 +134,15 @@ export function readScheduleDocumentSync(projectDir) {
|
|
|
121
134
|
}
|
|
122
135
|
function parseScheduleDocument(text) {
|
|
123
136
|
const document = object(yaml.load(text, { schema: yaml.CORE_SCHEMA }));
|
|
124
|
-
if (document.version !== 1)
|
|
125
|
-
throw new Error("schedules.yaml must have version: 1.");
|
|
137
|
+
if (document.version !== 1 && document.version !== 2)
|
|
138
|
+
throw new Error("schedules.yaml must have version: 1 or 2.");
|
|
126
139
|
if (!Array.isArray(document.schedules))
|
|
127
140
|
throw new Error("schedules.yaml must contain a schedules list.");
|
|
128
141
|
if (document.schedules.length > MAX_SCHEDULES)
|
|
129
142
|
throw new Error(`A project can have at most ${MAX_SCHEDULES} schedules.`);
|
|
130
143
|
const schedules = document.schedules.map(parseSchedule);
|
|
144
|
+
if (document.version === 1 && schedules.some(item => item.every === "event"))
|
|
145
|
+
throw new Error("Event schedules require version: 2.");
|
|
131
146
|
if (new Set(schedules.map(item => item.id)).size !== schedules.length)
|
|
132
147
|
throw new Error("Schedule IDs must be unique within a project.");
|
|
133
148
|
return { document, schedules };
|
|
@@ -190,7 +205,7 @@ function serializeScheduleDocument(schedules, original) {
|
|
|
190
205
|
if (schedules.length > MAX_SCHEDULES)
|
|
191
206
|
throw new Error(`A project can have at most ${MAX_SCHEDULES} schedules.`);
|
|
192
207
|
schedules.forEach(parseSchedule);
|
|
193
|
-
return yaml.dump({ ...original, version: 1, schedules }, { lineWidth: 1000, noRefs: true, sortKeys: false });
|
|
208
|
+
return yaml.dump({ ...original, version: schedules.some(item => item.every === "event") || original.version === 2 ? 2 : 1, schedules }, { lineWidth: 1000, noRefs: true, sortKeys: false });
|
|
194
209
|
}
|
|
195
210
|
export function canonicalComputer(value) {
|
|
196
211
|
const normalized = value.trim().toLowerCase();
|
|
@@ -303,6 +318,8 @@ function localDate(value) {
|
|
|
303
318
|
&& date.getHours() === parts[3] && date.getMinutes() === parts[4] && date.getSeconds() === parts[5] ? date : null;
|
|
304
319
|
}
|
|
305
320
|
export function nextRun(schedule, lastRun) {
|
|
321
|
+
if (schedule.every === "event")
|
|
322
|
+
return null;
|
|
306
323
|
if (schedule.every === "once")
|
|
307
324
|
return lastRun ? null : localDate(schedule.once);
|
|
308
325
|
const after = new Date(lastRun?.startedAt ?? schedule.createdAt);
|
|
@@ -375,7 +392,25 @@ export async function readScheduleRuns(file) {
|
|
|
375
392
|
export async function writeScheduleRuns(file, runs) {
|
|
376
393
|
// Open children still block their owner. Keep entire retained batches so
|
|
377
394
|
// trimming cannot hide a sibling's failure from the aggregate status.
|
|
395
|
+
const counts = new Map();
|
|
396
|
+
const retained = new Set(runs.filter(run => run.outcome && run.outcome !== "accepted").reverse().filter(run => {
|
|
397
|
+
const key = `${run.scheduleProject ?? run.project}/${run.scheduleId}`, count = (counts.get(key) ?? 0) + 1;
|
|
398
|
+
counts.set(key, count);
|
|
399
|
+
return count <= 50;
|
|
400
|
+
}).map(run => run.id));
|
|
401
|
+
runs = runs.filter(run => !run.outcome || run.outcome === "accepted" || retained.has(run.id));
|
|
378
402
|
const recent = new Set(runs.slice(-MAX_RUNS).map(run => run.id));
|
|
403
|
+
// History noise must not erase an event schedule's coalescing watermark.
|
|
404
|
+
// A window is at most 24 hours; retain the latest accepted batch per owner
|
|
405
|
+
// within that horizon, measured against the newest recorded event/run.
|
|
406
|
+
const newest = runs.reduce((time, run) => Math.max(time, Date.parse(run.startedAt) || 0), 0);
|
|
407
|
+
const accepted = new Map();
|
|
408
|
+
for (const run of runs)
|
|
409
|
+
if (run.outcome === "accepted" && Date.parse(run.startedAt) >= newest - 86400_000) {
|
|
410
|
+
accepted.set(`${run.scheduleProject ?? run.project}/${run.scheduleId}`, run);
|
|
411
|
+
}
|
|
412
|
+
for (const run of accepted.values())
|
|
413
|
+
recent.add(run.id);
|
|
379
414
|
const batches = new Set(runs.filter(run => recent.has(run.id) || runningStatuses.has(run.status))
|
|
380
415
|
.map(run => run.batchId).filter((id) => Boolean(id)));
|
|
381
416
|
const kept = runs.filter(run => recent.has(run.id) || runningStatuses.has(run.status) || (run.batchId && batches.has(run.batchId)));
|
|
@@ -2,7 +2,7 @@ import path from "node:path";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { getProjectDirs } from "../shared.js";
|
|
4
4
|
import { BridgeError } from "./protocol.js";
|
|
5
|
-
import { SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_NOTIFY, SCHEDULE_SESSIONS, WEEKDAYS, parseSchedule, readScheduleDocumentSync, withScheduleLock, writeScheduleDocumentSync, } from "./schedule-format.js";
|
|
5
|
+
import { SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_NOTIFY, SCHEDULE_SESSIONS, WEEKDAYS, eventNameSchema, eventFiltersSchema, parseSchedule, readScheduleDocumentSync, withScheduleLock, writeScheduleDocumentSync, } from "./schedule-format.js";
|
|
6
6
|
const optional = (schema) => schema.nullable().optional();
|
|
7
7
|
const updateSchema = z.object({
|
|
8
8
|
project: z.string().min(1).max(200),
|
|
@@ -17,6 +17,7 @@ const updateSchema = z.object({
|
|
|
17
17
|
session: optional(z.enum(SCHEDULE_SESSIONS)), at: optional(z.string()),
|
|
18
18
|
days: optional(z.array(z.enum(WEEKDAYS))), interval: optional(z.string()),
|
|
19
19
|
once: optional(z.string()), cron: optional(z.string()),
|
|
20
|
+
event: optional(eventNameSchema), filters: optional(eventFiltersSchema), coalesceSeconds: optional(z.number().int().min(0).max(86400)),
|
|
20
21
|
}).strict(),
|
|
21
22
|
}).strict();
|
|
22
23
|
/** Merge only client edits into a fresh document under the CLI writers' lock. */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { open, stat } from "node:fs/promises";
|
|
2
2
|
import { findPane, paneIdentity, snapshot } from "./herdr.js";
|
|
3
|
+
import { classifyClaudeInput } from "./input-classification.js";
|
|
3
4
|
import { readPaneText } from "./pane-text.js";
|
|
4
5
|
import { object, objects } from "./protocol.js";
|
|
5
6
|
import { transcriptPath } from "./transcripts.js";
|
|
@@ -217,12 +218,18 @@ export function finalTurnFromLines(lines, source) {
|
|
|
217
218
|
tail.awaited.clear();
|
|
218
219
|
}
|
|
219
220
|
}
|
|
221
|
+
if (source === "claude" && (raw.type === "assistant" || (raw.type === "system" && raw.subtype === "turn_duration"))
|
|
222
|
+
&& classifyClaudeInput({ text: "execution", origin: raw.origin, isSidechain: raw.isSidechain }).category !== "owner")
|
|
223
|
+
continue;
|
|
220
224
|
if (turnInterrupted(raw, source)) {
|
|
221
225
|
interrupted = true;
|
|
222
226
|
completed = false;
|
|
223
227
|
continue;
|
|
224
228
|
}
|
|
225
|
-
|
|
229
|
+
// Only the owner's input opens a new turn. A task notification, a teammate
|
|
230
|
+
// message or a harness envelope in the same turn never clears the reply or
|
|
231
|
+
// the completion identity.
|
|
232
|
+
const userTurn = source === "claude" ? ownerPrompt(raw)
|
|
226
233
|
: source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user"
|
|
227
234
|
: source === "copilot" ? raw.type === "user.message"
|
|
228
235
|
: raw.type === "user/message";
|
|
@@ -265,14 +272,17 @@ export function finalTurnFromLines(lines, source) {
|
|
|
265
272
|
...(completed && tail.endless.size ? { endless: tail.endless.size } : {}) };
|
|
266
273
|
}
|
|
267
274
|
/** A prompt the owner (or a dispatcher) typed, not a task's notification or
|
|
268
|
-
* a teammate's message waking the session.
|
|
275
|
+
* a teammate's message waking the session. The shared classifier is the one
|
|
276
|
+
* answer: provenance first, then a leading harness envelope. */
|
|
269
277
|
function ownerPrompt(raw) {
|
|
270
278
|
// Claude files "[Request interrupted by user]" as a user row too: that is a stop, not the owner moving on.
|
|
271
|
-
|
|
279
|
+
if (raw.type !== "user" || raw.isMeta || turnInterrupted(raw, "claude"))
|
|
280
|
+
return false;
|
|
281
|
+
const content = claudeUserText(raw);
|
|
272
282
|
if (content === undefined)
|
|
273
283
|
return false;
|
|
274
|
-
|
|
275
|
-
|
|
284
|
+
return classifyClaudeInput({ text: content, hasImage: objects(object(raw.message).content).some(block => block.type === "image"), origin: raw.origin, commandMode: raw.commandMode,
|
|
285
|
+
isMeta: raw.isMeta, isSidechain: raw.isSidechain, isCompactSummary: raw.isCompactSummary }).category === "owner";
|
|
276
286
|
}
|
|
277
287
|
/** A Claude user row's text when it is a message someone typed: a string, or blocks of text and images (a
|
|
278
288
|
* prompt with a pasted screenshot). A tool's result, which Claude also files as a user row, is not one. */
|
|
@@ -16,6 +16,7 @@ export declare class Scheduler {
|
|
|
16
16
|
private readonly revisionWaitMs;
|
|
17
17
|
private serial;
|
|
18
18
|
private ticking;
|
|
19
|
+
private eventSerial;
|
|
19
20
|
private readonly dispatching;
|
|
20
21
|
/** Runs this process launched; any other open run was left by an earlier Hook. */
|
|
21
22
|
private readonly own;
|
|
@@ -50,12 +51,20 @@ export declare class Scheduler {
|
|
|
50
51
|
id?: string;
|
|
51
52
|
limit?: number;
|
|
52
53
|
}): Promise<ScheduleRun[]>;
|
|
54
|
+
/** Delivery IDs are Hook-wide, independent of the bounded run history. */
|
|
55
|
+
ingestEvent(body: unknown): Promise<{
|
|
56
|
+
ok: true;
|
|
57
|
+
duplicate: boolean;
|
|
58
|
+
runs: ScheduleRun[];
|
|
59
|
+
}>;
|
|
53
60
|
launchNow(projectName: string, id: string, onlyIfDue?: boolean, expectedUpdatedAt?: string): Promise<ScheduleRun[]>;
|
|
54
61
|
/** An edit made on another computer reaches this one with the store's sync. A Run now right after it waits for the
|
|
55
62
|
* schedule to arrive (or catch up) rather than failing; a copy newer than the app's, or none after the wait, is
|
|
56
63
|
* left to `prepareAndLaunch`'s revision check. */
|
|
57
64
|
private awaitRevision;
|
|
58
65
|
private prepareAndLaunch;
|
|
66
|
+
private prepareRun;
|
|
67
|
+
private launchPrepared;
|
|
59
68
|
private updateRun;
|
|
60
69
|
private finishRun;
|
|
61
70
|
private recordBlockedStartup;
|
package/dist/bridge/schedules.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { localNames, stableComputerName } from "./computer-names.js";
|
|
4
4
|
import path from "node:path";
|
|
5
|
-
import {
|
|
5
|
+
import { parseScheduleEvent, scheduleEventPrompt } from "./schedule-events.js";
|
|
6
|
+
import { atomicInPrivateDir, BridgeError } from "./protocol.js";
|
|
6
7
|
import { scheduleProblems } from "./schedule-problems.js";
|
|
8
|
+
import { redactSecretsForLog } from "../content/secrets.js";
|
|
7
9
|
import { getProjectSourcePath } from "../project-config.js";
|
|
8
10
|
import { getProjectDirs } from "../shared.js";
|
|
9
11
|
import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunches, runningStatuses, scheduleNotifications, scheduleSessionRoute, readScheduleDocumentSync, withScheduleLock, writeScheduleDocumentSync, writeScheduleRuns, } from "./schedule-format.js";
|
|
@@ -24,6 +26,7 @@ export class Scheduler {
|
|
|
24
26
|
revisionWaitMs;
|
|
25
27
|
serial = Promise.resolve();
|
|
26
28
|
ticking = false;
|
|
29
|
+
eventSerial = Promise.resolve();
|
|
27
30
|
dispatching = new Set();
|
|
28
31
|
/** Runs this process launched; any other open run was left by an earlier Hook. */
|
|
29
32
|
own = new Set();
|
|
@@ -92,6 +95,7 @@ export class Scheduler {
|
|
|
92
95
|
lastRun: last ? { startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}), status: last.status,
|
|
93
96
|
...(last.batchId ? { batchId: last.batchId, scheduleProject: last.scheduleProject } : {}),
|
|
94
97
|
...(last.reason ? { reason: last.reason } : {}),
|
|
98
|
+
...(last.trigger ? { trigger: last.trigger, outcome: last.outcome, fields: last.fields } : {}),
|
|
95
99
|
...(last.blockedStartupPrompt ? { blockedStartupPrompt: last.blockedStartupPrompt } : {}),
|
|
96
100
|
...(last.blockNotified !== undefined ? { blockNotified: last.blockNotified } : {}), launch: last.launch } : null, running });
|
|
97
101
|
}
|
|
@@ -103,6 +107,85 @@ export class Scheduler {
|
|
|
103
107
|
return (await readScheduleRuns(this.runsFile)).filter(run => (!filters.project || (run.scheduleProject ?? run.project).toLowerCase() === filters.project.toLowerCase())
|
|
104
108
|
&& (!filters.id || run.scheduleId === filters.id)).slice(-limit).reverse();
|
|
105
109
|
}
|
|
110
|
+
/** Delivery IDs are Hook-wide, independent of the bounded run history. */
|
|
111
|
+
ingestEvent(body) {
|
|
112
|
+
const receivedAt = this.now().toISOString(), event = parseScheduleEvent(body);
|
|
113
|
+
const work = this.eventSerial.catch(() => undefined).then(async () => {
|
|
114
|
+
const duplicate = await this.exclusive(async () => {
|
|
115
|
+
const file = `${this.runsFile}.deliveries.json`;
|
|
116
|
+
let ids;
|
|
117
|
+
try {
|
|
118
|
+
const value = JSON.parse(await readFile(file, "utf8"));
|
|
119
|
+
if (!Array.isArray(value) || !value.every(id => typeof id === "string"))
|
|
120
|
+
throw new Error("Invalid schedule delivery ledger.");
|
|
121
|
+
ids = value;
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error.code !== "ENOENT")
|
|
125
|
+
throw error;
|
|
126
|
+
ids = [];
|
|
127
|
+
}
|
|
128
|
+
const key = createHash("sha256").update(event.deliveryId).digest("hex");
|
|
129
|
+
if (ids.includes(key))
|
|
130
|
+
return true;
|
|
131
|
+
await atomicInPrivateDir(file, JSON.stringify([...ids, key].slice(-1000)) + "\n");
|
|
132
|
+
return false;
|
|
133
|
+
});
|
|
134
|
+
const runs = [], launches = [];
|
|
135
|
+
const failures = [];
|
|
136
|
+
for (const directory of this.projectDirectories()) {
|
|
137
|
+
let schedules;
|
|
138
|
+
try {
|
|
139
|
+
schedules = (await readScheduleDocument(directory)).schedules;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
for (const schedule of schedules) {
|
|
145
|
+
if (schedule.every !== "event" || schedule.event !== event.event || !this.owns(schedule))
|
|
146
|
+
continue;
|
|
147
|
+
const project = path.basename(directory), received = { ...event, duplicate, receivedAt };
|
|
148
|
+
let prepared;
|
|
149
|
+
try {
|
|
150
|
+
prepared = await this.prepareRun(project, schedule.id, false, undefined, received);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
// A definition with unavailable targets must not consume the event
|
|
154
|
+
// for its healthy siblings. Persist its own failed attempt first.
|
|
155
|
+
const failed = { id: randomUUID(), scheduleId: schedule.id, project, scheduleProject: project,
|
|
156
|
+
startedAt: receivedAt, finishedAt: this.now().toISOString(), status: "failed", outcome: "accepted",
|
|
157
|
+
trigger: { event: event.event, deliveryId: event.deliveryId }, launch: { mode: "headless" },
|
|
158
|
+
fields: scheduleEventPrompt(schedule, event).fields,
|
|
159
|
+
reason: redactSecretsForLog(error instanceof Error ? error.message : "Schedule preparation failed.").slice(0, 1000) };
|
|
160
|
+
await this.exclusive(async () => writeScheduleRuns(this.runsFile, [...await readScheduleRuns(this.runsFile), failed]));
|
|
161
|
+
runs.push(failed);
|
|
162
|
+
failures.push({ run: failed, schedule });
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (!prepared)
|
|
166
|
+
continue;
|
|
167
|
+
runs.push(...prepared.decisions ?? prepared.children.map(child => child.run));
|
|
168
|
+
if (prepared.children.length)
|
|
169
|
+
launches.push(prepared);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return { response: { ok: true, duplicate, runs }, launches, failures };
|
|
173
|
+
});
|
|
174
|
+
// Serialize only ledger updates and durable reservations. External worker
|
|
175
|
+
// startup is independent of later deliveries and their acknowledgements.
|
|
176
|
+
this.eventSerial = work.then(() => undefined, () => undefined);
|
|
177
|
+
return work.then(({ response, launches, failures }) => {
|
|
178
|
+
for (const { run, schedule } of failures)
|
|
179
|
+
void this.notifyRun(run, schedule, "scheduleFailed").catch(() => {
|
|
180
|
+
this.log(`[schedule] Could not record preparation failure notification for ${run.id}.`);
|
|
181
|
+
});
|
|
182
|
+
for (const prepared of launches)
|
|
183
|
+
void this.launchPrepared(prepared).catch(() => {
|
|
184
|
+
this.log(`[schedule] Could not persist event launch results for ${prepared.schedule.id}.`);
|
|
185
|
+
});
|
|
186
|
+
return response;
|
|
187
|
+
});
|
|
188
|
+
}
|
|
106
189
|
async launchNow(projectName, id, onlyIfDue = false, expectedUpdatedAt) {
|
|
107
190
|
const key = `${projectName.toLowerCase()}/${id}`;
|
|
108
191
|
if (this.dispatching.has(key))
|
|
@@ -132,11 +215,16 @@ export class Scheduler {
|
|
|
132
215
|
}
|
|
133
216
|
}
|
|
134
217
|
async prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt) {
|
|
135
|
-
|
|
218
|
+
return this.launchPrepared(await this.prepareRun(projectName, id, onlyIfDue, expectedUpdatedAt));
|
|
219
|
+
}
|
|
220
|
+
async prepareRun(projectName, id, onlyIfDue, expectedUpdatedAt, event) {
|
|
221
|
+
return this.exclusive(async () => {
|
|
136
222
|
const projectDir = this.projectDirectory(projectName), project = path.basename(projectDir);
|
|
137
|
-
const file = await readScheduleDocument(projectDir)
|
|
138
|
-
|
|
223
|
+
const file = await readScheduleDocument(projectDir);
|
|
224
|
+
const stored = file.schedules.find(item => item.id === id);
|
|
225
|
+
if (!stored)
|
|
139
226
|
throw new BridgeError(404, `Schedule "${id}" was not found in ${project}.`);
|
|
227
|
+
let schedule = stored;
|
|
140
228
|
if (expectedUpdatedAt !== undefined && expectedUpdatedAt !== schedule.updatedAt) {
|
|
141
229
|
throw new BridgeError(409, "This computer has a different schedule revision. Wait for store sync to finish, refresh the schedule, and try Run now again.");
|
|
142
230
|
}
|
|
@@ -144,6 +232,26 @@ export class Scheduler {
|
|
|
144
232
|
throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
145
233
|
const runs = await readScheduleRuns(this.runsFile);
|
|
146
234
|
const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === id);
|
|
235
|
+
let eventFields;
|
|
236
|
+
if (event) {
|
|
237
|
+
// Recheck the current definition after ingestion's snapshot.
|
|
238
|
+
if (schedule.every !== "event" || schedule.event !== event.event)
|
|
239
|
+
return undefined;
|
|
240
|
+
const rendered = scheduleEventPrompt(schedule, event);
|
|
241
|
+
eventFields = rendered.fields;
|
|
242
|
+
const lastAccepted = matching.filter(run => run.outcome === "accepted").at(-1);
|
|
243
|
+
const outcome = event.duplicate ? "duplicate" : !schedule.enabled || !rendered.matches ? "ignored"
|
|
244
|
+
: lastAccepted && Date.parse(event.receivedAt) - Date.parse(lastAccepted.startedAt) < (schedule.coalesceSeconds ?? 0) * 1000 ? "coalesced"
|
|
245
|
+
: matching.some(run => runningStatuses.has(run.status)) ? "ignored" : "accepted";
|
|
246
|
+
if (outcome !== "accepted") {
|
|
247
|
+
const run = { id: randomUUID(), scheduleId: id, project, scheduleProject: project,
|
|
248
|
+
startedAt: event.receivedAt, finishedAt: event.receivedAt, status: "skipped", launch: { mode: "headless" },
|
|
249
|
+
trigger: { event: event.event, deliveryId: event.deliveryId }, outcome, fields: eventFields };
|
|
250
|
+
await writeScheduleRuns(this.runsFile, [...runs, run]);
|
|
251
|
+
return { schedule, children: [], decisions: [run] };
|
|
252
|
+
}
|
|
253
|
+
schedule = { ...schedule, prompt: rendered.prompt };
|
|
254
|
+
}
|
|
147
255
|
if (matching.some(run => runningStatuses.has(run.status))) {
|
|
148
256
|
throw new BridgeError(409, `Schedule "${schedule.name}" is already running.`);
|
|
149
257
|
}
|
|
@@ -163,11 +271,12 @@ export class Scheduler {
|
|
|
163
271
|
}
|
|
164
272
|
targets.push({ project: target, projectDir: targetDir, cwd });
|
|
165
273
|
}
|
|
166
|
-
const batchId = randomUUID(), startedAt = this.now().toISOString();
|
|
274
|
+
const batchId = randomUUID(), startedAt = event?.receivedAt ?? this.now().toISOString();
|
|
167
275
|
const children = targets.map(target => ({ ...target,
|
|
168
276
|
...(schedule.session === "reuse" ? { reuse: reusableLaunches(matching.filter(run => run.project === target.project)) } : {}), run: {
|
|
169
277
|
id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
|
|
170
278
|
startedAt, status: "launched", launch: { mode: "headless" },
|
|
279
|
+
...(event ? { trigger: { event: event.event, deliveryId: event.deliveryId }, outcome: "accepted", fields: eventFields } : {}),
|
|
171
280
|
} }));
|
|
172
281
|
// One atomic replacement reserves every target before any external launch.
|
|
173
282
|
await writeScheduleRuns(this.runsFile, [...runs, ...children.map(child => child.run)]);
|
|
@@ -198,8 +307,12 @@ export class Scheduler {
|
|
|
198
307
|
}
|
|
199
308
|
return { schedule, children };
|
|
200
309
|
});
|
|
310
|
+
}
|
|
311
|
+
async launchPrepared(prepared) {
|
|
201
312
|
if (!prepared)
|
|
202
313
|
return [];
|
|
314
|
+
if (prepared.decisions)
|
|
315
|
+
return prepared.decisions;
|
|
203
316
|
// Independent attempts: one target's startup failure never cancels siblings.
|
|
204
317
|
return Promise.all(prepared.children.map(async (child) => {
|
|
205
318
|
try {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type TurnQueue } from "./turn-queue.js";
|
|
1
2
|
import type { IncomingHttpHeaders, ServerResponse } from "node:http";
|
|
2
3
|
import { type GitWriteDiagnostics } from "./git-write-policy.js";
|
|
3
4
|
import type { AgentHooks } from "./agent-hooks.js";
|
|
@@ -13,6 +14,7 @@ import { type SideQuestions } from "./side-questions.js";
|
|
|
13
14
|
* secrets, uploads, diffs, git, approvals and questions. A starting pane (no
|
|
14
15
|
* conversation yet) takes keys, a secret or a first prompt. */
|
|
15
16
|
export interface PaneRouteContext {
|
|
17
|
+
turnQueue?: TurnQueue;
|
|
16
18
|
gitWrites?: GitWriteDiagnostics;
|
|
17
19
|
agentHooks: AgentHooks;
|
|
18
20
|
modelSwitcher: ModelSwitcher;
|
|
@@ -35,7 +37,7 @@ export declare function gitRepository(pane: Json, target: Target, child: unknown
|
|
|
35
37
|
export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
|
|
36
38
|
/** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
|
|
37
39
|
* pending there and no dialog on its screen. */
|
|
38
|
-
export declare function promptGuards(agentHooks: Pick<AgentHooks, "approval" | "terminalPrompt" | "servedQuestion">, target: Target): PromptGuards
|
|
40
|
+
export declare function promptGuards(agentHooks: Pick<AgentHooks, "approval" | "terminalPrompt" | "servedQuestion">, target: Target): Required<PromptGuards>;
|
|
39
41
|
/** A Claude pane showing a subagent's view (its empty input reads "Message
|
|
40
42
|
* @<agent>…") takes typed text for that subagent, so a phone message never
|
|
41
43
|
* reached the turn and failed when it ended (owner, 2026-10-21). Escape returns
|
|
@@ -48,12 +50,9 @@ export declare function leaveClaudeSubagentView(agentHooks: Pick<AgentHooks, "pa
|
|
|
48
50
|
* it again under the same delivery id, once. Any other outcome, a changed
|
|
49
51
|
* pane, or ten minutes end the watch. */
|
|
50
52
|
export declare function retryAfterSubagentView(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, id: string, intervalMs?: number, limitMs?: number, escapeWaitMs?: number): void;
|
|
51
|
-
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
|
|
55
|
-
* press Enter once. A closed or replaced pane, a delivery the conversation
|
|
56
|
-
* took, or ten minutes end the watch; a pane asking for input is never answered. */
|
|
57
|
-
export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, intervalMs?: number): void;
|
|
53
|
+
/** Observe while the original conversation works, then allow 30 seconds for
|
|
54
|
+
* its submission acknowledgement after it finishes. A new legitimate turn
|
|
55
|
+
* resets that window. No observation sends input to the terminal. */
|
|
56
|
+
export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, id?: string, intervalMs?: number): void;
|
|
58
57
|
export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, headers?: IncomingHttpHeaders): Promise<unknown>;
|
|
59
58
|
export declare function paneRouteOnce(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, typing: () => void | Promise<void>): Promise<unknown>;
|