@phren/cli 0.3.11 → 0.3.12
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-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +5 -0
- package/dist/bridge/agent-hooks.d.ts +159 -5
- package/dist/bridge/agent-hooks.js +663 -49
- package/dist/bridge/approval-summary.d.ts +16 -0
- package/dist/bridge/approval-summary.js +133 -0
- package/dist/bridge/authority-command.d.ts +20 -0
- package/dist/bridge/authority-command.js +120 -0
- package/dist/bridge/authority.d.ts +223 -0
- package/dist/bridge/authority.js +231 -0
- package/dist/bridge/claude-account-setup.d.ts +14 -0
- package/dist/bridge/claude-account-setup.js +69 -0
- package/dist/bridge/claude-accounts.d.ts +49 -0
- package/dist/bridge/claude-accounts.js +195 -0
- package/dist/bridge/code-routes.js +2 -2
- package/dist/bridge/codex-app-server.d.ts +144 -0
- package/dist/bridge/codex-app-server.js +319 -0
- package/dist/bridge/codex-auth-refresh.d.ts +33 -0
- package/dist/bridge/codex-auth-refresh.js +71 -0
- package/dist/bridge/codex-question-reply.d.ts +16 -0
- package/dist/bridge/codex-question-reply.js +57 -0
- package/dist/bridge/codex-review-mode.d.ts +10 -0
- package/dist/bridge/codex-review-mode.js +74 -0
- package/dist/bridge/codex-servers.d.ts +217 -0
- package/dist/bridge/codex-servers.js +636 -0
- package/dist/bridge/command.js +94 -4
- package/dist/bridge/computer-identity.d.ts +75 -0
- package/dist/bridge/computer-identity.js +166 -0
- package/dist/bridge/conductor-group.d.ts +91 -8
- package/dist/bridge/conductor-group.js +105 -9
- package/dist/bridge/conductor-role.d.ts +94 -0
- package/dist/bridge/conductor-role.js +176 -0
- package/dist/bridge/conductor-sets.d.ts +20 -0
- package/dist/bridge/conductor-sets.js +59 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +75 -11
- package/dist/bridge/dispatch-returns.d.ts +123 -19
- package/dist/bridge/dispatch-returns.js +357 -50
- package/dist/bridge/dispatch.d.ts +103 -2
- package/dist/bridge/dispatch.js +272 -40
- package/dist/bridge/fanouts.d.ts +7 -1
- package/dist/bridge/fanouts.js +39 -4
- package/dist/bridge/folder-trust.d.ts +56 -0
- package/dist/bridge/folder-trust.js +195 -0
- package/dist/bridge/grants.d.ts +22 -1
- package/dist/bridge/grants.js +57 -9
- package/dist/bridge/hand-off.d.ts +21 -9
- package/dist/bridge/hand-off.js +58 -45
- package/dist/bridge/harness-status.d.ts +11 -0
- package/dist/bridge/harness-status.js +32 -0
- package/dist/bridge/harnesses.d.ts +39 -0
- package/dist/bridge/harnesses.js +65 -0
- package/dist/bridge/health.d.ts +2 -0
- package/dist/bridge/health.js +1 -1
- package/dist/bridge/herdr.d.ts +11 -2
- package/dist/bridge/herdr.js +98 -23
- package/dist/bridge/hook-fast.d.ts +4 -0
- package/dist/bridge/hook-fast.js +68 -0
- package/dist/bridge/install.d.ts +16 -1
- package/dist/bridge/install.js +88 -21
- package/dist/bridge/launch-brief.d.ts +96 -0
- package/dist/bridge/launch-brief.js +164 -0
- package/dist/bridge/model-switch.d.ts +3 -0
- package/dist/bridge/model-switch.js +17 -1
- package/dist/bridge/models.d.ts +8 -4
- package/dist/bridge/models.js +24 -8
- package/dist/bridge/mux-wire.d.ts +9 -0
- package/dist/bridge/mux-wire.js +19 -0
- package/dist/bridge/opencode-pane-server.d.ts +113 -0
- package/dist/bridge/opencode-pane-server.js +332 -0
- package/dist/bridge/opencode-panes.d.ts +111 -0
- package/dist/bridge/opencode-panes.js +295 -0
- package/dist/bridge/pane-accounts.d.ts +8 -0
- package/dist/bridge/pane-accounts.js +46 -0
- package/dist/bridge/prompt-startup.d.ts +5 -0
- package/dist/bridge/prompt-startup.js +24 -0
- package/dist/bridge/protocol.d.ts +5 -0
- package/dist/bridge/protocol.js +4 -0
- package/dist/bridge/push.d.ts +5 -4
- package/dist/bridge/push.js +6 -4
- package/dist/bridge/questions.d.ts +37 -2
- package/dist/bridge/questions.js +158 -15
- package/dist/bridge/resources.d.ts +9 -3
- package/dist/bridge/resources.js +24 -8
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-format.js +3 -0
- package/dist/bridge/schedule-launch.d.ts +2 -1
- package/dist/bridge/schedule-launch.js +23 -53
- package/dist/bridge/schedule-watch.d.ts +10 -1
- package/dist/bridge/schedule-watch.js +54 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +225 -29
- package/dist/bridge/server-overview.d.ts +3 -3
- package/dist/bridge/server-overview.js +22 -14
- package/dist/bridge/server-pane-routes.d.ts +2 -0
- package/dist/bridge/server-pane-routes.js +145 -15
- package/dist/bridge/server-routes.d.ts +7 -0
- package/dist/bridge/server-routes.js +163 -35
- package/dist/bridge/server-stream.d.ts +2 -0
- package/dist/bridge/server-stream.js +22 -8
- package/dist/bridge/server.d.ts +6 -1
- package/dist/bridge/server.js +44 -12
- package/dist/bridge/session-activity.d.ts +81 -0
- package/dist/bridge/session-activity.js +117 -0
- package/dist/bridge/session-rename.d.ts +48 -0
- package/dist/bridge/session-rename.js +190 -0
- package/dist/bridge/session-servers.js +2 -2
- package/dist/bridge/settings-switch.d.ts +60 -0
- package/dist/bridge/settings-switch.js +287 -0
- package/dist/bridge/speech-voice.d.ts +55 -0
- package/dist/bridge/speech-voice.js +132 -0
- package/dist/bridge/speech.d.ts +70 -11
- package/dist/bridge/speech.js +169 -41
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +3 -3
- package/dist/bridge/terminal-tmux.js +24 -9
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.js +57 -12
- package/dist/bridge/transcript-codex.d.ts +0 -2
- package/dist/bridge/transcript-codex.js +29 -4
- package/dist/bridge/transcript-preview.d.ts +1 -0
- package/dist/bridge/transcript-preview.js +24 -4
- package/dist/bridge/transcripts.d.ts +15 -2
- package/dist/bridge/transcripts.js +47 -16
- package/dist/bridge/turn-records.d.ts +85 -0
- package/dist/bridge/turn-records.js +143 -0
- package/dist/bridge/uploads.d.ts +3 -0
- package/dist/bridge/uploads.js +14 -0
- package/dist/bridge/usage.d.ts +39 -10
- package/dist/bridge/usage.js +155 -44
- package/dist/bridge-hook.mjs +19169 -13176
- package/dist/cli/claude-unmanaged.d.ts +12 -0
- package/dist/cli/claude-unmanaged.js +105 -0
- package/dist/cli/schedules.js +2 -1
- package/dist/cli/session-start.js +10 -1
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.js +24 -5
- package/dist/data/task-receipts.d.ts +19 -0
- package/dist/data/task-receipts.js +68 -0
- package/dist/data/tasks.js +4 -1
- package/dist/generated/memory-ui-graph.browser.js +63 -63
- package/dist/graph-core/model.js +24 -3
- package/dist/graph-core/types.d.ts +4 -1
- package/dist/graph-core/types.js +1 -0
- package/dist/init/init-preset.js +7 -3
- package/dist/init/init-uninstall.js +2 -11
- package/dist/init/teardown.d.ts +3 -0
- package/dist/init/teardown.js +47 -0
- package/dist/link/context.js +21 -9
- package/dist/mcp/plugin-mode.js +1 -1
- package/dist/memory-ui-graph.runtime.js +63 -63
- package/dist/modules/code-package.d.ts +1 -0
- package/dist/modules/code-package.js +36 -7
- package/dist/modules/registry.js +14 -13
- package/dist/profile-store.d.ts +6 -0
- package/dist/profile-store.js +25 -1
- package/dist/shell/graph/glyphs.js +4 -0
- package/dist/shell/graph/graph-view.js +2 -0
- package/dist/status.js +7 -1
- package/dist/sync/task-claim.js +3 -2
- package/dist/task/lifecycle.js +25 -4
- package/dist/test-global-setup.js +5 -0
- package/dist/tools/dispatch.js +35 -2
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/skills/conductor/SKILL.md +17 -2
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
|
|
1
2
|
import path from "node:path";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import { saveCodeNote } from "./code-note.js";
|
|
@@ -5,31 +6,43 @@ import { handOff } from "./hand-off.js";
|
|
|
5
6
|
import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
|
|
6
7
|
import { homeDir } from "../home-paths.js";
|
|
7
8
|
import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
|
|
8
|
-
import { dispatchProjectDirectory, dispatchStatus } from "./dispatch.js";
|
|
9
|
-
import {
|
|
9
|
+
import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
|
|
10
|
+
import { hookWorkers } from "./dispatch-returns.js";
|
|
10
11
|
import { remoteChildren } from "./dispatch-tree.js";
|
|
11
|
-
import {
|
|
12
|
+
import { briefArrival, briefId } from "./launch-brief.js";
|
|
13
|
+
import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
|
|
14
|
+
import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
|
|
15
|
+
import { readComputers } from "./computer-identity.js";
|
|
12
16
|
import { optionalHookPeers, peerRequest } from "./peers.js";
|
|
13
17
|
import { candidateRepos, enrollProject } from "./enroll.js";
|
|
14
18
|
import { browseFiles } from "./files.js";
|
|
15
19
|
import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
|
|
16
20
|
import { storeRoute } from "./memory-store.js";
|
|
17
|
-
import {
|
|
21
|
+
import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
|
|
22
|
+
import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
|
|
18
23
|
import { locateProject } from "./locate.js";
|
|
19
24
|
import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
|
|
20
25
|
import { BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
|
|
21
26
|
import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
|
|
22
|
-
import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript,
|
|
27
|
+
import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath } from "./transcripts.js";
|
|
23
28
|
import { listUploads, saveUpload, uploadImage } from "./uploads.js";
|
|
24
29
|
import { currentModel, currentStep } from "./steps.js";
|
|
25
30
|
import { usageForCaller } from "./usage.js";
|
|
31
|
+
import { readFinalTurn } from "./schedule-watch.js";
|
|
26
32
|
import { healthDetails, listsCaller } from "./health.js";
|
|
27
33
|
import { defaultPhrenPath } from "../shared.js";
|
|
28
34
|
import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
|
|
29
35
|
import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
|
|
30
|
-
import {
|
|
36
|
+
import { renameSession } from "./session-rename.js";
|
|
37
|
+
import { launchSession, makeConductor, stopConductor, workspaceAction } from "./server-launch.js";
|
|
38
|
+
import { conductorAnswer, nameSet, readSets } from "./conductor-sets.js";
|
|
39
|
+
import { conductorPane } from "./conductor-role.js";
|
|
31
40
|
import { hookMetrics } from "./metrics.js";
|
|
32
|
-
import { streamSpeech } from "./speech.js";
|
|
41
|
+
import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
|
|
42
|
+
import { readSpeechKey } from "./speech-key.js";
|
|
43
|
+
import { DEFAULT_SPEECH_VOICE, listSpeechVoices, resolveSpeechVoice } from "./speech-voice.js";
|
|
44
|
+
import { terminalKind, terminalMux } from "./terminal.js";
|
|
45
|
+
import { muxListForClient, muxReplyForClient, typedMuxRequest } from "./mux-wire.js";
|
|
33
46
|
const CHILD_ACTIVITY_CACHE_MS = 5_000;
|
|
34
47
|
/** How long the overview waits for per-tab git and transcript reads; the phone gives up at 20 s. */
|
|
35
48
|
export const OVERVIEW_ENRICH_BUDGET_MS = 5_000;
|
|
@@ -50,9 +63,9 @@ async function childActivity(source, session) {
|
|
|
50
63
|
return result;
|
|
51
64
|
}
|
|
52
65
|
export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
53
|
-
terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
66
|
+
terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
54
67
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
55
|
-
files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, transcribe: true, memoryStore: true, promptOnce: true, resources: true };
|
|
68
|
+
files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true };
|
|
56
69
|
export function capabilitiesForModules(snapshot) {
|
|
57
70
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
58
71
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -88,9 +101,19 @@ async function body(request) {
|
|
|
88
101
|
}
|
|
89
102
|
export function selectedServer(url) {
|
|
90
103
|
const mux = url.searchParams.get("mux");
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
104
|
+
const selected = mux ? /^(herdr|tmux):(.+)$/.exec(mux) : undefined;
|
|
105
|
+
if (mux && !selected)
|
|
106
|
+
throw new BridgeError(400, "Select a terminal source.");
|
|
107
|
+
const explicit = url.searchParams.get("server");
|
|
108
|
+
if (explicit && selected && explicit !== selected[2])
|
|
109
|
+
throw new BridgeError(400, "Conflicting terminal sources.");
|
|
110
|
+
const server = serverName.parse(explicit || selected?.[2] || "default");
|
|
111
|
+
// Old phones used herdr:tmux. Keep that alias, but a typed tmux id must
|
|
112
|
+
// never silently route to a Herdr session with the same server name.
|
|
113
|
+
if (selected?.[1] === "tmux" && terminalKind(server) !== "tmux") {
|
|
114
|
+
throw new BridgeError(409, "This terminal source changed. Refresh the computer.", { code: "mux-kind-mismatch" });
|
|
115
|
+
}
|
|
116
|
+
return server;
|
|
94
117
|
}
|
|
95
118
|
export function workspacesReader(ctx) {
|
|
96
119
|
const { modules, info, agentHooks, journal, tabActivity, contextUsage } = ctx;
|
|
@@ -101,7 +124,9 @@ export function workspacesReader(ctx) {
|
|
|
101
124
|
const context = await contextUsage.read(server, s);
|
|
102
125
|
await journal.record(server, objects(s.panes));
|
|
103
126
|
const chatStates = new Map(await Promise.all(objects(s.panes).filter(p => p.agent).map(async (p) => [p, await paneChatState(server, p, { tokenWhenIdentified: false }).catch(() => ({}))])));
|
|
104
|
-
|
|
127
|
+
// The Hook's record says which pane is the conductor, whatever the agent is named.
|
|
128
|
+
const conductor = await conductorPane(server, s).catch(() => undefined);
|
|
129
|
+
const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged, conductor ? String(conductor.pane_id) : null);
|
|
105
130
|
// The branch each tab's agent is on, for the session cards.
|
|
106
131
|
const agentsByTab = new Map();
|
|
107
132
|
for (const pane of objects(s.panes)) {
|
|
@@ -122,6 +147,8 @@ export function workspacesReader(ctx) {
|
|
|
122
147
|
const chat = chatStates.get(agents[0]);
|
|
123
148
|
if (chat?.starting === true)
|
|
124
149
|
tab.starting = true;
|
|
150
|
+
// After the identity probe above, which is what learns a pane's transcript.
|
|
151
|
+
Object.assign(tab, paneAccountField(server, agents[0]));
|
|
125
152
|
if (typeof chat?.sessionId === "string" && provider.safeParse(agents[0].agent).success) {
|
|
126
153
|
tab.target = { server, workspace: group.id, tab: tab.id, pane: agents[0].pane_id, source: agents[0].agent, session: chat.sessionId };
|
|
127
154
|
}
|
|
@@ -131,8 +158,27 @@ export function workspacesReader(ctx) {
|
|
|
131
158
|
// the phone waits, so the computer read as offline. The overview answers
|
|
132
159
|
// within its budget with whatever decoration is ready; a later read fills in.
|
|
133
160
|
let expired = false;
|
|
161
|
+
let timer;
|
|
162
|
+
const budget = new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); });
|
|
163
|
+
// First, each pane's own turn record (one small file): whether its ended
|
|
164
|
+
// turn still has background work, and which dispatch it is. It runs ahead
|
|
165
|
+
// of the slower reads so the status does not flicker between answers, but
|
|
166
|
+
// inside the budget, so a stuck disk cannot hold the overview either.
|
|
167
|
+
const records = Promise.all(tabs.map(async ({ group, tab }) => {
|
|
168
|
+
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
|
|
169
|
+
const session = agents.length === 1 && object(tab.target).session;
|
|
170
|
+
const record = typeof session === "string" ? await paneRecord(server, agents[0], session) : undefined;
|
|
171
|
+
const [title, background] = await Promise.all([
|
|
172
|
+
recordTitle(record, { paneLabel: tab.paneLabel, harnessTitle: tab.title, tabLabel: tab.label, workspaceLabel: group.label, fallbackLabel: tab.label }),
|
|
173
|
+
liveBackground(record, readFinalTurn),
|
|
174
|
+
]);
|
|
175
|
+
if (expired)
|
|
176
|
+
return;
|
|
177
|
+
markBackground(tab, background);
|
|
178
|
+
tab.title = title;
|
|
179
|
+
}));
|
|
134
180
|
let nextTab = 0;
|
|
135
|
-
const enrich = Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
|
|
181
|
+
const enrich = records.then(() => Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
|
|
136
182
|
while (!expired && nextTab < tabs.length) {
|
|
137
183
|
const { group, tab } = tabs[nextTab++];
|
|
138
184
|
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
|
|
@@ -160,15 +206,18 @@ export function workspacesReader(ctx) {
|
|
|
160
206
|
}
|
|
161
207
|
}
|
|
162
208
|
// A row finished after the answer left belongs to the next read.
|
|
163
|
-
if (!expired)
|
|
209
|
+
if (!expired) {
|
|
164
210
|
Object.assign(tab, Object.fromEntries(Object.entries(found).filter(([, value]) => value !== undefined)));
|
|
211
|
+
// Codex subagents and fanout jobs keep an idle-looking session working too.
|
|
212
|
+
markBackground(tab, typeof found.runningChildren === "number" ? found.runningChildren : undefined);
|
|
213
|
+
}
|
|
165
214
|
}
|
|
166
|
-
}));
|
|
167
|
-
|
|
168
|
-
await Promise.race([enrich, new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); })]);
|
|
215
|
+
})));
|
|
216
|
+
await Promise.race([enrich, budget]);
|
|
169
217
|
expired = true;
|
|
170
218
|
clearTimeout(timer);
|
|
171
|
-
|
|
219
|
+
const mux = terminalMux(server);
|
|
220
|
+
return { ...workspaces, kind: mux.kind, mux, phren: info };
|
|
172
221
|
};
|
|
173
222
|
}
|
|
174
223
|
/** One read-only GET to every linked peer, each answer or its error by computer name. */
|
|
@@ -224,22 +273,66 @@ export function createRouteHandler(ctx) {
|
|
|
224
273
|
case "/v1/dispatch":
|
|
225
274
|
result = { dispatches: await dispatchStatus() };
|
|
226
275
|
break;
|
|
276
|
+
// Receiving side of a launched brief: what the worker's hooks reported for it.
|
|
277
|
+
case "/v1/dispatch/arrival":
|
|
278
|
+
result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
|
|
279
|
+
break;
|
|
227
280
|
case "/v1/conductor/grants":
|
|
228
|
-
result = { grants: await
|
|
281
|
+
result = { grants: await listNamedGrants() };
|
|
282
|
+
break;
|
|
283
|
+
// The owner's release authority policy, which conductors read and quote in briefs.
|
|
284
|
+
case "/v1/authority": {
|
|
285
|
+
const policy = await readAuthority();
|
|
286
|
+
const project = url.searchParams.get("project");
|
|
287
|
+
result = project !== null ? { authority: projectAuthority(policy, z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/).parse(project)) }
|
|
288
|
+
: { source: policy.source, ...(policy.updatedAt ? { updatedAt: policy.updatedAt } : {}), ...(policy.updatedBy ? { updatedBy: policy.updatedBy } : {}),
|
|
289
|
+
projects: Object.keys(policy.projects).sort().map(name => projectAuthority(policy, name)), confirmations: await listConfirmations() };
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
// One row per real computer, however many names machines.yaml and the network give it.
|
|
293
|
+
case "/v1/computers": {
|
|
294
|
+
const { computers, peerError } = await readComputers({ probe: true, local: { id: info.computer.id } });
|
|
295
|
+
result = { computers, ...(peerError ? { peerError } : {}) };
|
|
229
296
|
break;
|
|
230
|
-
|
|
297
|
+
}
|
|
298
|
+
// Asked by linked peers to place this computer in a set, and before they start a conductor: one per set.
|
|
231
299
|
case "/v1/conductor":
|
|
232
|
-
result =
|
|
300
|
+
result = await conductorAnswer(info, url);
|
|
301
|
+
break;
|
|
302
|
+
case "/v1/sets":
|
|
303
|
+
result = await readSets(info);
|
|
304
|
+
break;
|
|
305
|
+
// Bounded like capacity: a cold `claude auth status` per home can take seconds. Without
|
|
306
|
+
// `harnesses` the phone treats the computer as unknown and offers everything; the probe keeps
|
|
307
|
+
// running, so the next request answers from cache.
|
|
308
|
+
case "/v1/harnesses":
|
|
309
|
+
result = await harnessInventoryWithin(2_500) ?? { pending: true };
|
|
233
310
|
break;
|
|
234
311
|
case "/v1/dispatch/capacity": {
|
|
235
312
|
const live = await servers();
|
|
236
313
|
const snapshots = await Promise.all(live.map(server => snapshot(String(server.session))));
|
|
237
|
-
|
|
238
|
-
|
|
314
|
+
// Asked by a conductor with its name or host key: whether this computer links it back, so it dispatches only within its set.
|
|
315
|
+
const caller = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() })
|
|
316
|
+
.parse({ name: url.searchParams.get("name") ?? undefined, hostKey: url.searchParams.get("hostKey") ?? undefined });
|
|
317
|
+
const linksBack = caller.name || caller.hostKey ? { knowsCaller: (await listsCaller(caller)).knowsCaller } : {};
|
|
318
|
+
result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session), ...linksBack,
|
|
319
|
+
working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0),
|
|
320
|
+
// Bounded so a peer's capacity probe never waits on a cold `claude auth status`; missing means unknown.
|
|
321
|
+
// PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
|
|
322
|
+
...(launchCheckOff() ? {} : await harnessInventoryWithin(2_500).then(inventory => inventory ? { harnesses: inventory.harnesses } : {})) };
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
case "/v1/speech/voices": {
|
|
326
|
+
// The phone's voice picker: this computer's setting and the voices its account has.
|
|
327
|
+
const key = await readSpeechKey();
|
|
328
|
+
if (!key)
|
|
329
|
+
throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
|
|
330
|
+
const current = await resolveSpeechVoice();
|
|
331
|
+
result = { voice: current.voice, source: current.source, defaultVoice: DEFAULT_SPEECH_VOICE, voices: await listSpeechVoices(key) };
|
|
239
332
|
break;
|
|
240
333
|
}
|
|
241
334
|
case "/v1/muxes":
|
|
242
|
-
result = { muxes: await servers() };
|
|
335
|
+
result = { muxes: muxListForClient(await servers(), url.searchParams.get("typed") === "1") };
|
|
243
336
|
break;
|
|
244
337
|
case "/v1/activity":
|
|
245
338
|
result = { events: await journal.recent() };
|
|
@@ -284,7 +377,7 @@ export function createRouteHandler(ctx) {
|
|
|
284
377
|
break;
|
|
285
378
|
}
|
|
286
379
|
case "/v1/models":
|
|
287
|
-
result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? "")) };
|
|
380
|
+
result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? ""), url.searchParams.get("account") ?? undefined) };
|
|
288
381
|
break;
|
|
289
382
|
case "/v1/projects/files": {
|
|
290
383
|
const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
|
|
@@ -315,12 +408,15 @@ export function createRouteHandler(ctx) {
|
|
|
315
408
|
// they go only to callers that ask with `goPlan=1`; others keep the
|
|
316
409
|
// Go account and its message without windows.
|
|
317
410
|
const goPlan = url.searchParams.get("goPlan") === "1";
|
|
318
|
-
|
|
411
|
+
// Likewise one `claude` row: a phone that shipped before accounts refuses
|
|
412
|
+
// two rows with one source, so extra Claude homes come only with `accounts=all`.
|
|
413
|
+
const allAccounts = url.searchParams.get("accounts") === "all";
|
|
414
|
+
const usage = await accountUsage.read(known, allAccounts);
|
|
319
415
|
result = { ...usage, accounts: usageForCaller(usage.accounts, known, goPlan) };
|
|
320
416
|
// `peers=1` (the memory-free `phren usage`): each linked computer's own answer too.
|
|
321
417
|
if (url.searchParams.get("peers") === "1")
|
|
322
418
|
result = { ...result, computer: info.computer,
|
|
323
|
-
...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...(goPlan ? { goPlan: "1" } : {}) })}`) };
|
|
419
|
+
...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...(goPlan ? { goPlan: "1" } : {}), ...(allAccounts ? { accounts: "all" } : {}) })}`) };
|
|
324
420
|
break;
|
|
325
421
|
}
|
|
326
422
|
case "/v1/resources": {
|
|
@@ -348,17 +444,17 @@ export function createRouteHandler(ctx) {
|
|
|
348
444
|
break;
|
|
349
445
|
case "/v1/workspaces": {
|
|
350
446
|
const server = selectedServer(url);
|
|
351
|
-
result = await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1");
|
|
447
|
+
result = muxReplyForClient(await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1"), typedMuxRequest(url));
|
|
352
448
|
break;
|
|
353
449
|
}
|
|
354
450
|
case "/v1/workspaces/panes":
|
|
355
|
-
result = await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || "");
|
|
451
|
+
result = muxReplyForClient(await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || ""), typedMuxRequest(url));
|
|
356
452
|
break;
|
|
357
453
|
case "/v1/transcripts/blob": {
|
|
358
454
|
const target = targetFromURL(url);
|
|
359
455
|
await validateTarget(target);
|
|
360
456
|
const inner = url.searchParams.get("inner");
|
|
361
|
-
const bytes = await historicalImage(await
|
|
457
|
+
const bytes = await historicalImage(await targetTranscriptPath(target), Number(url.searchParams.get("line")), Number(url.searchParams.get("block")), target.source, inner === null ? undefined : Number(inner));
|
|
362
458
|
response.setHeader("Content-Type", "application/octet-stream");
|
|
363
459
|
response.end(bytes);
|
|
364
460
|
return;
|
|
@@ -482,6 +578,9 @@ export function createRouteHandler(ctx) {
|
|
|
482
578
|
harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
|
|
483
579
|
} : undefined);
|
|
484
580
|
}
|
|
581
|
+
else if (url.pathname === "/v1/sessions/rename") {
|
|
582
|
+
result = await renameSession(selectedServer(url), data);
|
|
583
|
+
}
|
|
485
584
|
else if (url.pathname === "/v1/schedules") {
|
|
486
585
|
result = await scheduler.statuses();
|
|
487
586
|
}
|
|
@@ -508,14 +607,36 @@ export function createRouteHandler(ctx) {
|
|
|
508
607
|
result = await dispatches.dispatch(brief, origin);
|
|
509
608
|
}
|
|
510
609
|
else if (url.pathname === "/v1/dispatch/workers") {
|
|
511
|
-
result = await
|
|
610
|
+
result = await hookWorkers(agentHooks)(data);
|
|
512
611
|
}
|
|
513
612
|
else if (url.pathname === "/v1/dispatch/returns") {
|
|
514
613
|
result = { returns: await ctx.returns.take() };
|
|
515
614
|
}
|
|
615
|
+
else if (url.pathname === "/v1/dispatch/approve") {
|
|
616
|
+
const body = z.object({ id: z.string().uuid(), decision: z.enum(["approve", "deny"]), actionId: z.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
|
|
617
|
+
await ctx.returns.answerApproval(body.id, body.decision, body.actionId, body.origin);
|
|
618
|
+
result = { ok: true };
|
|
619
|
+
}
|
|
516
620
|
else if (url.pathname === "/v1/conductor/grants") {
|
|
517
621
|
result = { ok: true, grant: await addGrant(data) };
|
|
518
622
|
}
|
|
623
|
+
else if (url.pathname === "/v1/authority" || url.pathname === "/v1/authority/confirm") {
|
|
624
|
+
// The owner writes the policy from the phone; an agent's call names its pane.
|
|
625
|
+
if (data.origin !== undefined)
|
|
626
|
+
throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
|
|
627
|
+
result = url.pathname === "/v1/authority" ? { ok: true, authority: await setProjectAuthority(data, "phone") }
|
|
628
|
+
: { ok: true, confirmation: await confirmAuthority(data, "phone") };
|
|
629
|
+
}
|
|
630
|
+
else if (url.pathname === "/v1/conductor/make") {
|
|
631
|
+
// Serialized with launches, so a conductor launch and a make cannot both pass the set check.
|
|
632
|
+
result = await launches.run(async () => makeConductor(selectedServer(url), data));
|
|
633
|
+
}
|
|
634
|
+
else if (url.pathname === "/v1/conductor/stop") {
|
|
635
|
+
result = await launches.run(async () => stopConductor(data));
|
|
636
|
+
}
|
|
637
|
+
else if (url.pathname === "/v1/sets/name") {
|
|
638
|
+
result = await nameSet(data);
|
|
639
|
+
}
|
|
519
640
|
else if (url.pathname === "/v1/push/register") {
|
|
520
641
|
// Registration is kept for when a key is added; the reply says whether push works now.
|
|
521
642
|
await agentHooks.push.register(data);
|
|
@@ -558,7 +679,8 @@ export function createRouteHandler(ctx) {
|
|
|
558
679
|
const cwd = storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
|
|
559
680
|
: data.project !== undefined ? await dispatchProjectDirectory(data.project)
|
|
560
681
|
: await launchDirectory(data.cwd, await journal.recent(), locatedDirectories);
|
|
561
|
-
|
|
682
|
+
// A project the Hook resolved (a dispatch) is a folder it may trust; a folder the phone named is not.
|
|
683
|
+
return launchSession(selectedServer(url), { ...data, cwd }, { trustFolder: data.project !== undefined });
|
|
562
684
|
});
|
|
563
685
|
}
|
|
564
686
|
else if (url.pathname.startsWith("/v1/workspaces/")) {
|
|
@@ -572,10 +694,16 @@ export function createRouteHandler(ctx) {
|
|
|
572
694
|
}
|
|
573
695
|
}
|
|
574
696
|
else if (request.method === "DELETE") {
|
|
575
|
-
if (url.pathname !== "/v1/conductor/grants")
|
|
697
|
+
if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority")
|
|
576
698
|
throw new BridgeError(404, "Unknown Phren Hook route.");
|
|
577
699
|
const data = await body(request);
|
|
578
|
-
|
|
700
|
+
if (url.pathname === "/v1/authority") {
|
|
701
|
+
if (data.origin !== undefined)
|
|
702
|
+
throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
|
|
703
|
+
result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
|
|
704
|
+
}
|
|
705
|
+
else
|
|
706
|
+
result = { ok: true, grant: await removeGrant(data) };
|
|
579
707
|
}
|
|
580
708
|
else
|
|
581
709
|
throw new BridgeError(405, "Unsupported request method.");
|
|
@@ -6,6 +6,7 @@ import type { HookInfo } from "./server-routes.js";
|
|
|
6
6
|
import type { SideQuestions } from "./side-questions.js";
|
|
7
7
|
import { TranscriptReader } from "./transcripts.js";
|
|
8
8
|
import type { ModuleSnapshot } from "../modules/runtime.js";
|
|
9
|
+
import { type SettingsSwitcher } from "./settings-switch.js";
|
|
9
10
|
/** The WebSocket transcript and status streams: the backlog, appended rows and
|
|
10
11
|
* previews on a tick loop, older pages on request, and the pane's status. */
|
|
11
12
|
export interface StreamContext {
|
|
@@ -13,6 +14,7 @@ export interface StreamContext {
|
|
|
13
14
|
agentHooks: AgentHooks;
|
|
14
15
|
codexQuestions: CodexQuestions;
|
|
15
16
|
sideQuestions?: SideQuestions;
|
|
17
|
+
settingsSwitcher?: SettingsSwitcher;
|
|
16
18
|
info: HookInfo;
|
|
17
19
|
activeCapabilities: Record<string, unknown>;
|
|
18
20
|
}
|
|
@@ -6,8 +6,11 @@ import { SNAPSHOT_SHARE_MS, trustedDirectory, validateTarget } from "./herdr.js"
|
|
|
6
6
|
import { repositoryBranch } from "./projects.js";
|
|
7
7
|
import { BridgeError, MAX_FRAME, object, targetFromURL } from "./protocol.js";
|
|
8
8
|
import { TranscriptPreviewStream } from "./transcript-preview.js";
|
|
9
|
-
import { childAgent, childAgentTree, refreshTranscript,
|
|
9
|
+
import { childAgent, childAgentTree, refreshTranscript, targetTranscriptPath, TranscriptReader } from "./transcripts.js";
|
|
10
10
|
import { countTick } from "./metrics.js";
|
|
11
|
+
import { approvalSummary } from "./approval-summary.js";
|
|
12
|
+
import { codexServers } from "./codex-servers.js";
|
|
13
|
+
import { settingsCapabilities } from "./settings-switch.js";
|
|
11
14
|
function send(socket, frame) {
|
|
12
15
|
if (socket.readyState !== WebSocket.OPEN)
|
|
13
16
|
return;
|
|
@@ -37,13 +40,13 @@ export function streamCloseReason(error) {
|
|
|
37
40
|
return reason;
|
|
38
41
|
}
|
|
39
42
|
export function transcriptStreams(ctx) {
|
|
40
|
-
const { modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities } = ctx;
|
|
43
|
+
const { modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities } = ctx;
|
|
41
44
|
/** A conversation the agent has identified but not written yet (Claude
|
|
42
45
|
* Code creates its file on the first turn) is an empty transcript, not a
|
|
43
46
|
* missing one: `reader` stays undefined until the file appears. */
|
|
44
47
|
async function conversationReader(target) {
|
|
45
48
|
try {
|
|
46
|
-
const reader = new TranscriptReader(await
|
|
49
|
+
const reader = new TranscriptReader(await targetTranscriptPath(target), target.source, undefined, modules.has("git") ? agentHooks.changes.view(`${target.source}:${target.session}`) : undefined);
|
|
47
50
|
return { reader, source: target.source, session: target.session };
|
|
48
51
|
}
|
|
49
52
|
catch (error) {
|
|
@@ -155,7 +158,10 @@ export function transcriptStreams(ctx) {
|
|
|
155
158
|
await agentHooks.syncTerminalDialog(target, waiting && !pendingQuestions?.length);
|
|
156
159
|
pendingApproval = agentHooks.approval(target);
|
|
157
160
|
}
|
|
158
|
-
|
|
161
|
+
// A served OpenCode pane's question comes from its own API, whatever
|
|
162
|
+
// status its terminal reports.
|
|
163
|
+
const servedQuestion = agentHooks.servedQuestion(target);
|
|
164
|
+
const hookPrompt = servedQuestion ?? (waiting ? agentHooks.terminalPrompt(target) : undefined);
|
|
159
165
|
// Codex 0.155's queued follow-up question never becomes a held
|
|
160
166
|
// PermissionRequest: it lives as a thread item the terminal shows
|
|
161
167
|
// under "Queued follow-up inputs". With nothing else to ask, read
|
|
@@ -164,21 +170,29 @@ export function transcriptStreams(ctx) {
|
|
|
164
170
|
const terminalPrompt = hookPrompt
|
|
165
171
|
?? (waiting && target.source === "codex" && !pendingQuestions?.length
|
|
166
172
|
? await queuedQuestion(target.session).then(queued => queued ? {
|
|
167
|
-
toolName: "Question", message: queued.title, queued: true,
|
|
173
|
+
toolName: "Question", message: queued.title, request: approvalSummary({ tool: "Question", message: queued.title, question: true }).request, queued: true,
|
|
168
174
|
choice: { title: queued.title, options: queued.options },
|
|
169
175
|
} : undefined).catch(() => undefined)
|
|
170
176
|
: undefined);
|
|
177
|
+
// Claude's own state comes from its footer, which leads the transcript.
|
|
178
|
+
const codexServed = target.source === "codex" && !!codexServers.forTarget(target);
|
|
179
|
+
const { settings, settingsState } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed)
|
|
180
|
+
: { settings: settingsCapabilities(target.source, codexServed), settingsState: undefined };
|
|
171
181
|
const historyHealth = target.source === "codex" ? await threadHealth(target.session, pane.agent_status) : { stalled: false };
|
|
172
182
|
send(client, { agentStatus: { source: target.source, session: target.session,
|
|
173
|
-
status: pendingApproval ? "waiting" : pane.agent_status, pendingApproval, pendingQuestions, terminalPrompt,
|
|
183
|
+
status: pendingApproval || servedQuestion ? "waiting" : pane.agent_status, pendingApproval, pendingQuestions, terminalPrompt,
|
|
174
184
|
...(waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {}),
|
|
175
185
|
compacting: agentHooks.compacting(target),
|
|
176
186
|
...(historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {}),
|
|
177
187
|
modules: info.modules, store: info.store, profile: info.profile, generation: info.generation,
|
|
178
|
-
capabilities: { ...activeCapabilities, asyncQuestions:
|
|
188
|
+
capabilities: { ...activeCapabilities, asyncQuestions: codexQuestions.availableFor(target),
|
|
189
|
+
// Answers to Codex questions may carry the phone's uploads.
|
|
190
|
+
...(codexQuestions.availableFor(target) ? { questionAttachments: true } : {}),
|
|
179
191
|
// Claude's AskUserQuestion is answered in its terminal dialog
|
|
180
192
|
// through /v1/questions/answer, whether or not a hold caught it.
|
|
181
|
-
...(target.source === "claude" ? { questions: true } : {})
|
|
193
|
+
...(target.source === "claude" || servedQuestion ? { questions: true } : {}),
|
|
194
|
+
// What the composer's permission, plan and fast chips can change here.
|
|
195
|
+
...(settings ? { settings } : {}) }, ...(settingsState ? { settingsState } : {}), branch } });
|
|
182
196
|
}
|
|
183
197
|
if (sideAnswers && sideQuestions) {
|
|
184
198
|
for (const { revision, ...side } of sideQuestions.list(target)) {
|
package/dist/bridge/server.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
+
import { ModelCatalog } from "./models.js";
|
|
2
|
+
import { AccountUsageReader } from "./usage.js";
|
|
1
3
|
export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
|
|
2
4
|
export { streamCloseReason } from "./server-stream.js";
|
|
3
5
|
export { herdrAgentName, launchSession } from "./server-launch.js";
|
|
4
|
-
export declare function serve(version: string
|
|
6
|
+
export declare function serve(version: string, options?: {
|
|
7
|
+
modelCatalog?: ModelCatalog;
|
|
8
|
+
accountUsage?: AccountUsageReader;
|
|
9
|
+
}): Promise<void>;
|
package/dist/bridge/server.js
CHANGED
|
@@ -17,7 +17,7 @@ import { startChangeRetention } from "./changes.js";
|
|
|
17
17
|
import { CodeReindexer, CodeRoutes } from "./code-routes.js";
|
|
18
18
|
import { WorkspaceContextUsage } from "./context.js";
|
|
19
19
|
import { DispatchService } from "./dispatch.js";
|
|
20
|
-
import { DispatchReturns } from "./dispatch-returns.js";
|
|
20
|
+
import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
|
|
21
21
|
import { findPane, paneChatState, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
|
|
22
22
|
import { LaunchLimiter } from "./limits.js";
|
|
23
23
|
import { locateProject } from "./locate.js";
|
|
@@ -27,6 +27,7 @@ import { TabActivityStore } from "./tab-activity.js";
|
|
|
27
27
|
import { childAgentTree } from "./transcripts.js";
|
|
28
28
|
import { ModelCatalog } from "./models.js";
|
|
29
29
|
import { ModelSwitcher } from "./model-switch.js";
|
|
30
|
+
import { SettingsSwitcher } from "./settings-switch.js";
|
|
30
31
|
import { SideQuestions } from "./side-questions.js";
|
|
31
32
|
import { AccountUsageReader } from "./usage.js";
|
|
32
33
|
import { ResourceMonitor } from "./resources.js";
|
|
@@ -34,14 +35,17 @@ import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules
|
|
|
34
35
|
import { dailyCanaryDue, runCanary } from "./canary.js";
|
|
35
36
|
import { defaultPhrenPath } from "../shared.js";
|
|
36
37
|
import { capabilitiesForModules, createRouteHandler, requireRoute, selectedServer, workspacesReader } from "./server-routes.js";
|
|
38
|
+
import { typedMuxRequest } from "./mux-wire.js";
|
|
37
39
|
import { overviewStream } from "./server-overview.js";
|
|
38
40
|
import { transcriptStreams } from "./server-stream.js";
|
|
39
41
|
import { launchSession } from "./server-launch.js";
|
|
42
|
+
import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
|
|
43
|
+
import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.js";
|
|
40
44
|
import { localNames } from "./computer-names.js";
|
|
41
45
|
export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
|
|
42
46
|
export { streamCloseReason } from "./server-stream.js";
|
|
43
47
|
export { herdrAgentName, launchSession } from "./server-launch.js";
|
|
44
|
-
export async function serve(version) {
|
|
48
|
+
export async function serve(version, options = {}) {
|
|
45
49
|
process.umask(0o077);
|
|
46
50
|
const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
|
|
47
51
|
if (!modules.has("hook"))
|
|
@@ -68,26 +72,39 @@ export async function serve(version) {
|
|
|
68
72
|
return agent.success && typeof pane?.terminal_id === "string" ? { agent: agent.data, terminal: pane.terminal_id } : undefined;
|
|
69
73
|
} })
|
|
70
74
|
: undefined;
|
|
71
|
-
// Follows what dispatched workers do and tells the dispatching agent.
|
|
72
|
-
const returns = dispatches ? new DispatchReturns() : undefined;
|
|
73
75
|
const locatedDirectories = new Set();
|
|
74
76
|
const journal = new ActivityJournal();
|
|
75
77
|
const agentHooks = new AgentHooks(undefined, modules);
|
|
78
|
+
// Follows what dispatched workers do and tells the dispatching agent.
|
|
79
|
+
const returns = dispatches ? new DispatchReturns({
|
|
80
|
+
localWorkers: hookWorkers(agentHooks),
|
|
81
|
+
localAnswer: (target, actionId, decision) => agentHooks.answer(target, actionId, decision),
|
|
82
|
+
// A worker's request the worker's own Hook did not push reaches this Hook's phone.
|
|
83
|
+
onApproval: (receipt, approval) => {
|
|
84
|
+
if (approval.pushed || !agentHooks.push.available)
|
|
85
|
+
return;
|
|
86
|
+
agentHooks.pushForwarded({ provider: receipt.harness, computer: receipt.computer, project: receipt.project,
|
|
87
|
+
request: approval.request ?? approval.title ?? approval.tool, ...(approval.requestKind ? { requestKind: approval.requestKind } : {}) }, decision => returns.answerApproval(receipt.id, decision, approval.actionId));
|
|
88
|
+
return true;
|
|
89
|
+
},
|
|
90
|
+
}) : undefined;
|
|
76
91
|
// Push is offered only once an APNs sender loaded; phones may still register.
|
|
77
92
|
if ("approvalPush" in activeCapabilities) {
|
|
78
93
|
Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
|
|
79
94
|
}
|
|
80
|
-
const modelCatalog = new ModelCatalog();
|
|
95
|
+
const modelCatalog = options.modelCatalog ?? new ModelCatalog();
|
|
81
96
|
const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
|
|
97
|
+
const settingsSwitcher = new SettingsSwitcher(agentHooks);
|
|
82
98
|
const sideQuestions = new SideQuestions();
|
|
83
99
|
const contextUsage = new WorkspaceContextUsage();
|
|
84
|
-
const accountUsage = new AccountUsageReader();
|
|
100
|
+
const accountUsage = options.accountUsage ?? new AccountUsageReader();
|
|
85
101
|
const resources = new ResourceMonitor();
|
|
86
102
|
const tabActivity = new TabActivityStore();
|
|
87
|
-
const codexQuestions = new CodexQuestions();
|
|
103
|
+
const codexQuestions = new CodexQuestions(undefined, codexServers);
|
|
88
104
|
const scheduleStore = defaultPhrenPath();
|
|
89
105
|
const scheduler = modules.has("schedules") ? new Scheduler({ now: () => new Date(), store: scheduleStore, runsFile: scheduleRunsFile(),
|
|
90
|
-
|
|
106
|
+
// A schedule starts in its project's folder, which the Hook resolved itself.
|
|
107
|
+
launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
|
|
91
108
|
push: { notify: value => agentHooks.push.notifySchedule(value) },
|
|
92
109
|
locateProject: async (project) => (await locateProject(project, await journal.recent()))[0]?.directory }) : undefined;
|
|
93
110
|
const fanoutMessages = new FanoutMessages({ ...process.env, PHREN_PATH: scheduleStore }, {
|
|
@@ -134,7 +151,7 @@ export async function serve(version) {
|
|
|
134
151
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => { };
|
|
135
152
|
if (modules.has("git"))
|
|
136
153
|
await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
137
|
-
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
154
|
+
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
|
|
138
155
|
const { stream } = streams;
|
|
139
156
|
// The phone's overview, pushed over a WebSocket when it changes.
|
|
140
157
|
const overview = overviewStream({
|
|
@@ -144,7 +161,7 @@ export async function serve(version) {
|
|
|
144
161
|
resources: () => resources.read(),
|
|
145
162
|
});
|
|
146
163
|
const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
|
|
147
|
-
journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
|
|
164
|
+
journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
|
|
148
165
|
fanoutMessages, canary, streams, returns }));
|
|
149
166
|
http.requestTimeout = 20_000;
|
|
150
167
|
http.headersTimeout = 10_000;
|
|
@@ -168,7 +185,7 @@ export async function serve(version) {
|
|
|
168
185
|
ws.clients.delete(oldest);
|
|
169
186
|
}
|
|
170
187
|
if (overviewServer !== undefined) {
|
|
171
|
-
overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1");
|
|
188
|
+
overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1", typedMuxRequest(url));
|
|
172
189
|
return;
|
|
173
190
|
}
|
|
174
191
|
if (url.pathname === "/v1/speech/transcribe") {
|
|
@@ -185,13 +202,25 @@ export async function serve(version) {
|
|
|
185
202
|
await new Promise((resolve, reject) => { http.once("error", reject); http.listen(socketPath(), () => resolve()); });
|
|
186
203
|
await chmod(socketPath(), 0o600);
|
|
187
204
|
await agentHooks.start();
|
|
205
|
+
// Codex panes on the Hook's own app-servers: their requests become
|
|
206
|
+
// approval cards, and servers a previous Hook started are rejoined.
|
|
207
|
+
codexServers.setSink({ request: (target, request, answer) => agentHooks.codexRequest(target, request, answer),
|
|
208
|
+
resolved: (target, requestId) => agentHooks.codexResolved(target, requestId) });
|
|
209
|
+
await codexServers.adopt().catch(() => { });
|
|
188
210
|
void scheduler?.tick().catch(() => { });
|
|
189
211
|
const scheduleTimer = scheduler ? setInterval(() => { countTick("schedules"); void scheduler.tick().catch(() => { }); }, 30_000) : undefined;
|
|
190
212
|
// Off unless PHREN_CANARY_DAILY=1 or `phren canary --daily on`.
|
|
213
|
+
// Refresh the shared Codex sign-in before its workers each try to at once.
|
|
214
|
+
const codexAuth = codexAppServerEnabled() && codexAuthRefreshEnabled() ? new CodexAuthKeeper(codexServers) : undefined;
|
|
215
|
+
const codexAuthTimer = codexAuth ? setInterval(() => { void codexAuth.tick().catch(() => { }); }, 60 * 60_000) : undefined;
|
|
216
|
+
if (codexAuth)
|
|
217
|
+
setTimeout(() => { void codexAuth.tick().catch(() => { }); }, 60_000).unref();
|
|
191
218
|
const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
|
|
192
219
|
let recording = false;
|
|
193
220
|
const activityTimer = setInterval(() => {
|
|
194
221
|
countTick("activity");
|
|
222
|
+
// Served OpenCode panes: follow new ones, drop those whose process is gone.
|
|
223
|
+
agentHooks.paneServers.tick();
|
|
195
224
|
if (recording)
|
|
196
225
|
return;
|
|
197
226
|
recording = true;
|
|
@@ -207,6 +236,8 @@ export async function serve(version) {
|
|
|
207
236
|
const name = String(server.session), current = await sharedSnapshot(name, 4000);
|
|
208
237
|
await tabActivity.observe(name, current);
|
|
209
238
|
await journal.record(name, objects(current.panes));
|
|
239
|
+
// A Codex app-server whose pane closed is stopped; a dead one forgotten.
|
|
240
|
+
await codexServers.reap(name, current).catch(() => { });
|
|
210
241
|
// Approvals drawn in a terminal reach a phone with phren closed.
|
|
211
242
|
await agentHooks.observeWaitingPanes(name, objects(current.panes), async (pane) => {
|
|
212
243
|
const state = await paneChatState(name, pane, { tokenWhenIdentified: false });
|
|
@@ -217,13 +248,14 @@ export async function serve(version) {
|
|
|
217
248
|
}
|
|
218
249
|
catch { /* A disconnected computer keeps its previous local activity. */ }
|
|
219
250
|
}
|
|
251
|
+
await codexServers.sweep(live.map(server => String(server.session))).catch(() => { });
|
|
220
252
|
// Dispatch returns ride this tick and its shared snapshots. The returns
|
|
221
253
|
// loop throttles its own peer polls and never holds up activity.
|
|
222
254
|
void returns?.tick();
|
|
223
255
|
})().finally(() => { recording = false; }).catch(() => { });
|
|
224
256
|
}, 5000);
|
|
225
257
|
await new Promise(resolve => {
|
|
226
|
-
const stop = () => { fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
258
|
+
const stop = () => { fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
227
259
|
process.once("SIGTERM", stop);
|
|
228
260
|
process.once("SIGINT", stop);
|
|
229
261
|
});
|