@phren/cli 0.3.41 → 0.3.43

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.
@@ -81,6 +81,11 @@ function recordFor(server, pane, by, session) {
81
81
  ...(session ? { session } : {}), since: new Date().toISOString(), by,
82
82
  };
83
83
  }
84
+ /** The one pane in a snapshot whose agent reports this session; none when it is absent or ambiguous. */
85
+ function sessionPane(session, s) {
86
+ const found = objects(s.panes).filter(p => runsAgent(p) && objects([p.agent_session])[0]?.value === session);
87
+ return found.length === 1 ? found[0] : undefined;
88
+ }
84
89
  /** The recorded pane in a snapshot of its server, when it is still the same terminal. */
85
90
  function recordedPane(record, s) {
86
91
  const pane = objects(s.panes).find(p => p.pane_id === record.pane);
@@ -109,10 +114,17 @@ export function conductorPane(server, s) {
109
114
  const record = state.conductor;
110
115
  if (!record || record.server !== server)
111
116
  return undefined;
112
- const pane = recordedPane(record, s);
117
+ let pane = recordedPane(record, s);
113
118
  if (!pane) {
114
- await writeRoleState({ ...state, conductor: null });
115
- return undefined;
119
+ // The pane went away or was recreated (a moved tab, a Herdr restart): the
120
+ // role follows the session, so a pane running it takes the role over.
121
+ const adopted = record.session ? sessionPane(record.session, s) : undefined;
122
+ if (!adopted) {
123
+ await writeRoleState({ ...state, conductor: null });
124
+ return undefined;
125
+ }
126
+ await writeRoleState({ ...state, conductor: { ...recordFor(server, adopted, record.by, record.session), since: record.since } });
127
+ return adopted;
116
128
  }
117
129
  // Keep the place current: a pane moved to another tab or workspace is the same pane.
118
130
  const moved = (id.safeParse(pane.workspace_id).success && pane.workspace_id !== record.workspace) || (id.safeParse(pane.tab_id).success && pane.tab_id !== record.tab)
@@ -29,4 +29,9 @@ export declare const findingWriteSchema: z.ZodObject<{
29
29
  name: z.ZodOptional<z.ZodString>;
30
30
  }, z.core.$strict>>;
31
31
  }, z.core.$strict>;
32
+ /** Complete one task by its stable id (`bid:` plus 8 hex digits), as `/tasks?branch=` lists it. */
33
+ export declare const taskCompleteSchema: z.ZodObject<{
34
+ id: z.ZodString;
35
+ }, z.core.$strict>;
36
+ export type TaskComplete = z.infer<typeof taskCompleteSchema>;
32
37
  export type FindingWrite = z.infer<typeof findingWriteSchema>;
@@ -44,3 +44,5 @@ export const findingWriteSchema = z.object({
44
44
  name: z.string().min(1).max(200).refine(value => !/[\x00-\x1f\x7f]/.test(value)).optional(),
45
45
  }).strict().optional(),
46
46
  }).strict();
47
+ /** Complete one task by its stable id (`bid:` plus 8 hex digits), as `/tasks?branch=` lists it. */
48
+ export const taskCompleteSchema = z.object({ id: z.string().regex(/^bid:[0-9a-f]{8}$/) }).strict();
@@ -241,7 +241,7 @@ async function runScopedPair(args, version) {
241
241
  text = await readFile(key, "utf8");
242
242
  const line = await acceptScopedKey(scope, text);
243
243
  const fingerprint = await hostFingerprint();
244
- console.log(`Authorized ${SCOPE_KEY_COMMENT[scope]} for ${scope}: ${scope === "gitboy-write" ? "POST /v1/projects/<project>/findings only" : "GET /v1/projects/<project>/memory, memory/files, memory/search and tasks only"}.`);
244
+ console.log(`Authorized ${SCOPE_KEY_COMMENT[scope]} for ${scope}: ${scope === "gitboy-write" ? "POST /v1/projects/<project>/findings and tasks/complete only" : "GET /v1/projects/<project>/memory, memory/files, memory/search and tasks only"}.`);
245
245
  console.log(` ${line}`);
246
246
  console.log(` SSH user: ${userInfo().username} host key: ${fingerprint ?? "unknown (no /etc/ssh/ssh_host_ed25519_key.pub)"}`);
247
247
  console.log(` Addresses: ${(await pairingHosts()).join(", ") || "none found"}`);
@@ -0,0 +1,8 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** `GET /v1/projects/:project/git`: the project's host, branch and open pull
3
+ * requests with their checks, read from its checkout on this computer, so the
4
+ * desktop's Projects page needs no session running there. */
5
+ export declare const PROJECT_GIT_ROUTE: RegExp;
6
+ /** The recorded source folder for this computer wins; otherwise the folders
7
+ * `/v1/projects/locate` offers, newest session first. */
8
+ export declare function projectGit(base: string, rawProject: string, activity: Json[]): Promise<Json>;
@@ -0,0 +1,39 @@
1
+ import { getProjectSourcePath } from "../project-config.js";
2
+ import { resolveProject } from "../store-routing.js";
3
+ import { isValidProjectName } from "../utils.js";
4
+ import { gitPulls } from "./git.js";
5
+ import { locateProject } from "./locate.js";
6
+ import { gitRoot } from "./projects.js";
7
+ import { BridgeError } from "./protocol.js";
8
+ /** `GET /v1/projects/:project/git`: the project's host, branch and open pull
9
+ * requests with their checks, read from its checkout on this computer, so the
10
+ * desktop's Projects page needs no session running there. */
11
+ export const PROJECT_GIT_ROUTE = /^\/v1\/projects\/([^/]+)\/git$/;
12
+ /** The recorded source folder for this computer wins; otherwise the folders
13
+ * `/v1/projects/locate` offers, newest session first. */
14
+ export async function projectGit(base, rawProject, activity) {
15
+ let project;
16
+ try {
17
+ project = decodeURIComponent(rawProject);
18
+ }
19
+ catch {
20
+ throw new BridgeError(400, "Invalid project name.");
21
+ }
22
+ if (!isValidProjectName(project))
23
+ throw new BridgeError(400, "Invalid project name.");
24
+ const folders = [];
25
+ try {
26
+ const source = getProjectSourcePath(resolveProject(base, project).store.path, project);
27
+ if (source)
28
+ folders.push(source);
29
+ }
30
+ catch { /* not in the store: located folders only */ }
31
+ for (const candidate of await locateProject(project, activity))
32
+ folders.push(candidate.directory);
33
+ for (const folder of folders) {
34
+ const root = await gitRoot(folder).catch(() => undefined);
35
+ if (root)
36
+ return { project, directory: root, ...(await gitPulls(root)) };
37
+ }
38
+ throw new BridgeError(404, "No checkout of this project on this computer.", { code: "no-checkout" });
39
+ }
@@ -92,3 +92,15 @@ export declare function saveFinding(base: string, rawProject: string, input: unk
92
92
  status: string;
93
93
  finding: MemoryFinding | null;
94
94
  }>;
95
+ /** Mark one open task done, by the stable id `/tasks?branch=` gave gitboy when
96
+ * its pull request merged. Exact ids only: no text matching, so a wrong guess
97
+ * can never complete another task. A task already done answers `already-done`. */
98
+ export declare function completeProjectTask(base: string, rawProject: string, input: unknown): {
99
+ project: string;
100
+ id: string;
101
+ status: "already-done";
102
+ } | {
103
+ project: string;
104
+ id: string;
105
+ status: "completed";
106
+ };
@@ -1,7 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { readFindings } from "../data/access.js";
4
- import { readTasks } from "../data/tasks.js";
4
+ import { completeTask, readTasks } from "../data/tasks.js";
5
5
  import { taskStores } from "../data/task-store-directory.js";
6
6
  import { FINDING_TAGS } from "../phren-core.js";
7
7
  import { getProjectRemote, readProjectConfig } from "../project-config.js";
@@ -12,13 +12,13 @@ import { BridgeError } from "./protocol.js";
12
12
  import { moduleEnabled } from "../modules/runtime.js";
13
13
  import { loadCodePackage } from "../modules/code-package.js";
14
14
  import { bestChunkMatch, tokenizeForOverlap } from "../shared/retrieval.js";
15
- import { findingWriteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, MAX_SEARCH_LIMIT } from "./gitboy-contract.js";
15
+ import { findingWriteSchema, taskCompleteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, MAX_SEARCH_LIMIT } from "./gitboy-contract.js";
16
16
  // `GET /v1/projects/:project/memory`: one project's findings, truths and
17
17
  // tasks as a fixed read-only contract, for a client that renders them beside
18
18
  // the repository (gitboy). Phren stays the source of truth; nothing here
19
19
  // writes. The scoped `gitboy-read` SSH key reaches only this route
20
20
  // (scoped-gateway.ts). Contract: docs/phren-hook.md#gitboy-read-only-memory.
21
- export const PROJECT_MEMORY_ROUTE = /^\/v1\/projects\/([^/]+)\/(memory|memory\/files|memory\/search|tasks|findings)$/;
21
+ export const PROJECT_MEMORY_ROUTE = /^\/v1\/projects\/([^/]+)\/(memory|memory\/files|memory\/search|tasks|tasks\/complete|findings)$/;
22
22
  export const MEMORY_LIMITS = { findings: 500, active: 200, queue: 200, done: 50 };
23
23
  const TAG = new RegExp(`^\\[(${FINDING_TAGS.join("|")})\\]\\s*`, "i");
24
24
  const DATE = /^\d{4}-\d{2}-\d{2}/;
@@ -233,3 +233,27 @@ export async function saveFinding(base, rawProject, input) {
233
233
  .find(item => item.text === (result.data?.finding ?? "").replace(/^-\s+/, "").trim()) : undefined;
234
234
  return { project, status, finding: saved ? finding(saved) : null };
235
235
  }
236
+ // ── POST /tasks/complete ─────────────────────────────────────────────────────
237
+ /** Mark one open task done, by the stable id `/tasks?branch=` gave gitboy when
238
+ * its pull request merged. Exact ids only: no text matching, so a wrong guess
239
+ * can never complete another task. A task already done answers `already-done`. */
240
+ export function completeProjectTask(base, rawProject, input) {
241
+ const { project, root } = locate(base, rawProject);
242
+ if (Buffer.byteLength(JSON.stringify(input ?? null)) > 256)
243
+ throw new BridgeError(413, "The body must be at most 256 bytes.");
244
+ const { id } = taskCompleteSchema.parse(input);
245
+ const doc = readTasks(root, project);
246
+ if (!doc.ok)
247
+ throw new BridgeError(404, "No tasks for this project.");
248
+ const stable = id.slice(4);
249
+ const open = [...doc.data.items.Active, ...doc.data.items.Queue].find(item => item.stableId === stable);
250
+ if (!open) {
251
+ if (doc.data.items.Done.some(item => item.stableId === stable))
252
+ return { project, id, status: "already-done" };
253
+ throw new BridgeError(404, "No task with this id.");
254
+ }
255
+ const done = completeTask(root, project, id);
256
+ if (!done.ok)
257
+ throw new BridgeError(400, safe(done.error));
258
+ return { project, id, status: "completed" };
259
+ }
@@ -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)
@@ -1,6 +1,6 @@
1
1
  import { connect } from "node:net";
2
2
  import { BridgeError } from "./protocol.js";
3
- import { findingWriteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, PROJECT_NAME, } from "./gitboy-contract.js";
3
+ import { findingWriteSchema, taskCompleteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, PROJECT_NAME, } from "./gitboy-contract.js";
4
4
  // A scoped SSH key reaches the Hook through this gateway instead of the full
5
5
  // byte pipe. The key's forced command names the scope
6
6
  // (`sh ~/.local/share/phren/bridge/dispatch-scoped gitboy-read`); the gateway
@@ -51,12 +51,13 @@ const RULES = {
51
51
  } },
52
52
  ],
53
53
  "gitboy-write": [
54
+ { method: "POST", path: new RegExp(`^/v1/projects/${PROJECT}/tasks/complete$`), body: { max: 256, schema: taskCompleteSchema } },
54
55
  { method: "POST", path: new RegExp(`^/v1/projects/${PROJECT}/findings$`), body: { max: MAX_FINDING_BODY, schema: findingWriteSchema } },
55
56
  ],
56
57
  };
57
58
  const DESCRIBE = {
58
59
  "gitboy-read": "GET /v1/projects/<project>/memory, /memory/files, /memory/search and /tasks",
59
- "gitboy-write": "POST /v1/projects/<project>/findings",
60
+ "gitboy-write": "POST /v1/projects/<project>/findings and /tasks/complete",
60
61
  };
61
62
  export function isGatewayScope(value) {
62
63
  return GATEWAY_SCOPES.includes(value);
@@ -27,7 +27,8 @@ import { browseFiles } from "./files.js";
27
27
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
28
28
  import { resolveFilePath } from "./file-resolve.js";
29
29
  import { storeRoute } from "./memory-store.js";
30
- import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding, tasksForBranch } from "./project-memory.js";
30
+ import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding, tasksForBranch, completeProjectTask } from "./project-memory.js";
31
+ import { PROJECT_GIT_ROUTE, projectGit } from "./project-git.js";
31
32
  import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
32
33
  import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
33
34
  import { locateProject } from "./locate.js";
@@ -313,11 +314,11 @@ export function createRouteHandler(ctx) {
313
314
  const memoryRoute = PROJECT_MEMORY_ROUTE.exec(url.pathname);
314
315
  if (memoryRoute) {
315
316
  const [, project, route] = memoryRoute;
316
- if (request.method !== (route === "findings" ? "POST" : "GET"))
317
+ if (request.method !== (route === "findings" || route === "tasks/complete" ? "POST" : "GET"))
317
318
  throw new BridgeError(405, "Unsupported request method.");
318
319
  if (!modules.has("memory"))
319
320
  throw new BridgeError(404, disabledHint("memory"));
320
- if (route === "tasks" && !modules.has("tasks"))
321
+ if ((route === "tasks" || route === "tasks/complete") && !modules.has("tasks"))
321
322
  throw new BridgeError(404, disabledHint("tasks"));
322
323
  if (route === "memory")
323
324
  result = projectMemory(modules.store, project);
@@ -327,9 +328,18 @@ export function createRouteHandler(ctx) {
327
328
  result = memorySearch(modules.store, project, url.searchParams.get("q") ?? "", Number(url.searchParams.get("limit") ?? "5"));
328
329
  else if (route === "tasks")
329
330
  result = tasksForBranch(modules.store, project, url.searchParams.get("branch") ?? "");
331
+ else if (route === "tasks/complete")
332
+ result = completeProjectTask(modules.store, project, await body(request));
330
333
  else
331
334
  result = await saveFinding(modules.store, project, await body(request));
332
335
  }
336
+ else if (PROJECT_GIT_ROUTE.test(url.pathname)) {
337
+ if (request.method !== "GET")
338
+ throw new BridgeError(405, "Unsupported request method.");
339
+ if (!modules.has("git"))
340
+ throw new BridgeError(404, disabledHint("git"));
341
+ result = await projectGit(modules.store, PROJECT_GIT_ROUTE.exec(url.pathname)[1], await journal.recent());
342
+ }
333
343
  else if (url.pathname.startsWith("/v1/store/")) {
334
344
  result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
335
345
  }
@@ -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.43" : "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) => {
@@ -45900,6 +45973,27 @@ function addTask(phrenPath, project, item, opts) {
45900
45973
  });
45901
45974
  return opts?.responsibility !== void 0 ? withTaskGraphLock(opts.graphRoot ?? phrenPath, create) : create();
45902
45975
  }
45976
+ function completeTask(phrenPath, project, match) {
45977
+ const bPath = canonicalTaskFilePath(phrenPath, project);
45978
+ if (!bPath) return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
45979
+ const preCheck = ensureProject(phrenPath, project);
45980
+ if (!preCheck.ok) return forwardErr(preCheck);
45981
+ return withSafeLock(bPath, () => {
45982
+ const parsed = readTasks(phrenPath, project);
45983
+ if (!parsed.ok) return forwardErr(parsed);
45984
+ const found = findItemByMatch(parsed.data, match);
45985
+ if (found.error) return phrenErr(found.error, found.errorCode ?? PhrenError.AMBIGUOUS_MATCH);
45986
+ if (!found.match) return taskItemNotFound(project, match);
45987
+ const [item] = parsed.data.items[found.match.section].splice(found.match.index, 1);
45988
+ item.section = "Done";
45989
+ item.checked = true;
45990
+ if (item.history !== void 0) item.history.push({ at: (/* @__PURE__ */ new Date()).toISOString(), change: `completed${item.claim ? `; released claim by ${item.claim.computer}` : ""}` });
45991
+ item.claim = void 0;
45992
+ parsed.data.items.Done.unshift(item);
45993
+ writeTaskDoc(parsed.data);
45994
+ return phrenOk(`Marked done in ${project}: ${item.line}`);
45995
+ });
45996
+ }
45903
45997
  function updateTask(phrenPath, project, match, updates, graphRoot = phrenPath, expectedRevision) {
45904
45998
  const bPath = canonicalTaskFilePath(phrenPath, project);
45905
45999
  if (!bPath) return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
@@ -50051,6 +50145,10 @@ function recordFor(server, pane, by, session) {
50051
50145
  by
50052
50146
  };
50053
50147
  }
50148
+ function sessionPane(session, s) {
50149
+ const found = objects(s.panes).filter((p) => runsAgent(p) && objects([p.agent_session])[0]?.value === session);
50150
+ return found.length === 1 ? found[0] : void 0;
50151
+ }
50054
50152
  function recordedPane(record4, s) {
50055
50153
  const pane = objects(s.panes).find((p) => p.pane_id === record4.pane);
50056
50154
  if (!pane) return void 0;
@@ -50068,10 +50166,15 @@ function conductorPane(server, s) {
50068
50166
  }
50069
50167
  const record4 = state.conductor;
50070
50168
  if (!record4 || record4.server !== server) return void 0;
50071
- const pane = recordedPane(record4, s);
50169
+ let pane = recordedPane(record4, s);
50072
50170
  if (!pane) {
50073
- await writeRoleState({ ...state, conductor: null });
50074
- return void 0;
50171
+ const adopted = record4.session ? sessionPane(record4.session, s) : void 0;
50172
+ if (!adopted) {
50173
+ await writeRoleState({ ...state, conductor: null });
50174
+ return void 0;
50175
+ }
50176
+ await writeRoleState({ ...state, conductor: { ...recordFor(server, adopted, record4.by, record4.session), since: record4.since } });
50177
+ return adopted;
50075
50178
  }
50076
50179
  const moved = id.safeParse(pane.workspace_id).success && pane.workspace_id !== record4.workspace || id.safeParse(pane.tab_id).success && pane.tab_id !== record4.tab || provider.safeParse(pane.agent).success && pane.agent !== record4.source;
50077
50180
  if (moved) await writeRoleState({ ...state, conductor: {
@@ -56318,7 +56421,7 @@ function isBranchName(value2) {
56318
56421
  function isSearchText(value2) {
56319
56422
  return value2.trim().length > 0 && value2.length <= MAX_SEARCH_QUERY && !/[\x00-\x08\x0b-\x1f\x7f]/.test(value2);
56320
56423
  }
56321
- var PROJECT_NAME2, FINDING_TYPE_VALUES, MAX_FILE_PATHS, MAX_SEARCH_QUERY, MAX_SEARCH_LIMIT, MAX_FINDING_BODY, MAX_FINDING_TEXT, noControls, findingWriteSchema;
56424
+ var PROJECT_NAME2, FINDING_TYPE_VALUES, MAX_FILE_PATHS, MAX_SEARCH_QUERY, MAX_SEARCH_LIMIT, MAX_FINDING_BODY, MAX_FINDING_TEXT, noControls, findingWriteSchema, taskCompleteSchema;
56322
56425
  var init_gitboy_contract = __esm({
56323
56426
  "src/bridge/gitboy-contract.ts"() {
56324
56427
  "use strict";
@@ -56341,6 +56444,7 @@ var init_gitboy_contract = __esm({
56341
56444
  name: external_exports.string().min(1).max(200).refine((value2) => !/[\x00-\x1f\x7f]/.test(value2)).optional()
56342
56445
  }).strict().optional()
56343
56446
  }).strict();
56447
+ taskCompleteSchema = external_exports.object({ id: external_exports.string().regex(/^bid:[0-9a-f]{8}$/) }).strict();
56344
56448
  }
56345
56449
  });
56346
56450
 
@@ -56550,12 +56654,13 @@ var init_scoped_gateway = __esm({
56550
56654
  } }
56551
56655
  ],
56552
56656
  "gitboy-write": [
56657
+ { method: "POST", path: new RegExp(`^/v1/projects/${PROJECT}/tasks/complete$`), body: { max: 256, schema: taskCompleteSchema } },
56553
56658
  { method: "POST", path: new RegExp(`^/v1/projects/${PROJECT}/findings$`), body: { max: MAX_FINDING_BODY, schema: findingWriteSchema } }
56554
56659
  ]
56555
56660
  };
56556
56661
  DESCRIBE = {
56557
56662
  "gitboy-read": "GET /v1/projects/<project>/memory, /memory/files, /memory/search and /tasks",
56558
- "gitboy-write": "POST /v1/projects/<project>/findings"
56663
+ "gitboy-write": "POST /v1/projects/<project>/findings and /tasks/complete"
56559
56664
  };
56560
56665
  refuse = (status, error62) => ({ ok: false, status, error: error62 });
56561
56666
  REASONS = { 400: "Bad Request", 403: "Forbidden", 408: "Request Timeout", 413: "Content Too Large", 415: "Unsupported Media Type", 503: "Service Unavailable" };
@@ -71856,6 +71961,22 @@ async function saveFinding(base, rawProject, input2) {
71856
71961
  const saved = status === "saved" ? sortedFindings(locate(base, rawProject).root, project).find((item) => item.text === (result.data?.finding ?? "").replace(/^-\s+/, "").trim()) : void 0;
71857
71962
  return { project, status, finding: saved ? finding(saved) : null };
71858
71963
  }
71964
+ function completeProjectTask(base, rawProject, input2) {
71965
+ const { project, root } = locate(base, rawProject);
71966
+ if (Buffer.byteLength(JSON.stringify(input2 ?? null)) > 256) throw new BridgeError(413, "The body must be at most 256 bytes.");
71967
+ const { id: id2 } = taskCompleteSchema.parse(input2);
71968
+ const doc = readTasks(root, project);
71969
+ if (!doc.ok) throw new BridgeError(404, "No tasks for this project.");
71970
+ const stable = id2.slice(4);
71971
+ const open30 = [...doc.data.items.Active, ...doc.data.items.Queue].find((item) => item.stableId === stable);
71972
+ if (!open30) {
71973
+ if (doc.data.items.Done.some((item) => item.stableId === stable)) return { project, id: id2, status: "already-done" };
71974
+ throw new BridgeError(404, "No task with this id.");
71975
+ }
71976
+ const done = completeTask(root, project, id2);
71977
+ if (!done.ok) throw new BridgeError(400, safe(done.error));
71978
+ return { project, id: id2, status: "completed" };
71979
+ }
71859
71980
  var PROJECT_MEMORY_ROUTE, MEMORY_LIMITS, TAG, DATE, safe, writes4;
71860
71981
  var init_project_memory = __esm({
71861
71982
  "src/bridge/project-memory.ts"() {
@@ -71873,7 +71994,7 @@ var init_project_memory = __esm({
71873
71994
  init_code_package();
71874
71995
  init_retrieval();
71875
71996
  init_gitboy_contract();
71876
- PROJECT_MEMORY_ROUTE = /^\/v1\/projects\/([^/]+)\/(memory|memory\/files|memory\/search|tasks|findings)$/;
71997
+ PROJECT_MEMORY_ROUTE = /^\/v1\/projects\/([^/]+)\/(memory|memory\/files|memory\/search|tasks|tasks\/complete|findings)$/;
71877
71998
  MEMORY_LIMITS = { findings: 500, active: 200, queue: 200, done: 50 };
71878
71999
  TAG = new RegExp(`^\\[(${FINDING_TAGS.join("|")})\\]\\s*`, "i");
71879
72000
  DATE = /^\d{4}-\d{2}-\d{2}/;
@@ -71882,6 +72003,43 @@ var init_project_memory = __esm({
71882
72003
  }
71883
72004
  });
71884
72005
 
72006
+ // src/bridge/project-git.ts
72007
+ async function projectGit(base, rawProject, activity) {
72008
+ let project;
72009
+ try {
72010
+ project = decodeURIComponent(rawProject);
72011
+ } catch {
72012
+ throw new BridgeError(400, "Invalid project name.");
72013
+ }
72014
+ if (!isValidProjectName(project)) throw new BridgeError(400, "Invalid project name.");
72015
+ const folders = [];
72016
+ try {
72017
+ const source = getProjectSourcePath(resolveProject(base, project).store.path, project);
72018
+ if (source) folders.push(source);
72019
+ } catch {
72020
+ }
72021
+ for (const candidate of await locateProject(project, activity)) folders.push(candidate.directory);
72022
+ for (const folder of folders) {
72023
+ const root = await gitRoot(folder).catch(() => void 0);
72024
+ if (root) return { project, directory: root, ...await gitPulls(root) };
72025
+ }
72026
+ throw new BridgeError(404, "No checkout of this project on this computer.", { code: "no-checkout" });
72027
+ }
72028
+ var PROJECT_GIT_ROUTE;
72029
+ var init_project_git = __esm({
72030
+ "src/bridge/project-git.ts"() {
72031
+ "use strict";
72032
+ init_project_config();
72033
+ init_store_routing();
72034
+ init_utils();
72035
+ init_git();
72036
+ init_locate();
72037
+ init_projects();
72038
+ init_protocol();
72039
+ PROJECT_GIT_ROUTE = /^\/v1\/projects\/([^/]+)\/git$/;
72040
+ }
72041
+ });
72042
+
71885
72043
  // src/bridge/simulators.ts
71886
72044
  import { execFile as execFile30 } from "node:child_process";
71887
72045
  import { chmod as chmod5, mkdir as mkdir34, readFile as readFile54, rename as rename11, stat as stat30, unlink as unlink9, writeFile as writeFile12 } from "node:fs/promises";
@@ -72983,14 +73141,19 @@ function createRouteHandler(ctx) {
72983
73141
  const memoryRoute = PROJECT_MEMORY_ROUTE.exec(url2.pathname);
72984
73142
  if (memoryRoute) {
72985
73143
  const [, project, route2] = memoryRoute;
72986
- if (request9.method !== (route2 === "findings" ? "POST" : "GET")) throw new BridgeError(405, "Unsupported request method.");
73144
+ if (request9.method !== (route2 === "findings" || route2 === "tasks/complete" ? "POST" : "GET")) throw new BridgeError(405, "Unsupported request method.");
72987
73145
  if (!modules.has("memory")) throw new BridgeError(404, disabledHint("memory"));
72988
- if (route2 === "tasks" && !modules.has("tasks")) throw new BridgeError(404, disabledHint("tasks"));
73146
+ if ((route2 === "tasks" || route2 === "tasks/complete") && !modules.has("tasks")) throw new BridgeError(404, disabledHint("tasks"));
72989
73147
  if (route2 === "memory") result = projectMemory(modules.store, project);
72990
73148
  else if (route2 === "memory/files") result = await memoryForFiles(modules.store, project, url2.searchParams.getAll("path"));
72991
73149
  else if (route2 === "memory/search") result = memorySearch(modules.store, project, url2.searchParams.get("q") ?? "", Number(url2.searchParams.get("limit") ?? "5"));
72992
73150
  else if (route2 === "tasks") result = tasksForBranch(modules.store, project, url2.searchParams.get("branch") ?? "");
73151
+ else if (route2 === "tasks/complete") result = completeProjectTask(modules.store, project, await body(request9));
72993
73152
  else result = await saveFinding(modules.store, project, await body(request9));
73153
+ } else if (PROJECT_GIT_ROUTE.test(url2.pathname)) {
73154
+ if (request9.method !== "GET") throw new BridgeError(405, "Unsupported request method.");
73155
+ if (!modules.has("git")) throw new BridgeError(404, disabledHint("git"));
73156
+ result = await projectGit(modules.store, PROJECT_GIT_ROUTE.exec(url2.pathname)[1], await journal.recent());
72994
73157
  } else if (url2.pathname.startsWith("/v1/store/")) {
72995
73158
  result = await storeRoute(modules.store, request9.method ?? "", url2, request9.method === "POST" ? await body(request9) : void 0);
72996
73159
  } else if (request9.method === "GET") {
@@ -73578,6 +73741,7 @@ var init_server_routes = __esm({
73578
73741
  init_file_resolve();
73579
73742
  init_memory_store();
73580
73743
  init_project_memory();
73744
+ init_project_git();
73581
73745
  init_session_activity();
73582
73746
  init_herdr();
73583
73747
  init_locate();
@@ -74639,7 +74803,13 @@ async function serve(version2, options = {}) {
74639
74803
  runsFile: scheduleRunsFile(),
74640
74804
  aliases: [computerID2],
74641
74805
  // A schedule starts in its project's folder, which the Hook resolved itself.
74642
- launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
74806
+ launch: createScheduleLauncher(
74807
+ (server, data) => launchSession(server, data, { trustFolder: true }),
74808
+ scheduleStore,
74809
+ // `session: reuse` continues a session through the same queue a hand-off takes.
74810
+ (target, text5, deliveryId) => handOffs ? handOffs.enqueue({ target, text: text5, deliveryId }) : sendPrompt(target, text5, deliveryId, async () => {
74811
+ })
74812
+ ),
74643
74813
  push: { notify: (value2) => agentHooks.push.notifySchedule(value2) },
74644
74814
  locateProject: async (project) => (await locateProject(project, await journal.recent()))[0]?.directory
74645
74815
  }) : void 0;
@@ -75371,7 +75541,7 @@ async function main() {
75371
75541
  return askpass2(args[1]);
75372
75542
  }
75373
75543
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
75374
- return runBridge2(args, "0.3.41");
75544
+ return runBridge2(args, "0.3.43");
75375
75545
  }
75376
75546
  main().then((code) => {
75377
75547
  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.43",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {