@phren/cli 0.3.45 → 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.
- package/dist/bridge/agent-hook-asks.d.ts +34 -0
- package/dist/bridge/agent-hook-asks.js +72 -0
- package/dist/bridge/agent-hook-callback.d.ts +22 -0
- package/dist/bridge/agent-hook-callback.js +114 -0
- package/dist/bridge/agent-hooks.d.ts +7 -74
- package/dist/bridge/agent-hooks.js +22 -186
- package/dist/bridge/claude-question-dialog.d.ts +6 -0
- package/dist/bridge/claude-question-dialog.js +29 -7
- package/dist/bridge/codex-app-server.d.ts +5 -0
- package/dist/bridge/codex-app-server.js +15 -0
- package/dist/bridge/codex-auth-refresh.d.ts +7 -0
- package/dist/bridge/codex-auth-refresh.js +22 -0
- package/dist/bridge/dispatch-command.js +7 -1
- package/dist/bridge/file-write.js +3 -1
- package/dist/bridge/git-host-auth.d.ts +6 -0
- package/dist/bridge/git-host-auth.js +45 -0
- package/dist/bridge/git-publish.d.ts +1 -1
- package/dist/bridge/git-publish.js +75 -8
- package/dist/bridge/git-review.js +23 -2
- package/dist/bridge/git-write-policy.d.ts +13 -0
- package/dist/bridge/git-write-policy.js +39 -0
- package/dist/bridge/git.d.ts +5 -1
- package/dist/bridge/git.js +103 -8
- package/dist/bridge/health.d.ts +1 -0
- package/dist/bridge/health.js +8 -5
- package/dist/bridge/lookup-cache.d.ts +17 -0
- package/dist/bridge/lookup-cache.js +70 -0
- package/dist/bridge/memory-store.js +40 -14
- package/dist/bridge/pair.js +4 -0
- package/dist/bridge/peers.js +36 -0
- package/dist/bridge/projects.d.ts +14 -0
- package/dist/bridge/projects.js +48 -1
- package/dist/bridge/prompt-deliveries.d.ts +38 -3
- package/dist/bridge/prompt-deliveries.js +196 -36
- package/dist/bridge/schedule-format.d.ts +7 -0
- package/dist/bridge/schedule-format.js +73 -2
- package/dist/bridge/schedule-problems.js +4 -0
- 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/scoped-gateway.d.ts +1 -0
- package/dist/bridge/scoped-gateway.js +10 -1
- package/dist/bridge/server-launch.js +6 -2
- package/dist/bridge/server-pane-routes.d.ts +4 -2
- package/dist/bridge/server-pane-routes.js +8 -2
- package/dist/bridge/server-routes.js +14 -4
- package/dist/bridge/session-servers.js +3 -0
- package/dist/bridge/{codex-thread-origin.d.ts → thread-origin.d.ts} +8 -0
- package/dist/bridge/{codex-thread-origin.js → thread-origin.js} +24 -6
- package/dist/bridge/usage.d.ts +4 -0
- package/dist/bridge/usage.js +22 -8
- package/dist/bridge-hook.mjs +1420 -553
- package/dist/cli/actions.js +4 -0
- package/dist/cli/namespaces-tasks.js +19 -5
- package/dist/cli/ops.d.ts +1 -1
- package/dist/cli/ops.js +2 -2
- package/dist/cli/schedules.js +16 -9
- package/dist/content/summarize.js +46 -6
- package/dist/content/validate.d.ts +3 -1
- package/dist/content/validate.js +33 -4
- package/dist/data/access.d.ts +8 -1
- package/dist/data/access.js +27 -9
- package/dist/data/notes.d.ts +2 -0
- package/dist/data/notes.js +2 -1
- package/dist/entrypoint.js +2 -1
- package/dist/generated/memory-ui-graph.browser.js +1 -1
- package/dist/governance/locks.js +17 -1
- package/dist/governance/policy.js +37 -23
- package/dist/mcp/profile.js +23 -4
- package/dist/memory-ui-graph.runtime.js +1 -1
- package/dist/modules/registry.js +2 -2
- package/dist/sync/conflict-resolve.d.ts +1 -1
- package/dist/sync/conflict-resolve.js +91 -8
- package/dist/task/lifecycle.js +5 -3
- package/package.json +1 -1
|
@@ -13,6 +13,10 @@ import { canonicalComputer } from "./schedule-format.js";
|
|
|
13
13
|
*/
|
|
14
14
|
export async function scheduleProblems(schedule, project, options) {
|
|
15
15
|
const problems = [];
|
|
16
|
+
// A heredoc slip once saved the prompt ">" and the schedule fired an empty brief every hour.
|
|
17
|
+
if ((schedule.prompt.match(/[\p{L}\p{N}]/gu) ?? []).length < 3) {
|
|
18
|
+
problems.push("The prompt has no words in it, so every run would start with an empty brief. Set a prompt with --prompt or --prompt-file.");
|
|
19
|
+
}
|
|
16
20
|
const machines = listMachines(options.store);
|
|
17
21
|
if (!options.owned && machines.ok && !Object.keys(machines.data).some(name => canonicalComputer(name) === canonicalComputer(schedule.computer))) {
|
|
18
22
|
problems.push(`Computer "${schedule.computer}" is not a machine in this store, so no Hook will run this schedule.`);
|
|
@@ -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
|
|
@@ -19,6 +19,10 @@ const MAX_HEAD = 256 * 1024;
|
|
|
19
19
|
const MAX_HEADER_LINE = 8192;
|
|
20
20
|
const MAX_HEADERS = 32;
|
|
21
21
|
const READ_TIMEOUT_MS = 10_000;
|
|
22
|
+
/** How long the Hook may go quiet on an admitted request: every scoped route is
|
|
23
|
+
* a store read or one finding/task write (whose file lock waits at most 5 s),
|
|
24
|
+
* so a minute of silence means it is stuck, not slow. */
|
|
25
|
+
const ANSWER_IDLE_MS = 60_000;
|
|
22
26
|
const PROJECT = PROJECT_NAME.source.slice(1, -1);
|
|
23
27
|
const one = (query, key) => query.get(key)?.length === 1 ? query.get(key)[0] : undefined;
|
|
24
28
|
const only = (query, keys) => [...query.keys()].every(key => keys.includes(key));
|
|
@@ -235,6 +239,11 @@ export async function scopedDispatch(scope, command, io) {
|
|
|
235
239
|
answered = true;
|
|
236
240
|
io.output.write(httpResponse(503, "Phren Hook is not running on this computer."));
|
|
237
241
|
});
|
|
238
|
-
|
|
242
|
+
// A stalled route or a gone SSH client must not hold this process open.
|
|
243
|
+
socket.setTimeout(io.answerIdleMs ?? ANSWER_IDLE_MS, () => socket.destroy());
|
|
244
|
+
const drop = () => socket.destroy();
|
|
245
|
+
io.output.once("error", drop);
|
|
246
|
+
io.output.once("close", drop);
|
|
247
|
+
socket.on("close", () => { io.output.off("error", drop); io.output.off("close", drop); resolve(); });
|
|
239
248
|
});
|
|
240
249
|
}
|
|
@@ -23,7 +23,7 @@ import { pickClaudeAccount } from "./account-choice.js";
|
|
|
23
23
|
import { harnessInventoryWithin, hasUsable, launchCheckOff } from "./harnesses.js";
|
|
24
24
|
import { paneAccountKey, recordPaneAccount } from "./pane-accounts.js";
|
|
25
25
|
import { optionalHookPeers } from "./peers.js";
|
|
26
|
-
import { AppServerRpcError } from "./codex-app-server.js";
|
|
26
|
+
import { AppServerRpcError, AppServerUnsupportedError } from "./codex-app-server.js";
|
|
27
27
|
import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
|
|
28
28
|
import { logger } from "../logger.js";
|
|
29
29
|
import { JobRegistry } from "./job-registry.js";
|
|
@@ -467,7 +467,11 @@ async function startSession(server, data, options) {
|
|
|
467
467
|
const structuredLaunch = structured ? await codexServers.launch({ server, ...place }, { cwd, ...(model ? { model } : {}),
|
|
468
468
|
...(data.effort === undefined ? {} : { effort }), env: { ...(terminalProvider().paneEnv?.(server, place) ?? {}), ...(env ?? {}) },
|
|
469
469
|
...(brief ? { dispatchId: brief.id } : {}), startThread: !!brief, ...(permissionMode ? { remoteArgs: codexModeFlags(permissionMode) } : {}) }).catch(error => {
|
|
470
|
-
|
|
470
|
+
const note = `Codex app-server unavailable, typing instead: ${error instanceof Error ? error.message : String(error)}`;
|
|
471
|
+
if (error instanceof AppServerUnsupportedError)
|
|
472
|
+
logger.debug("launch", note);
|
|
473
|
+
else
|
|
474
|
+
logger.warn("launch", note);
|
|
471
475
|
return undefined;
|
|
472
476
|
}) : undefined;
|
|
473
477
|
const appServer = structuredLaunch?.entry;
|
|
@@ -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);
|
|
@@ -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
|
-
|
|
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(
|
|
947
|
+
result = await paneRoute(paneContext, url, data, response, request.headers);
|
|
938
948
|
}
|
|
939
949
|
}
|
|
940
950
|
}
|
|
@@ -53,6 +53,9 @@ export function descendsFrom(pid, roots, parents) {
|
|
|
53
53
|
export function attributeServers(input) {
|
|
54
54
|
const result = [];
|
|
55
55
|
for (const server of input.servers) {
|
|
56
|
+
// A listing whose owner could not be verified may be shown, but it belongs to no session.
|
|
57
|
+
if (server.unverified)
|
|
58
|
+
continue;
|
|
56
59
|
if (descendsFrom(server.pid, input.ownRoots, input.parents))
|
|
57
60
|
result.push({ ...server, source: "started" });
|
|
58
61
|
else if (input.mentioned.has(server.port) && !descendsFrom(server.pid, input.otherRoots, input.parents)) {
|
|
@@ -10,3 +10,11 @@ export declare function codexForeignThread(transcriptPath: unknown): Promise<boo
|
|
|
10
10
|
/** The session_meta fields come before its long instructions, so the head of
|
|
11
11
|
* the line is enough; no full parse. */
|
|
12
12
|
export declare function foreignMeta(head: string): boolean;
|
|
13
|
+
/** Whether a Claude hook callback comes from a headless run (`claude -p`, the
|
|
14
|
+
* Agent SDK) started inside the pane: it inherits HERDR_* and
|
|
15
|
+
* PHREN_DISPATCH_ID, so its callbacks name the pane and overwrite the parent's
|
|
16
|
+
* turn record. Interactive transcripts say `"entrypoint":"cli"`, headless ones
|
|
17
|
+
* `sdk-cli`/`sdk-ts`/`sdk-py`, on the first user row. A transcript that cannot
|
|
18
|
+
* be read, or has a long first prompt, counts as the pane's own. */
|
|
19
|
+
export declare function claudeHeadlessThread(transcriptPath: unknown): Promise<boolean>;
|
|
20
|
+
export declare function headlessEntrypoint(head: string): boolean;
|
|
@@ -11,15 +11,19 @@ import path from "node:path";
|
|
|
11
11
|
export async function codexForeignThread(transcriptPath) {
|
|
12
12
|
if (typeof transcriptPath !== "string" || !path.isAbsolute(transcriptPath) || !/^rollout-.*\.jsonl$/.test(path.basename(transcriptPath)))
|
|
13
13
|
return false;
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
return foreignMeta(await readHead(transcriptPath, 4096));
|
|
15
|
+
}
|
|
16
|
+
/** The first `bytes` of a transcript; "" when it cannot be read. */
|
|
17
|
+
async function readHead(file, bytes) {
|
|
18
|
+
const handle = await open(file, "r").catch(() => undefined);
|
|
19
|
+
if (!handle)
|
|
20
|
+
return "";
|
|
17
21
|
try {
|
|
18
|
-
const buffer = Buffer.alloc(
|
|
19
|
-
return
|
|
22
|
+
const buffer = Buffer.alloc(bytes), { bytesRead } = await handle.read(buffer, 0, bytes, 0);
|
|
23
|
+
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
20
24
|
}
|
|
21
25
|
finally {
|
|
22
|
-
await
|
|
26
|
+
await handle.close();
|
|
23
27
|
}
|
|
24
28
|
}
|
|
25
29
|
/** The session_meta fields come before its long instructions, so the head of
|
|
@@ -29,3 +33,17 @@ export function foreignMeta(head) {
|
|
|
29
33
|
return false;
|
|
30
34
|
return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
|
|
31
35
|
}
|
|
36
|
+
/** Whether a Claude hook callback comes from a headless run (`claude -p`, the
|
|
37
|
+
* Agent SDK) started inside the pane: it inherits HERDR_* and
|
|
38
|
+
* PHREN_DISPATCH_ID, so its callbacks name the pane and overwrite the parent's
|
|
39
|
+
* turn record. Interactive transcripts say `"entrypoint":"cli"`, headless ones
|
|
40
|
+
* `sdk-cli`/`sdk-ts`/`sdk-py`, on the first user row. A transcript that cannot
|
|
41
|
+
* be read, or has a long first prompt, counts as the pane's own. */
|
|
42
|
+
export async function claudeHeadlessThread(transcriptPath) {
|
|
43
|
+
if (typeof transcriptPath !== "string" || !path.isAbsolute(transcriptPath) || !transcriptPath.endsWith(".jsonl"))
|
|
44
|
+
return false;
|
|
45
|
+
return headlessEntrypoint(await readHead(transcriptPath, 32_768));
|
|
46
|
+
}
|
|
47
|
+
export function headlessEntrypoint(head) {
|
|
48
|
+
return /"entrypoint"\s*:\s*"sdk-[a-z]+"/.test(head);
|
|
49
|
+
}
|
package/dist/bridge/usage.d.ts
CHANGED
|
@@ -175,6 +175,10 @@ export declare function settleClaudeUsage(usage: AccountUsage, now: number): Acc
|
|
|
175
175
|
/** `opencode stats` scans OpenCode's whole database, several CPU-seconds on a
|
|
176
176
|
* busy machine, for a rolling seven-day cost that barely moves in a minute. */
|
|
177
177
|
export declare const OPENCODE_STATS_REUSE_MS: number;
|
|
178
|
+
/** Longest one reader may hold its shared slot. A read that never settles (a
|
|
179
|
+
* child whose grandchild keeps stdout open, say) would otherwise block every
|
|
180
|
+
* later poll until the Hook restarts. */
|
|
181
|
+
export declare const USAGE_READ_LIMIT_MS = 30000;
|
|
178
182
|
export declare class AccountUsageReader {
|
|
179
183
|
private readCodex;
|
|
180
184
|
private now;
|
package/dist/bridge/usage.js
CHANGED
|
@@ -771,6 +771,16 @@ export function settleClaudeUsage(usage, now) {
|
|
|
771
771
|
/** `opencode stats` scans OpenCode's whole database, several CPU-seconds on a
|
|
772
772
|
* busy machine, for a rolling seven-day cost that barely moves in a minute. */
|
|
773
773
|
export const OPENCODE_STATS_REUSE_MS = 10 * 60_000;
|
|
774
|
+
/** Longest one reader may hold its shared slot. A read that never settles (a
|
|
775
|
+
* child whose grandchild keeps stdout open, say) would otherwise block every
|
|
776
|
+
* later poll until the Hook restarts. */
|
|
777
|
+
export const USAGE_READ_LIMIT_MS = 30_000;
|
|
778
|
+
function bounded(read, fallback, ms = USAGE_READ_LIMIT_MS) {
|
|
779
|
+
let timer;
|
|
780
|
+
const late = new Promise(resolve => { timer = setTimeout(() => resolve(fallback()), ms); timer.unref?.(); });
|
|
781
|
+
return Promise.race([read, late]).finally(() => clearTimeout(timer));
|
|
782
|
+
}
|
|
783
|
+
const unanswered = (source, name) => ({ source, windows: [], message: `${name} did not answer in time on this computer. Phren will ask again shortly.` });
|
|
774
784
|
export class AccountUsageReader {
|
|
775
785
|
readCodex;
|
|
776
786
|
now;
|
|
@@ -812,7 +822,7 @@ export class AccountUsageReader {
|
|
|
812
822
|
/** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
|
|
813
823
|
async limits(allAccounts = true) {
|
|
814
824
|
if (!this.cached || this.now() - this.cached.at >= 60_000) {
|
|
815
|
-
this.pending ??= this.readCodex().then(value => { this.cached = { at: this.now(), value }; return value; }).finally(() => { this.pending = undefined; });
|
|
825
|
+
this.pending ??= bounded(this.readCodex(), () => unanswered("codex", "Codex")).then(value => { this.cached = { at: this.now(), value }; return value; }).finally(() => { this.pending = undefined; });
|
|
816
826
|
}
|
|
817
827
|
const codex = this.pending ?? Promise.resolve(this.cached.value);
|
|
818
828
|
// Every home, default first; the labels and keys are read once per poll.
|
|
@@ -822,7 +832,7 @@ export class AccountUsageReader {
|
|
|
822
832
|
const email = claudeAccountEmail(home);
|
|
823
833
|
const credits = claudeCredits(home.id);
|
|
824
834
|
// Claude Code's own answer only when the profile can't name the plan, or a credit asks whether this is a Console login.
|
|
825
|
-
const auth = credits.length || claudePlanUnknown(home) ? await this.readAuth(home).catch(() => undefined) : undefined;
|
|
835
|
+
const auth = credits.length || claudePlanUnknown(home) ? await bounded(this.readAuth(home).catch(() => undefined), () => undefined) : undefined;
|
|
826
836
|
const fallback = auth?.console ? "Console" : auth?.plan ? claudePlan({ subscriptionType: auth.plan }) : undefined;
|
|
827
837
|
const subscription = claudeAccountSubscription(home, now, fallback);
|
|
828
838
|
const usage = settleClaudeUsage(await this.claude(home), this.now());
|
|
@@ -840,9 +850,10 @@ export class AccountUsageReader {
|
|
|
840
850
|
if (!cached || this.now() - cached.at >= 60_000) {
|
|
841
851
|
const at = this.now();
|
|
842
852
|
if (!this.spendingPending.has(key)) {
|
|
843
|
-
const pending = Promise.all([this.openCode(at), this.readOpenCodeGo(new Date(at)),
|
|
844
|
-
|
|
845
|
-
|
|
853
|
+
const pending = Promise.all([this.openCode(at), bounded(this.readOpenCodeGo(new Date(at)), () => unanswered("opencode-go", "OpenCode Go")),
|
|
854
|
+
bounded(this.readOpenRouter(new Date(at)), () => undefined),
|
|
855
|
+
includeCopilot ? bounded(this.readCopilot(new Date(at)), () => unanswered("copilot", "GitHub Copilot")) : Promise.resolve(undefined),
|
|
856
|
+
includeElevenLabs ? bounded(this.readElevenLabs(new Date(at)).catch(() => undefined), () => undefined) : Promise.resolve(undefined)])
|
|
846
857
|
.then(([openCode, openCodeGo, openRouter, copilot, elevenLabs]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), ...(copilot ? [copilot] : []), ...(elevenLabs ? [elevenLabs] : [])])
|
|
847
858
|
.then(value => { this.spendingCached.set(key, { at, value }); return value; })
|
|
848
859
|
.finally(() => { this.spendingPending.delete(key); });
|
|
@@ -855,8 +866,11 @@ export class AccountUsageReader {
|
|
|
855
866
|
openCode(at) {
|
|
856
867
|
if (this.openCodeCached && at - this.openCodeCached.at < OPENCODE_STATS_REUSE_MS)
|
|
857
868
|
return Promise.resolve(this.openCodeCached.value);
|
|
858
|
-
|
|
859
|
-
|
|
869
|
+
let late = false;
|
|
870
|
+
this.openCodePending ??= bounded(this.readOpenCode(new Date(at)), () => { late = true; return unanswered("opencode", "opencode stats"); })
|
|
871
|
+
// A late answer is not kept for the ten minutes a real one is.
|
|
872
|
+
.then(value => { if (!late)
|
|
873
|
+
this.openCodeCached = { at, value }; return value; })
|
|
860
874
|
.finally(() => { this.openCodePending = undefined; });
|
|
861
875
|
return this.openCodePending;
|
|
862
876
|
}
|
|
@@ -870,7 +884,7 @@ export class AccountUsageReader {
|
|
|
870
884
|
if (!cached || this.now() - cached.at >= 60_000) {
|
|
871
885
|
const at = this.now();
|
|
872
886
|
if (!this.claudePending.has(home.dir))
|
|
873
|
-
this.claudePending.set(home.dir, this.readClaudeLive(new Date(at), home)
|
|
887
|
+
this.claudePending.set(home.dir, bounded(this.readClaudeLive(new Date(at), home), () => undefined)
|
|
874
888
|
.then(value => { this.claudeCached.set(home.dir, { at, value }); return value; })
|
|
875
889
|
.catch(() => { this.claudeCached.set(home.dir, { at, value: undefined }); return undefined; })
|
|
876
890
|
.finally(() => { this.claudePending.delete(home.dir); }));
|