@phren/cli 0.3.46 → 0.3.47

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.
@@ -14,6 +14,13 @@ export declare const REFRESH_AFTER_MS: number;
14
14
  /** The sign-in's last refresh, or undefined when auth.json holds no ChatGPT
15
15
  * sign-in (an API key, no file) and there is nothing to refresh. */
16
16
  export declare function lastCodexRefresh(file?: string): Promise<number | undefined>;
17
+ /** A doctor line for the ChatGPT sign-in Codex shares on this computer, or undefined when there is none
18
+ * to judge (no Codex, or an API key). A refresh token that has gone unused for over 9 days has expired
19
+ * server-side, and every `codex exec` and Hook-run worker then fails with a 401 until `codex login`. */
20
+ export declare function codexSignInCheck(file?: string, now?: number): Promise<{
21
+ ok: boolean;
22
+ message: string;
23
+ } | undefined>;
17
24
  export declare function codexAuthRefreshEnabled(env?: NodeJS.ProcessEnv): boolean;
18
25
  export interface CodexAuthRefresher {
19
26
  /** One proactive refresh through Codex's own flow (`account/read` with
@@ -31,6 +31,21 @@ export async function lastCodexRefresh(file = path.join(codexHome(), "auth.json"
31
31
  return undefined;
32
32
  }
33
33
  }
34
+ /** Codex's own refresh threshold; a sign-in refreshed longer ago than this plus a day has not been kept alive. */
35
+ const CODEX_SIGNIN_STALE_MS = 9 * 86_400_000;
36
+ /** A doctor line for the ChatGPT sign-in Codex shares on this computer, or undefined when there is none
37
+ * to judge (no Codex, or an API key). A refresh token that has gone unused for over 9 days has expired
38
+ * server-side, and every `codex exec` and Hook-run worker then fails with a 401 until `codex login`. */
39
+ export async function codexSignInCheck(file, now = Date.now()) {
40
+ const at = await lastCodexRefresh(file);
41
+ if (at === undefined)
42
+ return undefined;
43
+ const days = Math.floor((now - at) / 86_400_000);
44
+ if (at === 0 || now - at > CODEX_SIGNIN_STALE_MS) {
45
+ return { ok: false, message: `Codex sign-in was last refreshed ${at === 0 ? "at an unknown time" : `${days} days ago`} and has probably expired (run: codex login)` };
46
+ }
47
+ return { ok: true, message: `Codex sign-in refreshed ${days === 0 ? "today" : `${days} day${days === 1 ? "" : "s"} ago`}` };
48
+ }
34
49
  export function codexAuthRefreshEnabled(env = process.env) {
35
50
  return !/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_AUTH_REFRESH ?? "");
36
51
  }
@@ -0,0 +1,13 @@
1
+ import type { IncomingHttpHeaders } from "node:http";
2
+ export declare const EXPECTED_REPOSITORY_REQUIRED = false;
3
+ export declare const isGitWriteRoute: (route: string) => boolean;
4
+ /** Per Hook run, bounded client counts and one warning per client and route. */
5
+ export declare class GitWriteDiagnostics {
6
+ private readonly clients;
7
+ record(route: string, headers: IncomingHttpHeaders): void;
8
+ snapshot(): {
9
+ client: string;
10
+ count: number;
11
+ warning: string;
12
+ }[];
13
+ }
@@ -0,0 +1,39 @@
1
+ // Require this no earlier than the first Hook release on or after 2026-11-15,
2
+ // once the warning counts show no older clients (owner-approved 2026-10-14).
3
+ export const EXPECTED_REPOSITORY_REQUIRED = false;
4
+ const WRITE_ROUTES = new Set(["stage", "unstage", "discard", "commit", "push", "pr", "pr/merge", "host-token", "checkout", "fetch", "pull", "apply"]
5
+ .map(action => `/v1/git/${action}`));
6
+ export const isGitWriteRoute = (route) => WRITE_ROUTES.has(route);
7
+ /** Request metadata is a diagnostic hint, never an authentication identity.
8
+ * The raw SSH byte pipe does not expose the paired key's label to the Hook. */
9
+ function clientIdentity(headers) {
10
+ const clean = (value) => (Array.isArray(value) ? value.join(", ") : value ?? "")
11
+ .replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200);
12
+ const client = clean(headers["x-phren-client"]);
13
+ const version = clean(headers["x-phren-app-version"] || headers["x-phren-client-version"]);
14
+ const agent = clean(headers["user-agent"]);
15
+ return [client, version, agent].filter(Boolean).join(" / ") || "unknown client";
16
+ }
17
+ /** Per Hook run, bounded client counts and one warning per client and route. */
18
+ export class GitWriteDiagnostics {
19
+ clients = new Map();
20
+ record(route, headers) {
21
+ let client = clientIdentity(headers);
22
+ if (!this.clients.has(client) && this.clients.size >= 128)
23
+ client = "other clients";
24
+ let entry = this.clients.get(client);
25
+ if (!entry) {
26
+ entry = { count: 0, routes: new Set() };
27
+ this.clients.set(client, entry);
28
+ }
29
+ entry.count++;
30
+ if (!entry.routes.has(route)) {
31
+ entry.routes.add(route);
32
+ console.warn(`[phren-hook] ${route}: git write without expectedRepository from ${client}; update the app before the compatibility window ends.`);
33
+ }
34
+ }
35
+ snapshot() {
36
+ return [...this.clients].map(([client, entry]) => ({ client, count: entry.count,
37
+ warning: `${entry.count} git writes without expectedRepository from ${client}` }));
38
+ }
39
+ }
@@ -114,11 +114,14 @@ export declare const runningStatuses: Set<"blocked" | "failed" | "finished" | "l
114
114
  export declare function intervalMilliseconds(value: string): number;
115
115
  export declare function parseSchedule(value: unknown): Schedule;
116
116
  export declare function readScheduleDocument(projectDir: string): Promise<ScheduleDocument>;
117
+ /** Synchronous I/O for writers sharing a lock with synchronous store routes. */
118
+ export declare function readScheduleDocumentSync(projectDir: string): ScheduleDocument;
117
119
  /** Hold `<project>/schedules.yaml.lock` (one holder per file, in this process and
118
120
  * across processes) for one read, check and write, so two edits never
119
121
  * overwrite each other. */
120
- export declare function withScheduleLock<T>(projectDir: string, work: () => Promise<T>): Promise<T>;
122
+ export declare function withScheduleLock<T>(projectDir: string, work: () => T | Promise<T>): Promise<T>;
121
123
  export declare function writeScheduleDocument(projectDir: string, schedules: Schedule[], original?: Record<string, unknown>): Promise<void>;
124
+ export declare function writeScheduleDocumentSync(projectDir: string, schedules: Schedule[], original?: Record<string, unknown>): void;
122
125
  export declare function canonicalComputer(value: string): string;
123
126
  export declare function computerMatches(wanted: string, current: string): boolean;
124
127
  export declare function scheduleNotifications(schedule: Schedule): Set<ScheduleNotify>;
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
4
  import path from "node:path";
4
5
  import * as yaml from "js-yaml";
5
6
  import { z } from "zod";
@@ -103,6 +104,22 @@ export async function readScheduleDocument(projectDir) {
103
104
  return { document: { version: 1 }, schedules: [] };
104
105
  throw error;
105
106
  }
107
+ return parseScheduleDocument(text);
108
+ }
109
+ /** Synchronous I/O for writers sharing a lock with synchronous store routes. */
110
+ export function readScheduleDocumentSync(projectDir) {
111
+ let text;
112
+ try {
113
+ text = readFileSync(schedulePath(projectDir), "utf8");
114
+ }
115
+ catch (error) {
116
+ if (error.code === "ENOENT")
117
+ return { document: { version: 1 }, schedules: [] };
118
+ throw error;
119
+ }
120
+ return parseScheduleDocument(text);
121
+ }
122
+ function parseScheduleDocument(text) {
106
123
  const document = object(yaml.load(text, { schema: yaml.CORE_SCHEMA }));
107
124
  if (document.version !== 1)
108
125
  throw new Error("schedules.yaml must have version: 1.");
@@ -133,7 +150,10 @@ export async function withScheduleLock(projectDir, work) {
133
150
  release = tryFileLock(file);
134
151
  }
135
152
  try {
136
- return await work();
153
+ const result = work();
154
+ // A synchronous writer must release before yielding: a store route
155
+ // waiting synchronously on this lock otherwise stalls its owner too.
156
+ return result instanceof Promise ? await result : result;
137
157
  }
138
158
  finally {
139
159
  release();
@@ -149,11 +169,28 @@ export async function withScheduleLock(projectDir, work) {
149
169
  }
150
170
  }
151
171
  export async function writeScheduleDocument(projectDir, schedules, original = { version: 1 }) {
172
+ await atomicInPrivateDir(schedulePath(projectDir), serializeScheduleDocument(schedules, original));
173
+ }
174
+ export function writeScheduleDocumentSync(projectDir, schedules, original = { version: 1 }) {
175
+ const text = serializeScheduleDocument(schedules, original), file = schedulePath(projectDir);
176
+ mkdirSync(projectDir, { recursive: true, mode: 0o700 });
177
+ const temporary = `${file}.${randomBytes(8).toString("hex")}.tmp`;
178
+ try {
179
+ writeFileSync(temporary, text, { mode: 0o600, flag: "wx" });
180
+ renameSync(temporary, file);
181
+ }
182
+ finally {
183
+ try {
184
+ unlinkSync(temporary);
185
+ }
186
+ catch { /* already renamed or not created */ }
187
+ }
188
+ }
189
+ function serializeScheduleDocument(schedules, original) {
152
190
  if (schedules.length > MAX_SCHEDULES)
153
191
  throw new Error(`A project can have at most ${MAX_SCHEDULES} schedules.`);
154
192
  schedules.forEach(parseSchedule);
155
- const text = yaml.dump({ ...original, version: 1, schedules }, { lineWidth: 1000, noRefs: true, sortKeys: false });
156
- await atomicInPrivateDir(schedulePath(projectDir), text);
193
+ return yaml.dump({ ...original, version: 1, schedules }, { lineWidth: 1000, noRefs: true, sortKeys: false });
157
194
  }
158
195
  export function canonicalComputer(value) {
159
196
  const normalized = value.trim().toLowerCase();
@@ -0,0 +1,6 @@
1
+ import { type Schedule } from "./schedule-format.js";
2
+ /** Merge only client edits into a fresh document under the CLI writers' lock. */
3
+ export declare function updateScheduleRoute(store: string, body: unknown): Promise<{
4
+ ok: true;
5
+ schedule: Schedule;
6
+ }>;
@@ -0,0 +1,63 @@
1
+ import path from "node:path";
2
+ import { z } from "zod";
3
+ import { getProjectDirs } from "../shared.js";
4
+ import { BridgeError } from "./protocol.js";
5
+ import { SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_NOTIFY, SCHEDULE_SESSIONS, WEEKDAYS, parseSchedule, readScheduleDocumentSync, withScheduleLock, writeScheduleDocumentSync, } from "./schedule-format.js";
6
+ const optional = (schema) => schema.nullable().optional();
7
+ const updateSchema = z.object({
8
+ project: z.string().min(1).max(200),
9
+ id: z.string().regex(/^[a-f0-9]{8}$/),
10
+ expectedUpdatedAt: z.string().datetime({ offset: true }),
11
+ changes: z.object({
12
+ name: z.string().optional(), prompt: z.string().optional(), enabled: z.boolean().optional(),
13
+ computer: z.string().optional(), harness: z.enum(SCHEDULE_HARNESSES).optional(),
14
+ every: z.enum(SCHEDULE_EVERY).optional(),
15
+ model: optional(z.string()), account: optional(z.string()),
16
+ notify: optional(z.array(z.enum(SCHEDULE_NOTIFY))), projects: optional(z.array(z.string())),
17
+ session: optional(z.enum(SCHEDULE_SESSIONS)), at: optional(z.string()),
18
+ days: optional(z.array(z.enum(WEEKDAYS))), interval: optional(z.string()),
19
+ once: optional(z.string()), cron: optional(z.string()),
20
+ }).strict(),
21
+ }).strict();
22
+ /** Merge only client edits into a fresh document under the CLI writers' lock. */
23
+ export async function updateScheduleRoute(store, body) {
24
+ let input;
25
+ try {
26
+ input = updateSchema.parse(body);
27
+ }
28
+ catch (error) {
29
+ throw new BridgeError(400, error instanceof Error ? error.message : "Invalid schedule update.");
30
+ }
31
+ const directory = getProjectDirs(store).find(dir => path.basename(dir).toLowerCase() === input.project.toLowerCase());
32
+ if (!directory)
33
+ throw new BridgeError(404, `Unknown project "${input.project}".`);
34
+ return withScheduleLock(directory, () => {
35
+ const file = readScheduleDocumentSync(directory);
36
+ // Keep raw siblings too: parsing can normalize duplicate days/notifications.
37
+ const schedules = file.document.schedules ?? [];
38
+ const index = schedules.findIndex(schedule => schedule.id === input.id);
39
+ if (index < 0)
40
+ throw new BridgeError(404, `Schedule "${input.id}" was not found in ${input.project}.`);
41
+ const current = schedules[index];
42
+ if (current.updatedAt !== input.expectedUpdatedAt) {
43
+ throw new BridgeError(409, "This schedule changed. Refresh it and try again.", { schedule: current });
44
+ }
45
+ const updated = { ...current };
46
+ for (const [key, value] of Object.entries(input.changes)) {
47
+ if (value === null)
48
+ delete updated[key];
49
+ else
50
+ updated[key] = value;
51
+ }
52
+ try {
53
+ parseSchedule(updated);
54
+ }
55
+ catch (error) {
56
+ throw new BridgeError(400, error instanceof Error ? error.message : "Invalid schedule.");
57
+ }
58
+ updated.updatedAt = new Date(Math.max(Date.now(), Date.parse(current.updatedAt) + 1)).toISOString();
59
+ schedules[index] = updated;
60
+ writeScheduleDocumentSync(directory, schedules, file.document);
61
+ return { ok: true, schedule: updated };
62
+ });
63
+ }
@@ -6,7 +6,7 @@ import { BridgeError } from "./protocol.js";
6
6
  import { scheduleProblems } from "./schedule-problems.js";
7
7
  import { getProjectSourcePath } from "../project-config.js";
8
8
  import { getProjectDirs } from "../shared.js";
9
- import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunches, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
9
+ import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunches, runningStatuses, scheduleNotifications, scheduleSessionRoute, readScheduleDocumentSync, withScheduleLock, writeScheduleDocumentSync, writeScheduleRuns, } from "./schedule-format.js";
10
10
  export * from "./schedule-format.js";
11
11
  export * from "./schedule-launch.js";
12
12
  export * from "./schedule-watch.js";
@@ -137,7 +137,7 @@ export class Scheduler {
137
137
  const file = await readScheduleDocument(projectDir), schedule = file.schedules.find(item => item.id === id);
138
138
  if (!schedule)
139
139
  throw new BridgeError(404, `Schedule "${id}" was not found in ${project}.`);
140
- if (expectedUpdatedAt !== undefined && Date.parse(expectedUpdatedAt) !== Date.parse(schedule.updatedAt)) {
140
+ if (expectedUpdatedAt !== undefined && expectedUpdatedAt !== schedule.updatedAt) {
141
141
  throw new BridgeError(409, "This computer has a different schedule revision. Wait for store sync to finish, refresh the schedule, and try Run now again.");
142
142
  }
143
143
  if (!this.owns(schedule))
@@ -174,9 +174,21 @@ export class Scheduler {
174
174
  for (const child of children)
175
175
  this.own.add(child.run.id);
176
176
  if (schedule.every === "once" && schedule.enabled) {
177
- const schedules = file.schedules.map(item => item.id === id ? { ...item, enabled: false, updatedAt: startedAt } : item);
178
177
  try {
179
- await writeScheduleDocument(projectDir, schedules, file.document);
178
+ await withScheduleLock(projectDir, () => {
179
+ const current = readScheduleDocumentSync(projectDir);
180
+ const schedules = current.document.schedules ?? [];
181
+ const index = schedules.findIndex(item => item.id === id);
182
+ if (index < 0)
183
+ return; // A concurrent removal must stay removed.
184
+ const occurrence = schedules[index];
185
+ // Consume only the revision that fired, never an edited or rescheduled row.
186
+ if (occurrence.every !== "once" || occurrence.once !== schedule.once || occurrence.updatedAt !== schedule.updatedAt)
187
+ return;
188
+ schedules[index] = { ...schedules[index], enabled: false,
189
+ updatedAt: new Date(Math.max(this.now().getTime(), Date.parse(schedules[index].updatedAt) + 1)).toISOString() };
190
+ writeScheduleDocumentSync(projectDir, schedules, current.document);
191
+ });
180
192
  }
181
193
  catch (error) {
182
194
  // The durable batch already consumes the occurrence. A YAML write
@@ -1,4 +1,5 @@
1
- import type { ServerResponse } from "node:http";
1
+ import type { IncomingHttpHeaders, ServerResponse } from "node:http";
2
+ import { type GitWriteDiagnostics } from "./git-write-policy.js";
2
3
  import type { AgentHooks } from "./agent-hooks.js";
3
4
  import { type WorktreeWorker } from "./git-worktrees.js";
4
5
  import { type ModelSwitcher } from "./model-switch.js";
@@ -11,6 +12,7 @@ import { type SideQuestions } from "./side-questions.js";
11
12
  * secrets, uploads, diffs, git, approvals and questions. A starting pane (no
12
13
  * conversation yet) takes keys, a secret or a first prompt. */
13
14
  export interface PaneRouteContext {
15
+ gitWrites?: GitWriteDiagnostics;
14
16
  agentHooks: AgentHooks;
15
17
  modelSwitcher: ModelSwitcher;
16
18
  settingsSwitcher: SettingsSwitcher;
@@ -37,5 +39,5 @@ export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
37
39
  * press Enter once. A closed or replaced pane, a delivery the conversation
38
40
  * took, or ten minutes end the watch; a pane asking for input is never answered. */
39
41
  export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, intervalMs?: number): void;
40
- export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse): Promise<unknown>;
42
+ export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, headers?: IncomingHttpHeaders): Promise<unknown>;
41
43
  export declare function paneRouteOnce(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, typing: () => void | Promise<void>): Promise<unknown>;
@@ -1,3 +1,4 @@
1
+ import { EXPECTED_REPOSITORY_REQUIRED, isGitWriteRoute } from "./git-write-policy.js";
1
2
  import path from "node:path";
2
3
  import { setTimeout as sleep } from "node:timers/promises";
3
4
  import { z } from "zod";
@@ -266,7 +267,12 @@ function deliveryReply(agentHooks, id, target, text) {
266
267
  return { ok: status.state !== "failed", state: status.state, ...(status.state === "delivered" ? { delivered: true } : {}),
267
268
  ...(status.state === "queued" ? { queued: true } : {}), ...(status.reason ? { reason: status.reason } : {}) };
268
269
  }
269
- export async function paneRoute(ctx, url, data, response) {
270
+ export async function paneRoute(ctx, url, data, response, headers = {}) {
271
+ if (isGitWriteRoute(url.pathname) && data.expectedRepository === undefined) {
272
+ ctx.gitWrites?.record(url.pathname, headers);
273
+ if (EXPECTED_REPOSITORY_REQUIRED)
274
+ throw new BridgeError(400, "This app is too old to change Git safely. Update it.", { code: "expected-repository-required" });
275
+ }
270
276
  if (["/v1/diff", "/v1/git/status", "/v1/git/worktrees"].includes(url.pathname)) {
271
277
  return withGitReadDeadline(() => paneRouteOnce(ctx, url, data, response, () => { }));
272
278
  }
@@ -684,7 +690,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
684
690
  // Git routes read the pane's repository, or a spawned child's own
685
691
  // worktree, exactly as /v1/diff resolves it.
686
692
  let cwd = await gitRepository(pane, target, data.child, data.worktree);
687
- if (["stage", "unstage", "discard", "commit", "push", "pr", "pr/merge", "host-token", "checkout", "fetch", "pull", "apply"].some(action => url.pathname === `/v1/git/${action}`)
693
+ if (isGitWriteRoute(url.pathname)
688
694
  && data.expectedRepository !== undefined) {
689
695
  const expected = z.string().min(1).max(4096).refine(value => path.isAbsolute(value) && !value.includes("\0"), "Expected an absolute repository path.").parse(data.expectedRepository);
690
696
  const root = await gitRoot(cwd);
@@ -40,6 +40,7 @@ import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript,
40
40
  import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
41
41
  import { currentModel, currentStep } from "./steps.js";
42
42
  import { capacityRoom, usageForCaller } from "./usage.js";
43
+ import { updateScheduleRoute } from "./schedule-update.js";
43
44
  import { readFinalTurn } from "./schedule-watch.js";
44
45
  import { cachedStoreWarnings, healthDetails, listsCaller } from "./health.js";
45
46
  import { defaultPhrenPath } from "../shared.js";
@@ -50,6 +51,7 @@ import { launchSession, makeConductor, stopConductor, workspaceAction } from "./
50
51
  import { conductorAnswer, linkSetMember, nameSet, readSets } from "./conductor-sets.js";
51
52
  import { conductorPane } from "./conductor-role.js";
52
53
  import { hookMetrics } from "./metrics.js";
54
+ import { GitWriteDiagnostics } from "./git-write-policy.js";
53
55
  import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
54
56
  import { readSpeechKey } from "./speech-key.js";
55
57
  import { DEFAULT_SPEECH_VOICE, listSpeechVoices, resolveSpeechVoice } from "./speech-voice.js";
@@ -88,8 +90,10 @@ export function capabilitiesForModules(snapshot) {
88
90
  result[name] = true;
89
91
  if (snapshot.has("hook"))
90
92
  result.approvalRules = { version: 2, effects: ["always-ask", "deny"], harnesses: ["claude"], events: ["PermissionRequest"], tools: ["Bash"], inputField: "command", conductorTools: false, mcpTools: false, preExecution: false };
91
- if (snapshot.has("schedules"))
93
+ if (snapshot.has("schedules")) {
92
94
  result.scheduleProjects = true;
95
+ result.scheduleUpdate = true;
96
+ }
93
97
  if (snapshot.has("tasks")) {
94
98
  result.taskDependencies = true;
95
99
  result.taskWriterSafety = true;
@@ -306,6 +310,8 @@ export function createRouteHandler(ctx) {
306
310
  const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, resources, launches, locatedDirectories, fanoutMessages, canary } = ctx;
307
311
  const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
308
312
  const readWorkspaces = workspacesReader(ctx);
313
+ const gitWrites = new GitWriteDiagnostics();
314
+ const paneContext = { ...ctx, gitWrites };
309
315
  return async (request, response) => {
310
316
  response.setHeader("X-Phren-Protocol", String(PROTOCOL));
311
317
  response.setHeader("Cache-Control", "no-store");
@@ -362,8 +368,9 @@ export function createRouteHandler(ctx) {
362
368
  result = hookMetrics.snapshot();
363
369
  break;
364
370
  case "/v1/health/details":
365
- result = await healthDetails({ hookVersion: version, computerId: computerID, store: scheduleStore,
366
- scheduler: scheduler ? { running: true, lastTickAt: scheduler.lastTickAt } : undefined, push: agentHooks.push.status });
371
+ result = { ...await healthDetails({ hookVersion: version, computerId: computerID, store: scheduleStore,
372
+ scheduler: scheduler ? { running: true, lastTickAt: scheduler.lastTickAt } : undefined, push: agentHooks.push.status }),
373
+ gitWrites: gitWrites.snapshot() };
367
374
  break;
368
375
  case "/v1/health/peers": {
369
376
  // A peer's health probe asks whether this computer lists it back.
@@ -774,6 +781,9 @@ export function createRouteHandler(ctx) {
774
781
  const runs = await scheduler.launchNow(input.project, input.id, false, input.expectedUpdatedAt);
775
782
  result = { ok: runs.every(run => run.status !== "failed"), run: runs[0], runs };
776
783
  }
784
+ else if (url.pathname === "/v1/schedules/update") {
785
+ result = await updateScheduleRoute(scheduleStore, data);
786
+ }
777
787
  else if (url.pathname === "/v1/schedules/history") {
778
788
  const input = z.object({ project: z.string().min(1).max(200).optional(), id: z.string().regex(/^[a-f0-9]{8}$/).optional(),
779
789
  limit: z.number().int().min(1).max(500).optional() }).parse(data);
@@ -934,7 +944,7 @@ export function createRouteHandler(ctx) {
934
944
  : await workspaceAction(selectedServer(url), operation, data);
935
945
  }
936
946
  else {
937
- result = await paneRoute(ctx, url, data, response);
947
+ result = await paneRoute(paneContext, url, data, response, request.headers);
938
948
  }
939
949
  }
940
950
  }