@phren/cli 0.3.3 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hooks.d.ts +6 -0
- package/dist/bridge/agent-hooks.js +66 -25
- package/dist/bridge/canary.d.ts +4 -0
- package/dist/bridge/canary.js +17 -4
- package/dist/bridge/changes.d.ts +7 -0
- package/dist/bridge/changes.js +6 -1
- package/dist/bridge/client.js +2 -1
- package/dist/bridge/command.js +7 -5
- package/dist/bridge/conductor-group.d.ts +1 -0
- package/dist/bridge/conductor-group.js +4 -3
- package/dist/bridge/dispatch-command.js +2 -2
- package/dist/bridge/fanouts.js +6 -2
- package/dist/bridge/hand-off.d.ts +1 -0
- package/dist/bridge/hand-off.js +3 -2
- package/dist/bridge/harness-status.d.ts +12 -0
- package/dist/bridge/harness-status.js +153 -0
- package/dist/bridge/health.d.ts +18 -0
- package/dist/bridge/health.js +30 -4
- package/dist/bridge/herdr.d.ts +6 -0
- package/dist/bridge/herdr.js +62 -8
- package/dist/bridge/install.js +4 -0
- package/dist/bridge/model-switch.d.ts +4 -1
- package/dist/bridge/model-switch.js +12 -7
- package/dist/bridge/models.js +3 -2
- package/dist/bridge/pane-status.d.ts +37 -0
- package/dist/bridge/pane-status.js +139 -0
- package/dist/bridge/pane-text.d.ts +3 -11
- package/dist/bridge/pane-text.js +9 -16
- package/dist/bridge/peers.js +9 -6
- package/dist/bridge/prompt-once.d.ts +26 -0
- package/dist/bridge/prompt-once.js +69 -0
- package/dist/bridge/protocol.d.ts +10 -0
- package/dist/bridge/protocol.js +10 -0
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-launch.d.ts +10 -1
- package/dist/bridge/schedule-launch.js +29 -3
- package/dist/bridge/schedule-watch.js +1 -1
- package/dist/bridge/schedules.d.ts +10 -0
- package/dist/bridge/schedules.js +40 -0
- package/dist/bridge/server-launch.js +12 -10
- package/dist/bridge/server-pane-routes.js +23 -9
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/session-servers.js +5 -6
- package/dist/bridge/side-questions.js +6 -5
- package/dist/bridge/terminal-choice.d.ts +12 -5
- package/dist/bridge/terminal-choice.js +66 -0
- package/dist/bridge/terminal-herdr.d.ts +5 -0
- package/dist/bridge/terminal-herdr.js +57 -0
- package/dist/bridge/terminal-tmux.d.ts +111 -0
- package/dist/bridge/terminal-tmux.js +549 -0
- package/dist/bridge/terminal.d.ts +119 -0
- package/dist/bridge/terminal.js +66 -0
- package/dist/bridge/transcript-claude.d.ts +6 -0
- package/dist/bridge/transcript-claude.js +20 -0
- package/dist/bridge/transcript-opencode.js +1 -1
- package/dist/bridge/transcript-preview.d.ts +5 -0
- package/dist/bridge/transcript-preview.js +52 -2
- package/dist/bridge/transport.js +10 -4
- package/dist/bridge-hook.mjs +4852 -3391
- package/dist/cli-registry.js +7 -0
- package/dist/entrypoint.js +2 -1
- package/dist/init/init.js +4 -0
- package/dist/link/doctor.js +33 -30
- package/dist/modules/agent-package.d.ts +35 -0
- package/dist/modules/agent-package.js +133 -0
- package/dist/modules/registry.js +2 -2
- package/dist/session/utils.js +1 -1
- package/dist/tools/dispatch.js +2 -2
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +97 -6
package/dist/cli-registry.js
CHANGED
|
@@ -318,6 +318,13 @@ export const REGISTRY = [
|
|
|
318
318
|
],
|
|
319
319
|
run: async (args, ctx) => (await (await import("./modules/code-package.js")).requireCodePackage(ctx.phrenPath())).runCodeCommand(args, ctx),
|
|
320
320
|
},
|
|
321
|
+
{
|
|
322
|
+
name: "agent",
|
|
323
|
+
topic: "core",
|
|
324
|
+
usage: "phren agent [options] [task]",
|
|
325
|
+
summary: "Run phren's coding agent (needs @phren/agent); phren agent --help lists its options",
|
|
326
|
+
run: async (args) => (await import("./modules/agent-package.js")).runAgentCommand(args),
|
|
327
|
+
},
|
|
321
328
|
{
|
|
322
329
|
name: "shell",
|
|
323
330
|
topic: "core",
|
package/dist/entrypoint.js
CHANGED
|
@@ -174,7 +174,8 @@ export async function runTopLevelCommand(argv, opts = {}) {
|
|
|
174
174
|
ensureFtsCacheRootPrivate();
|
|
175
175
|
// Intercept before any handler runs - in particular before namespace
|
|
176
176
|
// handlers that used to print their own per-subcommand help text.
|
|
177
|
-
|
|
177
|
+
// `phren agent` hands every argument to the agent, which prints its own help.
|
|
178
|
+
if (cmd.name !== "agent" && (argv.includes("--help") || argv.includes("-h")) || (argv.length === 1 && ["maintain", "config", "bridge"].includes(cmd.name))) {
|
|
178
179
|
const out = formatCommand(cmd.name, snapshot);
|
|
179
180
|
if (out)
|
|
180
181
|
console.log(out);
|
package/dist/init/init.js
CHANGED
|
@@ -703,6 +703,10 @@ export async function runInit(opts = {}) {
|
|
|
703
703
|
log(`\nNext:`);
|
|
704
704
|
let step = 1;
|
|
705
705
|
log(` ${step++}. Start a new agent session (Claude, Codex, Copilot…) in a project. Phren loads its memory automatically.`);
|
|
706
|
+
const { agentInstalled } = await import("../modules/agent-package.js");
|
|
707
|
+
log(agentInstalled()
|
|
708
|
+
? ` Or use phren's own coding agent: phren agent -i`
|
|
709
|
+
: ` phren's own coding agent is optional: npm install -g @phren/agent, then phren agent -i`);
|
|
706
710
|
if (!paired)
|
|
707
711
|
log(` ${step++}. Connect your phone any time: phren pair`);
|
|
708
712
|
if (!synced) {
|
package/dist/link/doctor.js
CHANGED
|
@@ -670,6 +670,38 @@ export async function runDoctor(phrenPath, fix = false, checkData = false, confi
|
|
|
670
670
|
detail: `index build/query failed: ${errorMessage(err)}`,
|
|
671
671
|
});
|
|
672
672
|
}
|
|
673
|
+
// Repair before the hook and wrapper checks below, so they report what
|
|
674
|
+
// --fix left behind: the relink is what writes codex.json, the Copilot and
|
|
675
|
+
// Cursor hook files and the wrappers.
|
|
676
|
+
if (fix) {
|
|
677
|
+
const repaired = repairPreexistingInstall(phrenPath);
|
|
678
|
+
const details = [];
|
|
679
|
+
if (repaired.removedLegacyProjects > 0)
|
|
680
|
+
details.push(`removed ${repaired.removedLegacyProjects} legacy sample profile entries`);
|
|
681
|
+
if (repaired.createdContextFile)
|
|
682
|
+
details.push("recreated ~/.phren-context.md");
|
|
683
|
+
if (repaired.createdRootMemory)
|
|
684
|
+
details.push("recreated generated MEMORY.md");
|
|
685
|
+
if (details.length === 0)
|
|
686
|
+
details.push("baseline repair complete");
|
|
687
|
+
checks.push({ name: "baseline-repair", ok: true, detail: details.join("; ") });
|
|
688
|
+
}
|
|
689
|
+
if (fix && invalidProjectDirs.length > 0) {
|
|
690
|
+
const migration = migrateInvalidProjectNames(phrenPath);
|
|
691
|
+
const unresolved = migration.outcomes.filter((o) => o.action !== "renamed");
|
|
692
|
+
checks.push({
|
|
693
|
+
name: "project-names-migrate",
|
|
694
|
+
ok: unresolved.length === 0,
|
|
695
|
+
detail: formatMigrationSummary(migration),
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
if (fix && profile && profileFile) {
|
|
699
|
+
await runLink(phrenPath, { machine, profile });
|
|
700
|
+
checks.push({ name: "self-heal", ok: true, detail: "relinked hooks, symlinks, context, memory pointers" });
|
|
701
|
+
}
|
|
702
|
+
else if (fix) {
|
|
703
|
+
checks.push({ name: "self-heal", ok: false, detail: "relink blocked: machine/profile not fully configured" });
|
|
704
|
+
}
|
|
673
705
|
const detected = detectInstalledTools();
|
|
674
706
|
if (detected.has("copilot")) {
|
|
675
707
|
const copilotHooks = hookConfigPath("copilot", phrenPath);
|
|
@@ -721,36 +753,7 @@ export async function runDoctor(phrenPath, fix = false, checkData = false, confi
|
|
|
721
753
|
checks.push(wrapperCheck(tool, wrapperState(tool)));
|
|
722
754
|
}
|
|
723
755
|
checks.push(wrapperCheck("phren", wrapperState("phren")));
|
|
724
|
-
if (fix) {
|
|
725
|
-
const repaired = repairPreexistingInstall(phrenPath);
|
|
726
|
-
const details = [];
|
|
727
|
-
if (repaired.removedLegacyProjects > 0)
|
|
728
|
-
details.push(`removed ${repaired.removedLegacyProjects} legacy sample profile entries`);
|
|
729
|
-
if (repaired.createdContextFile)
|
|
730
|
-
details.push("recreated ~/.phren-context.md");
|
|
731
|
-
if (repaired.createdRootMemory)
|
|
732
|
-
details.push("recreated generated MEMORY.md");
|
|
733
|
-
if (details.length === 0)
|
|
734
|
-
details.push("baseline repair complete");
|
|
735
|
-
checks.push({ name: "baseline-repair", ok: true, detail: details.join("; ") });
|
|
736
|
-
}
|
|
737
|
-
if (fix && invalidProjectDirs.length > 0) {
|
|
738
|
-
const migration = migrateInvalidProjectNames(phrenPath);
|
|
739
|
-
const unresolved = migration.outcomes.filter((o) => o.action !== "renamed");
|
|
740
|
-
checks.push({
|
|
741
|
-
name: "project-names-migrate",
|
|
742
|
-
ok: unresolved.length === 0,
|
|
743
|
-
detail: formatMigrationSummary(migration),
|
|
744
|
-
});
|
|
745
|
-
}
|
|
746
|
-
if (fix && profile && profileFile) {
|
|
747
|
-
await runLink(phrenPath, { machine, profile });
|
|
748
|
-
checks.push({ name: "self-heal", ok: true, detail: "relinked hooks, symlinks, context, memory pointers" });
|
|
749
|
-
}
|
|
750
|
-
else if (fix) {
|
|
751
|
-
checks.push({ name: "self-heal", ok: false, detail: "relink blocked: machine/profile not fully configured" });
|
|
752
|
-
}
|
|
753
|
-
else {
|
|
756
|
+
if (!fix) {
|
|
754
757
|
// Read-only mode: just check if hook configs exist, don't write anything
|
|
755
758
|
const detectedTools = detected;
|
|
756
759
|
const hookChecks = [];
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `phren agent` launches phren's coding agent, which ships separately as
|
|
3
|
+
* `@phren/agent` (it brings ink and React, which the CLI must not carry). Like
|
|
4
|
+
* `@phren/code` it is optional: nothing here is imported until the command
|
|
5
|
+
* runs, and a missing package is a one-line hint, not a stack trace.
|
|
6
|
+
*/
|
|
7
|
+
export declare const AGENT_PACKAGE_HINT = "phren agent needs @phren/agent: run npm install -g @phren/agent";
|
|
8
|
+
export interface AgentPackage {
|
|
9
|
+
directory: string;
|
|
10
|
+
bin: string;
|
|
11
|
+
version?: string;
|
|
12
|
+
source: string;
|
|
13
|
+
}
|
|
14
|
+
/** The installed package in `directory`, if it is @phren/agent and its binary is built. */
|
|
15
|
+
export declare function agentPackageAt(directory: string, source: string): AgentPackage | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* Resolution order, first hit wins: an explicit directory
|
|
18
|
+
* (`PHREN_AGENT_PACKAGE`), a package Node resolves next to this CLI, this
|
|
19
|
+
* repository's own packages/agent in a workspace checkout, then npm's global
|
|
20
|
+
* root. `global: false` skips the npm call for quick probes such as init's.
|
|
21
|
+
*/
|
|
22
|
+
export declare function findAgentPackage(options?: {
|
|
23
|
+
global?: boolean;
|
|
24
|
+
}): AgentPackage | undefined;
|
|
25
|
+
/** Whether the agent can start here, from a local package or a `phren-agent`
|
|
26
|
+
* on PATH. Cheap enough for init's summary: no npm call. */
|
|
27
|
+
export declare function agentInstalled(): boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Run the agent in a child process with this terminal. The child's argv[0] is
|
|
30
|
+
* `phren-agent`, so the tmux provider and anything else that reads the process
|
|
31
|
+
* table sees the same agent whichever entry point started it; the environment
|
|
32
|
+
* (HERDR_PANE_ID, PHREN_PATH) passes through unchanged, which is what binds a
|
|
33
|
+
* Herdr pane to the session's event log.
|
|
34
|
+
*/
|
|
35
|
+
export declare function runAgentCommand(args: string[]): Promise<number>;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
/**
|
|
7
|
+
* `phren agent` launches phren's coding agent, which ships separately as
|
|
8
|
+
* `@phren/agent` (it brings ink and React, which the CLI must not carry). Like
|
|
9
|
+
* `@phren/code` it is optional: nothing here is imported until the command
|
|
10
|
+
* runs, and a missing package is a one-line hint, not a stack trace.
|
|
11
|
+
*/
|
|
12
|
+
export const AGENT_PACKAGE_HINT = "phren agent needs @phren/agent: run npm install -g @phren/agent";
|
|
13
|
+
function readManifest(directory) {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** The installed package in `directory`, if it is @phren/agent and its binary is built. */
|
|
22
|
+
export function agentPackageAt(directory, source) {
|
|
23
|
+
const manifest = readManifest(directory);
|
|
24
|
+
if (manifest?.name !== "@phren/agent")
|
|
25
|
+
return undefined;
|
|
26
|
+
const relative = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.["phren-agent"];
|
|
27
|
+
if (!relative)
|
|
28
|
+
return undefined;
|
|
29
|
+
const bin = path.join(directory, relative);
|
|
30
|
+
return fs.existsSync(bin) ? { directory, bin, version: manifest.version, source } : undefined;
|
|
31
|
+
}
|
|
32
|
+
/** This repository checked out as a workspace, if its packages/agent is present. */
|
|
33
|
+
function workspaceDirectory() {
|
|
34
|
+
let directory = path.dirname(fileURLToPath(import.meta.url));
|
|
35
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
36
|
+
const candidate = path.join(directory, "packages", "agent");
|
|
37
|
+
if (fs.existsSync(path.join(candidate, "package.json")))
|
|
38
|
+
return candidate;
|
|
39
|
+
const parent = path.dirname(directory);
|
|
40
|
+
if (parent === directory)
|
|
41
|
+
break;
|
|
42
|
+
directory = parent;
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
function resolvedDirectory() {
|
|
47
|
+
try {
|
|
48
|
+
return path.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function globalDirectory() {
|
|
55
|
+
try {
|
|
56
|
+
const options = { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] };
|
|
57
|
+
const root = (process.platform === "win32"
|
|
58
|
+
? execFileSync("npm.cmd", ["root", "-g"], { ...options, shell: true })
|
|
59
|
+
: execFileSync("npm", ["root", "-g"], options)).trim();
|
|
60
|
+
return root ? path.join(root, "@phren", "agent") : undefined;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Resolution order, first hit wins: an explicit directory
|
|
68
|
+
* (`PHREN_AGENT_PACKAGE`), a package Node resolves next to this CLI, this
|
|
69
|
+
* repository's own packages/agent in a workspace checkout, then npm's global
|
|
70
|
+
* root. `global: false` skips the npm call for quick probes such as init's.
|
|
71
|
+
*/
|
|
72
|
+
export function findAgentPackage(options = {}) {
|
|
73
|
+
const candidates = [
|
|
74
|
+
[() => process.env.PHREN_AGENT_PACKAGE, "PHREN_AGENT_PACKAGE"],
|
|
75
|
+
[resolvedDirectory, "@phren/agent"],
|
|
76
|
+
[workspaceDirectory, "workspace"],
|
|
77
|
+
];
|
|
78
|
+
if (options.global !== false)
|
|
79
|
+
candidates.push([globalDirectory, "npm global"]);
|
|
80
|
+
for (const [locate, source] of candidates) {
|
|
81
|
+
const directory = locate();
|
|
82
|
+
const found = directory ? agentPackageAt(directory, source) : undefined;
|
|
83
|
+
if (found)
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
/** Whether the agent can start here, from a local package or a `phren-agent`
|
|
89
|
+
* on PATH. Cheap enough for init's summary: no npm call. */
|
|
90
|
+
export function agentInstalled() {
|
|
91
|
+
if (findAgentPackage({ global: false }))
|
|
92
|
+
return true;
|
|
93
|
+
try {
|
|
94
|
+
execFileSync(process.platform === "win32" ? "where.exe" : "which", ["phren-agent"], { stdio: "ignore", timeout: 5_000 });
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Run the agent in a child process with this terminal. The child's argv[0] is
|
|
103
|
+
* `phren-agent`, so the tmux provider and anything else that reads the process
|
|
104
|
+
* table sees the same agent whichever entry point started it; the environment
|
|
105
|
+
* (HERDR_PANE_ID, PHREN_PATH) passes through unchanged, which is what binds a
|
|
106
|
+
* Herdr pane to the session's event log.
|
|
107
|
+
*/
|
|
108
|
+
export async function runAgentCommand(args) {
|
|
109
|
+
const agent = findAgentPackage();
|
|
110
|
+
if (!agent) {
|
|
111
|
+
console.error(AGENT_PACKAGE_HINT);
|
|
112
|
+
return 1;
|
|
113
|
+
}
|
|
114
|
+
const child = spawn(process.execPath, [agent.bin, ...args], { stdio: "inherit", argv0: "phren-agent", env: process.env });
|
|
115
|
+
// The terminal delivers Ctrl-C to the whole foreground group; the child
|
|
116
|
+
// decides what it means. This process only waits and relays its exit.
|
|
117
|
+
const forward = (signal) => () => { if (!child.killed)
|
|
118
|
+
child.kill(signal); };
|
|
119
|
+
const onTerm = forward("SIGTERM"), onHup = forward("SIGHUP"), onInt = () => { };
|
|
120
|
+
process.on("SIGINT", onInt).on("SIGTERM", onTerm).on("SIGHUP", onHup);
|
|
121
|
+
try {
|
|
122
|
+
return await new Promise((resolve) => {
|
|
123
|
+
child.on("error", (error) => { console.error(`phren agent: ${error.message}`); resolve(1); });
|
|
124
|
+
child.on("exit", (code, signal) => resolve(code ?? (signal ? 128 + (signalNumber(signal) ?? 1) : 1)));
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
process.off("SIGINT", onInt).off("SIGTERM", onTerm).off("SIGHUP", onHup);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function signalNumber(signal) {
|
|
132
|
+
return { SIGHUP: 1, SIGINT: 2, SIGKILL: 9, SIGTERM: 15 }[signal];
|
|
133
|
+
}
|
package/dist/modules/registry.js
CHANGED
|
@@ -25,7 +25,7 @@ export const BUILTIN_MODULES = [
|
|
|
25
25
|
]),
|
|
26
26
|
],
|
|
27
27
|
cliCommands: [
|
|
28
|
-
"init", "quickstart", "add", "projects", "search", "status", "doctor", "web-ui", "graph", "shell",
|
|
28
|
+
"init", "quickstart", "add", "agent", "projects", "search", "status", "doctor", "web-ui", "graph", "shell",
|
|
29
29
|
"add-finding", "pin", "review", "session-context", "sessions", "finding", "note", "notes",
|
|
30
30
|
"search-fragments", "related-docs", "truths", "promote", "skills", "detect-skills", "hooks", "config",
|
|
31
31
|
"maintain", "consolidation-status", "quality-feedback", "mcp-mode", "hooks-mode", "preset", "snippet",
|
|
@@ -96,7 +96,7 @@ export const BUILTIN_MODULES = [
|
|
|
96
96
|
capabilities: [
|
|
97
97
|
"hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "herdr",
|
|
98
98
|
"webServers", "webPreview", "activity", "approvals", "questions", "accountUsage", "providers",
|
|
99
|
-
"files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "transcribe",
|
|
99
|
+
"files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "transcribe", "promptOnce",
|
|
100
100
|
],
|
|
101
101
|
storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
|
|
102
102
|
localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily"],
|
package/dist/session/utils.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import { errorMessage } from "../utils.js";
|
|
4
|
-
// The
|
|
4
|
+
// The coding agent (@phren/agent) imports the sessions directory from here.
|
|
5
5
|
export { sessionsDir } from "../phren-paths.js";
|
|
6
6
|
import { atomicWriteText } from "../phren-paths.js";
|
|
7
7
|
/**
|
package/dist/tools/dispatch.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { hookRequest } from "../bridge/client.js";
|
|
2
2
|
import { dispatchSchema } from "../bridge/dispatch.js";
|
|
3
3
|
import { handOff, handOffSchema, listLiveSessions } from "../bridge/hand-off.js";
|
|
4
|
-
import {
|
|
4
|
+
import { terminalPaneFromEnv } from "../bridge/terminal.js";
|
|
5
5
|
import { mcpResponse } from "./types.js";
|
|
6
6
|
export function register(server) {
|
|
7
7
|
server.registerTool("dispatch", {
|
|
@@ -11,7 +11,7 @@ export function register(server) {
|
|
|
11
11
|
}, async (input) => {
|
|
12
12
|
try {
|
|
13
13
|
// The pane this agent runs in receives the one-line return notices.
|
|
14
|
-
const origin =
|
|
14
|
+
const origin = await terminalPaneFromEnv();
|
|
15
15
|
const result = await hookRequest("/v1/dispatch", { ...input, ...(origin ? { origin } : {}) }, undefined, 180_000);
|
|
16
16
|
return mcpResponse({ ok: result.ok === true, data: result, message: `${result.computer}: ${result.state}.` });
|
|
17
17
|
}
|
package/package.json
CHANGED
|
@@ -6,6 +6,12 @@ import path from "node:path";
|
|
|
6
6
|
const PHREN_STORE = "__PHREN_STORE__";
|
|
7
7
|
const FLUSH_MS = 250;
|
|
8
8
|
const MAX_TOOL_OUTPUT = 200_000;
|
|
9
|
+
// OpenCode's read tool returns a picture as an inline data URL on the tool
|
|
10
|
+
// part (`state.attachments`). The Hook serves images up to 8 MiB; the session
|
|
11
|
+
// budget bounds what every flush rewrites.
|
|
12
|
+
const MAX_IMAGE_DATA = 4_000_000;
|
|
13
|
+
const MAX_SESSION_IMAGE_DATA = 24_000_000;
|
|
14
|
+
const IMAGE_DATA_URL = /^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;
|
|
9
15
|
const STOP_REASONS = { stop: "end_turn", "tool-calls": "tool_use", length: "max_tokens" };
|
|
10
16
|
const OPENCODE_SESSION = /^ses_[0-9A-Za-z]{1,64}$/;
|
|
11
17
|
const APPROVAL_POLL_MS = 200;
|
|
@@ -145,14 +151,36 @@ function blocksFor(message) {
|
|
|
145
151
|
return blocks;
|
|
146
152
|
}
|
|
147
153
|
|
|
148
|
-
|
|
154
|
+
/** A tool's picture attachments as Anthropic-shaped image blocks, the form the
|
|
155
|
+
* Hook's image route and the phone already read from Claude Code. Only inline
|
|
156
|
+
* data URLs are carried; an image over the caps becomes a text marker. */
|
|
157
|
+
function toolImages(state, budget) {
|
|
158
|
+
const blocks = [];
|
|
159
|
+
for (const attachment of Array.isArray(state?.attachments) ? state.attachments : []) {
|
|
160
|
+
if (attachment?.type !== "file" || typeof attachment.url !== "string") continue;
|
|
161
|
+
const match = IMAGE_DATA_URL.exec(attachment.url);
|
|
162
|
+
if (!match) continue;
|
|
163
|
+
const data = match[2];
|
|
164
|
+
if (data.length > MAX_IMAGE_DATA || data.length > budget.remaining) {
|
|
165
|
+
blocks.push({ type: "text", text: "[Image not included: too large to show on the phone]" });
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
budget.remaining -= data.length;
|
|
169
|
+
blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data } });
|
|
170
|
+
}
|
|
171
|
+
return blocks;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function toolResults(message, budget) {
|
|
149
175
|
const results = [];
|
|
150
176
|
for (const id of message.partOrder) {
|
|
151
177
|
const part = message.parts.get(id);
|
|
152
178
|
if (!part || part.type !== "tool" || typeof part.callID !== "string") continue;
|
|
153
179
|
const status = part.state?.status;
|
|
154
180
|
if (status !== "completed" && status !== "error") continue;
|
|
155
|
-
|
|
181
|
+
const output = toolOutput(part.state), images = toolImages(part.state, budget);
|
|
182
|
+
const content = images.length ? [{ type: "text", text: output }, ...images] : output;
|
|
183
|
+
results.push({ type: "tool_result", tool_use_id: part.callID, content, is_error: status === "error" });
|
|
156
184
|
}
|
|
157
185
|
return results;
|
|
158
186
|
}
|
|
@@ -163,6 +191,7 @@ function linesFor(session) {
|
|
|
163
191
|
.filter(Boolean)
|
|
164
192
|
.sort((a, b) => (a.info?.time?.created ?? 0) - (b.info?.time?.created ?? 0) || String(a.info?.id).localeCompare(String(b.info?.id)));
|
|
165
193
|
const lines = [];
|
|
194
|
+
const budget = { remaining: MAX_SESSION_IMAGE_DATA };
|
|
166
195
|
let seq = 0;
|
|
167
196
|
const emit = (type, data, created) => {
|
|
168
197
|
lines.push(JSON.stringify({ seq: seq++, time: new Date(created || Date.now()).toISOString(), type, data }));
|
|
@@ -180,15 +209,48 @@ function linesFor(session) {
|
|
|
180
209
|
data.usage = { input_tokens: info.tokens.input ?? 0, output_tokens: info.tokens.output ?? 0 };
|
|
181
210
|
}
|
|
182
211
|
if (blocks.length) emit("assistant/message", data, info.time?.created);
|
|
183
|
-
const results = toolResults(message);
|
|
212
|
+
const results = toolResults(message, budget);
|
|
184
213
|
if (results.length) emit("tool/results", { message: { role: "user", content: results } }, info.time?.updated ?? info.time?.created);
|
|
185
214
|
}
|
|
186
215
|
}
|
|
187
216
|
return lines;
|
|
188
217
|
}
|
|
189
218
|
|
|
219
|
+
/** Which conversation this OpenCode process is showing, by PID: the Hook
|
|
220
|
+
* reads it to bind a pane when Herdr reports no session for it. */
|
|
221
|
+
const pidBindingFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-pid-${process.pid}.json`);
|
|
222
|
+
function writePidBinding(sessionID) {
|
|
223
|
+
mkdirSync(path.dirname(pidBindingFile()), { recursive: true });
|
|
224
|
+
writeJsonAtomic(pidBindingFile(), { session: sessionID, at: new Date().toISOString() });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** What this OpenCode process is doing, by PID: "working", "idle" or
|
|
228
|
+
* "blocked" (a permission waits for an answer). The Hook reads it for a pane
|
|
229
|
+
* whose terminal does not watch its agents (tmux); Herdr has its own. */
|
|
230
|
+
const statusFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-status-${process.pid}.json`);
|
|
231
|
+
|
|
190
232
|
export const PhrenTranscriptPlugin = async () => {
|
|
191
233
|
const sessions = new Map();
|
|
234
|
+
// Subagent sessions run inside the same process; the pane shows their parent.
|
|
235
|
+
const children = new Set();
|
|
236
|
+
let boundSession;
|
|
237
|
+
// A reused PID must not inherit an old process's conversation or state.
|
|
238
|
+
try { removeFile(pidBindingFile()); removeFile(statusFile()); } catch {}
|
|
239
|
+
let recordedStatus;
|
|
240
|
+
// Permission asks still open, by id: while any is, the process is blocked.
|
|
241
|
+
const asking = new Set();
|
|
242
|
+
const recordStatus = (status, sessionID) => {
|
|
243
|
+
// A fan-out worker runs headless, in no pane.
|
|
244
|
+
if (process.env.PHREN_FANOUT_JOB) return;
|
|
245
|
+
const next = asking.size && status === "working" ? "blocked" : status;
|
|
246
|
+
if (next === recordedStatus) return;
|
|
247
|
+
try {
|
|
248
|
+
mkdirSync(path.dirname(statusFile()), { recursive: true });
|
|
249
|
+
writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at: new Date().toISOString() });
|
|
250
|
+
recordedStatus = next;
|
|
251
|
+
} catch {}
|
|
252
|
+
};
|
|
253
|
+
const permissionId = properties => text(properties?.permissionID) || text(properties?.requestID) || text(properties?.id);
|
|
192
254
|
const timers = new Map();
|
|
193
255
|
const written = new Map();
|
|
194
256
|
const pendingApprovals = new Set();
|
|
@@ -257,8 +319,12 @@ export const PhrenTranscriptPlugin = async () => {
|
|
|
257
319
|
return {
|
|
258
320
|
"chat.message": async (input, output) => {
|
|
259
321
|
if (!OPENCODE_SESSION.test(text(input?.sessionID)) || !output?.message) return;
|
|
322
|
+
if (!process.env.PHREN_FANOUT_JOB && !children.has(input.sessionID) && boundSession !== input.sessionID) {
|
|
323
|
+
try { writePidBinding(input.sessionID); boundSession = input.sessionID; } catch {}
|
|
324
|
+
}
|
|
260
325
|
rememberInfo(input.sessionID, output.message);
|
|
261
326
|
for (const part of output.parts ?? []) rememberPart(input.sessionID, output.message.id, part);
|
|
327
|
+
if (!children.has(input.sessionID)) recordStatus("working", input.sessionID);
|
|
262
328
|
},
|
|
263
329
|
"permission.ask": async (input, output) => {
|
|
264
330
|
// A fan-out worker runs headless in its own worktree with nobody watching
|
|
@@ -276,7 +342,11 @@ export const PhrenTranscriptPlugin = async () => {
|
|
|
276
342
|
writeBlocked(input);
|
|
277
343
|
return;
|
|
278
344
|
}
|
|
279
|
-
let request, answer, pendingSession;
|
|
345
|
+
let request, answer, pendingSession, decision;
|
|
346
|
+
// The ask blocks the process until it is answered: here from the
|
|
347
|
+
// phone, or in the terminal (permission.replied below).
|
|
348
|
+
const askId = text(input?.id);
|
|
349
|
+
if (askId) { asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }
|
|
280
350
|
try {
|
|
281
351
|
const sessionID = text(input?.sessionID), id = text(input?.id);
|
|
282
352
|
if (!OPENCODE_SESSION.test(sessionID) || !id) { setStatus(output, "ask"); return; }
|
|
@@ -294,7 +364,6 @@ export const PhrenTranscriptPlugin = async () => {
|
|
|
294
364
|
title: text(input.title) || `Allow ${text(input.type) || "action"}?`, message: permissionMessage(input),
|
|
295
365
|
createdAt: new Date(created).toISOString(), expiresAt: new Date(created + APPROVAL_DEADLINE_MS).toISOString() });
|
|
296
366
|
const deadline = created + APPROVAL_DEADLINE_MS;
|
|
297
|
-
let decision;
|
|
298
367
|
while (Date.now() < deadline) {
|
|
299
368
|
await sleep(APPROVAL_POLL_MS);
|
|
300
369
|
try {
|
|
@@ -311,11 +380,25 @@ export const PhrenTranscriptPlugin = async () => {
|
|
|
311
380
|
if (answer) removeFile(answer);
|
|
312
381
|
if (request) removeFile(request);
|
|
313
382
|
if (pendingSession) pendingApprovals.delete(pendingSession);
|
|
383
|
+
// Answered from the phone: back to work. Otherwise the terminal asks.
|
|
384
|
+
if (askId && (decision === "approve" || decision === "deny")) { asking.delete(askId); recordStatus("working", pendingSession); }
|
|
314
385
|
}
|
|
315
386
|
},
|
|
316
387
|
event: async ({ event }) => {
|
|
317
388
|
const properties = event?.properties ?? {};
|
|
389
|
+
if ((event?.type === "session.created" || event?.type === "session.updated") && properties.info?.parentID
|
|
390
|
+
&& OPENCODE_SESSION.test(text(properties.info.id))) children.add(properties.info.id);
|
|
318
391
|
const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : properties.info?.sessionID ?? properties.part?.sessionID;
|
|
392
|
+
// Permission events name the ask (permission.updated / permission.asked)
|
|
393
|
+
// and its answer, which may come from the terminal.
|
|
394
|
+
if (event?.type === "permission.updated" || event?.type === "permission.asked") {
|
|
395
|
+
const id = permissionId(properties);
|
|
396
|
+
if (id) { asking.add(id); recordStatus("blocked", text(sessionID)); }
|
|
397
|
+
} else if (event?.type === "permission.replied") {
|
|
398
|
+
const id = permissionId(properties);
|
|
399
|
+
if (id) asking.delete(id); else asking.clear();
|
|
400
|
+
recordStatus("working", text(sessionID));
|
|
401
|
+
}
|
|
319
402
|
if (!OPENCODE_SESSION.test(text(sessionID))) return;
|
|
320
403
|
if (event.type === "message.updated") rememberInfo(sessionID, properties.info);
|
|
321
404
|
else if (event.type === "message.part.updated") rememberPart(sessionID, properties.part?.messageID, properties.part);
|
|
@@ -334,7 +417,15 @@ export const PhrenTranscriptPlugin = async () => {
|
|
|
334
417
|
} else if (event.type === "session.idle" || event.type === "session.error") {
|
|
335
418
|
sessionState(sessionID).idle = true;
|
|
336
419
|
flush(sessionID);
|
|
337
|
-
|
|
420
|
+
if (!children.has(sessionID)) { asking.clear(); recordStatus("idle", sessionID); }
|
|
421
|
+
} else if (event.type === "session.status") {
|
|
422
|
+
if (properties.status?.type === "busy") sessionState(sessionID).idle = false;
|
|
423
|
+
// A subagent's session runs inside its parent's turn.
|
|
424
|
+
if (!children.has(sessionID) && ["busy", "retry", "idle"].includes(properties.status?.type)) {
|
|
425
|
+
if (properties.status.type === "idle") asking.clear();
|
|
426
|
+
recordStatus(properties.status.type === "idle" ? "idle" : "working", sessionID);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
338
429
|
},
|
|
339
430
|
};
|
|
340
431
|
};
|