@phren/cli 0.3.41 → 0.3.42

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.
@@ -5,10 +5,13 @@ export declare const SCHEDULE_EVERY: readonly ["interval", "daily", "weekly", "o
5
5
  export declare const SCHEDULE_HARNESSES: readonly ["claude", "codex", "opencode", "copilot"];
6
6
  export declare const SCHEDULE_NOTIFY: readonly ["start", "finish", "failure"];
7
7
  export declare const WEEKDAYS: readonly ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
8
+ /** `new` starts a session per firing; `reuse` types the prompt into the schedule's last session while it is still open. */
9
+ export declare const SCHEDULE_SESSIONS: readonly ["new", "reuse"];
8
10
  export type ScheduleEvery = typeof SCHEDULE_EVERY[number];
9
11
  export type ScheduleHarness = typeof SCHEDULE_HARNESSES[number];
10
12
  export type ScheduleNotify = typeof SCHEDULE_NOTIFY[number];
11
13
  export type Weekday = typeof WEEKDAYS[number];
14
+ export type ScheduleSession = typeof SCHEDULE_SESSIONS[number];
12
15
  export declare const SCHEDULE_RUN_STATUSES: readonly ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
13
16
  export type ScheduleRunStatus = typeof SCHEDULE_RUN_STATUSES[number];
14
17
  /** How a run ended: done, done but waiting on the owner's answer, or not done. */
@@ -28,6 +31,8 @@ export interface Schedule {
28
31
  notify?: ScheduleNotify[];
29
32
  /** Explicit targets; absent means the directory owning this schedule. */
30
33
  projects?: string[];
34
+ /** Absent means `new`. */
35
+ session?: ScheduleSession;
31
36
  every: ScheduleEvery;
32
37
  at?: string;
33
38
  days?: Weekday[];
@@ -47,6 +52,8 @@ export interface ScheduleLaunchRecord {
47
52
  sessionId?: string;
48
53
  server?: string;
49
54
  jobDir?: string;
55
+ /** The prompt went to the schedule's earlier session instead of a new one. */
56
+ reused?: boolean;
50
57
  }
51
58
  export interface ScheduleRun {
52
59
  id: string;
@@ -67,6 +74,8 @@ export interface ScheduleRun {
67
74
  export interface ScheduleLaunchResult {
68
75
  launch: ScheduleLaunchRecord;
69
76
  completion?: Promise<ScheduleRunOutcome>;
77
+ /** Nothing was started: the reused session was busy, for this reason. */
78
+ skipped?: string;
70
79
  }
71
80
  export interface ScheduleLaunchContext {
72
81
  schedule: Schedule;
@@ -74,6 +83,8 @@ export interface ScheduleLaunchContext {
74
83
  projectDir: string;
75
84
  cwd: string;
76
85
  runId: string;
86
+ /** With `session: reuse`, the session this target's last run used, to continue if it is still open. */
87
+ reuse?: ScheduleLaunchRecord;
77
88
  blockedStartup?: (promptText: string) => void | Promise<void>;
78
89
  }
79
90
  export type ScheduleLauncher = ((context: ScheduleLaunchContext) => Promise<ScheduleLaunchResult>) & {
@@ -112,6 +123,8 @@ export declare function latestScheduleBatch(runs: ScheduleRun[]): {
112
123
  lastRun: ScheduleRun | undefined;
113
124
  lastRuns: ScheduleRun[];
114
125
  };
126
+ /** The newest Herdr session among a target's runs, which `session: reuse` continues. */
127
+ export declare function reusableLaunch(runs: readonly ScheduleRun[]): ScheduleLaunchRecord | undefined;
115
128
  export declare function readScheduleRuns(file: string): Promise<ScheduleRun[]>;
116
129
  export declare function writeScheduleRuns(file: string, runs: ScheduleRun[]): Promise<void>;
117
130
  export declare function newScheduleId(existing: Iterable<string>): string;
@@ -12,6 +12,8 @@ export const SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
12
12
  export const SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
13
13
  export const SCHEDULE_NOTIFY = ["start", "finish", "failure"];
14
14
  export const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
15
+ /** `new` starts a session per firing; `reuse` types the prompt into the schedule's last session while it is still open. */
16
+ export const SCHEDULE_SESSIONS = ["new", "reuse"];
15
17
  export const SCHEDULE_RUN_STATUSES = ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
16
18
  const scheduleId = z.string().regex(/^[a-f0-9]{8}$/);
17
19
  const plain = (max) => z.string().min(1).max(max).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value));
@@ -65,6 +67,8 @@ export function parseSchedule(value) {
65
67
  if (raw.projects !== undefined)
66
68
  schedule.projects = z.array(z.string().refine(isValidProjectName, "Invalid project slug."))
67
69
  .min(1).max(64).refine(projects => new Set(projects).size === projects.length, "Projects must be unique.").parse(raw.projects);
70
+ if (raw.session !== undefined)
71
+ schedule.session = z.enum(SCHEDULE_SESSIONS).parse(raw.session);
68
72
  if (raw.model !== undefined)
69
73
  schedule.model = singleLine(200).parse(raw.model);
70
74
  if (raw.account !== undefined)
@@ -251,6 +255,15 @@ export function latestScheduleBatch(runs) {
251
255
  : lastRuns.map(run => run.finishedAt).filter((time) => Boolean(time)).sort().at(-1);
252
256
  return { lastRun: { ...representative, finishedAt }, lastRuns };
253
257
  }
258
+ /** The newest Herdr session among a target's runs, which `session: reuse` continues. */
259
+ export function reusableLaunch(runs) {
260
+ for (let index = runs.length - 1; index >= 0; index--) {
261
+ const launch = runs[index].launch;
262
+ if (launch.mode === "herdr" && launch.server && launch.workspaceId && launch.tabId && launch.paneId && launch.sessionId)
263
+ return launch;
264
+ }
265
+ return undefined;
266
+ }
254
267
  export async function readScheduleRuns(file) {
255
268
  let text;
256
269
  try {
@@ -1,8 +1,23 @@
1
- import { type Json } from "./protocol.js";
2
- import type { Schedule, ScheduleLauncher, ScheduleRun, ScheduleRunOutcome } from "./schedule-format.js";
3
- import { watchHerdrRun } from "./schedule-watch.js";
1
+ import { type Json, type Target } from "./protocol.js";
2
+ import type { Schedule, ScheduleLauncher, ScheduleLaunchContext, ScheduleLaunchRecord, ScheduleLaunchResult, ScheduleRun, ScheduleRunOutcome } from "./schedule-format.js";
3
+ import { realTranscriptStamp, watchHerdrRun } from "./schedule-watch.js";
4
4
  type HerdrLauncher = (server: string, data: Json) => Promise<Json>;
5
- export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store?: string): ScheduleLauncher;
5
+ /** Types a prompt into a live session: the Hook's hand-off queue. */
6
+ export type ScheduleDeliver = (target: Target, text: string, deliveryId: string) => Promise<Json>;
7
+ export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store?: string, deliver?: ScheduleDeliver): ScheduleLauncher;
8
+ export interface ContinueEnv {
9
+ panes?: (server: string) => Promise<Json[]>;
10
+ transcriptStamp?: typeof realTranscriptStamp;
11
+ watch?: typeof watchHerdrRun;
12
+ }
13
+ /**
14
+ * `session: reuse`: types the prompt into the session the target's last run
15
+ * used, while its pane still runs that harness. A busy session is skipped
16
+ * rather than given a second prompt. Undefined when the session is gone (the
17
+ * pane closed, its agent exited, its conversation was replaced), so the caller
18
+ * starts a new one, which the next firing continues.
19
+ */
20
+ export declare function continueSession(context: ScheduleLaunchContext, previous: ScheduleLaunchRecord, deliver: ScheduleDeliver, signal: AbortSignal, env?: ContinueEnv): Promise<ScheduleLaunchResult | undefined>;
6
21
  /**
7
22
  * The outcome of a run a previous Hook process launched and never saw finish
8
23
  * (a restart or crash mid-run). A Herdr pane is followed again to its real
@@ -10,15 +10,20 @@ import { fanoutRoot } from "./fanouts.js";
10
10
  import { pretrustFolder } from "./folder-trust.js";
11
11
  import { findPane, paneIdentity, servers, snapshot } from "./herdr.js";
12
12
  import { agentNotReady, terminalProvider } from "./terminal.js";
13
- import { atomicInPrivateDir, BridgeError } from "./protocol.js";
13
+ import { atomicInPrivateDir, BridgeError, object, objects } from "./protocol.js";
14
14
  import { defaultPhrenPath } from "../shared.js";
15
- import { watchHerdrRun } from "./schedule-watch.js";
15
+ import { realTranscriptStamp, watchHerdrRun } from "./schedule-watch.js";
16
16
  /** Starting a scheduled run: in a Herdr pane when a server is live, otherwise
17
17
  * as a headless job under the fan-out root. */
18
18
  const CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
19
- export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
19
+ export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath(), deliver) {
20
20
  const abort = new AbortController(), children = new Set();
21
21
  const launcher = async (context) => {
22
+ if (context.reuse && deliver) {
23
+ const continued = await continueSession(context, context.reuse, deliver, abort.signal);
24
+ if (continued)
25
+ return continued;
26
+ }
22
27
  const live = await servers();
23
28
  if (live.length)
24
29
  return launchInHerdr(String(live[0].session), context, launchHerdr, abort.signal);
@@ -29,6 +34,50 @@ export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath())
29
34
  launcher.resume = (run, schedule) => resumeScheduleRun(run, schedule, abort.signal);
30
35
  return launcher;
31
36
  }
37
+ function busyReason(status) {
38
+ const state = status === "blocked" || status === "waiting" ? "is waiting for you" : status === "working" || status === "starting" ? "is still working" : `is ${status || "busy"}`;
39
+ return `The session this schedule continues ${state}, so this firing was skipped.`;
40
+ }
41
+ /**
42
+ * `session: reuse`: types the prompt into the session the target's last run
43
+ * used, while its pane still runs that harness. A busy session is skipped
44
+ * rather than given a second prompt. Undefined when the session is gone (the
45
+ * pane closed, its agent exited, its conversation was replaced), so the caller
46
+ * starts a new one, which the next firing continues.
47
+ */
48
+ export async function continueSession(context, previous, deliver, signal, env = {}) {
49
+ const { server, workspaceId, tabId, paneId, sessionId } = previous, source = context.schedule.harness;
50
+ if (!server || !workspaceId || !tabId || !paneId || !sessionId)
51
+ return undefined;
52
+ const panes = env.panes ?? (async (name) => objects((await snapshot(name)).panes));
53
+ const pane = findPane({ panes: await panes(server).catch(() => []) }, { workspace: workspaceId, tab: tabId, pane: paneId, source });
54
+ if (!pane)
55
+ return undefined;
56
+ const launch = { mode: "herdr", server, workspaceId, tabId, paneId, sessionId, reused: true };
57
+ const status = String(pane.agent_status ?? "");
58
+ if (status !== "idle" && status !== "done")
59
+ return { launch, skipped: busyReason(status) };
60
+ const transcript = await (env.transcriptStamp ?? realTranscriptStamp)(source, sessionId).catch(() => undefined);
61
+ let result;
62
+ try {
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;
70
+ }
71
+ if (result.state === "failed")
72
+ return undefined;
73
+ if (result.delivered !== true && result.queued !== true) {
74
+ throw new Error(`The prompt to the session this schedule continues was not confirmed${typeof result.error === "string" ? `: ${result.error}` : "."}`);
75
+ }
76
+ // A Claude /clear in the same terminal moves the delivery to the new conversation.
77
+ const session = typeof object(result.target).session === "string" ? String(object(result.target).session) : sessionId;
78
+ return { launch: { ...launch, sessionId: session },
79
+ completion: (env.watch ?? watchHerdrRun)(server, { workspaceId, tabId, paneId }, signal, { source, startedAt: Date.now(), sessionId: session, continued: { transcript } }) };
80
+ }
32
81
  /**
33
82
  * The outcome of a run a previous Hook process launched and never saw finish
34
83
  * (a restart or crash mid-run). A Herdr pane is followed again to its real
@@ -17,7 +17,18 @@ interface StartupWatch {
17
17
  startedAt: number;
18
18
  sessionId?: string;
19
19
  onBlocked?: (promptText: string) => void | Promise<void>;
20
+ /** The prompt went to a session that was already idle, whose transcript
21
+ * looked like this beforehand. Idle ends the run only once the pane was
22
+ * seen busy or the transcript moved; otherwise it is the turn not started. */
23
+ continued?: {
24
+ transcript?: {
25
+ size: number;
26
+ mtimeMs: number;
27
+ };
28
+ };
20
29
  }
30
+ /** How long a continued session may sit idle without taking up the prompt. */
31
+ export declare const CONTINUED_TURN_START_MS = 120000;
21
32
  export interface StartupWatchEnv {
22
33
  now?: () => number;
23
34
  pause?: (ms: number) => Promise<void>;
@@ -75,6 +86,10 @@ export declare function readFinalTurn(source: ScheduleHarness, sessionId: string
75
86
  /** When a finished reply ends by asking the owner something (a question, or
76
87
  * numbered options introduced as a choice), the question's first line. */
77
88
  export declare function ownerQuestion(text: string): string | undefined;
89
+ export declare function realTranscriptStamp(source: ScheduleHarness, sessionId: string | undefined): Promise<{
90
+ size: number;
91
+ mtimeMs: number;
92
+ } | undefined>;
78
93
  export declare function watchHerdrRun(server: string, target: {
79
94
  workspaceId: string;
80
95
  tabId: string;
@@ -35,6 +35,8 @@ export function watchFailureReason(error) {
35
35
  const first = (error instanceof Error ? error.message : String(error)).split("\n")[0].replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200);
36
36
  return `Watching the scheduled prompt failed: ${first || "unknown error"}`;
37
37
  }
38
+ /** How long a continued session may sit idle without taking up the prompt. */
39
+ export const CONTINUED_TURN_START_MS = 120_000;
38
40
  /** The public text of one assistant row, without reasoning or tool output. */
39
41
  export function publicAssistant(raw, source) {
40
42
  if (source === "codex") {
@@ -326,7 +328,7 @@ export function ownerQuestion(text) {
326
328
  first--;
327
329
  return plainLine(lines[first]) || last;
328
330
  }
329
- async function realTranscriptStamp(source, sessionId) {
331
+ export async function realTranscriptStamp(source, sessionId) {
330
332
  if (!sessionId)
331
333
  return undefined;
332
334
  const file = await transcriptPath(source, sessionId).catch(() => undefined);
@@ -346,6 +348,7 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
346
348
  let stamp;
347
349
  let recordedBlock = false;
348
350
  let paneReads = 0;
351
+ let turnStarted = !startup.continued;
349
352
  while (!signal.aborted) {
350
353
  await pause(1000);
351
354
  if (signal.aborted)
@@ -360,6 +363,16 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
360
363
  if (status === "idle" || status === "done") {
361
364
  if (!sessionId)
362
365
  sessionId = await resolveSession(server, pane);
366
+ if (!turnStarted) {
367
+ const moved = await transcriptStamp(startup.source, sessionId);
368
+ const before = startup.continued?.transcript;
369
+ turnStarted = !!moved && (!before || moved.size !== before.size || moved.mtimeMs !== before.mtimeMs);
370
+ if (!turnStarted) {
371
+ if (now() - startup.startedAt > CONTINUED_TURN_START_MS)
372
+ return { status: "failed", reason: "The session this schedule continues never took up the prompt." };
373
+ continue;
374
+ }
375
+ }
363
376
  const turn = await finalTurn(startup.source, sessionId).catch(() => undefined);
364
377
  if (turn?.completed && turn.error)
365
378
  return { status: "failed", reason: turn.error };
@@ -369,6 +382,7 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
369
382
  if (!["working", "starting", "blocked", "waiting", "unknown"].includes(status)) {
370
383
  return { status: "failed", reason: "The scheduled agent stopped before the prompt finished." };
371
384
  }
385
+ turnStarted = true;
372
386
  const elapsedMs = now() - startup.startedAt;
373
387
  const withinWindow = elapsedMs <= STARTUP_BLOCK_WINDOW_MS + STARTUP_BLOCK_WINDOW_OPEN_MS;
374
388
  if (!transcriptActive && startup.onBlocked && !recordedBlock && withinWindow) {
@@ -5,7 +5,7 @@ import path from "node:path";
5
5
  import { BridgeError } from "./protocol.js";
6
6
  import { getProjectSourcePath } from "../project-config.js";
7
7
  import { getProjectDirs } from "../shared.js";
8
- import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
8
+ import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunch, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
9
9
  export * from "./schedule-format.js";
10
10
  export * from "./schedule-launch.js";
11
11
  export * from "./schedule-watch.js";
@@ -144,7 +144,8 @@ export class Scheduler {
144
144
  targets.push({ project: target, projectDir: targetDir, cwd });
145
145
  }
146
146
  const batchId = randomUUID(), startedAt = this.now().toISOString();
147
- const children = targets.map(target => ({ ...target, run: {
147
+ const children = targets.map(target => ({ ...target,
148
+ ...(schedule.session === "reuse" ? { reuse: reusableLaunch(matching.filter(run => run.project === target.project)) } : {}), run: {
148
149
  id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
149
150
  startedAt, status: "launched", launch: { mode: "headless" },
150
151
  } }));
@@ -171,8 +172,12 @@ export class Scheduler {
171
172
  return Promise.all(prepared.children.map(async (child) => {
172
173
  try {
173
174
  const launched = await this.launch({ schedule: prepared.schedule, project: child.project, projectDir: child.projectDir,
174
- cwd: child.cwd, runId: child.run.id,
175
+ cwd: child.cwd, runId: child.run.id, ...(child.reuse ? { reuse: child.reuse } : {}),
175
176
  blockedStartup: promptText => this.recordBlockedStartup(child.run.id, prepared.schedule, promptText) });
177
+ // A busy reused session keeps its turn; this firing is recorded and nothing is sent.
178
+ if (launched.skipped) {
179
+ return await this.updateRun(child.run.id, { status: "skipped", finishedAt: this.now().toISOString(), reason: launched.skipped, launch: launched.launch });
180
+ }
176
181
  const running = await this.updateRun(child.run.id, { status: "running", launch: launched.launch });
177
182
  const notified = this.notifyRun(running, prepared.schedule, "scheduleStarted");
178
183
  if (launched.completion)
@@ -172,7 +172,9 @@ export async function serve(version, options = {}) {
172
172
  const scheduler = modules.has("schedules") ? new Scheduler({ now: () => new Date(), store: scheduleStore, runsFile: scheduleRunsFile(),
173
173
  aliases: [computerID],
174
174
  // A schedule starts in its project's folder, which the Hook resolved itself.
175
- launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
175
+ launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore,
176
+ // `session: reuse` continues a session through the same queue a hand-off takes.
177
+ (target, text, deliveryId) => handOffs ? handOffs.enqueue({ target, text, deliveryId }) : sendPrompt(target, text, deliveryId, async () => { })),
176
178
  push: { notify: value => agentHooks.push.notifySchedule(value) },
177
179
  locateProject: async (project) => (await locateProject(project, await journal.recent()))[0]?.directory }) : undefined;
178
180
  const fanoutMessages = new FanoutMessages({ ...process.env, PHREN_PATH: scheduleStore }, {
@@ -37849,7 +37849,7 @@ var init_package_metadata = __esm({
37849
37849
  __dirname = path37.dirname(fileURLToPath2(import.meta.url));
37850
37850
  ROOT = path37.join(__dirname, "..");
37851
37851
  PACKAGE_JSON_PATH = path37.join(ROOT, "package.json");
37852
- BUNDLED_VERSION = true ? "0.3.41" : "0.0.0";
37852
+ BUNDLED_VERSION = true ? "0.3.42" : "0.0.0";
37853
37853
  PACKAGE_JSON = readPackageJson();
37854
37854
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
37855
37855
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -42323,6 +42323,7 @@ function parseSchedule(value2) {
42323
42323
  updatedAt: timestamp2.parse(raw.updatedAt)
42324
42324
  };
42325
42325
  if (raw.projects !== void 0) schedule.projects = external_exports.array(external_exports.string().refine(isValidProjectName, "Invalid project slug.")).min(1).max(64).refine((projects) => new Set(projects).size === projects.length, "Projects must be unique.").parse(raw.projects);
42326
+ if (raw.session !== void 0) schedule.session = external_exports.enum(SCHEDULE_SESSIONS).parse(raw.session);
42326
42327
  if (raw.model !== void 0) schedule.model = singleLine(200).parse(raw.model);
42327
42328
  if (raw.account !== void 0) schedule.account = external_exports.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(raw.account);
42328
42329
  if (raw.notify !== void 0) schedule.notify = external_exports.array(external_exports.enum(SCHEDULE_NOTIFY)).max(3).parse(raw.notify).filter((kind, index2, kinds) => kinds.indexOf(kind) === index2);
@@ -42474,6 +42475,13 @@ function latestScheduleBatch(runs) {
42474
42475
  const finishedAt = lastRuns.some((run4) => runningStatuses.has(run4.status)) ? void 0 : lastRuns.map((run4) => run4.finishedAt).filter((time3) => Boolean(time3)).sort().at(-1);
42475
42476
  return { lastRun: { ...representative, finishedAt }, lastRuns };
42476
42477
  }
42478
+ function reusableLaunch(runs) {
42479
+ for (let index2 = runs.length - 1; index2 >= 0; index2--) {
42480
+ const launch2 = runs[index2].launch;
42481
+ if (launch2.mode === "herdr" && launch2.server && launch2.workspaceId && launch2.tabId && launch2.paneId && launch2.sessionId) return launch2;
42482
+ }
42483
+ return void 0;
42484
+ }
42477
42485
  async function readScheduleRuns(file4) {
42478
42486
  let text5;
42479
42487
  try {
@@ -42504,7 +42512,7 @@ async function writeScheduleRuns(file4, runs) {
42504
42512
  function scheduleRunsFile() {
42505
42513
  return path56.join(bridgeRoot(), "schedule-runs.jsonl");
42506
42514
  }
42507
- var SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_NOTIFY, WEEKDAYS, SCHEDULE_RUN_STATUSES, scheduleId, plain, singleLine, scheduleName, timestamp2, localTimestamp, clockTime, schedulePath, runningStatuses, MAX_SCHEDULES, MAX_RUNS;
42515
+ var SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_NOTIFY, WEEKDAYS, SCHEDULE_SESSIONS, SCHEDULE_RUN_STATUSES, scheduleId, plain, singleLine, scheduleName, timestamp2, localTimestamp, clockTime, schedulePath, runningStatuses, MAX_SCHEDULES, MAX_RUNS;
42508
42516
  var init_schedule_format = __esm({
42509
42517
  "src/bridge/schedule-format.ts"() {
42510
42518
  "use strict";
@@ -42517,6 +42525,7 @@ var init_schedule_format = __esm({
42517
42525
  SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
42518
42526
  SCHEDULE_NOTIFY = ["start", "finish", "failure"];
42519
42527
  WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
42528
+ SCHEDULE_SESSIONS = ["new", "reuse"];
42520
42529
  SCHEDULE_RUN_STATUSES = ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
42521
42530
  scheduleId = external_exports.string().regex(/^[a-f0-9]{8}$/);
42522
42531
  plain = (max) => external_exports.string().min(1).max(max).refine((value2) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value2));
@@ -42804,6 +42813,7 @@ async function watchHerdrRun(server, target, signal, startup, env = {}) {
42804
42813
  let stamp2;
42805
42814
  let recordedBlock = false;
42806
42815
  let paneReads = 0;
42816
+ let turnStarted = !startup.continued;
42807
42817
  while (!signal.aborted) {
42808
42818
  await pause(1e3);
42809
42819
  if (signal.aborted) break;
@@ -42813,6 +42823,15 @@ async function watchHerdrRun(server, target, signal, startup, env = {}) {
42813
42823
  const status = String(pane.agent_status);
42814
42824
  if (status === "idle" || status === "done") {
42815
42825
  if (!sessionId2) sessionId2 = await resolveSession(server, pane);
42826
+ if (!turnStarted) {
42827
+ const moved = await transcriptStamp2(startup.source, sessionId2);
42828
+ const before = startup.continued?.transcript;
42829
+ turnStarted = !!moved && (!before || moved.size !== before.size || moved.mtimeMs !== before.mtimeMs);
42830
+ if (!turnStarted) {
42831
+ if (now() - startup.startedAt > CONTINUED_TURN_START_MS) return { status: "failed", reason: "The session this schedule continues never took up the prompt." };
42832
+ continue;
42833
+ }
42834
+ }
42816
42835
  const turn = await finalTurn(startup.source, sessionId2).catch(() => void 0);
42817
42836
  if (turn?.completed && turn.error) return { status: "failed", reason: turn.error };
42818
42837
  const question2 = turn?.completed && turn.lastAssistant ? ownerQuestion(turn.lastAssistant) : void 0;
@@ -42821,6 +42840,7 @@ async function watchHerdrRun(server, target, signal, startup, env = {}) {
42821
42840
  if (!["working", "starting", "blocked", "waiting", "unknown"].includes(status)) {
42822
42841
  return { status: "failed", reason: "The scheduled agent stopped before the prompt finished." };
42823
42842
  }
42843
+ turnStarted = true;
42824
42844
  const elapsedMs = now() - startup.startedAt;
42825
42845
  const withinWindow = elapsedMs <= STARTUP_BLOCK_WINDOW_MS + STARTUP_BLOCK_WINDOW_OPEN_MS;
42826
42846
  if (!transcriptActive && startup.onBlocked && !recordedBlock && withinWindow) {
@@ -42851,7 +42871,7 @@ async function watchHerdrRun(server, target, signal, startup, env = {}) {
42851
42871
  }
42852
42872
  return { status: "failed", reason: "Phren Hook stopped while the scheduled prompt was running." };
42853
42873
  }
42854
- var STARTUP_BLOCK_WINDOW_MS, STARTUP_BLOCK_WINDOW_OPEN_MS, STARTUP_LATE_TRANSCRIPT_MS, STARTUP_PANE_READ_LIMIT, STARTUP_PROMPT_TAIL_LINES, STARTUP_BLOCK_STATUSES, STARTUP_PROMPT_MARKER, FINAL_TURN_TAIL_BYTES, CLAUDE_USAGE_LIMIT, isClaudeUsageLimit, ENDLESS_COMMAND, OPTION_LINE, CHOICE_WORDS;
42874
+ var STARTUP_BLOCK_WINDOW_MS, STARTUP_BLOCK_WINDOW_OPEN_MS, STARTUP_LATE_TRANSCRIPT_MS, STARTUP_PANE_READ_LIMIT, STARTUP_PROMPT_TAIL_LINES, STARTUP_BLOCK_STATUSES, STARTUP_PROMPT_MARKER, CONTINUED_TURN_START_MS, FINAL_TURN_TAIL_BYTES, CLAUDE_USAGE_LIMIT, isClaudeUsageLimit, ENDLESS_COMMAND, OPTION_LINE, CHOICE_WORDS;
42855
42875
  var init_schedule_watch = __esm({
42856
42876
  "src/bridge/schedule-watch.ts"() {
42857
42877
  "use strict";
@@ -42867,6 +42887,7 @@ var init_schedule_watch = __esm({
42867
42887
  STARTUP_PROMPT_TAIL_LINES = 12;
42868
42888
  STARTUP_BLOCK_STATUSES = ["blocked", "waiting"];
42869
42889
  STARTUP_PROMPT_MARKER = /[?❯]|\(y\/?n\)|^\s*\d+[.)]\s/m;
42890
+ CONTINUED_TURN_START_MS = 12e4;
42870
42891
  FINAL_TURN_TAIL_BYTES = 512 * 1024;
42871
42892
  CLAUDE_USAGE_LIMIT = "Claude usage limit:";
42872
42893
  isClaudeUsageLimit = (error62) => !!error62?.startsWith(CLAUDE_USAGE_LIMIT);
@@ -42882,9 +42903,13 @@ import { createWriteStream } from "node:fs";
42882
42903
  import { mkdir as mkdir16, readFile as readFile28 } from "node:fs/promises";
42883
42904
  import path57 from "node:path";
42884
42905
  import { finished as streamFinished } from "node:stream/promises";
42885
- function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
42906
+ function createScheduleLauncher(launchHerdr, store = defaultPhrenPath(), deliver) {
42886
42907
  const abort = new AbortController(), children = /* @__PURE__ */ new Set();
42887
42908
  const launcher = async (context3) => {
42909
+ if (context3.reuse && deliver) {
42910
+ const continued = await continueSession(context3, context3.reuse, deliver, abort.signal);
42911
+ if (continued) return continued;
42912
+ }
42888
42913
  const live = await servers();
42889
42914
  if (live.length) return launchInHerdr(String(live[0].session), context3, launchHerdr, abort.signal);
42890
42915
  return launchHeadless(context3, store, (child) => {
@@ -42900,6 +42925,46 @@ function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
42900
42925
  launcher.resume = (run4, schedule) => resumeScheduleRun(run4, schedule, abort.signal);
42901
42926
  return launcher;
42902
42927
  }
42928
+ function busyReason(status) {
42929
+ const state = status === "blocked" || status === "waiting" ? "is waiting for you" : status === "working" || status === "starting" ? "is still working" : `is ${status || "busy"}`;
42930
+ return `The session this schedule continues ${state}, so this firing was skipped.`;
42931
+ }
42932
+ async function continueSession(context3, previous, deliver, signal, env = {}) {
42933
+ const { server, workspaceId, tabId, paneId, sessionId: sessionId2 } = previous, source = context3.schedule.harness;
42934
+ if (!server || !workspaceId || !tabId || !paneId || !sessionId2) return void 0;
42935
+ const panes2 = env.panes ?? (async (name) => objects((await snapshot(name)).panes));
42936
+ const pane = findPane({ panes: await panes2(server).catch(() => []) }, { workspace: workspaceId, tab: tabId, pane: paneId, source });
42937
+ if (!pane) return void 0;
42938
+ const launch2 = { mode: "herdr", server, workspaceId, tabId, paneId, sessionId: sessionId2, reused: true };
42939
+ const status = String(pane.agent_status ?? "");
42940
+ if (status !== "idle" && status !== "done") return { launch: launch2, skipped: busyReason(status) };
42941
+ const transcript = await (env.transcriptStamp ?? realTranscriptStamp)(source, sessionId2).catch(() => void 0);
42942
+ let result;
42943
+ try {
42944
+ result = await deliver(
42945
+ { server, workspace: workspaceId, tab: tabId, pane: paneId, source, session: sessionId2 },
42946
+ context3.schedule.prompt,
42947
+ `schedule-${context3.runId.replaceAll("-", "")}`
42948
+ );
42949
+ } catch (error62) {
42950
+ if (error62 instanceof BridgeError && (error62.status === 404 || error62.status === 409)) return void 0;
42951
+ throw error62;
42952
+ }
42953
+ if (result.state === "failed") return void 0;
42954
+ if (result.delivered !== true && result.queued !== true) {
42955
+ throw new Error(`The prompt to the session this schedule continues was not confirmed${typeof result.error === "string" ? `: ${result.error}` : "."}`);
42956
+ }
42957
+ const session = typeof object2(result.target).session === "string" ? String(object2(result.target).session) : sessionId2;
42958
+ return {
42959
+ launch: { ...launch2, sessionId: session },
42960
+ completion: (env.watch ?? watchHerdrRun)(
42961
+ server,
42962
+ { workspaceId, tabId, paneId },
42963
+ signal,
42964
+ { source, startedAt: Date.now(), sessionId: session, continued: { transcript } }
42965
+ )
42966
+ };
42967
+ }
42903
42968
  async function resumeScheduleRun(run4, schedule, signal, watch2 = watchHerdrRun) {
42904
42969
  const launch2 = run4.launch;
42905
42970
  if (run4.status === "launched") return { status: "failed", reason: "Phren Hook restarted before this run finished launching." };
@@ -43229,16 +43294,20 @@ var init_schedules = __esm({
43229
43294
  targets.push({ project: target, projectDir: targetDir, cwd });
43230
43295
  }
43231
43296
  const batchId = randomUUID11(), startedAt2 = this.now().toISOString();
43232
- const children = targets.map((target) => ({ ...target, run: {
43233
- id: randomUUID11(),
43234
- scheduleId: id2,
43235
- project: target.project,
43236
- scheduleProject: project,
43237
- batchId,
43238
- startedAt: startedAt2,
43239
- status: "launched",
43240
- launch: { mode: "headless" }
43241
- } }));
43297
+ const children = targets.map((target) => ({
43298
+ ...target,
43299
+ ...schedule.session === "reuse" ? { reuse: reusableLaunch(matching.filter((run4) => run4.project === target.project)) } : {},
43300
+ run: {
43301
+ id: randomUUID11(),
43302
+ scheduleId: id2,
43303
+ project: target.project,
43304
+ scheduleProject: project,
43305
+ batchId,
43306
+ startedAt: startedAt2,
43307
+ status: "launched",
43308
+ launch: { mode: "headless" }
43309
+ }
43310
+ }));
43242
43311
  await writeScheduleRuns(this.runsFile, [...runs, ...children.map((child) => child.run)]);
43243
43312
  for (const child of children) this.own.add(child.run.id);
43244
43313
  if (schedule.every === "once" && schedule.enabled) {
@@ -43260,8 +43329,12 @@ var init_schedules = __esm({
43260
43329
  projectDir: child.projectDir,
43261
43330
  cwd: child.cwd,
43262
43331
  runId: child.run.id,
43332
+ ...child.reuse ? { reuse: child.reuse } : {},
43263
43333
  blockedStartup: (promptText2) => this.recordBlockedStartup(child.run.id, prepared.schedule, promptText2)
43264
43334
  });
43335
+ if (launched.skipped) {
43336
+ return await this.updateRun(child.run.id, { status: "skipped", finishedAt: this.now().toISOString(), reason: launched.skipped, launch: launched.launch });
43337
+ }
43265
43338
  const running2 = await this.updateRun(child.run.id, { status: "running", launch: launched.launch });
43266
43339
  const notified = this.notifyRun(running2, prepared.schedule, "scheduleStarted");
43267
43340
  if (launched.completion) void launched.completion.then(async (result) => {
@@ -74639,7 +74712,13 @@ async function serve(version2, options = {}) {
74639
74712
  runsFile: scheduleRunsFile(),
74640
74713
  aliases: [computerID2],
74641
74714
  // A schedule starts in its project's folder, which the Hook resolved itself.
74642
- launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
74715
+ launch: createScheduleLauncher(
74716
+ (server, data) => launchSession(server, data, { trustFolder: true }),
74717
+ scheduleStore,
74718
+ // `session: reuse` continues a session through the same queue a hand-off takes.
74719
+ (target, text5, deliveryId) => handOffs ? handOffs.enqueue({ target, text: text5, deliveryId }) : sendPrompt(target, text5, deliveryId, async () => {
74720
+ })
74721
+ ),
74643
74722
  push: { notify: (value2) => agentHooks.push.notifySchedule(value2) },
74644
74723
  locateProject: async (project) => (await locateProject(project, await journal.recent()))[0]?.directory
74645
74724
  }) : void 0;
@@ -75371,7 +75450,7 @@ async function main() {
75371
75450
  return askpass2(args[1]);
75372
75451
  }
75373
75452
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
75374
- return runBridge2(args, "0.3.41");
75453
+ return runBridge2(args, "0.3.42");
75375
75454
  }
75376
75455
  main().then((code) => {
75377
75456
  process.exitCode = code;
@@ -1,7 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import { request } from "node:http";
3
3
  import path from "node:path";
4
- import { SCHEDULE_EVERY, SCHEDULE_HARNESSES, WEEKDAYS, canonicalComputer, newScheduleId, parseSchedule, readScheduleDocument, writeScheduleDocument, } from "../bridge/schedules.js";
4
+ import { SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_SESSIONS, WEEKDAYS, canonicalComputer, newScheduleId, parseSchedule, readScheduleDocument, writeScheduleDocument, } from "../bridge/schedules.js";
5
5
  import { object, socketPath } from "../bridge/protocol.js";
6
6
  import { listMachines } from "../profile-store.js";
7
7
  import { getProjectDirs } from "../shared.js";
@@ -41,7 +41,7 @@ async function list(store, projectName) {
41
41
  console.log(`${project} ${schedule.id} ${schedule.enabled ? "enabled " : "paused "} ${schedule.name}`);
42
42
  if (schedule.projects)
43
43
  console.log(` targets: ${schedule.projects.join(", ")}`);
44
- console.log(` ${schedule.computer} · ${schedule.harness}${schedule.model ? `/${schedule.model}` : ""} · ${scheduleDescription(schedule)}`);
44
+ console.log(` ${schedule.computer} · ${schedule.harness}${schedule.model ? `/${schedule.model}` : ""} · ${scheduleDescription(schedule)}${schedule.session === "reuse" ? " · continues one session" : ""}`);
45
45
  }
46
46
  }
47
47
  if (!count)
@@ -60,6 +60,9 @@ async function add(store, args) {
60
60
  throw new Error(`--harness must be one of: ${SCHEDULE_HARNESSES.join(", ")}.`);
61
61
  if (!SCHEDULE_EVERY.includes(every))
62
62
  throw new Error(`--every must be one of: ${SCHEDULE_EVERY.join(", ")}.`);
63
+ const session = option(args, "--session");
64
+ if (session !== undefined && !SCHEDULE_SESSIONS.includes(session))
65
+ throw new Error(`--session must be one of: ${SCHEDULE_SESSIONS.join(", ")}.`);
63
66
  const machines = listMachines(store);
64
67
  if (!machines.ok)
65
68
  throw new Error(machines.error);
@@ -75,7 +78,7 @@ async function add(store, args) {
75
78
  id: newScheduleId(file.schedules.map(item => item.id)), name, enabled: true, computer, harness,
76
79
  ...(option(args, "--projects") ? { projects: option(args, "--projects").split(",").map(project => project.trim()) } : {}),
77
80
  ...(option(args, "--model") ? { model: option(args, "--model") } : {}),
78
- ...(option(args, "--account") ? { account: option(args, "--account") } : {}), every, prompt, createdAt: now, updatedAt: now,
81
+ ...(option(args, "--account") ? { account: option(args, "--account") } : {}), ...(session ? { session } : {}), every, prompt, createdAt: now, updatedAt: now,
79
82
  ...(option(args, "--at") ? { at: option(args, "--at") } : {}),
80
83
  ...(option(args, "--days") ? { days: option(args, "--days").split(",").map(day => day.trim().toLowerCase()) } : {}),
81
84
  ...(option(args, "--interval") ? { interval: option(args, "--interval") } : {}),
@@ -66,7 +66,7 @@ const PROJECTS_SUBCOMMANDS = [
66
66
  ];
67
67
  const SCHEDULE_SUBCOMMANDS = [
68
68
  { name: "list", usage: "phren schedule list [project]", summary: "List scheduled prompts" },
69
- { name: "add", usage: "phren schedule add <project> --name <name> --harness <name> --computer <name> [--model <model>] [--account <id>] [--projects <a,b>] --every <kind> [timing] (--prompt <text>|--prompt-file <path>)", summary: "Add a scheduled prompt" },
69
+ { name: "add", usage: "phren schedule add <project> --name <name> --harness <name> --computer <name> [--model <model>] [--account <id>] [--projects <a,b>] [--session new|reuse] --every <kind> [timing] (--prompt <text>|--prompt-file <path>)", summary: "Add a scheduled prompt" },
70
70
  { name: "remove", usage: "phren schedule remove <project> <id>", summary: "Remove a scheduled prompt" },
71
71
  { name: "enable", usage: "phren schedule enable <project> <id>", summary: "Resume a scheduled prompt" },
72
72
  { name: "disable", usage: "phren schedule disable <project> <id>", summary: "Pause a scheduled prompt" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.41",
3
+ "version": "0.3.42",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {