UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

362 lines (361 loc) • 24.4 kB
import { ownerInboxSchema } from "./owner-inbox.js"; import { prsSchema } from "./return-contract.js"; import { createReadStream } from "node:fs"; import { stat } from "node:fs/promises"; import { StringDecoder } from "node:string_decoder"; import { parseArgs } from "node:util"; import { ownerHookRequest, hookRequest } from "./client.js"; import { DISPATCH_PROMPT_LIMIT, dispatchSchema } from "./dispatch.js"; import { idempotencyKeySchema } from "./dispatch-idempotency.js"; import { waitForDispatch } from "./dispatch-wait.js"; import { handOff, moveSession } from "./hand-off.js"; import { terminalPaneFromEnv } from "./terminal.js"; import { dispatchIdFromEnv } from "./launch-brief.js"; import { addGrant, grantSchema, listNamedGrants, removeGrant } from "./grants.js"; import { sessionId } from "./protocol.js"; export async function runDispatch(args) { if (args[0] === "report") { const { values } = parseArgs({ args: args.slice(1), options: { prs: { type: "string" }, issue: { type: "string" } } }); const origin = await terminalPaneFromEnv(); if (!origin || !values.prs) throw new Error("Usage inside a worker pane: phren dispatch report --prs <JSON array> [--issue <repo#N>]"); const dispatch = dispatchIdFromEnv(); console.log(JSON.stringify(await hookRequest("/v1/dispatch/report", { origin, prs: prsSchema.parse(JSON.parse(values.prs)), ...(dispatch ? { dispatch } : {}), ...(values.issue ? { issue: values.issue } : {}) }), null, 2)); return 0; } if (args.length === 1 && args[0] === "close-self") { const origin = await terminalPaneFromEnv(); if (!origin) throw new Error("phren dispatch close-self runs inside the agent's own terminal pane."); const dispatch = dispatchIdFromEnv(); console.log(JSON.stringify(await hookRequest("/v1/dispatch/close-self", { origin, ...(dispatch ? { dispatch } : {}) }), null, 2)); return 0; } if (args.length === 1 && args[0] === "status") { console.log(JSON.stringify(await hookRequest("/v1/dispatch?limit=100"), null, 2)); return 0; } if (args.length === 1 && args[0] === "returns") { const origin = await terminalPaneFromEnv(); console.log(JSON.stringify(await hookRequest("/v1/dispatch/returns", { ...(origin ? { origin } : {}) }), null, 2)); return 0; } if (args[0] === "returns" && args.length <= 4 && args.slice(1).every(arg => ["--watch", "--json", "--consume"].includes(arg))) { const origin = await terminalPaneFromEnv(); // The watch peeks (an agent conductor on this Hook still takes its returns) unless told to take them. const peek = args.includes("--watch") && !args.includes("--consume"); const read = async () => { const answer = await hookRequest(peek ? "/v1/dispatch/returns?peek=1" : "/v1/dispatch/returns", { ...(origin ? { origin } : {}) }); return Array.isArray(answer.returns) ? answer.returns : []; }; // `returns --json` is `returns`, whose answer is JSON already. if (!args.includes("--watch")) { console.log(JSON.stringify({ returns: await read() }, null, 2)); return 0; } const { watchReturns } = await import("./dispatch-returns.js"); const stop = new AbortController(); // The first Ctrl-C ends the watch after the read in flight (which still prints; with --consume its // returns are already marked read); a second one leaves at once. process.on("SIGINT", () => { if (stop.signal.aborted) process.exit(130); stop.abort(); }); await watchReturns(read, line => console.log(line), { signal: stop.signal, json: args.includes("--json"), warn: line => console.error(line) }); return 130; } if (args[0] === "usage" && args.slice(1).every(arg => arg === "--json")) { const { readAccountUsage, formatAccountUsage } = await import("./account-usage.js"); const view = await readAccountUsage(); console.log(args.includes("--json") ? JSON.stringify(view, null, 2) : formatAccountUsage(view)); return 0; } if (args.length === 1 && args[0] === "sessions") { const { listLiveSessions } = await import("./hand-off.js"); console.log(JSON.stringify(await listLiveSessions(), null, 2)); return 0; } if (args[0] === "wait") { const { values, positionals } = parseArgs({ args: args.slice(1), allowPositionals: true, options: { timeout: { type: "string" }, json: { type: "boolean" }, follow: { type: "boolean" }, } }); if (positionals.length !== 1) throw new Error("Usage: phren dispatch wait <dispatch-id> [--timeout <seconds>] [--json] [--follow]"); const seconds = values.timeout === undefined ? undefined : Number(values.timeout); if (seconds !== undefined && (!Number.isFinite(seconds) || seconds < 0)) throw new Error("--timeout is a non-negative number of seconds."); return waitForDispatch(positionals[0], { timeoutMs: seconds === undefined ? undefined : seconds * 1000 }); } if (args[0] === "close") { const result = await hookRequest("/v1/dispatch/cancel", closeRequestFromArgs(args.slice(1))); console.log(JSON.stringify({ ...(typeof result.dispatch === "string" ? { dispatch: result.dispatch } : {}), closed: result.closed === true, ...(result.pending === true ? { pending: true } : {}) }, null, 2)); return result.pending === true ? 1 : 0; } const input = await dispatchInputFromArgs(args); // Run inside an agent's pane, the dispatch remembers that pane for return notices. const origin = await terminalPaneFromEnv(); const result = await hookRequest("/v1/dispatch", { ...input, ...(origin ? { origin } : {}) }, undefined, 180_000); console.log(JSON.stringify(result, null, 2)); return result.ok === true || result.existing === true ? 0 : 1; } const DISPATCH_USAGE = "Usage: phren dispatch <computer|anywhere|local> <project> --prompt <brief> | --prompt-file <path|-> [--harness codex|claude|opencode|copilot] [--label <label>] [--issue <repo#N>] [--idempotency-key <key>] [--worktree [--branch <name>]] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]"; /** The brief limit shared with dispatchSchema. */ export const PROMPT_LIMIT = DISPATCH_PROMPT_LIMIT; /** A brief from a file, or stdin for `-`. The text never goes through argv. */ export async function readPromptFile(file, stdin = process.stdin) { if (file !== "-") { const info = await stat(file); if (info.size > PROMPT_LIMIT) throw new Error(`Worker brief is too large: ${info.size} bytes; the limit is ${PROMPT_LIMIT} characters.`); } const stream = file === "-" ? stdin : createReadStream(file); const decoder = new StringDecoder("utf8"); let prompt = ""; try { for await (const chunk of stream) { prompt += decoder.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk); if (prompt.length > PROMPT_LIMIT) { throw new Error(`Worker brief is too large: more than ${PROMPT_LIMIT} characters.`); } } prompt += decoder.end(); } finally { if (file !== "-") stream.destroy(); } if (prompt.length > PROMPT_LIMIT) throw new Error(`Worker brief is too large: ${prompt.length} characters; the limit is ${PROMPT_LIMIT}.`); return prompt; } /** The dispatch form's argv, prompt file/stdin and defaults, without reaching a Hook. */ export async function dispatchInputFromArgs(args, stdin = process.stdin) { const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { "keep-open": { type: "boolean" }, harness: { type: "string", default: "codex" }, model: { type: "string" }, effort: { type: "string" }, account: { type: "string" }, "permission-mode": { type: "string" }, prompt: { type: "string" }, "prompt-file": { type: "string" }, label: { type: "string" }, issue: { type: "string" }, "idempotency-key": { type: "string" }, worktree: { type: "boolean" }, branch: { type: "string" }, "parent-provider": { type: "string" }, "parent-session": { type: "string" }, "parent-computer": { type: "string" }, "parent-server": { type: "string" }, "parent-workspace": { type: "string" }, "parent-tab": { type: "string" }, "parent-pane": { type: "string" }, } }); if (positionals.length !== 2) throw new Error(DISPATCH_USAGE); const [computer, project] = positionals; const promptFile = values["prompt-file"]; if ((values.prompt === undefined) === (promptFile === undefined)) throw new Error("Give exactly one of --prompt and --prompt-file."); const prompt = promptFile !== undefined ? await readPromptFile(promptFile, stdin) : values.prompt; const key = values["idempotency-key"]; if (key !== undefined && !idempotencyKeySchema.safeParse(key).success) { throw new Error(idempotencyKeySchema.safeParse(key).error.issues[0]?.message ?? "Invalid idempotency key."); } const label = values.label ?? (computer === "local" ? (key ? key.slice(0, 60) : "gitboy agent") : undefined); if (values.branch !== undefined && !values.worktree) throw new Error("--branch needs --worktree."); const parentValues = ["parent-provider", "parent-session", "parent-computer", "parent-server", "parent-workspace", "parent-tab", "parent-pane"]; const hasParent = parentValues.some(name => values[name] !== undefined); const parent = hasParent ? { provider: values["parent-provider"], session: values["parent-session"], computer: values["parent-computer"], } : undefined; const parentTarget = hasParent ? { server: values["parent-server"], workspace: values["parent-workspace"], tab: values["parent-tab"], pane: values["parent-pane"], source: values["parent-provider"], session: values["parent-session"], } : undefined; const { "permission-mode": permissionMode, "keep-open": keepOpen, prompt: _prompt, "prompt-file": _promptFile, "idempotency-key": _key, worktree, branch, ...rest } = values; const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([name]) => !name.startsWith("parent-"))), ...(permissionMode !== undefined ? { permissionMode } : {}), ...(keepOpen ? { closeOnFinish: false } : {}), ...(worktree ? { worktree: true } : {}), ...(branch !== undefined ? { branch } : {}), ...(key !== undefined ? { idempotencyKey: key } : {}) }; const parsed = dispatchSchema.safeParse({ computer, project, prompt, ...(label !== undefined ? { label } : {}), ...ordinary, ...(parent ? { parent, parentTarget } : {}) }); if (!parsed.success) { // Name the flag, not a schema path: a missing --label or --prompt is the usual slip. const flag = (path) => path.length ? (["computer", "project"].includes(String(path[0])) ? `<${String(path[0])}>` : `--${String(path[0]).replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`) : "input"; throw new Error(`phren dispatch: ${parsed.error.issues.map(issue => `${flag(issue.path)} ${issue.code === "invalid_type" && /received undefined/.test(issue.message) ? "is required" : issue.message}`).join("; ")}. Run phren dispatch for usage.`); } return parsed.data; } /** Exactly one of a dispatch id and an idempotency key, for `dispatch close`. */ export function closeRequestFromArgs(args) { const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { "idempotency-key": { type: "string" } } }); const key = values["idempotency-key"]; const id = positionals[0]; if (positionals.length > 1 || (id === undefined) === (key === undefined)) { throw new Error("Usage: phren dispatch close <dispatch-id> | phren dispatch close --idempotency-key <key>"); } if (key !== undefined && !idempotencyKeySchema.safeParse(key).success) { throw new Error(idempotencyKeySchema.safeParse(key).error.issues[0]?.message ?? "Invalid idempotency key."); } return key !== undefined ? { idempotencyKey: key } : { dispatch: id }; } export async function runHandOff(args) { const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { "delivery-id": { type: "string" }, status: { type: "boolean" }, session: { type: "string" }, text: { type: "string" }, project: { type: "string" }, account: { type: "string" }, } }); if (positionals.length !== 1 || !values.session || (!values.status && !values.text) || (values.status && !values["delivery-id"])) throw new Error("Usage: phren hand-off <computer|local> --session <id> --text <prompt> [--project <slug>] [--account <id>]"); const computer = positionals[0] === "local" ? undefined : positionals[0]; const result = await handOff({ ...(computer ? { computer } : {}), project: values.project, ...(values.account ? { account: values.account } : {}), session: sessionId.parse(values.session), ...(values.status ? { status: true } : { text: values.text }), ...(values["delivery-id"] ? { deliveryId: values["delivery-id"] } : {}) }); console.log(JSON.stringify(result, null, 2)); return result.ok ? 0 : 1; } const MOVE_USAGE = "Usage: phren move <session-or-pane> --to <claude|codex|opencode|copilot> [--model <model>] [--effort <effort>] [--account <id> [--resume]] [--computer <name>] [--no-wait] | phren move --status <move-id> [--computer <name>]"; /** `phren move`: a live session, named by its session id or its pane id (`wC9:p1`), to another agent, through its computer's Hook (session-move.ts). */ export async function runMove(args) { const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { to: { type: "string" }, account: { type: "string" }, model: { type: "string" }, effort: { type: "string" }, computer: { type: "string" }, status: { type: "string" }, id: { type: "string" }, "no-wait": { type: "boolean" }, resume: { type: "boolean" }, } }); const computer = values.computer ? { computer: values.computer } : {}; if (values.status) { if (positionals.length) throw new Error(MOVE_USAGE); const result = await moveSession({ ...computer, status: true, id: values.status }); console.log(JSON.stringify(result, null, 2)); return result.ok ? 0 : 1; } if (positionals.length !== 1 || !values.to) throw new Error(MOVE_USAGE); const named = sessionId.safeParse(positionals[0]).success ? { session: positionals[0] } : { pane: positionals[0] }; const result = await moveSession({ ...computer, ...named, harness: values.to, ...(values.account ? { account: values.account } : {}), ...(values.model ? { model: values.model } : {}), ...(values.effort ? { effort: values.effort } : {}), ...(values.id ? { id: values.id } : {}), ...(values["no-wait"] ? { wait: false } : {}), ...(values.resume ? { resume: true } : {}) }); console.log(JSON.stringify(result, null, 2)); return result.ok ? 0 : 1; } const CONDUCTOR_USAGE = "Usage: phren conductor status | make [--pane <id>] [--mux herdr:<name>|tmux:<name>] | stop [--pane <id>] | sets [--json] | sets name <name>|--clear | grants [list|add|remove]"; /** The Hook route for a pane's multiplexer: `--mux`, else the pane the command runs in. */ function muxQuery(mux, here) { if (mux) return `?mux=${encodeURIComponent(mux)}`; return here ? `?server=${encodeURIComponent(here.server)}` : ""; } /** One line per computer: name, reachability, link and conductor. */ export function formatSets(view) { const lines = []; const rows = (value) => Array.isArray(value) ? value.filter((item) => !!item && typeof item === "object") : []; for (const set of rows(view.sets)) { const conductors = typeof set.conductors === "number" ? set.conductors : 0; lines.push(`${typeof set.name === "string" ? set.name : "Unnamed set"}${set.local ? " (this computer)" : ""}${conductors > 1 ? `: ${conductors} conductors, stop all but one` : ""}`); for (const computer of rows(set.computers)) { const state = computer.link === "self" ? "this computer" : computer.reachable === true ? "reachable" : computer.reachable === false ? "unreachable" : "not asked"; const link = computer.link === "self" ? "" : `, ${String(computer.link)} link`; lines.push(` ${String(computer.name)}: ${state}${link}${computer.conductor ? ", conductor" : ""}${typeof computer.hint === "string" ? `. ${computer.hint}` : typeof computer.error === "string" ? `. ${computer.error}` : ""}`); } } const unlinked = rows(view.unlinked); if (unlinked.length) { lines.push("Not linked"); for (const computer of unlinked) lines.push(` ${String(computer.name)}. Link it with phren bridge link ${String(computer.name)}.`); } return lines.join("\n"); } export async function runConductor(args) { const [namespace = "status", action = "list", ...rest] = args; if (namespace === "status") { console.log(JSON.stringify(await hookRequest("/v1/conductor"), null, 2)); return 0; } if (namespace === "make" || namespace === "stop") { const { values } = parseArgs({ args: args.slice(1), options: { pane: { type: "string" }, mux: { type: "string" } } }); const here = await terminalPaneFromEnv(); if (namespace === "make") { const pane = values.pane ?? here?.pane; if (!pane) throw new Error("Run phren conductor make inside the agent's pane, or name it with --pane <id>."); const place = values.pane ? { paneId: values.pane } : { workspaceId: here.workspace, tabId: here.tab, paneId: here.pane }; const result = await ownerHookRequest(`/v1/conductor/make${muxQuery(values.mux, values.pane ? undefined : here)}`, place); console.log(JSON.stringify(result, null, 2)); return result.ok === true ? 0 : 1; } const result = await ownerHookRequest("/v1/conductor/stop", values.pane ? { paneId: values.pane } : {}); console.log(result.stopped ? "This computer has no conductor now." : "This computer had no conductor."); return 0; } if (namespace === "integrator") { const { values } = parseArgs({ args: args.slice(1), options: { session: { type: "string" }, computer: { type: "string" }, clear: { type: "boolean" } } }); if (values.clear) { console.log(JSON.stringify(await hookRequest("/v1/conductor/integrator", { integrator: null }), null, 2)); return 0; } if (!values.session) { console.log(JSON.stringify(await hookRequest("/v1/conductor/integrator"), null, 2)); return 0; } const { listLiveSessions } = await import("./hand-off.js"); const live = await listLiveSessions(), session = live.sessions.find(row => row.target?.session === values.session && (values.computer ? row.computer === values.computer : row.local)); if (!session?.target) throw new Error("That integrator is not a live session on the selected computer."); console.log(JSON.stringify(await hookRequest("/v1/conductor/integrator", { integrator: { target: session.target, ...(!session.local ? { computer: session.computer } : {}) } }), null, 2)); return 0; } if (namespace === "sets") { if (action === "name") { const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { clear: { type: "boolean" } } }); const name = values.clear ? null : positionals.join(" ").trim(); if (name === "") throw new Error("Usage: phren conductor sets name <name>|--clear"); console.log(JSON.stringify(await hookRequest("/v1/sets/name", { name }), null, 2)); return 0; } const view = await hookRequest("/v1/sets", undefined, undefined, 60_000); console.log(args.includes("--json") ? JSON.stringify(view, null, 2) : formatSets(view)); return 0; } if (namespace !== "grants") throw new Error(CONDUCTOR_USAGE); const grantOrigin = await terminalPaneFromEnv(); const grantCall = async (action, data) => grantOrigin ? hookRequest("/v1/conductor/call", { action, data, origin: grantOrigin }) : undefined; if (action === "list") { const forwarded = await grantCall("grants-list", {}); console.log(JSON.stringify(forwarded?.grants ?? await listNamedGrants(), null, 2)); return 0; } if (action === "add") { const { values } = parseArgs({ args: rest, allowPositionals: true, options: { scope: { type: "string" }, actions: { type: "string" }, computers: { type: "string" }, until: { type: "string" }, "max-permission-mode": { type: "string" }, } }); const actions = (values.actions ?? "dispatch,hand_off").split(",").map(value => value.trim()).filter(Boolean); const grant = grantSchema.parse({ scope: values.scope ?? "global", actions, ...(values.computers ? { computers: values.computers.split(",").map(value => value.trim()).filter(Boolean) } : {}), ...(values.until ? { until: values.until } : {}), ...(values["max-permission-mode"] ? { maxPermissionMode: values["max-permission-mode"] } : {}), }); const forwarded = await grantCall("grants-add", grant); console.log(JSON.stringify(forwarded?.grant ?? await addGrant(grant), null, 2)); return 0; } if (action === "remove") { const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { scope: { type: "string" }, index: { type: "string" }, } }); const index = values.index !== undefined ? Number(values.index) : positionals[0] !== undefined ? Number(positionals[0]) : undefined; if (index === undefined && !values.scope) throw new Error("Usage: phren conductor grants remove <index>|--scope <scope>"); if (index !== undefined && !Number.isInteger(index)) throw new Error("Grant index must be an integer."); const input = index !== undefined ? { index } : { scope: values.scope }; const forwarded = await grantCall("grants-remove", input); console.log(JSON.stringify(forwarded?.grant ?? await removeGrant(input), null, 2)); return 0; } throw new Error(CONDUCTOR_USAGE); } export async function runOwnerInbox(args) { const [action = "list", ...rest] = args; const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { computer: { type: "string" }, project: { type: "string" }, id: { type: "string" }, resolution: { type: "string" }, all: { type: "boolean" }, command: { type: "string" }, pr: { type: "string" }, issue: { type: "string" }, key: { type: "string" }, "if-updated-at": { type: "string" }, blocks: { type: "boolean" }, "no-blocks": { type: "boolean" } } }); const input = ownerInboxSchema.parse({ action, ...(values.computer ? { computer: values.computer === "local" ? undefined : values.computer } : {}), ...(action === "add" ? { title: positionals.join(" "), project: values.project, id: values.id, command: values.command, pr: values.pr, issue: values.issue, key: values.key, ...(values.blocks ? { blocks: true } : values["no-blocks"] ? { blocks: false } : {}) } : {}), ...(action === "resolve" ? { id: positionals[0], resolution: values.resolution, ...(values["if-updated-at"] !== undefined ? { ifUpdatedAt: values["if-updated-at"] } : {}) } : {}), ...(values.all ? { includeResolved: true } : {}) }); // `issues=1` is a query flag, never a body key: a Hook from before the field // existed reads this body with a strict schema. console.log(JSON.stringify(await hookRequest("/v1/owner-inbox?issues=1&rules=1", input), null, 2)); return 0; }