@phren/cli 0.3.20 → 0.3.21
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 +22 -19
- package/dist/bridge/agent-hooks.js +49 -33
- package/dist/bridge/approval-summary.d.ts +4 -0
- package/dist/bridge/approval-summary.js +12 -1
- package/dist/bridge/code-note.d.ts +1 -0
- package/dist/bridge/code-note.js +2 -2
- package/dist/bridge/codex-binary.d.ts +5 -0
- package/dist/bridge/codex-binary.js +7 -0
- package/dist/bridge/dispatch-command.js +1 -1
- package/dist/bridge/dispatch-returns.d.ts +3 -2
- package/dist/bridge/dispatch-returns.js +27 -11
- package/dist/bridge/dispatch.d.ts +4 -0
- package/dist/bridge/dispatch.js +5 -3
- package/dist/bridge/folder-trust.d.ts +13 -3
- package/dist/bridge/folder-trust.js +42 -4
- package/dist/bridge/hand-off.js +2 -1
- package/dist/bridge/herdr.js +6 -5
- package/dist/bridge/launch-brief.d.ts +3 -1
- package/dist/bridge/launch-brief.js +3 -1
- package/dist/bridge/memory-store.d.ts +7 -0
- package/dist/bridge/memory-store.js +37 -1
- package/dist/bridge/schedule-format.d.ts +1 -1
- package/dist/bridge/schedule-format.js +1 -1
- package/dist/bridge/schedule-launch.js +5 -0
- package/dist/bridge/schedule-watch.d.ts +5 -2
- package/dist/bridge/schedule-watch.js +59 -20
- package/dist/bridge/server-launch.d.ts +6 -0
- package/dist/bridge/server-launch.js +59 -11
- package/dist/bridge/server-pane-routes.js +20 -13
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/server-stream.js +12 -0
- package/dist/bridge/server.js +2 -2
- package/dist/bridge/session-activity.d.ts +6 -0
- package/dist/bridge/session-activity.js +16 -0
- package/dist/bridge/settings-switch.d.ts +7 -0
- package/dist/bridge/settings-switch.js +15 -0
- package/dist/bridge/speech-transcribe.d.ts +8 -1
- package/dist/bridge/speech-transcribe.js +18 -3
- package/dist/bridge/transcript-claude.js +39 -10
- package/dist/bridge/worker-close.js +3 -2
- package/dist/bridge/worker-unfinished.d.ts +8 -2
- package/dist/bridge/worker-unfinished.js +57 -24
- package/dist/bridge-hook.mjs +513 -277
- package/dist/cli-registry.js +1 -1
- package/dist/home-paths.d.ts +2 -0
- package/dist/home-paths.js +4 -0
- package/dist/modules/registry.js +1 -1
- package/dist/test-global-setup.js +2 -1
- package/dist/test-sandbox.d.ts +15 -0
- package/dist/test-sandbox.js +36 -0
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +2 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { lstat, mkdir, readFile, realpath, rmdir, stat, utimes } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { claudeConfigDir, codexHome, homeDir } from "../home-paths.js";
|
|
3
|
+
import { claudeConfigDir, codexHome, copilotHome, homeDir } from "../home-paths.js";
|
|
4
4
|
import { logger } from "../logger.js";
|
|
5
5
|
import { atomic } from "./protocol.js";
|
|
6
6
|
export function pretrustEnabled(env = process.env) {
|
|
@@ -156,19 +156,56 @@ export async function ensureCodexDirTrusted(dir, env = process.env) {
|
|
|
156
156
|
}
|
|
157
157
|
throw new Error("config.toml kept changing while it was being updated");
|
|
158
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* Adds `dir` to `trustedFolders` in Copilot's `settings.json`, creating the
|
|
161
|
+
* file when Copilot has none yet. Other settings are kept; a file that is not
|
|
162
|
+
* a JSON object is left alone (the launch then meets the trust screen).
|
|
163
|
+
*/
|
|
164
|
+
export async function ensureCopilotFolderTrusted(dir, env = process.env) {
|
|
165
|
+
const directory = copilotHome(env);
|
|
166
|
+
const configured = path.join(directory, "settings.json");
|
|
167
|
+
const file = await realpath(configured).catch(() => configured);
|
|
168
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
169
|
+
let text = "";
|
|
170
|
+
try {
|
|
171
|
+
text = await readFile(file, "utf8");
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
if (error.code !== "ENOENT")
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
const settings = text.trim() ? JSON.parse(text) : {};
|
|
178
|
+
if (!settings || typeof settings !== "object" || Array.isArray(settings))
|
|
179
|
+
throw new Error("settings.json is not a JSON object");
|
|
180
|
+
const record = settings;
|
|
181
|
+
if (record.trustedFolders !== undefined && !Array.isArray(record.trustedFolders))
|
|
182
|
+
throw new Error("trustedFolders in settings.json is not a list");
|
|
183
|
+
const trusted = (record.trustedFolders ?? []);
|
|
184
|
+
if (trusted.includes(dir))
|
|
185
|
+
return "already";
|
|
186
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
187
|
+
const metadata = await lstat(file).catch(() => undefined);
|
|
188
|
+
// Copilot may have rewritten the file meanwhile; start over from its text.
|
|
189
|
+
if (await readFile(file, "utf8").catch(() => "") !== text)
|
|
190
|
+
continue;
|
|
191
|
+
await atomic(file, JSON.stringify({ ...record, trustedFolders: [...trusted, dir] }, null, 2) + "\n", metadata ? metadata.mode & 0o777 : 0o600);
|
|
192
|
+
return "trusted";
|
|
193
|
+
}
|
|
194
|
+
throw new Error("settings.json kept changing while it was being updated");
|
|
195
|
+
}
|
|
159
196
|
/**
|
|
160
197
|
* Trusts `dir` for `harness` before a launch, when the harness has a trust
|
|
161
198
|
* screen and pre-trust is on. Never throws: a failure is logged and the
|
|
162
199
|
* launch goes on to meet the screen, which dispatch then reports.
|
|
163
200
|
*/
|
|
164
201
|
export async function pretrustFolder(harness, dir, why, env = process.env) {
|
|
165
|
-
if (harness !== "claude" && harness !== "codex")
|
|
202
|
+
if (harness !== "claude" && harness !== "codex" && harness !== "copilot")
|
|
166
203
|
return "skipped";
|
|
167
204
|
if (!pretrustEnabled(env))
|
|
168
205
|
return "skipped";
|
|
169
206
|
if (!path.isAbsolute(dir))
|
|
170
207
|
return "skipped";
|
|
171
|
-
const name = harness === "claude" ? "Claude" : "Codex";
|
|
208
|
+
const name = harness === "claude" ? "Claude" : harness === "codex" ? "Codex" : "Copilot";
|
|
172
209
|
// The same folder by the path the Hook was given and by its real path: the
|
|
173
210
|
// harness keys trust by whichever one its working directory reports.
|
|
174
211
|
const real = await realpath(dir).catch(() => undefined);
|
|
@@ -177,7 +214,8 @@ export async function pretrustFolder(harness, dir, why, env = process.env) {
|
|
|
177
214
|
let outcome = "already";
|
|
178
215
|
for (const folder of [...new Set([dir, real])]) {
|
|
179
216
|
try {
|
|
180
|
-
const result = harness === "claude" ? await ensureClaudeFolderTrusted(folder, env)
|
|
217
|
+
const result = harness === "claude" ? await ensureClaudeFolderTrusted(folder, env)
|
|
218
|
+
: harness === "codex" ? await ensureCodexDirTrusted(folder, env) : await ensureCopilotFolderTrusted(folder, env);
|
|
181
219
|
if (result === "trusted")
|
|
182
220
|
logger.info("launch", `Marked ${folder} trusted for ${name} (${why}).`);
|
|
183
221
|
else if (result === "skipped")
|
package/dist/bridge/hand-off.js
CHANGED
|
@@ -5,6 +5,7 @@ import { z } from "zod";
|
|
|
5
5
|
import { computerName } from "./computers.js";
|
|
6
6
|
import { hookRequest } from "./client.js";
|
|
7
7
|
import { projectName } from "./dispatch.js";
|
|
8
|
+
import { paneProject } from "./approval-summary.js";
|
|
8
9
|
import { isAccountSlug } from "./claude-accounts.js";
|
|
9
10
|
import { grantLabel, findGrant } from "./grants.js";
|
|
10
11
|
import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
|
|
@@ -131,7 +132,7 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
|
|
|
131
132
|
const text = (value) => typeof value === "string" && value ? value : undefined;
|
|
132
133
|
const changedAt = typeof tab.lastChangedAt === "string" ? Date.parse(tab.lastChangedAt) : NaN;
|
|
133
134
|
// A conductor sits in the store, not a project.
|
|
134
|
-
sessions.push({ computer, local, project: tab.role === "conductor" ? undefined : text(cwd
|
|
135
|
+
sessions.push({ computer, local, project: tab.role === "conductor" ? undefined : text(paneProject(cwd)), label: text(label),
|
|
135
136
|
title: text(tab.title), agent: tab.agent, status: text(tab.agentStatus), role: text(tab.role),
|
|
136
137
|
branch: text(tab.branch), model: text(tab.model), ...(typeof object(tab.account).id === "string" ? { account: String(object(tab.account).id) } : {}), ...(target.success ? { target: target.data } : {}),
|
|
137
138
|
...(typeof tab.backgroundTasks === "number" && tab.backgroundTasks > 0 ? { backgroundTasks: tab.backgroundTasks } : {}),
|
package/dist/bridge/herdr.js
CHANGED
|
@@ -304,14 +304,14 @@ async function resolveIdentity(server, pane, fresh) {
|
|
|
304
304
|
const owned = pane.agent === "codex" && !!codexServers.forPane(server, String(pane.pane_id))?.threadId;
|
|
305
305
|
if (pane.agent !== "copilot" && !owned && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
|
|
306
306
|
countIdentity("reported");
|
|
307
|
-
return { sessionId: reported.value };
|
|
307
|
+
return { sessionId: reported.value, noTranscriptLogs: false };
|
|
308
308
|
}
|
|
309
309
|
const pids = await foregroundPids(server, pane);
|
|
310
310
|
const key = identityKey(server, pane, pids);
|
|
311
311
|
const cached = identities.get(key);
|
|
312
312
|
if (!fresh && cached && Date.now() - cached.at < IDENTITY_CACHE_MS) {
|
|
313
313
|
countIdentity("cached");
|
|
314
|
-
return {
|
|
314
|
+
return { ...await cached.result, pids };
|
|
315
315
|
}
|
|
316
316
|
countIdentity(fresh ? "probe-fresh" : "probe");
|
|
317
317
|
const result = identityFromProcesses(server, pane, pids);
|
|
@@ -324,7 +324,7 @@ async function resolveIdentity(server, pane, fresh) {
|
|
|
324
324
|
// brand-new conversation it just proved as starting.
|
|
325
325
|
void result.then(() => { entry.at = Date.now(); }, () => { });
|
|
326
326
|
identities.set(key, entry);
|
|
327
|
-
return {
|
|
327
|
+
return { ...await result, pids };
|
|
328
328
|
}
|
|
329
329
|
export async function paneIdentity(server, pane, fresh = false) {
|
|
330
330
|
return (await resolveIdentity(server, pane, fresh)).sessionId;
|
|
@@ -562,8 +562,9 @@ export async function paneChatState(server, pane, options = {}) {
|
|
|
562
562
|
// An ambiguous set of open logs is not a brand-new conversation.
|
|
563
563
|
// Reuse the same two-second identity probe as context/overview polling;
|
|
564
564
|
// discovering a new chat must not run lsof again for every list refresh.
|
|
565
|
-
|
|
566
|
-
|
|
565
|
+
// Carry the evidence returned by this probe. A concurrent lookup may replace
|
|
566
|
+
// its cache entry, or a busy event loop may advance past the reuse window.
|
|
567
|
+
const starting = !sessionId && !!process && identity.noTranscriptLogs;
|
|
567
568
|
let binding = startingBindings.get(key);
|
|
568
569
|
if (process) {
|
|
569
570
|
// Lost identity, changed process, or newly ambiguous evidence requires a
|
|
@@ -12,7 +12,9 @@ import { type Target } from "./protocol.js";
|
|
|
12
12
|
*
|
|
13
13
|
* OpenCode takes its brief over the HTTP API its launched TUI serves
|
|
14
14
|
* (opencode-panes.ts); the file is still written so the arrival is recorded
|
|
15
|
-
* here. Copilot
|
|
15
|
+
* here. Copilot keeps the typed path: its `-i <prompt>` would submit a first
|
|
16
|
+
* prompt, but its hooks fire SessionStart lazily and their payload was not
|
|
17
|
+
* confirmed to carry the event name, so no arrival could be recorded.
|
|
16
18
|
*/
|
|
17
19
|
/** A dispatch receipt id or a scheduled run id: what `PHREN_DISPATCH_ID` carries. */
|
|
18
20
|
export declare const briefId: z.ZodString;
|
|
@@ -15,7 +15,9 @@ import { atomic, bridgeRoot, targetSchema } from "./protocol.js";
|
|
|
15
15
|
*
|
|
16
16
|
* OpenCode takes its brief over the HTTP API its launched TUI serves
|
|
17
17
|
* (opencode-panes.ts); the file is still written so the arrival is recorded
|
|
18
|
-
* here. Copilot
|
|
18
|
+
* here. Copilot keeps the typed path: its `-i <prompt>` would submit a first
|
|
19
|
+
* prompt, but its hooks fire SessionStart lazily and their payload was not
|
|
20
|
+
* confirmed to carry the event name, so no arrival could be recorded.
|
|
19
21
|
*/
|
|
20
22
|
/** A dispatch receipt id or a scheduled run id: what `PHREN_DISPATCH_ID` carries. */
|
|
21
23
|
export const briefId = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/);
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import { type Json } from "./protocol.js";
|
|
2
2
|
/** The sha git gives these bytes as a blob; GitHub reports the same one. */
|
|
3
3
|
export declare function blobSha(content: Buffer): string;
|
|
4
|
+
/** Only the public repository identity reaches the phone, never credentials
|
|
5
|
+
* embedded in a remote URL or a local filesystem path. */
|
|
6
|
+
export declare function githubStoreRepository(remote: string): string | undefined;
|
|
4
7
|
/** A tree sha for the store's current working tree, written through a private index. */
|
|
5
8
|
export declare function storeHead(store: string, indexFile?: string): Promise<{
|
|
6
9
|
sha: string;
|
|
10
|
+
repositoryIdentity?: {
|
|
11
|
+
repository: string;
|
|
12
|
+
branch: string;
|
|
13
|
+
};
|
|
7
14
|
}>;
|
|
8
15
|
/** The recursive tree for a head, with the fields the phone's GitTree decodes. */
|
|
9
16
|
export declare function storeTree(store: string, sha: string): Promise<Json>;
|
|
@@ -39,6 +39,40 @@ export function blobSha(content) {
|
|
|
39
39
|
async function isRepository(store) {
|
|
40
40
|
return (await lstat(path.join(store, ".git")).catch(() => undefined)) !== undefined;
|
|
41
41
|
}
|
|
42
|
+
/** Only the public repository identity reaches the phone, never credentials
|
|
43
|
+
* embedded in a remote URL or a local filesystem path. */
|
|
44
|
+
export function githubStoreRepository(remote) {
|
|
45
|
+
let host, pathname;
|
|
46
|
+
const scp = /^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i.exec(remote.trim());
|
|
47
|
+
if (scp) {
|
|
48
|
+
host = "github.com";
|
|
49
|
+
pathname = scp[1];
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
try {
|
|
53
|
+
const url = new URL(remote.trim());
|
|
54
|
+
if (!["https:", "ssh:"].includes(url.protocol) || url.search || url.hash)
|
|
55
|
+
return undefined;
|
|
56
|
+
host = url.hostname;
|
|
57
|
+
pathname = url.pathname.replace(/^\//, "");
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (host.toLowerCase() !== "github.com")
|
|
64
|
+
return undefined;
|
|
65
|
+
const repository = pathname.replace(/\/$/, "").replace(/\.git$/i, "");
|
|
66
|
+
return /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/.test(repository) ? repository.toLowerCase() : undefined;
|
|
67
|
+
}
|
|
68
|
+
async function storeRepositoryIdentity(store) {
|
|
69
|
+
const [remote, branch] = await Promise.all([
|
|
70
|
+
git(store, ["config", "--get", "remote.origin.url"]).catch(() => ""),
|
|
71
|
+
git(store, ["symbolic-ref", "--quiet", "--short", "HEAD"]).catch(() => ""),
|
|
72
|
+
]);
|
|
73
|
+
const repository = githubStoreRepository(remote);
|
|
74
|
+
return repository && branch.trim() ? { repository, branch: branch.trim() } : undefined;
|
|
75
|
+
}
|
|
42
76
|
/** A tree sha for the store's current working tree, written through a private index. */
|
|
43
77
|
export function storeHead(store, indexFile = path.join(bridgeRoot(), "store-snapshot.index")) {
|
|
44
78
|
return serialized(async () => {
|
|
@@ -51,7 +85,9 @@ export function storeHead(store, indexFile = path.join(bridgeRoot(), "store-snap
|
|
|
51
85
|
await git(store, head.trim() ? ["read-tree", "HEAD"] : ["read-tree", "--empty"], env);
|
|
52
86
|
}
|
|
53
87
|
await git(store, ["add", "--all", "--", "."], env);
|
|
54
|
-
|
|
88
|
+
const sha = (await git(store, ["write-tree"], env)).trim();
|
|
89
|
+
const repositoryIdentity = await storeRepositoryIdentity(store);
|
|
90
|
+
return { sha, ...(repositoryIdentity ? { repositoryIdentity } : {}) };
|
|
55
91
|
});
|
|
56
92
|
}
|
|
57
93
|
/** The recursive tree for a head, with the fields the phone's GitTree decodes. */
|
|
@@ -2,7 +2,7 @@ import type { SchedulePush, SchedulePushResult } from "./push.js";
|
|
|
2
2
|
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
3
3
|
* the five timing forms evaluated in local time, and the run history file. */
|
|
4
4
|
export declare const SCHEDULE_EVERY: readonly ["interval", "daily", "weekly", "once", "cron"];
|
|
5
|
-
export declare const SCHEDULE_HARNESSES: readonly ["claude", "codex", "opencode"];
|
|
5
|
+
export declare const SCHEDULE_HARNESSES: readonly ["claude", "codex", "opencode", "copilot"];
|
|
6
6
|
export declare const SCHEDULE_NOTIFY: readonly ["start", "finish", "failure"];
|
|
7
7
|
export declare const WEEKDAYS: readonly ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
8
8
|
export type ScheduleEvery = typeof SCHEDULE_EVERY[number];
|
|
@@ -8,7 +8,7 @@ import { isAccountSlug } from "./claude-accounts.js";
|
|
|
8
8
|
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
9
9
|
* the five timing forms evaluated in local time, and the run history file. */
|
|
10
10
|
export const SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
11
|
-
export const SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
11
|
+
export const SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
|
|
12
12
|
export const SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
13
13
|
export const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
14
14
|
export const SCHEDULE_RUN_STATUSES = ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
|
|
@@ -162,6 +162,11 @@ export function headlessCommand(schedule, cwd) {
|
|
|
162
162
|
"--skip-git-repo-check", "--json", "-"] };
|
|
163
163
|
if (schedule.harness === "opencode")
|
|
164
164
|
return { file: "opencode", cwd, args: ["run", "--format", "json", "--dir", cwd, ...model] };
|
|
165
|
+
// Copilot's non-interactive mode needs every tool allowed up front; file
|
|
166
|
+
// access stays inside the working folder. `=` keeps a prompt that starts
|
|
167
|
+
// with "-" from reading as a flag.
|
|
168
|
+
if (schedule.harness === "copilot")
|
|
169
|
+
return { file: "copilot", cwd, args: [`--prompt=${schedule.prompt}`, "--allow-all-tools", "--output-format", "json", ...model] };
|
|
165
170
|
return { file: "claude", cwd, args: ["-p", "--output-format", "stream-json", "--settings", CLAUDE_SCHEDULE_SETTINGS, ...model] };
|
|
166
171
|
}
|
|
167
172
|
async function writeManifest(jobDir, manifest) {
|
|
@@ -38,8 +38,10 @@ export interface StartupWatchEnv {
|
|
|
38
38
|
* `finishedTasks`: when each Claude background task the tail shows finishing
|
|
39
39
|
* finished (its first final task-notification's timestamp), one per task.
|
|
40
40
|
* `awaited`: those of the running tasks that are shells or monitors started
|
|
41
|
-
* since the owner's last prompt,
|
|
42
|
-
*
|
|
41
|
+
* since the owner's last prompt, or started before it and looked at since
|
|
42
|
+
* (its output read, its id named), other than streams that never end (a log
|
|
43
|
+
* tail, a watcher, a dev server). Sub-agents are left to the child tree.
|
|
44
|
+
* `endless`: the running shells that are such streams. */
|
|
43
45
|
export interface FinalTurn {
|
|
44
46
|
completed: boolean;
|
|
45
47
|
lastAssistant?: string;
|
|
@@ -48,6 +50,7 @@ export interface FinalTurn {
|
|
|
48
50
|
background?: number;
|
|
49
51
|
finishedTasks?: string[];
|
|
50
52
|
awaited?: number;
|
|
53
|
+
endless?: number;
|
|
51
54
|
}
|
|
52
55
|
/** The public text of one assistant row, without reasoning or tool output. */
|
|
53
56
|
export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
|
|
@@ -61,32 +61,50 @@ export function publicAssistant(raw, source) {
|
|
|
61
61
|
.filter(block => block.type === "text").map(block => String(block.text ?? "")).join("\n");
|
|
62
62
|
return text.trim() || undefined;
|
|
63
63
|
}
|
|
64
|
+
if (source === "copilot") {
|
|
65
|
+
// A sub-agent's messages carry its agentId; only the session's own reply counts.
|
|
66
|
+
const data = object(raw.data);
|
|
67
|
+
if (raw.type !== "assistant.message" || raw.agentId || typeof data.content !== "string")
|
|
68
|
+
return;
|
|
69
|
+
return data.content.trim() || undefined;
|
|
70
|
+
}
|
|
64
71
|
return;
|
|
65
72
|
}
|
|
66
73
|
const FINAL_TURN_TAIL_BYTES = 512 * 1024;
|
|
67
74
|
/** A turn's end as the harness writes it: Claude's end_turn reply or its
|
|
68
|
-
* turn_duration record, Codex's task_complete, opencode's end_turn step.
|
|
69
|
-
|
|
75
|
+
* turn_duration record, Codex's task_complete, opencode's end_turn step.
|
|
76
|
+
* Copilot writes a turn_start/turn_end pair per model call, so its turn ends
|
|
77
|
+
* at the turn_end after the reply marked `final_answer` (`copilotFinal`). */
|
|
78
|
+
function turnEnded(raw, source, copilotFinal = false) {
|
|
70
79
|
const payload = object(raw.payload), message = object(raw.message), data = object(raw.data);
|
|
71
80
|
if (source === "claude")
|
|
72
81
|
return (raw.type === "assistant" && message.stop_reason === "end_turn")
|
|
73
82
|
|| (raw.type === "system" && raw.subtype === "turn_duration");
|
|
74
83
|
if (source === "codex")
|
|
75
84
|
return raw.type === "event_msg" && ["task_complete", "task_completed"].includes(String(payload.type));
|
|
85
|
+
if (source === "copilot")
|
|
86
|
+
return raw.type === "session.error" || (raw.type === "assistant.turn_end" && !raw.agentId && copilotFinal);
|
|
76
87
|
return data.stop_reason === "end_turn";
|
|
77
88
|
}
|
|
78
89
|
/** The error a turn ended on, when the harness records one: Codex's
|
|
79
|
-
* task_complete carries `error.message` (a usage limit, a failed compaction)
|
|
90
|
+
* task_complete carries `error.message` (a usage limit, a failed compaction),
|
|
91
|
+
* Copilot's session.error its `message`. */
|
|
80
92
|
function turnError(raw, source) {
|
|
93
|
+
if (source === "copilot") {
|
|
94
|
+
const data = object(raw.data), message = raw.type === "session.error" && typeof data.message === "string" ? data.message.replace(/\s+/g, " ").trim() : "";
|
|
95
|
+
return message ? message.slice(0, 500) : raw.type === "session.error" ? "Copilot stopped on an error." : undefined;
|
|
96
|
+
}
|
|
81
97
|
if (source !== "codex")
|
|
82
98
|
return;
|
|
83
99
|
const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
|
|
84
100
|
return message ? message.slice(0, 500) : undefined;
|
|
85
101
|
}
|
|
86
|
-
/** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn. */
|
|
102
|
+
/** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn, Copilot's abort. */
|
|
87
103
|
function turnInterrupted(raw, source) {
|
|
88
104
|
if (source === "codex")
|
|
89
105
|
return raw.type === "event_msg" && object(raw.payload).type === "turn_aborted";
|
|
106
|
+
if (source === "copilot")
|
|
107
|
+
return raw.type === "abort";
|
|
90
108
|
if (source !== "claude" || raw.type !== "user")
|
|
91
109
|
return false;
|
|
92
110
|
const content = object(raw.message).content;
|
|
@@ -102,14 +120,25 @@ function turnInterrupted(raw, source) {
|
|
|
102
120
|
* row, and may stay there with no new turn to deliver it. */
|
|
103
121
|
/** A backgrounded command that runs until killed rather than finishing:
|
|
104
122
|
* following a log, watching files, serving a dev build. Nobody waits on it. */
|
|
105
|
-
export const ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|\
|
|
123
|
+
export const ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|(?:^|[;&|(]|\b(?:sudo|nohup|exec)\s)\s*watch\s|--watch\b|\binotifywait\b[^|;&]*\s-m\b|\bfswatch\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|serve|preview)\b|\bhttp\.server\b|\bsleep\s+infinity\b/;
|
|
106
124
|
function backgroundTasks(raw, running, finished, tail) {
|
|
107
125
|
const result = object(raw.toolUseResult), blocks = objects(object(raw.message).content);
|
|
108
126
|
if (raw.type === "assistant") {
|
|
109
127
|
for (const block of blocks) {
|
|
110
128
|
const input = object(block.input);
|
|
111
|
-
|
|
129
|
+
// A command can reach the background by outrunning its timeout too.
|
|
130
|
+
if (block.type === "tool_use" && typeof block.id === "string" && typeof input.command === "string")
|
|
112
131
|
tail.commands.set(block.id, input.command.slice(0, 2_000));
|
|
132
|
+
// Reading a task's output, or naming it, is still waiting on it
|
|
133
|
+
// (ios-fast-voice2, 2026-10-01: the dispatcher's prompt came mid-run).
|
|
134
|
+
if (block.type === "tool_use" && tail.earlier.size) {
|
|
135
|
+
const named = JSON.stringify(block.input ?? {});
|
|
136
|
+
for (const id of tail.earlier)
|
|
137
|
+
if (named.includes(id)) {
|
|
138
|
+
tail.earlier.delete(id);
|
|
139
|
+
tail.awaited.add(id);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
113
142
|
}
|
|
114
143
|
}
|
|
115
144
|
const shell = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId : undefined;
|
|
@@ -120,15 +149,16 @@ function backgroundTasks(raw, running, finished, tail) {
|
|
|
120
149
|
if (shell) {
|
|
121
150
|
const call = blocks.find(block => block.type === "tool_result")?.tool_use_id;
|
|
122
151
|
const command = typeof call === "string" ? tail.commands.get(call) : undefined;
|
|
123
|
-
if (
|
|
152
|
+
if (command && ENDLESS_COMMAND.test(command))
|
|
153
|
+
tail.endless.add(shell);
|
|
154
|
+
else
|
|
124
155
|
tail.awaited.add(shell);
|
|
125
156
|
}
|
|
126
157
|
else if (monitor)
|
|
127
158
|
tail.awaited.add(monitor);
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}
|
|
159
|
+
const ended = (id) => { running.delete(id); tail.awaited.delete(id); tail.earlier.delete(id); tail.endless.delete(id); };
|
|
160
|
+
if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message))
|
|
161
|
+
ended(result.task_id);
|
|
132
162
|
const content = object(raw.message).content, attachment = object(raw.attachment);
|
|
133
163
|
const notices = [typeof content === "string" ? content : "", typeof attachment.prompt === "string" ? attachment.prompt : "",
|
|
134
164
|
raw.type === "queue-operation" && typeof raw.content === "string" ? raw.content : ""];
|
|
@@ -137,8 +167,7 @@ function backgroundTasks(raw, running, finished, tail) {
|
|
|
137
167
|
const id = /<task-id>([^<\s]{1,100})<\/task-id>/.exec(block)?.[1];
|
|
138
168
|
if (!id || !/<status>(?:completed|failed|killed|stopped)<\/status>/.test(block))
|
|
139
169
|
continue;
|
|
140
|
-
|
|
141
|
-
tail.awaited.delete(id);
|
|
170
|
+
ended(id);
|
|
142
171
|
if (!finished.has(id) && typeof raw.timestamp === "string" && !Number.isNaN(Date.parse(raw.timestamp)))
|
|
143
172
|
finished.set(id, raw.timestamp);
|
|
144
173
|
}
|
|
@@ -146,8 +175,8 @@ function backgroundTasks(raw, running, finished, tail) {
|
|
|
146
175
|
/** The last assistant reply in a transcript and whether its turn finished.
|
|
147
176
|
* A person's message after the reply opens a new turn, so it clears both. */
|
|
148
177
|
export function finalTurnFromLines(lines, source) {
|
|
149
|
-
let completed = false, lastAssistant, error, interrupted = false;
|
|
150
|
-
const running = new Set(), finished = new Map(), tail = { commands: new Map(), awaited: new Set() };
|
|
178
|
+
let completed = false, lastAssistant, error, interrupted = false, copilotFinal = false;
|
|
179
|
+
const running = new Set(), finished = new Map(), tail = { commands: new Map(), awaited: new Set(), earlier: new Set(), endless: new Set() };
|
|
151
180
|
for (const line of lines) {
|
|
152
181
|
if (!line.trim())
|
|
153
182
|
continue;
|
|
@@ -162,9 +191,13 @@ export function finalTurnFromLines(lines, source) {
|
|
|
162
191
|
if (source === "claude") {
|
|
163
192
|
backgroundTasks(raw, running, finished, tail);
|
|
164
193
|
// The owner moving on leaves what earlier turns started behind: a
|
|
165
|
-
// shell still running from then is a leftover, not work in flight
|
|
166
|
-
|
|
194
|
+
// shell still running from then is a leftover, not work in flight,
|
|
195
|
+
// unless the agent looks at it again.
|
|
196
|
+
if (ownerPrompt(raw)) {
|
|
197
|
+
for (const id of tail.awaited)
|
|
198
|
+
tail.earlier.add(id);
|
|
167
199
|
tail.awaited.clear();
|
|
200
|
+
}
|
|
168
201
|
}
|
|
169
202
|
if (turnInterrupted(raw, source)) {
|
|
170
203
|
interrupted = true;
|
|
@@ -173,12 +206,14 @@ export function finalTurnFromLines(lines, source) {
|
|
|
173
206
|
}
|
|
174
207
|
const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && typeof object(raw.message).content === "string"
|
|
175
208
|
: source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user"
|
|
176
|
-
: raw.type === "user
|
|
209
|
+
: source === "copilot" ? raw.type === "user.message"
|
|
210
|
+
: raw.type === "user/message";
|
|
177
211
|
if (userTurn) {
|
|
178
212
|
completed = false;
|
|
179
213
|
lastAssistant = undefined;
|
|
180
214
|
error = undefined;
|
|
181
215
|
interrupted = false;
|
|
216
|
+
copilotFinal = false;
|
|
182
217
|
continue;
|
|
183
218
|
}
|
|
184
219
|
const text = publicAssistant(raw, source);
|
|
@@ -187,15 +222,19 @@ export function finalTurnFromLines(lines, source) {
|
|
|
187
222
|
completed = false;
|
|
188
223
|
interrupted = false;
|
|
189
224
|
}
|
|
190
|
-
if (
|
|
225
|
+
if (source === "copilot" && raw.type === "assistant.message" && !raw.agentId)
|
|
226
|
+
copilotFinal = object(raw.data).phase === "final_answer";
|
|
227
|
+
if (turnEnded(raw, source, copilotFinal)) {
|
|
191
228
|
completed = true;
|
|
192
229
|
interrupted = false;
|
|
193
230
|
error = turnError(raw, source);
|
|
231
|
+
copilotFinal = false;
|
|
194
232
|
}
|
|
195
233
|
}
|
|
196
234
|
return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {}),
|
|
197
235
|
...(interrupted ? { interrupted: true } : {}), ...(completed && running.size ? { background: running.size } : {}),
|
|
198
|
-
...(finished.size ? { finishedTasks: [...finished.values()] } : {}), ...(tail.awaited.size ? { awaited: tail.awaited.size } : {})
|
|
236
|
+
...(finished.size ? { finishedTasks: [...finished.values()] } : {}), ...(tail.awaited.size ? { awaited: tail.awaited.size } : {}),
|
|
237
|
+
...(completed && tail.endless.size ? { endless: tail.endless.size } : {}) };
|
|
199
238
|
}
|
|
200
239
|
/** A prompt the owner (or a dispatcher) typed, not a task's notification or
|
|
201
240
|
* a teammate's message waking the session. */
|
|
@@ -54,7 +54,13 @@ export interface LaunchOptions {
|
|
|
54
54
|
* Herdr's create calls do not return identifiers, so the new tab is found
|
|
55
55
|
* by diffing snapshots; `agent.start` returns once Herdr has detected the
|
|
56
56
|
* agent and it is ready for input, which can take most of `timeoutMs`.
|
|
57
|
+
* A `launchId` (a UUID the caller keeps for one intended launch) makes it
|
|
58
|
+
* idempotent: the same id again returns the first launch's pane while it is
|
|
59
|
+
* listed, with `reused: true`, instead of starting a second agent.
|
|
57
60
|
*/
|
|
58
61
|
export declare function launchSession(server: string, data: Json, options?: LaunchOptions): Promise<Json>;
|
|
62
|
+
export declare const LAUNCH_ID_TTL_MS: number;
|
|
63
|
+
/** For tests: forget every remembered launch. */
|
|
64
|
+
export declare function resetLaunchIds(): void;
|
|
59
65
|
export declare function workspaceAction(server: string, operation: string, data: Json): Promise<Json>;
|
|
60
66
|
export {};
|
|
@@ -26,7 +26,7 @@ import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
|
|
|
26
26
|
import { logger } from "../logger.js";
|
|
27
27
|
import { JobRegistry } from "./job-registry.js";
|
|
28
28
|
import { atomic, BridgeError, bridgeRoot, id, launchEfforts, objects, PERMISSION_MODES, provider } from "./protocol.js";
|
|
29
|
-
import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags } from "./settings-switch.js";
|
|
29
|
+
import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags, copilotModeFlags } from "./settings-switch.js";
|
|
30
30
|
/** Starting agents in Herdr from the phone: the launch route's harness
|
|
31
31
|
* arguments, the conductor brief, and workspace, tab and pane actions. */
|
|
32
32
|
const launchKinds = ["codex", "claude", "copilot", "opencode", "phren"];
|
|
@@ -62,6 +62,8 @@ function effortArgs(kind, effort) {
|
|
|
62
62
|
return ["-c", `model_reasoning_effort=${effort}`];
|
|
63
63
|
if (kind === "opencode")
|
|
64
64
|
return ["--variant", effort];
|
|
65
|
+
if (kind === "copilot")
|
|
66
|
+
return ["--reasoning-effort", effort];
|
|
65
67
|
// phren-agent takes low to xhigh, and max as xhigh.
|
|
66
68
|
if (kind === "phren")
|
|
67
69
|
return ["--reasoning", effort === "minimal" ? "low" : effort];
|
|
@@ -157,10 +159,9 @@ async function targetForPane(server, pane) {
|
|
|
157
159
|
if (!provider.safeParse(pane.agent).success || !id.safeParse(pane.workspace_id).success || !id.safeParse(pane.tab_id).success || !id.safeParse(pane.pane_id).success)
|
|
158
160
|
return undefined;
|
|
159
161
|
const binding = { server, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent };
|
|
160
|
-
const
|
|
161
|
-
if (
|
|
162
|
-
return { ...binding, session };
|
|
163
|
-
const chat = await paneChatState(server, pane).catch(() => ({}));
|
|
162
|
+
const chat = await paneChatState(server, pane, { tokenWhenIdentified: false }).catch(() => ({}));
|
|
163
|
+
if (typeof chat.sessionId === "string")
|
|
164
|
+
return { ...binding, session: chat.sessionId };
|
|
164
165
|
return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
|
|
165
166
|
}
|
|
166
167
|
/** The live conductor on this computer, as a target: the pane the Hook
|
|
@@ -290,8 +291,57 @@ async function requireAvailable(kind, account) {
|
|
|
290
291
|
* Herdr's create calls do not return identifiers, so the new tab is found
|
|
291
292
|
* by diffing snapshots; `agent.start` returns once Herdr has detected the
|
|
292
293
|
* agent and it is ready for input, which can take most of `timeoutMs`.
|
|
294
|
+
* A `launchId` (a UUID the caller keeps for one intended launch) makes it
|
|
295
|
+
* idempotent: the same id again returns the first launch's pane while it is
|
|
296
|
+
* listed, with `reused: true`, instead of starting a second agent.
|
|
293
297
|
*/
|
|
294
298
|
export async function launchSession(server, data, options = {}) {
|
|
299
|
+
const launchId = data.launchId === undefined || data.launchId === null ? undefined
|
|
300
|
+
: z.string().uuid("launchId must be a UUID.").parse(data.launchId);
|
|
301
|
+
if (!launchId)
|
|
302
|
+
return startSession(server, data, options);
|
|
303
|
+
const now = Date.now();
|
|
304
|
+
for (const [key, entry] of launchesById)
|
|
305
|
+
if (now - entry.at > LAUNCH_ID_TTL_MS)
|
|
306
|
+
launchesById.delete(key);
|
|
307
|
+
const key = `${server}\u0000${launchId}`;
|
|
308
|
+
const earlier = launchesById.get(key);
|
|
309
|
+
// Reserve the id before checking the old pane. Two retries after a closed
|
|
310
|
+
// chat must share its replacement, just as they share the initial launch.
|
|
311
|
+
const result = Promise.resolve().then(async () => {
|
|
312
|
+
if (earlier) {
|
|
313
|
+
const previous = await earlier.result;
|
|
314
|
+
if (await stillListed(server, previous))
|
|
315
|
+
return { ...previous, reused: true };
|
|
316
|
+
}
|
|
317
|
+
return startSession(server, data, options);
|
|
318
|
+
});
|
|
319
|
+
// An in-flight launch must not expire while another caller is waiting.
|
|
320
|
+
const entry = { at: Infinity, result };
|
|
321
|
+
launchesById.set(key, entry);
|
|
322
|
+
void result.then(() => { entry.at = Date.now(); }, () => {
|
|
323
|
+
if (launchesById.get(key) !== entry)
|
|
324
|
+
return;
|
|
325
|
+
// A temporary snapshot failure is not evidence that the old pane died.
|
|
326
|
+
if (earlier && Number.isFinite(earlier.at))
|
|
327
|
+
launchesById.set(key, earlier);
|
|
328
|
+
else
|
|
329
|
+
launchesById.delete(key);
|
|
330
|
+
});
|
|
331
|
+
return result;
|
|
332
|
+
}
|
|
333
|
+
/** Launches by the caller's `launchId`, for `LAUNCH_ID_TTL_MS`: a repeat
|
|
334
|
+
* joins the launch in flight or gets its pane back. In memory only. */
|
|
335
|
+
const launchesById = new Map();
|
|
336
|
+
export const LAUNCH_ID_TTL_MS = 10 * 60_000;
|
|
337
|
+
/** For tests: forget every remembered launch. */
|
|
338
|
+
export function resetLaunchIds() { launchesById.clear(); }
|
|
339
|
+
async function stillListed(server, result) {
|
|
340
|
+
const s = await snapshot(server);
|
|
341
|
+
return objects(s.tabs).some(t => t.tab_id === result.tabId && t.workspace_id === result.workspaceId)
|
|
342
|
+
&& objects(s.panes).some(p => p.pane_id === result.paneId && p.tab_id === result.tabId && p.workspace_id === result.workspaceId);
|
|
343
|
+
}
|
|
344
|
+
async function startSession(server, data, options) {
|
|
295
345
|
const role = z.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
296
346
|
const projectDirectory = z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
297
347
|
const worktreeRequest = data.worktree === undefined || data.worktree === null ? undefined : launchWorktreeSchema.parse(data.worktree);
|
|
@@ -305,11 +355,9 @@ export async function launchSession(server, data, options = {}) {
|
|
|
305
355
|
if (permissionMode && role === "conductor")
|
|
306
356
|
throw new BridgeError(400, "A conductor starts with its own permissions; permissionMode is for workers.");
|
|
307
357
|
if (permissionMode && kind === "opencode")
|
|
308
|
-
throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and
|
|
309
|
-
if (permissionMode && kind === "copilot")
|
|
310
|
-
throw new BridgeError(400, "Copilot takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
|
|
358
|
+
throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
|
|
311
359
|
if (permissionMode && kind === "phren")
|
|
312
|
-
throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude and
|
|
360
|
+
throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude, Codex and Copilot workers.");
|
|
313
361
|
if (role === "conductor" && kind === "copilot")
|
|
314
362
|
throw new BridgeError(400, "Copilot cannot run as a conductor.");
|
|
315
363
|
if (role === "conductor" && kind === "phren")
|
|
@@ -331,7 +379,7 @@ export async function launchSession(server, data, options = {}) {
|
|
|
331
379
|
const wanted = options.canary ? "phren-canary" : role === "conductor" ? (isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`))
|
|
332
380
|
: isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
|
|
333
381
|
const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : undefined;
|
|
334
|
-
const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", phren: "--model" };
|
|
382
|
+
const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", copilot: "--model", phren: "--model" };
|
|
335
383
|
let workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
|
|
336
384
|
// Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
|
|
337
385
|
const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
|
|
@@ -356,7 +404,7 @@ export async function launchSession(server, data, options = {}) {
|
|
|
356
404
|
workspace = undefined;
|
|
357
405
|
const args = role === "conductor" ? await prepareConductor(kind, effort, model)
|
|
358
406
|
: [...(kind === "phren" ? [...PHREN_AGENT_ARGS, ...phrenArgs] : []), ...(model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
|
|
359
|
-
...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [])];
|
|
407
|
+
...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : []), ...(permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : [])];
|
|
360
408
|
// A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
|
|
361
409
|
// pane joins the thread the Hook started, and the brief is that thread's
|
|
362
410
|
// first turn. The typed arguments below stay the fallback.
|