@phren/cli 0.3.46 → 0.3.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/codex-auth-refresh.d.ts +7 -0
- package/dist/bridge/codex-auth-refresh.js +15 -0
- package/dist/bridge/git-write-policy.d.ts +13 -0
- package/dist/bridge/git-write-policy.js +39 -0
- package/dist/bridge/herdr.js +7 -1
- package/dist/bridge/schedule-format.d.ts +4 -1
- package/dist/bridge/schedule-format.js +40 -3
- package/dist/bridge/schedule-update.d.ts +6 -0
- package/dist/bridge/schedule-update.js +63 -0
- package/dist/bridge/schedules.js +16 -4
- package/dist/bridge/server-pane-routes.d.ts +4 -2
- package/dist/bridge/server-pane-routes.js +8 -2
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +24 -6
- package/dist/bridge/session-move.d.ts +75 -2
- package/dist/bridge/session-move.js +80 -26
- package/dist/bridge-hook.mjs +10724 -10407
- package/dist/cli/actions.js +4 -0
- package/dist/mcp/profile.js +23 -4
- package/dist/modules/registry.js +3 -3
- package/dist/task/lifecycle.js +3 -2
- package/package.json +1 -1
|
@@ -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
|
+
}
|
package/dist/bridge/herdr.js
CHANGED
|
@@ -593,14 +593,20 @@ export async function panes(server, workspace, tab) {
|
|
|
593
593
|
if (!objects(s.tabs).some(t => t.tab_id === tab && t.workspace_id === workspace))
|
|
594
594
|
throw new BridgeError(409, "This terminal tab has changed. Refresh the computer.");
|
|
595
595
|
const mux = (await terminal()).terminalMux(server);
|
|
596
|
+
// Loaded lazily: session-move imports this module, and a static import back makes a cycle.
|
|
597
|
+
const { listMoves, moveSessionFields } = await import("./session-move.js");
|
|
598
|
+
const moves = await listMoves();
|
|
596
599
|
return { kind: mux.kind, mux, groupId: workspace, childId: tab, panes: await Promise.all(objects(s.panes)
|
|
597
600
|
.filter(p => p.workspace_id === workspace && p.tab_id === tab).map(async (p) => {
|
|
598
601
|
const chat = await paneChatState(server, p);
|
|
599
602
|
const record = await paneRecord(server, p, typeof chat.sessionId === "string" ? chat.sessionId : undefined);
|
|
600
603
|
const t = objects(s.tabs).find(candidate => candidate.tab_id === tab && candidate.workspace_id === workspace);
|
|
601
604
|
const w = objects(s.workspaces).find(candidate => candidate.workspace_id === workspace);
|
|
605
|
+
const title = await recordTitle(record, { paneLabel: p.label, harnessTitle: p.title || p.terminal_title_stripped, tabLabel: t?.label, workspaceLabel: w?.label, fallbackLabel: p.label || p.pane_id });
|
|
606
|
+
const moveFields = typeof chat.sessionId === "string" && provider.safeParse(p.agent).success
|
|
607
|
+
? moveSessionFields(moves, { server, workspace, tab, pane: String(p.pane_id), source: p.agent, session: chat.sessionId }, title) : {};
|
|
602
608
|
return { id: p.pane_id, label: p.label || p.pane_id, agent: p.agent, agentStatus: p.agent_status,
|
|
603
|
-
title
|
|
609
|
+
title, ...moveFields,
|
|
604
610
|
cwd: p.foreground_cwd || p.cwd, ...chat, ...paneAccountField(server, p) };
|
|
605
611
|
})) };
|
|
606
612
|
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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,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
|
+
}
|
package/dist/bridge/schedules.js
CHANGED
|
@@ -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,
|
|
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 &&
|
|
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
|
|
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 (
|
|
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);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { listMoves, readMove } from "./session-move.js";
|
|
1
|
+
import { listMoves, moveSessionFields, readMove } from "./session-move.js";
|
|
2
2
|
import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
|
|
3
3
|
import { ownerInboxView } from "./owner-inbox-view.js";
|
|
4
4
|
import { closeFinishedWorker, closeOwnPane } from "./worker-close.js";
|
|
@@ -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";
|
|
@@ -79,7 +81,7 @@ async function childActivity(source, session) {
|
|
|
79
81
|
export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
80
82
|
terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
81
83
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
82
|
-
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
|
|
84
|
+
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
|
|
83
85
|
export function capabilitiesForModules(snapshot) {
|
|
84
86
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
85
87
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -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;
|
|
@@ -162,6 +166,8 @@ export function workspacesReader(ctx) {
|
|
|
162
166
|
agents.push(pane);
|
|
163
167
|
agentsByTab.set(key, agents);
|
|
164
168
|
}
|
|
169
|
+
// Move records are decoration: read alongside the rest, inside the budget.
|
|
170
|
+
const movesRead = listMoves().catch(() => []);
|
|
165
171
|
const tabs = objects(workspaces.groups).flatMap(group => objects(group.children).map(tab => ({ group, tab })));
|
|
166
172
|
// What a chat needs to open (the exact conversation) comes straight from the
|
|
167
173
|
// chat states; everything below it is decoration.
|
|
@@ -210,6 +216,12 @@ export function workspacesReader(ctx) {
|
|
|
210
216
|
return;
|
|
211
217
|
Object.assign(tab, stall);
|
|
212
218
|
tab.title = title;
|
|
219
|
+
if (target.success) {
|
|
220
|
+
const moves = await movesRead;
|
|
221
|
+
if (expired)
|
|
222
|
+
return;
|
|
223
|
+
Object.assign(tab, moveSessionFields(moves, target.data, title));
|
|
224
|
+
}
|
|
213
225
|
// What a finished turn said last; a row still working (background work) has no last word yet.
|
|
214
226
|
const reply = tab.agentStatus === "working" ? undefined : replyExcerpt(record);
|
|
215
227
|
if (reply)
|
|
@@ -306,6 +318,8 @@ export function createRouteHandler(ctx) {
|
|
|
306
318
|
const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, resources, launches, locatedDirectories, fanoutMessages, canary } = ctx;
|
|
307
319
|
const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
|
|
308
320
|
const readWorkspaces = workspacesReader(ctx);
|
|
321
|
+
const gitWrites = new GitWriteDiagnostics();
|
|
322
|
+
const paneContext = { ...ctx, gitWrites };
|
|
309
323
|
return async (request, response) => {
|
|
310
324
|
response.setHeader("X-Phren-Protocol", String(PROTOCOL));
|
|
311
325
|
response.setHeader("Cache-Control", "no-store");
|
|
@@ -362,8 +376,9 @@ export function createRouteHandler(ctx) {
|
|
|
362
376
|
result = hookMetrics.snapshot();
|
|
363
377
|
break;
|
|
364
378
|
case "/v1/health/details":
|
|
365
|
-
result = await healthDetails({ hookVersion: version, computerId: computerID, store: scheduleStore,
|
|
366
|
-
|
|
379
|
+
result = { ...await healthDetails({ hookVersion: version, computerId: computerID, store: scheduleStore,
|
|
380
|
+
scheduler: scheduler ? { running: true, lastTickAt: scheduler.lastTickAt } : undefined, push: agentHooks.push.status }),
|
|
381
|
+
gitWrites: gitWrites.snapshot() };
|
|
367
382
|
break;
|
|
368
383
|
case "/v1/health/peers": {
|
|
369
384
|
// A peer's health probe asks whether this computer lists it back.
|
|
@@ -774,6 +789,9 @@ export function createRouteHandler(ctx) {
|
|
|
774
789
|
const runs = await scheduler.launchNow(input.project, input.id, false, input.expectedUpdatedAt);
|
|
775
790
|
result = { ok: runs.every(run => run.status !== "failed"), run: runs[0], runs };
|
|
776
791
|
}
|
|
792
|
+
else if (url.pathname === "/v1/schedules/update") {
|
|
793
|
+
result = await updateScheduleRoute(scheduleStore, data);
|
|
794
|
+
}
|
|
777
795
|
else if (url.pathname === "/v1/schedules/history") {
|
|
778
796
|
const input = z.object({ project: z.string().min(1).max(200).optional(), id: z.string().regex(/^[a-f0-9]{8}$/).optional(),
|
|
779
797
|
limit: z.number().int().min(1).max(500).optional() }).parse(data);
|
|
@@ -934,7 +952,7 @@ export function createRouteHandler(ctx) {
|
|
|
934
952
|
: await workspaceAction(selectedServer(url), operation, data);
|
|
935
953
|
}
|
|
936
954
|
else {
|
|
937
|
-
result = await paneRoute(
|
|
955
|
+
result = await paneRoute(paneContext, url, data, response, request.headers);
|
|
938
956
|
}
|
|
939
957
|
}
|
|
940
958
|
}
|
|
@@ -38,6 +38,10 @@ export declare const moveRequestSchema: z.ZodObject<{
|
|
|
38
38
|
xhigh: "xhigh";
|
|
39
39
|
}>>;
|
|
40
40
|
}, z.core.$strict>;
|
|
41
|
+
mode: z.ZodDefault<z.ZodEnum<{
|
|
42
|
+
"new-chat": "new-chat";
|
|
43
|
+
replace: "replace";
|
|
44
|
+
}>>;
|
|
41
45
|
id: z.ZodOptional<z.ZodString>;
|
|
42
46
|
handoffTimeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
43
47
|
}, z.core.$strict>;
|
|
@@ -48,6 +52,7 @@ declare const moveRecordSchema: z.ZodObject<{
|
|
|
48
52
|
failed: "failed";
|
|
49
53
|
"handing-off": "handing-off";
|
|
50
54
|
launching: "launching";
|
|
55
|
+
linking: "linking";
|
|
51
56
|
moved: "moved";
|
|
52
57
|
}>;
|
|
53
58
|
createdAt: z.ZodString;
|
|
@@ -88,6 +93,57 @@ declare const moveRecordSchema: z.ZodObject<{
|
|
|
88
93
|
xhigh: "xhigh";
|
|
89
94
|
}>>;
|
|
90
95
|
}, z.core.$strict>;
|
|
96
|
+
mode: z.ZodOptional<z.ZodEnum<{
|
|
97
|
+
"new-chat": "new-chat";
|
|
98
|
+
replace: "replace";
|
|
99
|
+
}>>;
|
|
100
|
+
handedOffTo: z.ZodOptional<z.ZodObject<{
|
|
101
|
+
target: z.ZodUnion<readonly [z.ZodObject<{
|
|
102
|
+
server: z.ZodString;
|
|
103
|
+
workspace: z.ZodString;
|
|
104
|
+
tab: z.ZodString;
|
|
105
|
+
pane: z.ZodString;
|
|
106
|
+
source: z.ZodEnum<{
|
|
107
|
+
claude: "claude";
|
|
108
|
+
codex: "codex";
|
|
109
|
+
copilot: "copilot";
|
|
110
|
+
opencode: "opencode";
|
|
111
|
+
phren: "phren";
|
|
112
|
+
}>;
|
|
113
|
+
session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
114
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
115
|
+
server: z.ZodString;
|
|
116
|
+
workspace: z.ZodString;
|
|
117
|
+
tab: z.ZodString;
|
|
118
|
+
pane: z.ZodString;
|
|
119
|
+
source: z.ZodEnum<{
|
|
120
|
+
claude: "claude";
|
|
121
|
+
codex: "codex";
|
|
122
|
+
copilot: "copilot";
|
|
123
|
+
opencode: "opencode";
|
|
124
|
+
phren: "phren";
|
|
125
|
+
}>;
|
|
126
|
+
starting: z.ZodLiteral<true>;
|
|
127
|
+
startingToken: z.ZodString;
|
|
128
|
+
}, z.core.$strip>]>;
|
|
129
|
+
}, z.core.$strict>>;
|
|
130
|
+
handedOffFrom: z.ZodOptional<z.ZodObject<{
|
|
131
|
+
target: z.ZodObject<{
|
|
132
|
+
server: z.ZodString;
|
|
133
|
+
workspace: z.ZodString;
|
|
134
|
+
tab: z.ZodString;
|
|
135
|
+
pane: z.ZodString;
|
|
136
|
+
source: z.ZodEnum<{
|
|
137
|
+
claude: "claude";
|
|
138
|
+
codex: "codex";
|
|
139
|
+
copilot: "copilot";
|
|
140
|
+
opencode: "opencode";
|
|
141
|
+
phren: "phren";
|
|
142
|
+
}>;
|
|
143
|
+
session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
144
|
+
}, z.core.$strip>;
|
|
145
|
+
title: z.ZodString;
|
|
146
|
+
}, z.core.$strict>>;
|
|
91
147
|
cwd: z.ZodString;
|
|
92
148
|
dispatch: z.ZodOptional<z.ZodString>;
|
|
93
149
|
handoff: z.ZodOptional<z.ZodObject<{
|
|
@@ -136,6 +192,21 @@ declare const moveRecordSchema: z.ZodObject<{
|
|
|
136
192
|
starting: z.ZodLiteral<true>;
|
|
137
193
|
startingToken: z.ZodString;
|
|
138
194
|
}, z.core.$strip>]>>;
|
|
195
|
+
paneTarget: z.ZodOptional<z.ZodObject<{
|
|
196
|
+
server: z.ZodString;
|
|
197
|
+
workspace: z.ZodString;
|
|
198
|
+
tab: z.ZodString;
|
|
199
|
+
pane: z.ZodString;
|
|
200
|
+
source: z.ZodEnum<{
|
|
201
|
+
claude: "claude";
|
|
202
|
+
codex: "codex";
|
|
203
|
+
copilot: "copilot";
|
|
204
|
+
opencode: "opencode";
|
|
205
|
+
phren: "phren";
|
|
206
|
+
}>;
|
|
207
|
+
}, z.core.$strip>>;
|
|
208
|
+
linkPending: z.ZodOptional<z.ZodBoolean>;
|
|
209
|
+
notice: z.ZodOptional<z.ZodString>;
|
|
139
210
|
movedAt: z.ZodOptional<z.ZodString>;
|
|
140
211
|
error: z.ZodOptional<z.ZodString>;
|
|
141
212
|
}, z.core.$strict>;
|
|
@@ -166,6 +237,8 @@ export declare function moveFrom(records: readonly MoveRecord[], target: {
|
|
|
166
237
|
source: string;
|
|
167
238
|
session?: string;
|
|
168
239
|
}): MoveRecord | undefined;
|
|
240
|
+
/** Conversation-bound annotations shared by tab and pane overview rows. */
|
|
241
|
+
export declare function moveSessionFields(records: readonly MoveRecord[], target: Target, title?: string): Json;
|
|
169
242
|
/** The receipt fields for a finished move. */
|
|
170
243
|
export declare function movedWorker(record: MoveRecord): MovedWorker | undefined;
|
|
171
244
|
/** A harness as people name it, with its account and model: "Claude (work, opus)". */
|
|
@@ -176,7 +249,7 @@ export declare function harnessName(to: {
|
|
|
176
249
|
effort?: string;
|
|
177
250
|
}): string;
|
|
178
251
|
/** What the moving agent is asked to write. */
|
|
179
|
-
export declare function handoffRequest(id: string, to: MoveTo): string;
|
|
252
|
+
export declare function handoffRequest(id: string, to: MoveTo, mode?: "replace" | "new-chat"): string;
|
|
180
253
|
/** The hand-off between the markers in the agent's replies after the request,
|
|
181
254
|
* or undefined while its end marker has not arrived. Code fences around the
|
|
182
255
|
* block are dropped. */
|
|
@@ -281,7 +354,7 @@ export declare class SessionMover {
|
|
|
281
354
|
private exit;
|
|
282
355
|
/** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
|
|
283
356
|
private relaunch;
|
|
284
|
-
/**
|
|
357
|
+
/** New chats remain open as linking while the harness establishes its conversation. */
|
|
285
358
|
private newTarget;
|
|
286
359
|
}
|
|
287
360
|
/** The last `bytes` of a transcript as lines, the first (cut) one dropped. */
|