@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
1,768 lines • 129 kB
JavaScript
import { CI_FAILURE_BODY_CAP, CI_FAILURE_PATH, CI_FAILURE_SCOPE } from "./ci-failure-contract.js";
import { authenticatedCiReporter, CI_PROOF_HEADER, CI_REPORTER_HEADER } from "./ci-authority.js";
import { receiveCiFailure } from "./ci-failures.js";
import { storeDirectory } from "./store-directory.js";
import { browserRoute } from "./browser-routes.js";
import { terminalProvider } from "./terminal.js";
import { peerFingerprint } from "./dispatch-hosts.js";
import { redactPeerHandoff } from "./peer-handoff.js";
import { relocationSupport } from "./worker-relocation.js";
import { CONVERSATION_FILE, CONVERSATION_MARKER, continuationConversationPage, continuationIntent, continuationLaunchSchema, continuationPlacement, fetchContinuationConversation, launchContinuation, withConversationPointer } from "./continuation-launch.js";
import { addClaudeAccount, signInClaudeAccount } from "./account-add.js";
import { ACCOUNT_ROLES, isAccountRole, setAccountSettings, setComputerAllowedPools } from "./account-pools.js";
import { claudeHome } from "./claude-accounts.js";
import { localMoveAvailability, moveComputers } from "./move-computers.js";
import { ownerRequest, requestPeer } from "./request-origin.js";
import { bodyDigest, OWNER_PROOF_HEADER, OwnerProof } from "./owner-proof.js";
import { listMoves, moveSessionFields, readMove } from "./session-move.js";
import { ownerInboxView } from "./owner-inbox-view.js";
import { inboxWire } from "./owner-inbox.js";
import { issueItemRoute, issueListRoute, issueWriteRoute } from "./issue-routes.js";
import { cancelDispatch, closeFinishedWorker, closeOwnPane } from "./worker-close.js";
import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js";
import { sessionStalls } from "./stalls.js";
import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
import path from "node:path";
import { stat } from "node:fs/promises";
import { z } from "zod";
import { sudoAnswer } from "./sudo.js";
import { secretAnswer } from "./secret.js";
import { saveCodeNote } from "./code-note.js";
import { handOff } from "./hand-off.js";
import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
import { homeDir } from "../home-paths.js";
import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
import { dispatchPhase, dispatchProjectDirectory, dispatchStatus, originPaneSchema, recentDispatches, reconcileInterruptedDispatches } from "./dispatch.js";
import { hookWorkers } from "./dispatch-returns.js";
import { remoteChildren } from "./dispatch-tree.js";
import { briefArrival, briefId, briefRoot, launchesWithBrief, readLaunchBrief } from "./launch-brief.js";
import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
import { addGrant, listGrants, listNamedGrants, removeGrant } from "./grants.js";
import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
import { readComputers } from "./computer-identity.js";
import { PEER_READ_TTL_MS, peerRead, refreshPeerReads } from "./peer-reads.js";
import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
import { candidateRepos, enrollProject } from "./enroll.js";
import { browseFiles } from "./files.js";
import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
import { chatFileMatches, readRecentChatFile, recentFileRepositories } from "./chat-file-matches.js";
import { resolveFilePath } from "./file-resolve.js";
import { ChatFiles } from "./chat-files.js";
import { isMediaPath, readMedia } from "./home-media.js";
import { storeRoute } from "./memory-store.js";
import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding } from "./project-memory.js";
import { PROJECT_GIT_ROUTE, projectGit, projectHostToken } from "./project-git.js";
import { availablePaneEvidence, childActivity, effectivePaneEvidence } from "./session-evidence.js";
import { liveWork, markBackground, ownRecord, paneTurnRecord, provisionalWork, recordTitle, replyExcerpt, resolveEffectiveStatus, turnCompletion } from "./session-activity.js";
import { herdrTurn, markSessionSeen, readSessionSeen, sessionPin, setSessionPin, tmuxCompletedTurn, tmuxCompletion } from "./session-seen.js";
import { readTurn, truncateUtf8, turnPhase } from "./turn-records.js";
import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
import { locateProject } from "./locate.js";
import { gitStatus } from "./git.js";
import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
import { approvalDecisions, atomicInPrivateDir, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema, sessionId } from "./protocol.js";
import { bootedSimulators, simulatorAct, simulatorApps, simulatorDevices, simulatorScreenshot } from "./simulators.js";
import { macWindowsAct, macWindowsList, macWindowsOwnerOnly, macWindowsRefusal, macWindowsRequestPermission, macWindowsSnapshot, macWindowsSupported } from "./mac-windows.js";
import { panesByTab, tabActivityKey } from "./tab-activity.js";
import { childAgentTree, completionEntry, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath, transcriptPath, TranscriptReader } from "./transcripts.js";
import { conversationSearch } from "./conversation-search.js";
import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
import { currentModel, currentStep } from "./steps.js";
import { capacityRoom, usageForCaller } from "./usage.js";
import { pressureReason, readBudget, readPressure } from "../heavy/budget.js";
import { SCHEDULE_EVENT_BODY_CAP } from "./schedule-events.js";
import { createScheduleRoute, updateScheduleRoute } from "./schedule-update.js";
import { scheduleFingerprintSchema } from "./schedule-approvals.js";
import { cachedStoreWarnings, healthDetails, listsCaller } from "./health.js";
import { defaultPhrenPath } from "../shared.js";
import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
import { renameSession } from "./session-rename.js";
import { launchSession, makeConductor, stopConductor, workspaceAction } from "./server-launch.js";
import { conductorAnswer, linkSetMember, nameSet, readSets } from "./conductor-sets.js";
import { conductorPane } from "./conductor-role.js";
import { hookMetrics } from "./metrics.js";
import { GitWriteDiagnostics, requireGitWrite } from "./git-write-policy.js";
import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
import { readSpeechKey } from "./speech-key.js";
import { DEFAULT_SPEECH_VOICE, listSpeechVoices, resolveSpeechVoice } from "./speech-voice.js";
import { terminalKind, terminalMux } from "./terminal.js";
import { resolveTerminalReference } from "./terminal-resolve.js";
import { muxListForClient, muxReplyForClient, typedMuxRequest } from "./mux-wire.js";
import { tabWaiting } from "./tab-waiting.js";
/** How long the overview waits for per-tab git and transcript reads; the phone gives up at 20 s. */
export const OVERVIEW_ENRICH_BUDGET_MS = 5_000;
const OVERVIEW_CHILD_STOP_WAIT_MS = 100;
/** How long activity sampling may spend resolving background work before it
* leaves an unresolved row at its last known status. */
export const STATUS_ENRICH_BUDGET_MS = 2_000;
async function effectiveStatus(server, tabPanes, row, hooks) {
const panes = tabPanes.filter(p => p.agent);
if (panes.length !== 1 || !provider.safeParse(panes[0].agent).success)
return row;
const pane = panes[0];
const chat = await paneChatState(server, pane, { tokenWhenIdentified: false }).catch(() => ({}));
const session = typeof chat.sessionId === "string" ? chat.sessionId : undefined;
if (!session)
return row;
const evidence = await effectivePaneEvidence(server, { ...pane, agent_status: row.status }, session, hooks);
const resolved = resolveEffectiveStatus(evidence);
return !resolved || resolved === row.status ? row : { ...row, status: resolved };
}
/** The status each tab's row sends after the same background-work rules the
* overview applies: an idle or done tab whose ended turn still awaits shells or
* running children is working. The activity timer uses this while no overview
* is open, so its status clock still moves. A row whose background reads do not
* finish inside `budgetMs` is left out, which preserves its last known status. */
export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BUDGET_MS, hooks) {
const deadline = Date.now() + budgetMs;
const grouped = panesByTab(s);
const rows = await Promise.all(objects(s.tabs).map(async (tab) => {
const row = { workspace: tab.workspace_id, tab: tab.tab_id, status: tab.agent_status };
let timer;
const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), Math.max(0, deadline - Date.now())); timer.unref(); });
try {
return await Promise.race([effectiveStatus(server, grouped.get(tabActivityKey(row.workspace, row.tab)) ?? [], row, hooks).catch(() => row), late]);
}
finally {
clearTimeout(timer);
}
}));
return rows.filter((row) => row !== undefined);
}
/**
* `POST /v1/owner-inbox/close`: a signed phone decision on one row, guarded by
* the exact revision the phone read (`ifUpdatedAt` is compared as the wire
* string). Resolve means handled; dismiss removes the row from the shared list.
*/
export const ownerInboxCloseSchema = z.object({
id: z.string().uuid(),
ifUpdatedAt: z.string().min(1).max(64),
decision: z.enum(["resolve", "dismiss"]),
}).strict();
async function observedChatFolders(target, pane) {
const record = ownRecord(await readTurn(target.server, target.pane).catch(() => undefined), pane, target.source, target.session);
return record?.observedDirectories ?? [];
}
async function chatRepositories(target, pane) {
return recentFileRepositories(await observedChatFolders(target, pane));
}
export const capabilities = { browsers: true, turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true, terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, sessionSeen: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
files: true, repositoryFiles: true, fileResolution: true, chatFileCandidates: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, ciFailureHandoff: 2, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", macWindows: macWindowsSupported() ? 1 : undefined, macWindowStream: macWindowsSupported() ? 1 : undefined, 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, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, secretExec: true, ownerProof: 1, ownerConfirm: 1, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, terminalAddresses: true, conversationSearch: true, housekeeping: 1, housekeepingInventory: 1, issues: 1 };
export function capabilitiesForModules(snapshot) {
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
// The Inbox also carries schedule approval requests when the conductor is off.
// Close requires a paired phone's signature. Pushes cover this Hook's own
// eligible rows and require a phone registration.
if (snapshot.has("schedules"))
result.ownerInbox = true;
if (result.ownerInbox === true) {
result.ownerInboxActions = true;
result.ownerInboxClose = true;
result.ownerInboxPush = true;
result.ownerInboxIssues = true;
result.ownerInboxRules = true;
}
for (const name of ["memory", "hook", "git", "schedules"])
if (snapshot.has(name))
result[name] = true;
if (snapshot.has("hook"))
result.approvalRules = { version: 2, effects: ["always-ask", "deny"], harnesses: ["claude"], events: ["PermissionRequest"], tools: ["Bash"], inputField: "command", conductorTools: false, mcpTools: false, preExecution: false };
if (snapshot.has("schedules")) {
result.scheduleProjects = true;
result.scheduleUpdate = true;
result.scheduleEvents = true;
}
return result;
}
export function requireRoute(snapshot, method, route) {
if (snapshot.has("schedules") && (route === "/v1/owner-inbox" || route === "/v1/owner-inbox/close"))
return;
const owner = BUILTIN_MODULES.find(module => module.hookRoutes.some(entry => entry.method === method && entry.path === route));
if (owner && !snapshot.has(owner.name))
throw new BridgeError(404, disabledHint(owner.name));
}
/** Whether the Hook can load @phren/code and, if so, from where. Reported by
* /v1/health so a phone can explain a missing code package. */
async function codePackageStatus(store, enabled) {
if (!enabled)
return { missing: true };
const code = await loadCodePackage(store);
const from = loadedFrom();
return code && from ? { loadedFrom: from } : { missing: true };
}
/** Owner-only actions need the paired phone's signature once it has signed one (owner-proof.ts). */
const ownerProof = new OwnerProof();
const bodyDigests = new WeakMap();
async function body(request, cap = 11_500_000) {
let size = 0;
const chunks = [];
for await (const chunk of request) {
size += chunk.length;
if (size > cap)
throw new BridgeError(413, "Request is too large.");
chunks.push(chunk);
}
const raw = Buffer.concat(chunks);
bodyDigests.set(request, bodyDigest(raw));
return object(JSON.parse(raw.toString() || "{}"));
}
export function selectedServer(url) {
const mux = url.searchParams.get("mux");
const selected = mux ? /^(herdr|tmux):(.+)$/.exec(mux) : undefined;
if (mux && !selected)
throw new BridgeError(400, "Select a terminal source.");
const explicit = url.searchParams.get("server");
if (explicit && selected && explicit !== selected[2])
throw new BridgeError(400, "Conflicting terminal sources.");
const server = serverName.parse(explicit || selected?.[2] || "default");
// Old phones used herdr:tmux. Keep that alias, but a typed tmux id must
// never silently route to a Herdr session with the same server name.
if (selected?.[1] === "tmux" && terminalKind(server) !== "tmux") {
throw new BridgeError(409, "This terminal source changed. Refresh the computer.", { code: "mux-kind-mismatch" });
}
return server;
}
export function workspacesReader(ctx) {
const { modules, info, agentHooks, journal, tabActivity, contextUsage } = ctx;
return async (server, s, watchApprovals, live) => {
const { generation, stamps: lastChanged } = await tabActivity.observe(server, s);
if (watchApprovals && (live?.() ?? true))
agentHooks.overview.renew(server);
const context = await contextUsage.read(server, s);
await journal.record(server, objects(s.panes));
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(() => ({}))])));
// The Hook's record says which pane is the conductor, whatever the agent is named.
const conductor = await conductorPane(server, s).catch(() => undefined);
const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged, conductor ? String(conductor.pane_id) : null);
// The branch each tab's agent is on, for the session cards.
const agentsByTab = panesByTab(s);
for (const [key, panes] of agentsByTab)
agentsByTab.set(key, panes.filter(pane => pane.agent));
// Move records are decoration: read alongside the rest, inside the budget.
const movesRead = listMoves().catch(() => []);
const tabs = objects(workspaces.groups).flatMap(group => objects(group.children).map(tab => ({ group, tab })));
// What a chat needs to open (the exact conversation) comes straight from the
// chat states; everything below it is decoration.
for (const { group, tab } of tabs) {
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
tab.queuedPrompts = agents.reduce((count, pane) => count + (ctx.turnQueue?.count(server, String(pane.pane_id)) ?? 0), 0);
if (agents.length !== 1)
continue;
const chat = chatStates.get(agents[0]);
tab.browserWatch = chat?.browserWatch ?? "unknown";
if (chat?.starting === true)
tab.starting = true;
// After the identity probe above, which is what learns a pane's transcript.
Object.assign(tab, paneAccountField(server, agents[0]));
if (typeof chat?.sessionId === "string" && provider.safeParse(agents[0].agent).success) {
tab.target = { server, workspace: group.id, tab: tab.id, pane: agents[0].pane_id, source: agents[0].agent, session: chat.sessionId };
}
}
// Branch, model, children and current step read git and transcripts. On a
// starved machine (load 230 on 10 cores, 2026-09-24) that took longer than
// the phone waits, so the computer read as offline. The overview answers
// within its budget with whatever decoration is ready; a later read fills in.
let expired = false;
let timer;
const budget = new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); });
// Each pane's own turn record (one small file): whether its ended
// turn still has background work, and which dispatch it is. It runs
// alongside the slower reads so a stuck transcript cannot hide children, but
// inside the budget, so a stuck disk cannot hold the overview either.
const recordEnrichment = [];
const turnPhases = new Map();
const turnReads = new Map();
const records = Promise.all(tabs.map(async ({ group, tab }) => {
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
const pane = agents.length === 1 ? agents[0] : undefined;
const session = pane ? object(tab.target).session : undefined;
const turnRead = typeof session === "string" && pane ? paneTurnRecord(server, pane, session).catch(() => undefined) : undefined;
if (turnRead)
turnReads.set(tab, turnRead);
const record = await turnRead;
if (expired)
return;
const phase = record ? turnPhase(record) : undefined;
if (phase)
turnPhases.set(tab, phase);
if (pane && typeof session === "string") {
const available = availablePaneEvidence(server, pane, session, record, agentHooks);
if (available.held || ["blocked", "waiting"].includes(String(available.paneStatus)) || phase?.phase === "working") {
const status = resolveEffectiveStatus(available);
if (status)
tab.agentStatus = status;
}
}
const native = s.kind !== "tmux" && pane && typeof session === "string" ? herdrTurn(pane) : undefined;
const completed = s.kind === "tmux" && typeof session === "string" && typeof pane?.agent === "string"
? await tmuxCompletedTurn(pane.agent, session, record).catch(() => record)
: record;
if (expired)
return;
const lifecycle = turnCompletion(completed);
// Core's counter and the harness Stop are independent. Without a
// correlation from Core, a Stop cannot identify this native turn.
const completion = native
? { id: native.id }
: lifecycle && completed?.stop && s.kind === "tmux"
? { ...lifecycle, id: tmuxCompletion(completed.source, completed.session, completed.stop.at, completed.stop.seq) }
: lifecycle;
const [legacySeen, pin] = pane ? await Promise.all([
readSessionSeen(server, String(pane.pane_id), completion?.id, lifecycle?.id),
s.kind === "tmux" ? undefined : sessionPin(server, pane),
]) : [];
if (expired)
return;
const seen = native?.seen === undefined ? legacySeen : native.seen ? native.id : undefined;
if (pin)
tab.sharedPin = pin;
if (native && pane) {
tab.turn = native.turn;
const labels = object(pane.labels);
tab.labels = Object.fromEntries(["herdr.seen", "herdr.pinned"].filter(key => typeof labels[key] === "string" && labels[key].length <= 256).map(key => [key, labels[key]]));
}
if (completion)
tab.completion = completion;
if (seen)
tab.seenCompletion = seen;
const title = await recordTitle(record, { paneLabel: tab.paneLabel, harnessTitle: tab.title, tabLabel: tab.label, workspaceLabel: group.label, fallbackLabel: tab.label });
if (expired)
return;
tab.title = title;
// Apply every row's small-file metadata before starting transcript reads.
// A stalled lookup must not hide another row's completion or pane label.
if (!native && completion && lifecycle && completed && pane)
recordEnrichment.push(async () => {
const file = await targetTranscriptPath({ server, pane: String(pane.pane_id), source: completed.source, session: completed.session });
await refreshTranscript(file, completed.source, completed.session);
const entry = await completionEntry(file, completed.source, completed.prompt.at, lifecycle.at, completed.stop);
if (!expired && entry !== undefined)
completion.entry = entry;
});
recordEnrichment.push(async () => {
const evidence = pane && typeof session === "string" ? await effectivePaneEvidence(server, pane, session, agentHooks, undefined, record ?? null) : undefined;
const background = evidence ? liveWork(record, evidence.final, evidence.runningChildren) ?? provisionalWork(evidence) : undefined;
if (expired)
return;
if (evidence) {
Object.assign(tab, evidence.children);
const resolved = resolveEffectiveStatus(evidence);
if (background && resolved === "working" && (phase?.phase === "ended" || ["idle", "done"].includes(String(tab.agentStatus))))
tab.backgroundTasks = background;
if (resolved)
tab.agentStatus = resolved;
if (phase?.phase === "ended" && !phase.reply && evidence.final?.lastAssistant) {
const { text, truncated } = truncateUtf8(evidence.final.lastAssistant);
turnPhases.set(tab, { ...phase, reply: text, truncated });
}
}
markBackground(tab, background);
const target = targetSchema.safeParse(tab.target);
const stall = target.success && agents.length === 1
? await sessionStalls.observe(target.data, { ...agents[0], agent_status: tab.agentStatus }, async () => background) : {};
if (expired)
return;
Object.assign(tab, stall);
if (target.success) {
const moves = await movesRead;
if (expired)
return;
Object.assign(tab, moveSessionFields(moves, target.data, title));
}
});
}));
// Separate bounded queues: a stalled git/model/step read cannot prevent
// the child tree from reaching the phone. Apply each answer as it arrives.
const eachTab = (read) => {
let next = 0;
return Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
while (!expired && next < tabs.length)
await read(tabs[next++]);
}));
};
const identified = (group, tab) => {
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
const session = agents.length === 1 ? chatStates.get(agents[0])?.sessionId : undefined;
return agents.length === 1 && provider.safeParse(agents[0].agent).success && typeof session === "string"
? { source: agents[0].agent, session, pane: agents[0] } : undefined;
};
const enrich = Promise.all([
records.then(() => {
if (expired)
return;
return Promise.all(recordEnrichment.map(read => read().catch(() => { })));
}),
eachTab(async ({ tab }) => {
if (!modules.has("git") || typeof tab.cwd !== "string" || !tab.agent)
return;
const branch = await repositoryBranch(tab.cwd);
if (!expired && branch !== undefined)
tab.branch = branch;
}),
// Use the pane's Stop when ready. Fall back to transcript evidence if
// the record is slow so child counts still fit inside the overview budget.
eachTab(async ({ group, tab }) => {
const identity = identified(group, tab);
if (!identity)
return;
const turnRead = turnReads.get(tab);
const record = turnRead && await within(OVERVIEW_CHILD_STOP_WAIT_MS, turnRead);
if (expired)
return;
const children = await childActivity(identity.source, identity.session, record).catch(() => undefined);
if (expired || !children)
return;
Object.assign(tab, children);
markBackground(tab, children.runningChildren);
}),
eachTab(async ({ group, tab }) => {
const identity = identified(group, tab);
if (!identity)
return;
const model = await currentModel(identity.source, identity.session).catch(() => undefined);
if (!expired && model)
tab.model = model;
}),
eachTab(async ({ group, tab }) => {
const identity = identified(group, tab);
if (!identity || identity.pane.agent_status !== "working")
return;
const step = await currentStep(identity.source, identity.session).catch(() => undefined);
if (!expired && step)
tab.currentStep = step;
}),
]);
await Promise.race([enrich, budget]);
expired = true;
clearTimeout(timer);
// Derive reply and wait from the evidence that arrived inside the budget.
for (const { tab } of tabs) {
const phase = turnPhases.get(tab);
if (phase?.phase !== "ended")
continue;
const reply = tab.agentStatus !== "working" || tab.backgroundTasks ? replyExcerpt(phase.reply) : undefined;
if (reply)
tab.lastReply = reply;
const waiting = tabWaiting(phase, tab);
if (waiting)
tab.waiting = waiting;
}
// The row's status may have changed above (background work turns idle into
// working): stamp what this reply sends, not the raw snapshot.
const activity = await tabActivity.recordStatus(server, tabs.map(({ group, tab }) => ({ workspace: group.id, tab: tab.id, status: tab.agentStatus })), generation);
for (const { group, tab } of tabs) {
const stamp = activity.get(tabActivityKey(group.id, tab.id));
if (stamp) {
tab.lastChangedAt = stamp.lastChangedAt;
tab.statusSince = stamp.statusSince;
}
}
const mux = terminalMux(server);
// A diverged or long-unsynced store, for the computer list (health.ts storeWarning).
const storeWarnings = cachedStoreWarnings(defaultPhrenPath());
return { ...workspaces, kind: mux.kind, mux, phren: info, ...(storeWarnings.length ? { storeWarnings } : {}) };
};
}
/** One read-only GET to every linked peer, each answer or its error by computer name. */
/** The value, or undefined once `ms` passes or it fails: a probe never waits on a slow reader. */
async function within(ms, value) {
let timer;
const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), ms); timer.unref(); });
try {
return await Promise.race([value.catch(() => undefined), late]);
}
finally {
clearTimeout(timer);
}
}
async function fromPeers(route) {
const { peers, peerError } = await optionalHookPeers();
const answers = await Promise.all(peers.map(async (peer) => {
try {
return { name: peer.name, ...await peerRead(peer, route, { timeout: 15_000, ttl: PEER_READ_TTL_MS }) };
}
catch (error) {
const code = error instanceof BridgeError && typeof error.details?.code === "string" ? error.details.code : undefined;
const older = error instanceof BridgeError && error.status === 404;
return { name: peer.name, error: older ? "This computer's Hook predates this report; update it with phren bridge update." : error instanceof Error ? error.message.slice(0, 300) : "Unavailable", ...(code ? { code } : {}) };
}
}));
return { peers: answers, ...(peerError ? { peerError } : {}) };
}
async function moveDestination(move, caller) {
if (!caller || !move.to.computer || caller.fingerprint !== move.computerFingerprint || caller.name && caller.name !== move.to.computer || caller.id && caller.id !== move.computerId)
throw new BridgeError(403, "This peer is not the move's source or destination.");
const peer = (await hookPeers()).find(peer => peerFingerprint(peer) === move.computerFingerprint && (!caller.name || caller.name === peer.name));
if (!peer || object((await peerRequest(peer, "/v1/health", undefined, 5_000)).computer).id !== move.computerId)
throw new BridgeError(403, "The move destination's enrollment changed.");
}
/** Destinations whose enrollment was checked for a move's conversation pages, until when. */
const verifiedPages = new Map();
/** The audit row a request to one of the Mac window routes would carry, set before proof and body parsing. */
function macWindowsAuditTarget(url) {
switch (url.pathname) {
case "/v1/mac/windows": return { action: "list" };
case "/v1/mac/windows/snapshot": return { action: "snapshot", id: url.searchParams.get("id") };
case "/v1/mac/windows/action": return { action: "invalid" };
case "/v1/mac/windows/permissions": return { action: "invalid" };
default: return undefined;
}
}
async function peerContinuationIntent(caller, id, conversation) {
const candidates = (await hookPeers()).filter(peer => peerFingerprint(peer) === caller.fingerprint && (!caller.name || caller.name === peer.name));
if (candidates.length !== 1)
throw new BridgeError(403, "The launch origin is not uniquely verified.");
return peerRequest(candidates[0], `/v1/sessions/move/intent?id=${z.string().uuid().parse(id)}${conversation === undefined ? "" : `&conversation=${conversation}`}`, undefined, 5_000);
}
export function createRouteHandler(ctx) {
const chatFiles = new ChatFiles();
const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, resources, launches, locatedDirectories, fanoutMessages, canary } = ctx;
const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
const readWorkspaces = workspacesReader(ctx);
const gitWrites = new GitWriteDiagnostics();
const paneContext = { ...ctx, gitWrites };
return async (request, response) => {
response.setHeader("X-Phren-Protocol", String(PROTOCOL));
response.setHeader("Cache-Control", "no-store");
// Set as soon as the path is known, so proof and body-parse refusals are audited too.
let macWindowAudit;
try {
const url = new URL(request.url || "/", "http://phren.local");
if (url.origin !== "http://phren.local")
throw new BridgeError(400, "Invalid request origin.");
macWindowAudit = macWindowsAuditTarget(url);
requireRoute(modules, request.method ?? "", url.pathname);
if (url.pathname === "/v1/browsers" || url.pathname.startsWith("/v1/browsers/")) {
browserRoute(ctx.browsers, request.method ?? "", url, response);
return;
}
let result;
if (url.pathname.startsWith("/v1/conductor/move/")) {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
if (request.method === "GET")
await ctx.succession.authorize(z.string().uuid().parse(url.searchParams.get("id")), requestPeer(request));
}
const memoryRoute = PROJECT_MEMORY_ROUTE.exec(url.pathname);
if (memoryRoute) {
const [, project, route] = memoryRoute;
if (request.method !== (route === "findings" ? "POST" : "GET"))
throw new BridgeError(405, "Unsupported request method.");
if (!modules.has("memory"))
throw new BridgeError(404, disabledHint("memory"));
if (route === "memory")
result = projectMemory(modules.store, project);
else if (route === "memory/files")
result = await memoryForFiles(modules.store, project, url.searchParams.getAll("path"));
else if (route === "memory/search")
result = memorySearch(modules.store, project, url.searchParams.get("q") ?? "", Number(url.searchParams.get("limit") ?? "5"));
else
result = await saveFinding(modules.store, project, await body(request));
}
else if (PROJECT_GIT_ROUTE.test(url.pathname)) {
const [, project, tokenRoute] = PROJECT_GIT_ROUTE.exec(url.pathname);
if (request.method !== (tokenRoute ? "POST" : "GET"))
throw new BridgeError(405, "Unsupported request method.");
if (!modules.has("git"))
throw new BridgeError(404, disabledHint("git"));
if (tokenRoute) {
const data = await body(request);
requireGitWrite("/v1/projects/:project/git/host-token", data.expectedRepository, request.headers ?? {}, gitWrites);
result = await projectHostToken(modules.store, project, await journal.recent(), data);
}
else
result = await projectGit(modules.store, project, await journal.recent());
}
else if (url.pathname === "/v1/store/directory" || url.pathname === "/v1/tasks/stores") {
if (request.method !== "GET")
throw new BridgeError(405, "Unsupported request method.");
result = await storeDirectory(modules.store);
}
else if (url.pathname === "/v1/store/pull-now") {
if (request.method !== "POST")
throw new BridgeError(405, "Unsupported request method.");
if (!ctx.storePulls)
throw new BridgeError(503, "Store pulls unavailable.");
result = await ctx.storePulls.route(request, await body(request));
}
else if (url.pathname.startsWith("/v1/store/")) {
result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
}
else if (request.method === "GET") {
// The owner asked for a fresh reading (pull to refresh, `phren computers`): peers are dialed again.
if (url.searchParams.get("refresh") === "1")
refreshPeerReads();
// Owner actions that a phone signs carry no body on GET: the signed digest is of zero bytes.
await ownerProof.check(request, url.pathname, {}, bodyDigest(Buffer.alloc(0)));
switch (url.pathname) {
case "/v1/health":
result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
break;
case "/v1/metrics":
result = hookMetrics.snapshot();
break;
case "/v1/health/details":
result = { ...await healthDetails({ hookVersion: version, computerId: computerID, store: scheduleStore,
scheduler: scheduler ? { running: true, lastTickAt: scheduler.lastTickAt } : undefined, push: agentHooks.push.status }),
gitboyWebhooks: ctx.gitboyWebhooks?.status ?? { configured: false, listening: false }, gitWrites: gitWrites.snapshot() };
break;
case "/v1/health/peers": {
// A peer's health probe asks whether this computer lists it back.
const caller = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() })
.parse({ name: url.searchParams.get("name") ?? undefined, hostKey: url.searchParams.get("hostKey") ?? undefined });
result = { computer: info.computer, version, ...await listsCaller(caller) };
break;
}
case "/v1/owner-inbox": {
const local = url.searchParams.get("local") === "1";
// `reconcile=1` only means anything to a peer reading this Hook: it
// keeps the keys the aggregate filters and dedupes on. `issues=1`
// asks for the structured issue link; without it the link is only
// in the title, which older strict readers still accept.
result = await ownerInboxView(ctx.inbox, { action: "list", includeResolved: url.searchParams.get("includeResolved") === "true",
issues: url.searchParams.get("issues") === "1", ...(url.searchParams.get("rules") === "1" ? { rules: true } : {}) }, local, url.searchParams.get("compact") === "1", local && url.searchParams.get("reconcile") === "1");
break;
}
// A terminal reference from chat text (alaarab/phren-apps#676): this computer's pane or tab, or a linked peer's.
case "/v1/terminals/resolve":
result = await resolveTerminalReference(url.searchParams.get("ref"), { computer: info.computer, from: url.searchParams.get("from"), fromCore: url.searchParams.get("fromCore"), owner: ownerRequest(request, {}) });
break;
case "/v1/conductor/integrator":
result = { integrator: await readIntegrator() ?? null };
break;
case "/v1/dispatch": {
await reconcileInterruptedDispatches();
// A bounded list: the phone reads this on a timer for one line.
// `id` names one receipt, wherever it sits in the ledger.
const limit = z.coerce.number().int().min(1).max(1024).optional().parse(url.searchParams.get("limit") ?? undefined);
const id = z.string().min(1).max(64).optional().parse(url.searchParams.get("id") ?? undefined);
const receipts = await dispatchStatus();
const list = id
? { dispatches: receipts.filter(receipt => receipt.id === id), total: receipts.length, truncated: false }
: recentDispatches(receipts, limit);
// `phase` folds each receipt's worker and return states into one word.
result = { ...list, dispatches: list.dispatches.map(receipt => ({ ...receipt, phase: dispatchPhase(receipt) })) };
break;
}
// A session move (session-move.ts) by its id, or this computer's recent moves.
case "/v1/conductor/move/launch": {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.launchIntent(z.string().uuid().parse(url.searchParams.get("id")));
break;
}
case "/v1/conductor/move/status": {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.status(z.string().uuid().parse(url.searchParams.get("id")));
break;
}
case "/v1/conductor/move/operation": {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.outgoing(z.string().uuid().parse(url.searchParams.get("id")), z.string().uuid().parse(url.searchParams.get("operationId")));
break;
}
case "/v1/conductor/move/notification": {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.notification(z.string().uuid().parse(url.searchParams.get("id")), z.string().parse(url.searchParams.get("deliveryId")));
break;
}
case "/v1/dispatch/relocation": {
result = await relocationSupport(z.string().parse(url.searchParams.get("id")), z.string().parse(url.searchParams.get("session")));
break;
}
case "/v1/sessions/move/intent": {
const id = z.string().uuid().parse(url.searchParams.get("id"));
const caller = requestPeer(request), move = await readMove(id);
if (!move || move.state === "failed")
throw new BridgeError(403, "This continuation intent is no longer authorized.");
// `conversation=<offset>`: a page of the conversation a summary-by-target move copies (continuation-launch.ts).
// The destination's enrollment is checked again (one SSH call back to it) at most once a minute while it pages.
const page = url.searchParams.get("conversation");
const verifiedKey = JSON.stringify([id, caller?.fingerprint, caller?.name, caller?.id]);
if (page === null || (verifiedPages.get(verifiedKey) ?? 0) <= Date.now()) {
await moveDestination(move, caller);
if (page !== null) {
verifiedPages.set(verifiedKey, Date.now() + 60_000);
if (verifiedPages.size > 64)
verifiedPages.delete(verifiedPages.keys().next().value);
}
}
result = page === null ? await continuationIntent(id) : await continuationConversationPage(id, z.coerce.number().int().nonnegative().parse(page));
break;
}
case "/v1/sessions/move/launch": {
const placement = await continuationPlacement(z.string().uuid().parse(url.searchParams.get("id")));
const caller = requestPeer(request);
if (!placement && caller) {
const id = z.string().uuid().parse(url.searchParams.get("id"));
const intent = continuationLaunchSchema.parse(await peerContinuationIntent(caller, id));
if (intent.computerId !== info.computer.id || intent.brief.id !== id)
throw new BridgeError(403, "This continuation is not intended for this Hook.");
result = { state: "not-placed" };
break;
}
if (!ownerRequest(request, {}) && (!caller || !placement?.caller || caller.name !== placement.caller.name || caller.id !== placement.caller.id || caller.fingerprint !== placement.caller.fingerprint))
throw new BridgeError(403, "This peer is not the launch's recorded counterpart.");
result = placement ?? { state: "missing" };
break;
}
case "/v1/sessions/move/computers": {
if (!ownerRequest(request, {}))
throw new BridgeError(403, "Only the owner can list continuation computers.");
const session = url.searchParams.get("session");
let currentAccount;
if (session) {
const server = selectedServer(url);
const rows = objects((await readWorkspaces(server, await snapshot(server), false)).groups).flatMap(group => objects(group.children));
const current = rows.find(row => object(row.target).session === session && row.agent === "claude");
if (current)
currentAccount = String(object(current.account).id ?? "default");
}
result = await moveComputers(url.searchParams.get("project"), info.computer.name, async () => ({ ...await localMoveAvailability(url.searchParams.get("project"), () => accountUsage.read(new Set(["claude"]), true), url.searchParams.get("conductor") === "1"), computerId: info.computer.id }), currentAccount, url.searchParams.get("conductor") === "1");
break;
}
// Local facts only: peers may probe these without starting a move or fanning out.
case "/v1/sessions/move/availability": {
if (!ownerRequest(request, {}) && request.headers?.["x-phren-origin"] !== "peer")
throw new BridgeError(403, "Only the owner or a verified peer can read continuation availability.");
const availability = await localMoveAvailability(url.searchParams.get("project"), () => accountUsage.read(new Set(["claude"]), true), url.searchParams.get("conductor") === "1");
if (!ownerRequest(request, {}))
for (const harness of availability.harnesses)
for (const account of harness.accounts ?? []) {
delete account.email;
delete account.plan;
}
result = { ...availability, computerId: info.computer.id };
break;
}
case "/v1/sessions/move": {
const move = await readMove(z.string().uuid().parse(url.searchParams.get("id")));
if (!move)
throw new BridgeError(404, "No move with that id on this computer.");
if (request.headers?.["x-phren-origin"] === "peer")
await moveDestination(move, requestPeer(request));
result = { move };
break;
}
case "/v1/sessions/moves":
result = { moves: (await listMoves()).slice(0, 50) };
break;
// Receiving side of a launched brief: what the worker's hooks reported for it.
case "/v1/dispatch/arrival":
result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
break;
// Asked by the dispatching Hook when this computer's worker hit its usage limit and continues on another account.
case "/v1/dispatch/brief":
result = { text: await readLaunchBrief(briefId.parse(url.searchParams.get("id"))) ?? null };
break;
case "/v1/approval-rules":
result = { rules: await listApprovalRules(undefined, z.string().regex(/^[A-Za-z0-9+/]{43}=$/).optional().parse(url.searchParams.get("pairedKey") ?? undefined)) };
break;
case "/v1/conductor/grants":
result = { grants: await listNamedGrants() };
break;
// The owner's release authority policy, which conductors read and quote in briefs.
case "/v1/authority": {
const policy = await readAuthority();
const project = url.searchParams.get("project");
result = project !== null ? { authority: projectAuthority(policy, z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/).parse(project)) }
: { source: policy.source, ...(policy.updatedAt ? { updatedAt: policy.updatedAt } : {}), ...(policy.updatedBy ? { updatedBy: policy.updatedBy } : {}),
projects: Object.keys(policy.projects).sort().map(name => projectAuthority(policy, name)), confirmations: await listConfirmations() };
break;
}
// One row per real computer, however many names machines.yaml and the network give it.
case "/v1/computers": {
const { computers, peerError } = await readComputers({ probe: true, local: { id: info.computer.id } });
result = { computers, ...(peerError ? { peerError } : {}) };
break;
}
// Asked by linked peers to place this computer in a set, and before they start a conductor: one per set.
case "/v1/conductor":
result = await conductorAnswer(info, url);
break;
case "/v1/sets":
result = await readSets(info);
break;
// Bounded like capacity: a cold `claude auth status` per home can take seconds. Without
// `harnesses` the phone treats the computer as unknown and offers everything; the probe keeps
// running, so the next request answers from cache.
case "/v1/harnesses":
result = await harnessInventoryWithin(2_500) ?? { pending: true };
break;
case "/v1/dispatch/capacity": {
const live = await servers();
const snapshots = await Promise.all(live.map(server => snapshot(String(server.session))));
// Asked by a conductor with its name or host key: whether this computer links it back, so it dispatches only within its set.
const caller = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() })
.parse({ name: url.searchParams.get("name") ?? undefined, hostKey: url.searchParams.get("hostKey") ?? undefined });
const linksBack = caller.name || caller.hostKey ? { knowsCaller: (await listsCaller(caller)).knowsCaller } : {};
// Both bounded so a peer's capacity probe never waits on a cold `claude auth status` or usage read; missing means unknown.
// PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
// `usage` is the room left per Codex and Claude account, so `anywhere` can break a tie by it.
const [inventory, limits, pressure] = await Promise.all([launchCheckOff() ? undefined : harnessInventoryWithin(2_500), within(2_500, accountUsage.limits(true)),
within(2_500, readPressure())]);
// Memory or load past this computer's budget (heavy/budget.ts): `anywhere` passes it over, and an agent may not name it.
const overBudget = pressure ? pressureReason(pressure, readBudget(pressure.totalBytes)) : undefined;
result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session), ...linksBack,
working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0),
...(inventory ? { harnesses: inventory.harnesses } : {}), ...(limits ? { usage: capacityRoom(limits, Date.now()) } : {}),
...(overBudget ? { overBudget } : {}) };
break;
}
case "/v1/speech/voices": {
// The phone's voice picker: this computer's setting and the voices its account has.
const key = await readSpeechKey();
if (!key)
throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
const current = await resolveSpeechVoice();
result = { voice: current.voice, source: current.source, defaultVoice: DEFAULT_SPEECH_VOICE, voices: await listSpeechVoices(key) };
break;
}
case "/v1/muxes":
result = { muxes: muxListForClient(await servers(), url.searchParams.get("typed") === "1") };
break;
case "/v1/activity":
result = { events: await journal.recent() };
break;
case "/v1/conversations/search":
result = await conversationSearch(url.searchParams.get("q"), url.searchParams.get("limit"), url.searchParams.get("cursor"));
break;
case "/v1/web-servers":
result = { servers: await webServers() };
break;
// `all=1` (capability simulatorDevices): every available device with its state, for the phone's picker.
case "/v1/simulators":
result = { simulators: url.searchParams.get("all") === "1" ? await simulatorDevices() : await bootedSimulators() };
break;
case "/v1/simulators/screenshot": {
const bytes = await simulatorScreenshot(String(url.searchParams.get("udid") ?? ""));
response.setHeader("Content-Type", "image/png");
response.end(bytes);
return;
}
// Phone control of this Mac's windows (mac-windows.ts); owner-only on every one of them.
// The handler's catch audits refusals (proof, body parse, owner, disabled, invalid input).
case "/v1/mac/windows": {
macWindowsOwnerOnly(ownerRequest(request, {}));
result = await macWindowsList();
break;
}
case "/v1/mac/windows/snapshot": {
macWindowsOwnerOnly(ownerRequest(request, {}));
const bytes = await macWindowsSnapshot(url.searchParams.get("id"), url.searchParams.get("size") ?? undefined, url.searchParams.get("quality") ?? undefined);
response.setHeader("Content-Type", "image/jpeg");
response.end(bytes);
return;
}
case "/v1/files":
result = { files: await listUploads("files") };
break;
case "/v1/git/status": {
result = await withGitReadDeadline(async () => {
const target = targetFromURL(url), pane = await validateTarget(target);
const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
return gitStatus(cwd, z.string().min(1).max(4096).optional().parse(url.searchParams.get("untrackedPath") ?? undefined));
});
break;
}
case "/v1/files/resolve": {
const target = targetFromURL(url), pane = await validateTarget(target);
const child = url.searchParams.get("child") ?? undefined, worktree = url.searchParams.get("worktree") ?? undefined;
const cwd = await gitRepository(pane, target, child, worktree);
const requested = url.searchParams.get("path") ?? "";
if (url.searchParams.get("candidates") !== "1") {
result = url.searchParams.get("matches") === "1"
? await withGitReadDeadline(async () => chatFileMatches(await gitRoot(cwd), cwd, requested, () => child || worktree ? Promise.resolve(new Map()) : chatRepositories(target, pane)))
: await resolveFilePath(await gitRoot(cwd), cwd, requested);
break;
}
result = await withGitReadDeadline(async () => chatFiles.resolve(target, await gitRoot(cwd), cwd, requested, url.searchParams.get("search") === "1", () => child || worktree
? Promise.resolve([]) : observedChatFolders(target, pane)));
break;
}
case "/v1/files/range": {
let root;
const requested = url.searchParams.get("path") ?? "", version = url.searchParams.get("version") ?? undefined;
const range = () => [rangeInteger(url.searchParams.get("offset"), 0), rangeInteger(url.searchParams.get("length"), MAX_FILE_RANGE)];
const fileToken = url.searchParams.get("fileToken");
if (fileToken !== null) {
const target = targetFromURL(url);
await validateTarget(target);
result = await chatFiles.read(target, fileToken, requested, ...range(), version);
break;
}
else if (url.searchParams.get("scope") === "uploads") {
root = path.join(bridgeRoot(), "uploads");
}
else if (url.searchParams.has("session")) {
const target = targetFromURL(url), pane = await validateTarget(target);
const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
const recentRoot = url.searchParams.get("recentRoot");
if (recentRoot !== null) {
if (url.searchParams.has("child") || url.searchParams.has("worktree"))
throw new BridgeError(400, "Choose one checkout.");
const [offset, length] = range();
result = await withGitReadDeadline(async () => readRecentChatFile(await chatRepositories(target, pane), recentRoot, requested, offset, length, version));
break;
}
const repository = await gitRoot(cwd);
// `~/<path>` and `~root/<root>/<path>` are media from /v1/files/resolve; a repository's own folder of that name still wins.
if (isMediaPath(requested)) {
const [offset, length] = range();
result = repository ? await readFileRange(repository, requested, offset, length, version).catch(error => {
if (error instanceof BridgeError && error.status === 404)
return readMedia(requested, offset, length, version);
throw error;
}) : await readMedia(requested, offset, length, version);
break;
}
if (!repository)
throw new BridgeError(409, "This pane is not in a project repository.");
root = repository;
}
else {
const candidates = await locateProject(url.searchParams.get("project") ?? "", await journal.recent());
const directory = url.searchParams.get("directory");
const candidate = directory ? candidates.find(item => item.directory === directory) : candidates[0];
if (!candidate)
throw new BridgeError(404, "This project folder is not available on this computer.");
root = candidate.directory;
}
result = await readFileRange(root, requested, ...range(), version);
break;
}
case "/v1/models":
result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? ""), url.searchParams.get("account") ?? undefined) };
break;
case "/v1/projects/files": {
const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
const directory = url.searchParams.get("directory");
const candidate = directory ? candidates.find(item => item.directory === directory) : candidates[0];
if (!candidate)
throw new BridgeError(404, "This project folder is not available on this computer.");
result = await browseFiles(candidate.directory, url.searchParams.get("path") ?? "");
break;
}
case "/v1/uploads/image": {
// A picture the phone sent, as the transcript names it by path.
const bytes = await uploadImage(String(url.searchParams.get("path") ?? ""));
response.setHeader("Content-Type", "application/octet-stream");
response.end(bytes);
return;
}
case "/v1/simulators/apps":
result = { apps: await simulatorApps(String(url.searchParams.get("udid") ?? "")) };
break;
case "/v1/usage": {
// A phone built before OpenCode Go rejects the whole response when it
// meets a source it does not know, so a client names the sources it
// understands and an older one gets the original four.
const known = new Set((url.searchParams.get("sources") ?? "codex,claude,opencode,openrouter").split(",").map(s => s.trim()).filter(Boolean));
// A phone built before Go's plan windows rejects a Go window with a
// percentage and no dollar limit (and the whole answer with it), so
// they go only to callers that ask with `goPlan=1`; others keep the
// Go account and its message without windows.
const goPlan = url.searchParams.get("goPlan") === "1";
// Likewise one `claude` row: a phone that shipped before accounts refuses
// two rows with one source, so extra Claude homes come only with `accounts=all`.
const allAccounts = url.searchParams.get("accounts") === "all";
const usage = await accountUsage.read(known, allAccounts);
result = { ...usage, accounts: usageForCaller(usage.accounts, known, goPlan) };
// `peers=1` (the memory-free `phren usage`): each linked computer's own answer too.
if (url.searchParams.get("peers") === "1")
result = { ...result, computer: info.computer,
...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...(goPlan ? { goPlan: "1" } : {}), ...(allAccounts ? { accounts: "all" } : {}) })}`) };
break;
}
case "/v1/resources": {
result = { computer: info.computer, resources: await resources.read() };
if (url.searchParams.get("peers") === "1")
result = { ...result, ...await fromPeers("/v1/resources") };
break;
}
case "/v1/issues": {
// The phone's issue list (docs/phren-hook.md#issues-from-the-phone): owner-only,
// bounded, bodies trimmed, and every store project's repo when none is named.
if (!ownerRequest(request, {}))
throw new BridgeError(403, "Only the owner reads issues.");
result = await issueListRoute(url, modules.store);
break;
}
case "/v1/issues/item": {
if (!ownerRequest(request, {}))
throw new BridgeError(403, "Only the owner reads issues.");
result = await issueItemRoute(url);
break;
}
case "/v1/housekeeping": {
// The newest housekeeping report (docs/housekeeping.md); null before the first pass.
// This computer only; the phone asks each computer itself. `peers=1` is for `phren housekeeping`.
if (!ctx.housekeeper)
throw new BridgeError(404, "Housekeeping is not running on this Hook.");
const dismissed = url.searchParams.get("dismissed") === "1", inventory = url.searchParams.get("inventory") === "1";
// Before the first scheduled pass, run one now so the answer always has the full shape.
const view = await ctx.housekeeper.view(dismissed, inventory) ?? (await ctx.housekeeper.run("manual"), await ctx.housekeeper.view(dismissed, inventory));
// No scan yet: start one; `inventory` appears once it lands (the revision changes).
if (inventory && !view?.inventory)
void ctx.housekeeper.scan().catch(() => { });
result = { computer: info.computer, ...view };
if (url.searchParams.get("peers") === "1")
result = { ...result, ...await fromPeers("/v1/housekeeping") };
break;
}
case "/v1/push/status":
result = agentHooks.push.status;
break;
case "/v1/sudo":
result = { requests: agentHooks.sudo.list() };
break;
case "/v1/secrets":
result = { requests: agentHooks.secrets.list() };
break;
case "/v1/owner-confirms":
result = { requests: agentHooks.ownerConfirms.list() };
break;
case "/v1/projects/locate": {
const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
for (const candidate of candidates) {
locatedDirectories.delete(candidate.directory);
locatedDirectories.add(candidate.directory);
if (locatedDirectories.size > 128)
locatedDirectories.delete(locatedDirectories.values().next().value);
}
result = { candidates };
break;
}
case "/v1/projects/repos":
result = { repos: await candidateRepos(await journal.recent()) };
break;
case "/v1/ci/failures": {
if (!ownerRequest(request, {}))
throw new BridgeError(403, "Only the owner can read session CI failures.");
if (!ctx.handOffs)
throw new BridgeError(503, "CI hand-offs are unavailable.");
const target = targetFromURL(url);
await validateTarget(target);
result = await ctx.handOffs.ciFailures(target);
break;
}
case "/v1/workspaces": {
const server = selectedServer(url);
result = muxReplyForClient(await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1"), typedMuxRequest(url));
break;
}
case "/v1/workspaces/layout": {
// A Herdr tab's split layout (pane rects and splits) around one of its panes, for
// Phren desktop's mirror of a Herdr tab. Herdr only: tmux has no such query here.
const server = selectedServer(url);
if (terminalKind(server) !== "herdr")
throw new BridgeError(501, "Pane layouts need Herdr.");
const pane = z.string().regex(/^[A-Za-z0-9_:.-]{1,100}$/).parse(url.searchParams.get("pane"));
const answer = await rpc(server, "pane.layout", { pane_id: pane });
result = { layout: object(answer).layout ?? null };
break;
}
case "/v1/workspaces/panes":
result = muxReplyForClient(await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || ""), typedMuxRequest(url));
break;
case "/v1/transcripts/blob": {
const target = targetFromURL(url);
await validateTarget(target);
const inner = url.searchParams.get("inner");
const bytes = await historicalImage(await targetTranscriptPath(target), Number(url.searchParams.get("line")), Number(url.searchParams.get("block")), target.source, inner === null ? undefined : Number(inner));
response.setHeader("Content-Type", "application/octet-stream");
response.end(bytes);
return;
}
case "/v1/transcripts/history": {
// Finished conversations use the same bounded history reader, but
// have no live pane to validate. Only the owner's gateway may read
// by identity; transcriptPath validates IDs and resolves known roots.
if (url.searchParams.get("historical") === "1") {
if (!ownerRequest(request, {}))
throw new BridgeError(403, "Only the owner can read historical conversations.");
if (["server", "workspace", "tab", "pane", "child"].some(key => url.searchParams.has(key)))
throw new BridgeError(400, "Historical reads cannot name a live target.");
const source = provider.parse(url.searchParams.get("source"));
const session = sessionId.parse(url.searchParams.get("session"));
const before = z.coerce.number().int().positive().safe().parse(url.searchParams.get("beforeLine"));
const abort = new AbortController();
response.once("close", () => { if (!response.writableEnded)
abort.abort(); });
const reader = new TranscriptReader(await transcriptPath(source, session), source);
await refreshTranscript(reader.file, source, session);
result = { ...await reader.read(before, abort.signal), type: "older", source, session };
break;
}
const target = targetFromURL(url);
const before = z.coerce.number().int().positive().parse(url.searchParams.get("beforeLine"));
const abort = new AbortController();
response.once("close", () => { if (!response.writableEnded)
abort.abort(); });
await validateTarget(target);
const child = url.searchParams.get("child");
const { reader, source, session } = child === null ? await conversationReader(target) : await childConversationReader(target, child);
if (reader)
await refreshTranscript(reader.file, source, session);
const page = reader ? await reader.read(before, abort.signal) : emptyPage;
result = { ...page, type: "older", source, session };
break;
}
case "/v1/subagents": {
const target = targetFromURL(url);
await validateTarget(target);
const local = await childAgentTree(target.source, target.session, 0, new Set(), computerID);
let remote = [];
let peerError;
if (url.searchParams.get("remote") !== "0") {
const { peers, peerError: reason } = await optionalHookPeers();
peerError = reason;
remote = await remoteChildren({ provider: target.source, session: target.session, computer: computerID },
// A worker whose turn finished shows as a completed lead.
(await dispatchStatus()).map(receipt => receipt.worker?.state === "done" ? { ...receipt, status: "completed" } : receipt), async (receipt) => {
const peer = peers.find(candidate => candidate.name === receipt.computer);
const remoteTarget = targetSchema.safeParse(receipt.target);
if (!peer || !remoteTarget.success)
return;
const query = new URLSearchParams(Object.entries(remoteTarget.data).map(([key, value]) => [key, String(value)]));
query.set("remote", "0");
const snapshot = await peerRequest(peer, `/v1/subagents?${query}`);
return { target: remoteTarget.data, computer: snapshot.computer,
agents: Array.isArray(snapshot.agents) ? snapshot.agents : [] };
});
}
result = { computer: info.computer, agents: publicChildAgents([...local, ...remote]), ...(peerError ? { peerError } : {}) };
break;
}
case "/v1/subagents/messages": {
result = await fanoutMessages.list(targetFromURL(url), url.searchParams.get("child"));
break;
}
case "/v1/subagents/transcript": {
const target = targetFromURL(url);
await validateTarget(target);
const { reader, source, session } = await childConversationReader(target, z.string().parse(url.searchParams.get("child")));
const page = reader ? await reader.read() : emptyPage;
result = { ...page, type: "backlog", source, session };
break;
}
case "/v1/code/tree":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).tree(url.searchParams.get("project"), url.searchParams.get("directory"));
break;
case "/v1/code/changed":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).whatChanged(url.searchParams.get("project"));
break;
case "/v1/code/change-counts":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).changeCounts(url.searchParams.get("project"), url.searchParams.get("paths"));
break;
case "/v1/code/usage-page":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).usagePage(url.searchParams.get("project"), {
kind: url.searchParams.get("kind"), file: url.searchParams.get("file"), directory: url.searchParams.get("directory"),
offset: url.searchParams.get("offset"), limit: url.searchParams.get("limit"), end: url.searchParams.get("end"),
});
break;
case "/v1/code/status":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).status(url.searchParams.get("project"));
break;
case "/v1/code/search":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).search(url.searchParams.get("project"), url.searchParams.get("q"), url.searchParams.get("kind"), url.searchParams.get("limit"), url.searchParams.get("directory"));
break;
case "/v1/code/files":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).files(url.searchParams.get("project"), url.searchParams.get("name"), url.searchParams.get("limit"));
break;
case "/v1/code/outline-summary":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).outlineSummary(url.searchParams.get("project"), url.searchParams.get("paths"));
break;
case "/v1/code/file-references":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).fileReferences(url.searchParams.get("project"), url.searchParams.get("path"));
break;
case "/v1/code/outline":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).outline(url.searchParams.get("project"), url.searchParams.get("path"));
break;
case "/v1/code/definition":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).definition(url.searchParams.get("project"), (url.searchParams.get("name") ?? url.searchParams.get("symbol")));
break;
case "/v1/code/references":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).references(url.searchParams.get("project"), (url.searchParams.get("name") ?? url.searchParams.get("symbol")), url.searchParams.get("limit"));
break;
case "/v1/code/usage":
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).usage(url.searchParams.get("project"), url.searchParams.get("top"));
break;
default: throw new BridgeError(404, "Unknown Phren Hook route.");
}
}
else if (request.method === "POST") {
let bodyCap;
if (url.pathname === CI_FAILURE_PATH) {
if (!request.headers[CI_PROOF_HEADER])
throw new BridgeError(403, "An authenticated CI reporting key is required.");
if (url.search)
throw new BridgeError(400, "This route takes no query.");
bodyCap = CI_FAILURE_BODY_CAP;
}
else if (url.pathname === "/v1/schedules/events")
bodyCap = SCHEDULE_EVENT_BODY_CAP;
const data = await body(request, bodyCap);
await ownerProof.check(request, url.pathname, data, bodyDigests.get(request), () => agentHooks.ownerConfirms.confirm(request.method ?? "POST", url.pathname, data, new Promise(done => response.once("close", () => done()))));
if (url.pathname.startsWith("/v1/conductor/move/"))
await ctx.succession.authorize(z.string().uuid().parse(data.id), requestPeer(request), url.pathname.endsWith("/prepare") ? z.string().uuid().parse(data.originId) : undefined);
const executeConductor = async (action, payload, origin, remote = false) => {
if (action === "dispatch")
return dispatches.dispatch(payload, { server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane });
if (action === "hand_off")
return handOff(payload, { bypassConductor: true });
if (action === "returns")
return { returns: await ctx.returns.take(!remote) };
if (action === "approve") {
const parsed = z.object({ id: z.string().uuid(), decision: z.enum(approvalDecisions), actionId: z.string().min(1).max(200) }).strict().parse(payload);
await ctx.returns.answerApproval(parsed.id, parsed.decision, parsed.actionId, origin);
return { ok: true };
}
if (action === "grants-list")
return { grants: await listGrants() };
if (action === "grants-add")
return { grant: await addGrant(payload) };
return { grant: await removeGrant(payload) };
};
const conductorCall = (action, payload, origin, run) => {
if (request.headers?.["x-phren-origin"] === "peer") {
if (action === "hand_off")
return run();
throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
}
return ctx.succession ? ctx.succession.call(action, payload, origin, run) : run();
};
if (url.pathname === "/v1/conductor/move/prepare") {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.prepare(data);
}
else if (url.pathname === "/v1/conductor/move/commit") {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.activate(data);
}
else if (url.pathname === "/v1/conductor/move/operate") {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.operate(data, executeConductor);
}
else if (url.pathname === "/v1/conductor/move/ack") {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.acknowledge(data, rows => ctx.returns.acknowledge(rows));
}
else if (url.pathname === "/v1/conductor/move/notice") {
if (!ctx.succession)
throw new BridgeError(503, "Conductor succession is unavailable.");
result = await ctx.succession.notice(data);
}
else if (url.pathname === "/v1/conductor/call") {
if (request.headers?.["x-phren-origin"] === "peer")
throw new BridgeError(403, "Only local agents use the conductor call route.");
const parsed = z.object({ action: z.enum(["dispatch", "hand_off", "returns", "approve", "grants-list", "grants-add", "grants-remove"]), data: z.record(z.string(), z.unknown()), origin: targetSchema.omit({ source: true, session: true }) }).strict().parse(data);
result = await conductorCall(parsed.action, parsed.data, parsed.origin, () => executeConductor(parsed.action, parsed.data, parsed.origin));
}
else if (url.pathname === "/v1/subagents/resume") {
result = await fanoutMessages.send(data);
}
else if (url.pathname === "/v1/subagents/archive-finished") {
result = await fanoutMessages.archiveFinished(data);
}
else if (url.pathname === "/v1/code/disable") {
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, typeof data.store === "string" ? data.store : undefined, true)))
.disable(z.string().parse(data.project));
}
else if (url.pathname === "/v1/code/reindex") {
result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, typeof data.store === "string" ? data.store : undefined, true)))
.reindex(z.string().parse(data.project));
}
else if (url.pathname === "/v1/code/note") {
result = await saveCodeNote(await resolveCodeStore(scheduleStore, typeof data.store === "string" ? data.store : undefined, true), data, dispatches ? async (note, prompt) => {
if (note.target && "session" in note.target)
return handOff({ session: note.target.session, project: note.project, text: prompt }, { bypassConductor: true });
return dispatches.dispatch({ computer: "anywhere", project: note.project,
harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
} : undefined);
}
else if (url.pathname === "/v1/sessions/move" && data.interrupt === true) {
// "Stop <agent> and hand off now": Escape only while the move's hand-off request is still held.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can interrupt a move's agent.");
if (!ctx.mover)
throw new BridgeError(503, "Session moves are unavailable.");
const { id } = z.object({ id: z.string().uuid(), interrupt: z.literal(true), origin: z.unknown().optional() }).strict().parse(data);
// Esc as /v1/keys sends it: a served OpenCode pane or a Codex pane on the Hook's own app-server stops
// its turn over its API; otherwise the key goes to the pane. A question the Hook holds is declined
// first, and the turn is still stopped: a declined question alone lets the turn carry on.
const escape = async (target) => {
if (await agentHooks.servedKeys(target, ["Escape"], "working", { abortTurn: true }))
return;
agentHooks.cancelHeldQuestion(target);
const { codexServers } = await import("./codex-servers.js");
const owned = codexServers.forTarget(target);
if (owned && await codexServers.interrupt(owned).catch(() => false)) {
agentHooks.clearTerminalPrompt(target);
return;
}
await terminalProvider().sendKeys(target.server, target.pane, ["esc"]);
};
result = { ok: true, ...await ctx.mover.interrupt(id, ctx.handOffs, escape) };
}
else if (url.pathname === "/v1/sessions/move") {
// Answers once the move is checked and recorded; the hand-off and relaunch run on, and GET says where it is.
if (!ctx.mover)
throw new BridgeError(503, "This Hook cannot move sessions.");
const { origin: _origin, ...input } = data;
result = { ok: true, move: await ctx.mover.start(input, { owner: ownerRequest(request, data) }) };
}
else if (url.pathname === "/v1/sessions/move/abort") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can abort a move.");
if (!ctx.mover)
throw new BridgeError(503, "Session moves are unavailable.");
result = { ok: true, move: await ctx.mover.abort(z.object({ id: z.string().uuid() }).strict().parse(data).id) };
}
else if (url.pathname === "/v1/sessions/move/launch") {
const caller = requestPeer(request);
if (!caller && !ownerRequest(request, data))
throw new BridgeError(403, "Only an authenticated owner or enrolled peer can launch a continuation.");
if (caller) {
const launch = continuationLaunchSchema.parse(data);
const canonical = await peerContinuationIntent(caller, launch.brief.id);
if (JSON.stringify(canonical) !== JSON.stringify(data))
throw new BridgeError(403, "This is not the origin Hook's owner-admitted continuation launch.");
}
const preparedRole = (await (await import("./conductor-role.js")).readRoleState())?.succession;
if (preparedRole && preparedRole.id === object(data.brief).id)
await ctx.succession.authorize(preparedRole.id, caller);
if (data.computerId !== info.computer.id)
throw new BridgeError(409, "The destination Hook identity changed; no chat was launched.");
const verified = ctx.succession ? await ctx.succession.verifiedLaunch(data) : data;
result = await launchContinuation(verified, (input, onPlaced) => launches.run(async () => {
const role = await (await import("./conductor-role.js")).readRoleState();
const prepared = role?.succession?.side === "successor" && role.succession.id === input.brief.id && role.succession.phase !== "aborted";
const cwd = prepared ? defaultPhrenPath() : await dispatchProjectDirectory(input.project);
// A summary-by-target move's whole conversation, from the source Hook that admitted it; none from an older one.
// Asked for only for those moves (the brief is the source's own, checked against its intent above), and only
// for a harness launched with a brief file: its folder is where the copy goes and the brief carries the line.
const wantsCopy = !!caller && input.brief.text.includes(CONVERSATION_MARKER) && launchesWithBrief(input.to.harness);
const conversation = wantsCopy ? await fetchContinuationConversation(offset => peerContinuationIntent(caller, input.brief.id, offset), redactPeerHandoff) : undefined;
const copied = conversation ? path.join(briefRoot(), input.brief.id, CONVERSATION_FILE) : undefined;
const brief = copied ? { ...input.brief, text: withConversationPointer(input.brief.text, copied) } : input.brief;
return launchSession(selectedServer(url), { cwd, kind: input.to.harness, account: input.to.account, model: input.to.model, effort: input.to.effort, label: `move-${input.brief.id}`, brief }, { trustFolder: true, onPlaced: async (target) => {
// Into the brief folder, which the new agent may read (Claude's --add-dir), as soon as it exists.
if (copied && conversation && await stat(path.dirname(copied)).catch(() => undefined))
await atomicInPrivateDir(copied, conversation).catch(() => undefined);
await onPlaced(target);
await terminalProvider().renamePane(selectedServer(url), z.string().parse(target.pane), input.label).catch(() => undefined);
} });
}), { caller, server: selectedServer(url) });
}
else if (url.pathname === "/v1/accounts/claude/add") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can add a Claude account.");
// `mode`: sign in a slot that exists but is signed out, or ask whether it is signed in yet.
result = data.mode === undefined ? await launches.run(() => addClaudeAccount(data, selectedServer(url)))
: data.mode === "sign-in-status" ? await signInClaudeAccount(data, selectedServer(url))
: await launches.run(() => signInClaudeAccount(data, selectedServer(url)));
}
else if (url.pathname === "/v1/accounts/claude/settings") {
// An account's pool and role (account-pools.ts): a field left out stays, null clears it.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can change an account's pool or role.");
const input = z.object({ slug: z.string().max(64), pool: z.string().max(64).nullable().optional(), role: z.string().max(32).nullable().optional(), origin: z.unknown().optional() }).strict().parse(data);
if (!claudeHome(input.slug))
throw new BridgeError(404, `There is no Claude account "${input.slug}" on this computer.`);
if (input.role !== undefined && input.role !== null && !isAccountRole(input.role))
throw new BridgeError(400, `A role is ${ACCOUNT_ROLES.join(", ")}.`);
const settings = await setAccountSettings(input.slug, { pool: input.pool, role: input.role })
.catch((error) => { throw new BridgeError(400, error.message); });
result = { ok: true, slug: input.slug, ...settings };
}
else if (url.pathname === "/v1/accounts/allowed-pools") {
// The pools this computer's accounts may do work for; null clears the list (any pool).
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can change this computer's allowed pools.");
const input = z.object({ allowedPools: z.array(z.string().max(64)).max(64).nullable(), origin: z.unknown().optional() }).strict().parse(data);
const allowedPools = await setComputerAllowedPools(input.allowedPools).catch((error) => { throw new BridgeError(400, error.message); });
result = { ok: true, ...(allowedPools ? { allowedPools } : {}) };
}
else if (url.pathname === "/v1/sessions/rename") {
result = await renameSession(selectedServer(url), data);
}
else if (url.pathname === "/v1/sessions/seen") {
result = await markSessionSeen(data);
}
else if (url.pathname === "/v1/sessions/pin") {
result = await setSessionPin(data);
}
else if (url.pathname.startsWith("/v1/issues/")) {
// Owner-only, owner-proof signed once the phone signs (owner-proof.ts). The
// bodies are the MCP issue tools' schemas (issue-routes.ts).
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner changes issues.");
result = await issueWriteRoute(url.pathname, data, info.computer.name);
}
else if (url.pathname === "/v1/housekeeping/scan") {
// Owner-only: a fresh inventory (sizes take a while); the answer comes back through the view's revision.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner starts a housekeeping scan.");
if (!ctx.housekeeper)
throw new BridgeError(404, "Housekeeping is not running on this Hook.");
void ctx.housekeeper.scan().catch(() => { });
result = { started: true };
}
else if (url.pathname === "/v1/housekeeping/approve" || url.pathname === "/v1/housekeeping/dismiss" || url.pathname === "/v1/housekeeping/restore") {
// Owner-only, and owner-proof signed once the phone signs (owner-proof.ts): agents and peers never apply housekeeping.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner applies or dismisses housekeeping.");
if (!ctx.housekeeper)
throw new BridgeError(404, "Housekeeping is not running on this Hook.");
const input = z.object({ ids: z.array(z.string().regex(/^[\w:.-]{1,200}$/)).min(1).max(200), revision: z.string().max(64).optional(),
by: z.enum(["phone", "cli"]).optional() }).strict().parse(data);
result = url.pathname.endsWith("/approve") ? await ctx.housekeeper.approve(input.ids, input.by ?? "phone")
: url.pathname.endsWith("/dismiss") ? await ctx.housekeeper.dismiss(input.ids) : await ctx.housekeeper.restore(input.ids);
}
else if (url.pathname === "/v1/jobs/cleanup") {
// Ends only registered worker process groups whose pane is gone.
result = { ok: true, ...await ctx.resources.cleanupJobs() };
}
else if (url.pathname === "/v1/schedules") {
result = await scheduler.statuses();
}
else if (url.pathname === "/v1/schedules/approve") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can approve a schedule.");
const input = z.object({ project: z.string().min(1).max(200), id: z.string().regex(/^[a-f0-9]{8}$/),
fingerprint: scheduleFingerprintSchema }).strict().parse(data);
result = await scheduler.approveSchedule(input.project, input.id, input.fingerprint);
}
else if (url.pathname === "/v1/schedules/run") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can run a schedule manually.");
const input = z.object({ project: z.string().min(1).max(200), id: z.string().regex(/^[a-f0-9]{8}$/),
expectedUpdatedAt: z.string().datetime({ offset: true }).optional() }).parse(data);
const runs = await scheduler.launchNow(input.project, input.id, false, input.expectedUpdatedAt);
result = { ok: runs.every(run => run.status !== "failed"), run: runs[0], runs };
}
else if (url.pathname === "/v1/schedules/events") {
result = await scheduler.ingestEvent(data);
}
else if (url.pathname === "/v1/schedules/update" || url.pathname === "/v1/schedules/create") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can save a schedule.");
const save = url.pathname === "/v1/schedules/create" ? createScheduleRoute : updateScheduleRoute;
result = await save(scheduleStore, data, (project, schedule) => scheduler.approveLocalEdit(project, schedule));
}
else if (url.pathname === "/v1/schedules/history") {
const input = z.object({ project: z.string().min(1).max(200).optional(), id: z.string().regex(/^[a-f0-9]{8}$/).optional(),
limit: z.number().int().min(1).max(500).optional() }).parse(data);
result = { runs: await scheduler.history(input) };
}
else if (url.pathname === "/v1/canary") {
result = await canary("manual");
}
else if (url.pathname === "/v1/speech") {
// Audio, not JSON: the route writes its own response.
await streamSpeech(data, response);
return;
}
else if (url.pathname === "/v1/owner-inbox") {
// `issues=1` is a query flag so a peer can ask for the structured
// issue link without a body key an older strict schema rejects.
result = await ownerInboxView(ctx.inbox, { ...data, ...(url.searchParams.get("issues") === "1" ? { issues: true } : {}), ...(url.searchParams.get("rules") === "1" ? { rules: true } : {}) }, false, url.searchParams.get("compact") === "1");
}
else if (url.pathname === "/v1/owner-inbox/close") {
// A signed decision from the paired phone, sent straight to the Hook
// that owns the row. The peer gateway stamps peer origin and strips
// client proof, so a peer can never carry the signature this needs.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner's phone closes inbox items.");
const input = ownerInboxCloseSchema.parse(data);
if (!ctx.inbox)
throw new BridgeError(503, "The owner inbox is unavailable on this Hook.");
const item = await ctx.inbox.close(input.id, input.ifUpdatedAt, input.decision);
// A phone that did not ask for the issue field gets the link in the title.
result = { ok: true, item: { ...inboxWire(item, url.searchParams.get("issues") === "1"), inboxComputer: "local" } };
}
else if (url.pathname === "/v1/conductor/integrator") {
result = await setIntegrator(data.integrator);
}
else if (url.pathname === "/v1/dispatch/report") {
result = await reportWorker(data);
}
else if (url.pathname === "/v1/dispatch/close") {
result = await closeFinishedWorker(data, ctx.handOffs);
}
else if (url.pathname === "/v1/dispatch/cancel") {
// Cancel a running dispatch by id: stop its agent and close its pane.
if (request.headers?.["x-phren-origin"] === "peer")
throw new BridgeError(403, "A peer cannot cancel a dispatch on this computer.");
result = await cancelDispatch(data);
}
else if (url.pathname === "/v1/dispatch/close-self") {
result = await closeOwnPane(data, undefined, ctx.handOffs);
}
else if (url.pathname === "/v1/ci/failures") {
if (!ctx.handOffs)
throw new BridgeError(503, "CI hand-offs are unavailable.");
const reporter = await authenticatedCiReporter(request.headers[CI_REPORTER_HEADER], request.headers[CI_PROOF_HEADER], bodyDigests.get(request));
result = await receiveCiFailure(ctx.handOffs, data, reporter);
}
else if (url.pathname === "/v1/hand-off") {
const forwarded = request.headers?.["x-phren-origin"] === "peer" && typeof data.deliveryId === "string" && /^handoff-notice-[a-f0-9]{40}$/.test(data.deliveryId)
? await ctx.succession?.forward(data.target, z.string().max(32768).parse(data.text), data.deliveryId) : undefined;
result = forwarded ? { ok: forwarded.delivered, delivered: forwarded.delivered, deliveryId: data.deliveryId } : await conductorCall("hand_off", data, data.origin, () => ctx.handOffs.enqueue(data));
}
else if (url.pathname === "/v1/hand-off/status") {
const body = z.object({ deliveryId: z.string().min(8).max(64), target: targetSchema }).strict().parse(data);
result = await ctx.handOffs.status(body.deliveryId, body.target);
}
else if (url.pathname === "/v1/dispatch") {
// `origin` is the caller's own pane, added by the MCP tool or CLI from Herdr's variables.
const { origin, ...brief } = data;
result = await conductorCall("dispatch", brief, origin, () => dispatches.dispatch(brief, origin));
}
else if (url.pathname === "/v1/dispatch/workers") {
result = await hookWorkers(agentHooks)(data);
}
else if (url.pathname === "/v1/dispatch/returns/ack") {
// `phren dispatch wait` acknowledges only the dispatch it followed,
// never the other returns a conductor on this Hook still needs.
if (request.headers?.["x-phren-origin"] === "peer")
throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
const body = z.object({ dispatch: z.string().uuid() }).strict().parse(data);
result = await ctx.returns.acknowledgeOne(body.dispatch);
}
else if (url.pathname === "/v1/dispatch/returns" && url.searchParams.get("peek") === "1") {
// The unread returns, left unread: a watcher (`phren dispatch returns --watch`) beside an agent
// conductor, which still takes them. Read here, never forwarded to a successor, which would take them.
if (request.headers?.["x-phren-origin"] === "peer")
throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
result = { returns: await ctx.returns.take(false) };
}
else if (url.pathname === "/v1/dispatch/returns") {
result = await conductorCall("returns", {}, data.origin, async () => ({ returns: await ctx.returns.take() }));
}
else if (url.pathname === "/v1/dispatch/approve") {
const body = z.object({ id: z.string().uuid(), decision: z.enum(approvalDecisions), actionId: z.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
const { origin, ...answer } = body;
result = await conductorCall("approve", answer, origin, async () => { await ctx.returns.answerApproval(body.id, body.decision, body.actionId, origin); return { ok: true }; });
}
else if (url.pathname === "/v1/approval-rules") {
result = await changeApprovalRule(data, "POST");
}
else if (url.pathname === "/v1/conductor/grants") {
const { origin, ...grant } = data;
result = await conductorCall("grants-add", grant, origin, async () => ({ ok: true, grant: await addGrant(grant) }));
}
else if (url.pathname === "/v1/authority" || url.pathname === "/v1/authority/confirm") {
// The owner writes the policy from the phone; an agent's call names its
// pane and a peer computer's arrives through its key's scope.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
result = url.pathname === "/v1/authority" ? { ok: true, authority: await setProjectAuthority(data, "phone") }
: { ok: true, confirmation: await confirmAuthority(data, "phone") };
}
else if (url.pathname === "/v1/conductor/make") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can change the conductor.");
// Serialized with launches, so a conductor launch and a make cannot both pass the set check.
result = await launches.run(async () => makeConductor(selectedServer(url), data));
}
else if (url.pathname === "/v1/conductor/stop") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner can change the conductor.");
result = await launches.run(async () => await ctx.succession?.stopOrigin(data.paneId) ?? stopConductor(data));
}
else if (url.pathname === "/v1/sets/name") {
result = await nameSet(data);
}
else if (url.pathname === "/v1/sets/link") {
result = await linkSetMember(data, request);
}
else if (url.pathname === "/v1/push/register") {
// Registration is kept for when a key is added; the reply says whether push works now.
// The owner's phone only: a linked computer or an agent must not add a destination for this computer's alerts.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner's phone registers for notifications.");
await agentHooks.push.register(data);
result = { ok: true, configured: agentHooks.push.status.configured };
}
else if (url.pathname === "/v1/push/forget") {
// `phren unpair` ends a removed phone's notifications with this.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner removes notification registrations.");
result = { ok: true, removed: await agentHooks.push.forgetAll() };
}
else if (url.pathname === "/v1/sudo/answer") {
// The owner answers from the phone; an agent's call names its pane and
// a peer computer's arrives through its key's scope.
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
let parsed;
try {
parsed = sudoAnswer(data);
}
catch {
throw new BridgeError(400, "Send an id and a password, or deny.");
}
const answered = agentHooks.sudo.answer(parsed.id, parsed.answer);
if (!answered)
throw new BridgeError(404, "This sudo request is no longer pending.");
// Asked for: whether sudo took the password, so the phone knows to save or forget it.
const outcome = parsed.outcome ? await answered.outcome : undefined;
result = { ok: true, ...(outcome ? { outcome } : {}) };
}
else if (url.pathname === "/v1/owner-confirms/answer") {
// Owner-proof route: the phone signs this answer, so an agent cannot approve its own held request.
if (!ownerRequest(request, data) || typeof request.headers?.[OWNER_PROOF_HEADER] !== "string")
throw new BridgeError(403, "Only the owner's phone answers, with its signature.", { code: "owner-proof-required" });
const input = z.object({ id: z.string().uuid(), approve: z.boolean() }).strict().parse(data);
if (!agentHooks.ownerConfirms.answer(input.id, input.approve))
throw new BridgeError(404, "This request is no longer waiting.");
result = { ok: true };
}
else if (url.pathname === "/v1/secrets/answer") {
if (data && typeof data === "object" && "origin" in data)
throw new BridgeError(403, "Only the owner answers a secret request, from the phone.");
let parsed;
try {
parsed = secretAnswer(data);
}
catch {
throw new BridgeError(400, "Send an id and a secret, or deny.");
}
if (!agentHooks.secrets.answer(parsed.id, parsed.answer))
throw new BridgeError(404, "This secret request is no longer pending.");
result = { ok: true };
}
else if (url.pathname === "/v1/push/answer") {
await agentHooks.answerPush(z.string().uuid().parse(data.binding), data.decision);
result = { ok: true };
}
else if (url.pathname === "/v1/push/presence") {
// Phren desktop: the owner is at the desk, so approval alerts wait before reaching the phone.
agentHooks.push.markDesk(z.number().int().min(0).max(120_000).parse(data.activeForMs));
result = { ok: true, deskActive: agentHooks.push.deskActive };
}
else if (url.pathname === "/v1/push/target") {
// A tapped notification opens its session; the binding stays unspent.
const target = agentHooks.pushTarget(z.string().uuid().parse(data.binding));
if (!target)
throw new BridgeError(409, "This approval is no longer pending.");
result = { target: { server: target.server, workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source } };
}
else if (url.pathname === "/v1/files") {
// Files the phone keeps on this computer, outside any session.
const { name, bytes } = uploadBody(data);
result = { ok: true, path: await saveUpload("files", name, bytes) };
}
else if (url.pathname === "/v1/files/delete") {
// One of those files, removed by the path the listing gave.
await removeUpload("files", z.string().parse(data.path));
result = { ok: true };
}
else if (url.pathname === "/v1/projects/add") {
// Enrolling a repository with phren from the phone: an existing
// checkout, or a clone. Serialized like launches — one at a time.
result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional(), project: z.string().max(100).optional(), store: z.string().max(200).optional() }).parse(data)));
}
else if (url.pathname === "/v1/simulators/action") {
result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(),
x1: z.number().optional(), y1: z.number().optional(), x2: z.number().optional(), y2: z.number().optional(), durationMs: z.number().optional(),
text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
}
else if (url.pathname === "/v1/mac/windows/action") {
macWindowAudit = { action: typeof data.action === "string" ? data.action : "invalid", id: data.id };
macWindowsOwnerOnly(ownerRequest(request, data));
result = await macWindowsAct(data);
}
else if (url.pathname === "/v1/mac/windows/permissions") {
macWindowAudit = { action: "permissions" };
macWindowsOwnerOnly(ownerRequest(request, data));
result = { permissions: await macWindowsRequestPermission(data.permission) };
}
else {
if (url.pathname === "/v1/workspaces/launch") {
result = await launches.run(async () => {
const owner = ownerRequest(request, data);
if (data.role === "conductor" && !owner)
throw new BridgeError(403, "Only the owner can change the conductor.");
if (data.role === "conductor" && !modules.has("conductor"))
throw new BridgeError(404, disabledHint("conductor"));
if (data.agentFolder === true && (data.role === "conductor" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
}
if (data.project !== undefined && data.cwd !== undefined)
throw new BridgeError(400, "Choose project or cwd, not both.");
// A conductor belongs to no one project: without a folder it starts in
// this computer's phren store and dispatches into any project from there.
const storeRooted = data.role === "conductor" && data.project === undefined && (data.cwd === undefined || data.cwd === "");
const cwd = data.agentFolder === true ? undefined : storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
: data.project !== undefined ? await dispatchProjectDirectory(data.project)
: await launchDirectory(data.cwd, await journal.recent(), locatedDirectories);
// Enrolled peers can dispatch into a project the Hook resolves.
// An explicit cwd needs the owner gateway's authority.
const projectTrust = data.project !== undefined
&& (owner || (data.origin === undefined && request.headers["x-phren-origin"] === "peer"));
const phoneFolder = owner && typeof data.cwd === "string" && data.cwd !== ""
&& (data.kind === "claude" || data.kind === "codex");
return launchSession(selectedServer(url), { ...data, cwd }, { trustFolder: phoneFolder ? "folder chosen on the phone" : projectTrust });
});
}
else if (url.pathname.startsWith("/v1/workspaces/")) {
const operation = url.pathname.split("/").at(-1);
result = operation === "create" ? await launches.run(async () => workspaceAction(selectedServer(url), operation, { ...data, cwd: await launchDirectory(data.cwd ?? homeDir(), await journal.recent(), locatedDirectories) }))
: await workspaceAction(selectedServer(url), operation, data);
}
else {
result = await paneRoute(paneContext, url, data, response, request.headers);
}
}
}
else if (request.method === "DELETE") {
if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority" && url.pathname !== "/v1/approval-rules")
throw new BridgeError(404, "Unknown Phren Hook route.");
const data = await body(request);
await ownerProof.check(request, url.pathname, data, bodyDigests.get(request), () => agentHooks.ownerConfirms.confirm(request.method ?? "POST", url.pathname, data, new Promise(done => response.once("close", () => done()))));
if (url.pathname === "/v1/conductor/grants" && request.headers?.["x-phren-origin"] === "peer")
throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
if (url.pathname === "/v1/approval-rules") {
result = await changeApprovalRule(data, "DELETE");
}
else if (url.pathname === "/v1/authority") {
if (!ownerRequest(request, data))
throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
}
else
result = { ok: true, grant: await removeGrant(data) };
}
else
throw new BridgeError(405, "Unsupported request method.");
const payload = JSON.stringify(result);
if (Buffer.byteLength(payload) > MAX_FRAME)
throw new BridgeError(413, "The response is too large.");
response.setHeader("Content-Type", "application/json");
response.end(payload);
}
catch (error) {
if (macWindowAudit)
await macWindowsRefusal(macWindowAudit.action, macWindowAudit.id, error);
response.statusCode = error instanceof BridgeError ? error.status : error instanceof z.ZodError || error instanceof SyntaxError ? 400 : 503;
response.setHeader("Content-Type", "application/json");
const failure = { error: error instanceof BridgeError ? error.message : "Phren Hook could not complete this request. Run phren bridge doctor on the computer.",
...(error instanceof BridgeError ? error.details : {}) };
response.end(JSON.stringify(["peer", CI_FAILURE_SCOPE].includes(String(request.headers?.["x-phren-origin"])) ? { ...failure, error: redactPeerHandoff(failure.error) } : failure));
}
};
}