@phren/cli 0.3.55 → 0.3.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hook-callback.js +1 -0
- package/dist/bridge/agent-hooks.js +1 -0
- package/dist/bridge/claude-suggestion.d.ts +9 -0
- package/dist/bridge/claude-suggestion.js +30 -4
- package/dist/bridge/dispatch-command.js +3 -3
- package/dist/bridge/dispatch-returns.d.ts +4 -0
- package/dist/bridge/dispatch-returns.js +10 -3
- package/dist/bridge/hand-off-queue.d.ts +21 -0
- package/dist/bridge/hand-off-queue.js +31 -2
- package/dist/bridge/hand-off.d.ts +1 -0
- package/dist/bridge/hand-off.js +5 -1
- package/dist/bridge/pair.d.ts +22 -0
- package/dist/bridge/pair.js +74 -1
- package/dist/bridge/prompt-deliveries.d.ts +21 -0
- package/dist/bridge/prompt-deliveries.js +140 -24
- package/dist/bridge/server-launch.d.ts +4 -0
- package/dist/bridge/server-launch.js +4 -1
- package/dist/bridge/server-pane-routes.d.ts +16 -0
- package/dist/bridge/server-pane-routes.js +132 -4
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/server.js +9 -2
- package/dist/bridge/session-activity.d.ts +28 -0
- package/dist/bridge/session-activity.js +30 -0
- package/dist/bridge/session-move.d.ts +25 -0
- package/dist/bridge/session-move.js +128 -9
- package/dist/bridge/speech-transcribe.js +28 -3
- package/dist/bridge/terminal-herdr.js +28 -8
- package/dist/bridge/turn-records.d.ts +2 -0
- package/dist/bridge/turn-records.js +6 -1
- package/dist/bridge-hook.mjs +1900 -1524
- package/dist/cli-registry.js +2 -2
- package/dist/modules/registry.js +1 -1
- package/dist/tools/dispatch.js +3 -2
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +7 -0
|
@@ -36,6 +36,34 @@ export declare const BACKGROUND_STALE_MS: number;
|
|
|
36
36
|
* the Stop's count less those `finishedTasks` (FinalTurn's) says finished
|
|
37
37
|
* after it. Undefined once none are left or the Stop is BACKGROUND_STALE_MS old. */
|
|
38
38
|
export declare function recordedBackground(record: TurnRecord | undefined, finishedTasks?: readonly string[], now?: number): number | undefined;
|
|
39
|
+
/** What may still be open in a pane whose turn record says it ended: Claude
|
|
40
|
+
* starts a turn on its own when a background agent finishes (its task
|
|
41
|
+
* notification, with no UserPromptSubmit), and that turn can open a dialog
|
|
42
|
+
* Herdr still reads as working (plan approval, an MCP elicitation, a
|
|
43
|
+
* permission request the Hook holds). Pasted text plus Enter would answer it. */
|
|
44
|
+
export interface PromptGuards {
|
|
45
|
+
/** An approval the Hook holds, a terminal prompt or a question it serves for this pane. */
|
|
46
|
+
held?: () => boolean;
|
|
47
|
+
/** The pane's visible screen; a dialog there (pane-status.ts `screenDialog`) or a failed read refuses. */
|
|
48
|
+
screen?: () => Promise<string>;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Whether the agent in a pane takes a typed prompt now: Herdr reads it idle or
|
|
52
|
+
* done, or it is a Claude session Herdr reads `working` whose own turn record
|
|
53
|
+
* ended with background tasks still running (`recordedBackground`). That is
|
|
54
|
+
* Claude's "Waiting for N background agents to finish": its turn is over and
|
|
55
|
+
* pasted text plus Enter submits at once and starts a turn (seen live, Claude
|
|
56
|
+
* Code 2.1.302), but Herdr keeps it `working` until the last background agent
|
|
57
|
+
* ends. Waiting for idle there held a hand-off or a dispatch-return notice for
|
|
58
|
+
* as long as a lead kept sub-agents running, over an hour. Another working
|
|
59
|
+
* pane, or one blocked, waiting or unknown, does not take one, nor one with a
|
|
60
|
+
* dialog open (`guards`). The record is read only for a working Claude pane,
|
|
61
|
+
* through the same guard the session rows use (`paneRecord`), so a leftover
|
|
62
|
+
* record of an earlier conversation never speaks for this one; once the prompt
|
|
63
|
+
* is submitted its UserPromptSubmit makes the turn working again. Past
|
|
64
|
+
* BACKGROUND_STALE_MS after the Stop the pane waits for idle again.
|
|
65
|
+
*/
|
|
66
|
+
export declare function takesPrompt(server: string, pane: Json, session: string | undefined, guards?: PromptGuards, now?: number): Promise<boolean>;
|
|
39
67
|
/** The background shells and monitors a turn still awaits, from its transcript
|
|
40
68
|
* final turn. A recorded ended turn bounds `FinalTurn.awaited` by the Stop's
|
|
41
69
|
* count less the tasks that finished since, and by the 2-hour cap; a Stop that
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { briefLabel } from "./launch-brief.js";
|
|
2
|
+
import { screenDialog } from "./pane-status.js";
|
|
2
3
|
import { provider } from "./protocol.js";
|
|
3
4
|
import { backgroundLeft, readTurn, turnPhase } from "./turn-records.js";
|
|
4
5
|
/**
|
|
@@ -49,6 +50,35 @@ export function recordedBackground(record, finishedTasks, now = Date.now()) {
|
|
|
49
50
|
return undefined;
|
|
50
51
|
return backgroundLeft(phase.background, phase.at, finishedTasks) || undefined;
|
|
51
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* Whether the agent in a pane takes a typed prompt now: Herdr reads it idle or
|
|
55
|
+
* done, or it is a Claude session Herdr reads `working` whose own turn record
|
|
56
|
+
* ended with background tasks still running (`recordedBackground`). That is
|
|
57
|
+
* Claude's "Waiting for N background agents to finish": its turn is over and
|
|
58
|
+
* pasted text plus Enter submits at once and starts a turn (seen live, Claude
|
|
59
|
+
* Code 2.1.302), but Herdr keeps it `working` until the last background agent
|
|
60
|
+
* ends. Waiting for idle there held a hand-off or a dispatch-return notice for
|
|
61
|
+
* as long as a lead kept sub-agents running, over an hour. Another working
|
|
62
|
+
* pane, or one blocked, waiting or unknown, does not take one, nor one with a
|
|
63
|
+
* dialog open (`guards`). The record is read only for a working Claude pane,
|
|
64
|
+
* through the same guard the session rows use (`paneRecord`), so a leftover
|
|
65
|
+
* record of an earlier conversation never speaks for this one; once the prompt
|
|
66
|
+
* is submitted its UserPromptSubmit makes the turn working again. Past
|
|
67
|
+
* BACKGROUND_STALE_MS after the Stop the pane waits for idle again.
|
|
68
|
+
*/
|
|
69
|
+
export async function takesPrompt(server, pane, session, guards = {}, now = Date.now()) {
|
|
70
|
+
const status = String(pane.agent_status);
|
|
71
|
+
if (status === "idle" || status === "done")
|
|
72
|
+
return true;
|
|
73
|
+
if (status !== "working" || pane.agent !== "claude")
|
|
74
|
+
return false;
|
|
75
|
+
if (!recordedBackground(await paneRecord(server, pane, session), [], now) || guards.held?.())
|
|
76
|
+
return false;
|
|
77
|
+
if (!guards.screen)
|
|
78
|
+
return true;
|
|
79
|
+
const screen = await guards.screen().catch(() => undefined);
|
|
80
|
+
return screen !== undefined && !screenDialog("claude", screen);
|
|
81
|
+
}
|
|
52
82
|
/** The background shells and monitors a turn still awaits, from its transcript
|
|
53
83
|
* final turn. A recorded ended turn bounds `FinalTurn.awaited` by the Stop's
|
|
54
84
|
* count less the tasks that finished since, and by the 2-hour cap; a Stop that
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ConductorSuccessionService } from "./conductor-succession.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
+
import { type ClaudeHome } from "./claude-accounts.js";
|
|
3
4
|
import { moveToSchema } from "./dispatch.js";
|
|
4
5
|
import { type HarnessInventory } from "./harnesses.js";
|
|
5
6
|
import { type Json, type Provider, type StartingTarget, type Target } from "./protocol.js";
|
|
@@ -44,6 +45,10 @@ export declare const moveRequestSchema: z.ZodObject<{
|
|
|
44
45
|
"new-chat": "new-chat";
|
|
45
46
|
replace: "replace";
|
|
46
47
|
}>>;
|
|
48
|
+
continuation: z.ZodDefault<z.ZodEnum<{
|
|
49
|
+
handoff: "handoff";
|
|
50
|
+
resume: "resume";
|
|
51
|
+
}>>;
|
|
47
52
|
id: z.ZodOptional<z.ZodString>;
|
|
48
53
|
handoffTimeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
49
54
|
}, z.core.$strict>;
|
|
@@ -105,6 +110,7 @@ declare const moveRecordSchema: z.ZodObject<{
|
|
|
105
110
|
"new-chat": "new-chat";
|
|
106
111
|
replace: "replace";
|
|
107
112
|
}>>;
|
|
113
|
+
continuation: z.ZodOptional<z.ZodLiteral<"resume">>;
|
|
108
114
|
modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
|
|
109
115
|
handedOffTo: z.ZodOptional<z.ZodObject<{
|
|
110
116
|
computer: z.ZodOptional<z.ZodString>;
|
|
@@ -326,10 +332,14 @@ export interface MoverDeps {
|
|
|
326
332
|
paneId: string;
|
|
327
333
|
};
|
|
328
334
|
dispatchId?: string;
|
|
335
|
+
resumeClaude?: string;
|
|
329
336
|
}) => Promise<Json>;
|
|
330
337
|
inventory: () => Promise<HarnessInventory | undefined>;
|
|
331
338
|
/** The conversation's transcript lines, its tail is enough. */
|
|
332
339
|
transcript: (target: Target) => Promise<string[]>;
|
|
340
|
+
/** Copies a Claude conversation into another account's home (`copyClaudeConversation` over its transcript).
|
|
341
|
+
* With `check`, only resolves and validates both ends, so a move is refused before the old agent exits. */
|
|
342
|
+
copyConversation?: (target: Target, to: ClaudeHome, check?: boolean) => Promise<string>;
|
|
333
343
|
git?: (directory: string) => Promise<GitState | undefined>;
|
|
334
344
|
processesBelow?: (pids: readonly number[]) => Promise<string[]>;
|
|
335
345
|
/** The Claude account the pane runs under, when known. */
|
|
@@ -385,6 +395,10 @@ export declare class SessionMover {
|
|
|
385
395
|
/** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
|
|
386
396
|
private askForHandoff;
|
|
387
397
|
private fallback;
|
|
398
|
+
/** The same conversation under another Claude account: the old agent exits,
|
|
399
|
+
* its transcript (now final) is copied into the target home, and Claude
|
|
400
|
+
* resumes it there. Nothing is asked of the old agent, so its quota does not matter. */
|
|
401
|
+
private switchAccount;
|
|
388
402
|
/** Ends the old agent with its own exit command; an interrupt, then a kill, only when it hangs. */
|
|
389
403
|
private exit;
|
|
390
404
|
/** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
|
|
@@ -394,3 +408,14 @@ export declare class SessionMover {
|
|
|
394
408
|
}
|
|
395
409
|
/** The last `bytes` of a transcript as lines, the first (cut) one dropped. */
|
|
396
410
|
export declare function transcriptTail(file: string, bytes?: number): Promise<string[]>;
|
|
411
|
+
/**
|
|
412
|
+
* Copies a Claude conversation into another account's home, at the same
|
|
413
|
+
* `projects/<folder key>/<session>.jsonl` path Claude reads it from with
|
|
414
|
+
* `--resume`, together with the session's own folder (subagent transcripts,
|
|
415
|
+
* tool results) when it has one. A copy already there is replaced: the
|
|
416
|
+
* source is the conversation as it stands now. Returns the copied transcript.
|
|
417
|
+
* Both ends are checked against the homes' real `projects` folders, so a
|
|
418
|
+
* symlinked folder inside the target home cannot redirect the write. With
|
|
419
|
+
* `check`, nothing is written.
|
|
420
|
+
*/
|
|
421
|
+
export declare function copyClaudeConversation(file: string, to: ClaudeHome, env?: NodeJS.ProcessEnv, check?: boolean): Promise<string>;
|
|
@@ -22,14 +22,14 @@ import { redactApproval } from "./approval-summary.js";
|
|
|
22
22
|
import { stableComputerName } from "./computer-names.js";
|
|
23
23
|
import { execFile } from "node:child_process";
|
|
24
24
|
import { randomUUID } from "node:crypto";
|
|
25
|
-
import { lstat, mkdir, open, readFile, readdir, realpath, rm } from "node:fs/promises";
|
|
25
|
+
import { copyFile, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat } from "node:fs/promises";
|
|
26
26
|
import path from "node:path";
|
|
27
27
|
import { promisify } from "node:util";
|
|
28
28
|
import { z } from "zod";
|
|
29
29
|
import { logger } from "../logger.js";
|
|
30
30
|
import { quoted, withOriginalBrief } from "./account-failover.js";
|
|
31
31
|
import { recordedConductor, runsAgent, transferConductor } from "./conductor-role.js";
|
|
32
|
-
import { DEFAULT_ACCOUNT } from "./claude-accounts.js";
|
|
32
|
+
import { claudeHome, claudeHomes, DEFAULT_ACCOUNT } from "./claude-accounts.js";
|
|
33
33
|
import { DISPATCH_HARNESSES, DispatchService, dispatchProjectDirectory, projectName, moveToSchema, repointDispatchOrigins } from "./dispatch.js";
|
|
34
34
|
import { hasUsable } from "./harnesses.js";
|
|
35
35
|
import { findPane } from "./herdr.js";
|
|
@@ -42,6 +42,11 @@ export const moveRequestSchema = z.object({
|
|
|
42
42
|
target: targetSchema,
|
|
43
43
|
to: moveToSchema,
|
|
44
44
|
mode: z.enum(["replace", "new-chat"]).default("replace"),
|
|
45
|
+
/** `resume` switches a Claude conversation to another account on this
|
|
46
|
+
* computer without a hand-off: the transcript is copied into the target
|
|
47
|
+
* account's home and the same conversation resumes there (`claude --resume`),
|
|
48
|
+
* so an account at its usage limit can still switch. */
|
|
49
|
+
continuation: z.enum(["handoff", "resume"]).default("handoff"),
|
|
45
50
|
/** Kept on a retry: the same id returns the move already under way. */
|
|
46
51
|
id: z.string().uuid().optional(),
|
|
47
52
|
/** How long the agent gets to write its hand-off before Phren builds one. */
|
|
@@ -60,6 +65,7 @@ const moveRecordSchema = z.object({
|
|
|
60
65
|
accountChoice: z.string().max(400).optional(),
|
|
61
66
|
project: projectName.optional(),
|
|
62
67
|
mode: z.enum(["replace", "new-chat"]).optional(),
|
|
68
|
+
continuation: z.literal("resume").optional(),
|
|
63
69
|
modeForced: z.literal("conductor").optional(),
|
|
64
70
|
handedOffTo: z.object({ computer: z.string().optional(), target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
|
|
65
71
|
handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
|
|
@@ -468,6 +474,25 @@ export class SessionMover {
|
|
|
468
474
|
const sameHarness = to.harness === target.source && (to.harness !== "claude" || (to.account ?? account) === account);
|
|
469
475
|
if (!peer && sameHarness && !to.model && !to.effort)
|
|
470
476
|
throw new BridgeError(400, "The session already runs there. Choose another harness, account, model or effort.");
|
|
477
|
+
if (data.continuation === "resume") {
|
|
478
|
+
if (peer)
|
|
479
|
+
throw new BridgeError(400, "Switching account keeps the conversation on this computer; continue on another computer with a hand-off.");
|
|
480
|
+
if (target.source !== "claude" || to.harness !== "claude")
|
|
481
|
+
throw new BridgeError(400, "Only a Claude conversation can switch account.");
|
|
482
|
+
if (!target.session)
|
|
483
|
+
throw new BridgeError(409, "The conversation has no session id yet, so it cannot resume under another account.");
|
|
484
|
+
if (data.mode === "new-chat")
|
|
485
|
+
throw new BridgeError(400, "Switching account continues the same conversation; it cannot keep the old chat running.");
|
|
486
|
+
if (conductor)
|
|
487
|
+
throw new BridgeError(409, "Switching the conductor's account is not supported yet; use Continue in… for the conductor.");
|
|
488
|
+
if (!to.account || to.account === account)
|
|
489
|
+
throw new BridgeError(400, "Choose another Claude account to switch to.");
|
|
490
|
+
if (!claudeHome(to.account))
|
|
491
|
+
throw new BridgeError(409, `No Claude account "${to.account}" on this computer.`, { code: "account_unavailable" });
|
|
492
|
+
if (!this.deps.copyConversation)
|
|
493
|
+
throw new BridgeError(503, "This Hook cannot switch accounts.");
|
|
494
|
+
await this.deps.copyConversation(target, claudeHome(to.account), true);
|
|
495
|
+
}
|
|
471
496
|
// Only harnesses signed in and usable here; an inventory that cannot be read lets the move go on, as a launch does.
|
|
472
497
|
const inventory = peer ? undefined : await this.deps.inventory().catch(() => undefined);
|
|
473
498
|
if (inventory) {
|
|
@@ -514,8 +539,9 @@ export class SessionMover {
|
|
|
514
539
|
const workerDispatch = peer && dispatch ? await (await import("./worker-relocation.js")).preflightWorkerRelocation(dispatch, target) : undefined;
|
|
515
540
|
const label = [pane.label, pane.title, pane.terminal_title_stripped, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
|
|
516
541
|
const at = new Date(this.now).toISOString();
|
|
517
|
-
const
|
|
518
|
-
|
|
542
|
+
const resume = data.continuation === "resume";
|
|
543
|
+
const record = { id: data.id ?? randomUUID(), state: resume ? "exiting" : "handing-off", createdAt: at, updatedAt: at,
|
|
544
|
+
...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(resume ? { continuation: "resume" } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
|
|
519
545
|
...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}), ...(workerDispatch ? { workerDispatch } : {}) };
|
|
520
546
|
await assertUnusedLaunchId(record.id);
|
|
521
547
|
if (conductor && peer) {
|
|
@@ -525,7 +551,7 @@ export class SessionMover {
|
|
|
525
551
|
}
|
|
526
552
|
await saveMove(record);
|
|
527
553
|
const key = `${target.server}\0${target.pane}`;
|
|
528
|
-
const work = this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor, peer, project).finally(() => this.running.delete(key));
|
|
554
|
+
const work = (resume ? this.switchAccount(record) : this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor, peer, project)).finally(() => this.running.delete(key));
|
|
529
555
|
this.running.set(key, work);
|
|
530
556
|
return record;
|
|
531
557
|
}
|
|
@@ -870,6 +896,36 @@ export class SessionMover {
|
|
|
870
896
|
entries: asked < 0 ? entries : entries.slice(0, asked), ...(original ? { original } : {}),
|
|
871
897
|
...(record.dispatch ? { dispatch: record.dispatch } : {}), ...(record.from.label ? { label: record.from.label } : {}) });
|
|
872
898
|
}
|
|
899
|
+
/** The same conversation under another Claude account: the old agent exits,
|
|
900
|
+
* its transcript (now final) is copied into the target home, and Claude
|
|
901
|
+
* resumes it there. Nothing is asked of the old agent, so its quota does not matter. */
|
|
902
|
+
async switchAccount(record) {
|
|
903
|
+
const from = record.from.target;
|
|
904
|
+
let copied = false;
|
|
905
|
+
try {
|
|
906
|
+
const exit = await this.exit(record);
|
|
907
|
+
await this.update(record, { exit });
|
|
908
|
+
await this.checkPromotion(record);
|
|
909
|
+
const home = claudeHome(record.to.account);
|
|
910
|
+
if (!home)
|
|
911
|
+
throw new BridgeError(409, `No Claude account "${record.to.account}" on this computer.`);
|
|
912
|
+
await this.deps.copyConversation(from, home);
|
|
913
|
+
copied = true;
|
|
914
|
+
await this.update(record, { state: "launching" });
|
|
915
|
+
const launched = await this.relaunch(record, { resume: from.session });
|
|
916
|
+
await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched });
|
|
917
|
+
logger.info("move", `Switched Claude in pane ${from.pane} from account ${record.from.account ?? DEFAULT_ACCOUNT} to ${record.to.account} (${launched.placement}).`);
|
|
918
|
+
}
|
|
919
|
+
catch (error) {
|
|
920
|
+
const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
|
|
921
|
+
// Until the copy is complete only the old account holds the conversation.
|
|
922
|
+
const resumeHome = claudeHome(copied ? record.to.account : record.from.account);
|
|
923
|
+
const hint = record.exit !== undefined
|
|
924
|
+
? ` The old agent has exited; resume it with \`claude --resume ${from.session}\`${resumeHome && !resumeHome.isDefault ? ` under CLAUDE_CONFIG_DIR=${resumeHome.dir}` : ""}.` : "";
|
|
925
|
+
await this.update(record, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
|
|
926
|
+
logger.warn("move", `Switching the account of pane ${from.pane} failed: ${message}`);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
873
929
|
/** Ends the old agent with its own exit command; an interrupt, then a kill, only when it hangs. */
|
|
874
930
|
async exit(record) {
|
|
875
931
|
const from = record.from.target;
|
|
@@ -922,7 +978,8 @@ export class SessionMover {
|
|
|
922
978
|
throw new BridgeError(409, "The old agent did not exit, even when killed; nothing was started.");
|
|
923
979
|
}
|
|
924
980
|
/** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
|
|
925
|
-
async relaunch(record,
|
|
981
|
+
async relaunch(record, start) {
|
|
982
|
+
const prompt = typeof start === "string" ? start : undefined;
|
|
926
983
|
const from = record.from.target;
|
|
927
984
|
const s = await this.deps.snapshot(from.server);
|
|
928
985
|
const pane = findPane(s, placeOf(from));
|
|
@@ -934,10 +991,11 @@ export class SessionMover {
|
|
|
934
991
|
const samePane = record.mode !== "new-chat" && ((this.deps.envAtStart?.(from.server) ?? false) || record.to.harness !== "claude" || account === shellAccount);
|
|
935
992
|
const data = { kind: record.to.harness, label: record.from.label ?? HARNESS_NAMES[record.to.harness], cwd: record.cwd,
|
|
936
993
|
...(record.to.model ? { model: record.to.model } : {}), ...(record.to.effort ? { effort: record.to.effort } : {}), ...(account ? { account } : {}),
|
|
937
|
-
brief: { id: record.id, text: prompt }, ...(samePane ? {} : { workspaceId: from.workspace }) };
|
|
994
|
+
...(prompt === undefined ? {} : { brief: { id: record.id, text: prompt } }), ...(samePane ? {} : { workspaceId: from.workspace }) };
|
|
938
995
|
const into = samePane ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : undefined;
|
|
939
996
|
await this.checkPromotion(record);
|
|
940
|
-
const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch && record.modeForced !== "conductor" ? { dispatchId: record.dispatch } : {})
|
|
997
|
+
const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch && record.modeForced !== "conductor" ? { dispatchId: record.dispatch } : {}),
|
|
998
|
+
...(prompt === undefined ? { resumeClaude: start.resume } : {}) });
|
|
941
999
|
// Keep the launched location even if delivering its first prompt fails.
|
|
942
1000
|
const paneTarget = targetSchema.omit({ session: true }).parse({ server: from.server,
|
|
943
1001
|
workspace: launched.workspaceId, tab: launched.tabId, pane: launched.paneId, source: record.to.harness });
|
|
@@ -945,7 +1003,7 @@ export class SessionMover {
|
|
|
945
1003
|
await this.update(record, { paneTarget, placement: samePane ? "same-pane" : "adjacent-pane",
|
|
946
1004
|
...(launchedTarget.success ? { target: launchedTarget.data } : {}) });
|
|
947
1005
|
// The target that takes no brief at launch (Copilot) gets it typed, as dispatch does.
|
|
948
|
-
if (launched.briefLaunched === false) {
|
|
1006
|
+
if (prompt !== undefined && launched.briefLaunched === false) {
|
|
949
1007
|
try {
|
|
950
1008
|
const typedTo = targetSchema.safeParse(launched.target);
|
|
951
1009
|
if (typedTo.success) {
|
|
@@ -1007,3 +1065,64 @@ export async function transcriptTail(file, bytes = 512 * 1024) {
|
|
|
1007
1065
|
await handle.close();
|
|
1008
1066
|
}
|
|
1009
1067
|
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Copies a Claude conversation into another account's home, at the same
|
|
1070
|
+
* `projects/<folder key>/<session>.jsonl` path Claude reads it from with
|
|
1071
|
+
* `--resume`, together with the session's own folder (subagent transcripts,
|
|
1072
|
+
* tool results) when it has one. A copy already there is replaced: the
|
|
1073
|
+
* source is the conversation as it stands now. Returns the copied transcript.
|
|
1074
|
+
* Both ends are checked against the homes' real `projects` folders, so a
|
|
1075
|
+
* symlinked folder inside the target home cannot redirect the write. With
|
|
1076
|
+
* `check`, nothing is written.
|
|
1077
|
+
*/
|
|
1078
|
+
export async function copyClaudeConversation(file, to, env = process.env, check = false) {
|
|
1079
|
+
const real = async (dir) => realpath(dir).catch(() => path.resolve(dir));
|
|
1080
|
+
const inside = (child, parent) => child.startsWith(parent + path.sep);
|
|
1081
|
+
const source = await real(file);
|
|
1082
|
+
// A home's projects folder may be a link elsewhere, as transcriptPath allows.
|
|
1083
|
+
const homes = await Promise.all(claudeHomes(env).map(async (home) => ({ home, dir: await real(home.dir), projects: await real(path.join(home.dir, "projects")) })));
|
|
1084
|
+
const longest = (list) => list.sort((a, b) => b.projects.length - a.projects.length)[0];
|
|
1085
|
+
const match = longest(homes.filter(item => inside(source, item.projects))) ?? longest(homes.filter(item => inside(source, item.dir)));
|
|
1086
|
+
if (!match)
|
|
1087
|
+
throw new BridgeError(409, "The conversation's transcript is not in a Claude home on this computer.");
|
|
1088
|
+
const from = match.home;
|
|
1089
|
+
if (from.dir === to.dir)
|
|
1090
|
+
throw new BridgeError(400, "The conversation already belongs to that account.");
|
|
1091
|
+
const projects = match.projects;
|
|
1092
|
+
const relative = path.relative(projects, source);
|
|
1093
|
+
if (!relative || !inside(source, projects) || !relative.endsWith(".jsonl")) {
|
|
1094
|
+
throw new BridgeError(409, "The conversation's transcript is not under its Claude home's projects folder.");
|
|
1095
|
+
}
|
|
1096
|
+
const targetProjects = path.join(to.dir, "projects");
|
|
1097
|
+
const destination = path.join(targetProjects, relative);
|
|
1098
|
+
// The deepest folder that exists on the way must resolve inside the target home's projects folder (or be the home itself).
|
|
1099
|
+
const targetRoot = await real(targetProjects);
|
|
1100
|
+
let existing = path.dirname(destination);
|
|
1101
|
+
while (!(await lstat(existing).catch(() => undefined)) && existing !== path.dirname(existing) && existing !== to.dir)
|
|
1102
|
+
existing = path.dirname(existing);
|
|
1103
|
+
const resolved = await real(existing);
|
|
1104
|
+
if (resolved !== targetRoot && !inside(resolved, targetRoot) && resolved !== await real(to.dir)) {
|
|
1105
|
+
throw new BridgeError(409, "The other account's projects folder points outside its Claude home.");
|
|
1106
|
+
}
|
|
1107
|
+
if (check)
|
|
1108
|
+
return destination;
|
|
1109
|
+
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
|
|
1110
|
+
const temporary = `${destination}.${randomUUID()}.tmp`;
|
|
1111
|
+
try {
|
|
1112
|
+
await copyFile(source, temporary);
|
|
1113
|
+
await rename(temporary, destination);
|
|
1114
|
+
}
|
|
1115
|
+
catch (error) {
|
|
1116
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
1117
|
+
throw error;
|
|
1118
|
+
}
|
|
1119
|
+
const folder = source.slice(0, -".jsonl".length);
|
|
1120
|
+
if ((await stat(folder).catch(() => undefined))?.isDirectory()) {
|
|
1121
|
+
const folderTo = destination.slice(0, -".jsonl".length);
|
|
1122
|
+
// A link left at the folder's place is replaced, never followed.
|
|
1123
|
+
if ((await lstat(folderTo).catch(() => undefined))?.isSymbolicLink())
|
|
1124
|
+
await rm(folderTo, { force: true });
|
|
1125
|
+
await cp(folder, folderTo, { recursive: true, force: true, verbatimSymlinks: true });
|
|
1126
|
+
}
|
|
1127
|
+
return destination;
|
|
1128
|
+
}
|
|
@@ -51,17 +51,37 @@ export function failRelay(client) {
|
|
|
51
51
|
}
|
|
52
52
|
export function relayTranscription(client, query, options = {}) {
|
|
53
53
|
const connect = options.connect ?? ((url, key) => new WebSocket(url, { headers: { "xi-api-key": key } }));
|
|
54
|
+
// The phone sends the audio it held while connecting as soon as the
|
|
55
|
+
// socket opens, before the key and region below are read: listen now and
|
|
56
|
+
// replay those frames once the relay is set up, so no opening word is lost.
|
|
57
|
+
let receive;
|
|
58
|
+
let early = [], earlyBytes = 0, hungUp = false;
|
|
59
|
+
client.on("message", (data, isBinary) => {
|
|
60
|
+
if (receive) {
|
|
61
|
+
receive(data, isBinary);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
// Past the relay's own limit the replay ends the session anyway.
|
|
65
|
+
if (early && (earlyBytes += data.length) <= MAX_PENDING_BYTES)
|
|
66
|
+
early.push([data, isBinary]);
|
|
67
|
+
});
|
|
68
|
+
client.on("close", () => { hungUp = true; });
|
|
54
69
|
return (async () => {
|
|
55
70
|
const key = await (options.key ?? readSpeechKey)();
|
|
56
71
|
const tell = (frame) => { if (client.readyState === OPEN)
|
|
57
72
|
client.send(JSON.stringify(frame)); };
|
|
73
|
+
if (hungUp)
|
|
74
|
+
return;
|
|
58
75
|
if (!key) {
|
|
59
76
|
tell({ type: "error", code: "transcribe-unconfigured", error: "This computer has no ElevenLabs key." });
|
|
60
77
|
client.close(1008, "No ElevenLabs key");
|
|
61
78
|
return;
|
|
62
79
|
}
|
|
63
80
|
const origin = options.origin ?? (await resolveSpeechRegion()).origin;
|
|
81
|
+
if (hungUp)
|
|
82
|
+
return;
|
|
64
83
|
const upstream = connect(transcribeURL(query, origin), key);
|
|
84
|
+
// Held until ElevenLabs answers; null is the phone's stop, kept in its place.
|
|
65
85
|
let pending = [], pendingBytes = 0, closed = false;
|
|
66
86
|
const finish = (code = 1000, reason = "") => {
|
|
67
87
|
if (closed)
|
|
@@ -82,13 +102,15 @@ export function relayTranscription(client, query, options = {}) {
|
|
|
82
102
|
const chunk = (audio, commit = false) => JSON.stringify({
|
|
83
103
|
message_type: "input_audio_chunk", audio_base_64: audio.toString("base64"), commit, sample_rate: TRANSCRIBE_RATE
|
|
84
104
|
});
|
|
85
|
-
|
|
105
|
+
receive = (data, isBinary) => {
|
|
86
106
|
if (closed)
|
|
87
107
|
return;
|
|
88
108
|
if (!isBinary) {
|
|
89
109
|
// The phone's only text frame: the person stopped, commit what's left.
|
|
90
110
|
if (upstream.readyState === OPEN)
|
|
91
111
|
upstream.send(chunk(Buffer.alloc(0), true));
|
|
112
|
+
else
|
|
113
|
+
pending.push(null);
|
|
92
114
|
return;
|
|
93
115
|
}
|
|
94
116
|
if (upstream.readyState === OPEN) {
|
|
@@ -102,12 +124,15 @@ export function relayTranscription(client, query, options = {}) {
|
|
|
102
124
|
return;
|
|
103
125
|
}
|
|
104
126
|
pending.push(data);
|
|
105
|
-
}
|
|
127
|
+
};
|
|
128
|
+
for (const [data, isBinary] of early ?? [])
|
|
129
|
+
receive(data, isBinary);
|
|
130
|
+
early = undefined;
|
|
106
131
|
client.on("close", () => finish());
|
|
107
132
|
client.on("error", () => finish());
|
|
108
133
|
upstream.on("open", () => {
|
|
109
134
|
for (const audio of pending)
|
|
110
|
-
upstream.send(chunk(audio));
|
|
135
|
+
upstream.send(audio ? chunk(audio) : chunk(Buffer.alloc(0), true));
|
|
111
136
|
pending = [];
|
|
112
137
|
pendingBytes = 0;
|
|
113
138
|
if (!closed)
|
|
@@ -18,13 +18,31 @@ export function phrenCommandLine(args) {
|
|
|
18
18
|
return [["phren", ...args].map(shellWord).join(" "),
|
|
19
19
|
`herdr pane release-agent "$HERDR_PANE_ID" --source ${PHREN_REPORT_SOURCE} --agent phren >/dev/null 2>&1`].join("; ");
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
22
|
-
|
|
21
|
+
/** Herdr's `agent.prompt` and `agent.send_keys` take only agents it started
|
|
22
|
+
* and still holds as active. A worker launched with its brief as the
|
|
23
|
+
* harness's first prompt goes straight to work and can stay `launch_pending`
|
|
24
|
+
* there, and an agent restarted in its pane (or alive across a Herdr restart)
|
|
25
|
+
* is detected but never named again; Herdr refuses all of them with
|
|
26
|
+
* `agent_not_ready` for good. Such a pane is typed into instead, the way the
|
|
27
|
+
* terminal view types, when its foreground program is the harness Herdr
|
|
28
|
+
* detects there (phren-agent counts by report alone, as Herdr cannot detect
|
|
29
|
+
* it). For a prompt Herdr must also read the agent at rest or at work, so
|
|
30
|
+
* text never lands in a starting harness or answers a dialog it draws. */
|
|
31
|
+
async function typableAgent(server, pane, forPrompt) {
|
|
23
32
|
const info = object((await rpc(server, "pane.get", { pane_id: pane }).catch(() => ({}))).pane);
|
|
24
|
-
|
|
33
|
+
if (info.agent === "phren")
|
|
34
|
+
return true;
|
|
35
|
+
if (typeof info.agent !== "string" || !info.agent)
|
|
36
|
+
return false;
|
|
37
|
+
if (forPrompt && !["idle", "working", "done"].includes(String(info.agent_status)))
|
|
38
|
+
return false;
|
|
39
|
+
const processes = object((await rpc(server, "pane.process_info", { pane_id: pane }).catch(() => ({}))).process_info);
|
|
40
|
+
// The shell in the foreground would run the text as a command.
|
|
41
|
+
if (!Number.isSafeInteger(processes.foreground_process_group_id) || processes.foreground_process_group_id === processes.shell_pid)
|
|
42
|
+
return false;
|
|
43
|
+
return objects(processes.foreground_processes).some(p => typeof p.cmdline === "string" && agentFromCommand(p.cmdline) === info.agent);
|
|
25
44
|
}
|
|
26
|
-
/**
|
|
27
|
-
* a phren-agent pane it knows by report gets the pane calls instead. */
|
|
45
|
+
/** The refusal `typableAgent` answers: an agent Herdr does not hold as named. */
|
|
28
46
|
function unnamedAgent(error) {
|
|
29
47
|
return error instanceof BridgeError && error.details?.herdrCode === "agent_not_ready" && /not an active named agent/.test(error.message);
|
|
30
48
|
}
|
|
@@ -88,7 +106,7 @@ export const herdrTerminal = {
|
|
|
88
106
|
await rpc(server, "agent.send_keys", { target: pane, keys });
|
|
89
107
|
}
|
|
90
108
|
catch (error) {
|
|
91
|
-
if (!unnamedAgent(error) || !await
|
|
109
|
+
if (!unnamedAgent(error) || !await typableAgent(server, pane, false))
|
|
92
110
|
throw error;
|
|
93
111
|
await rpc(server, "pane.send_keys", { pane_id: pane, keys });
|
|
94
112
|
}
|
|
@@ -115,9 +133,11 @@ export const herdrTerminal = {
|
|
|
115
133
|
await rpc(server, "agent.prompt", { target: pane, text });
|
|
116
134
|
}
|
|
117
135
|
catch (error) {
|
|
118
|
-
if (!unnamedAgent(error) || !await
|
|
136
|
+
if (!unnamedAgent(error) || !await typableAgent(server, pane, true))
|
|
119
137
|
throw error;
|
|
120
|
-
// One bracketed paste keeps the newlines in
|
|
138
|
+
// One bracketed paste keeps the newlines in the agent's composer; Enter submits it.
|
|
139
|
+
// The route's delivery record (by deliveryId) is already armed: the agent's
|
|
140
|
+
// UserPromptSubmit settles it, as for a prompt Herdr typed.
|
|
121
141
|
await rpc(server, "pane.send_text", { pane_id: pane, text: `\x1b[200~${text}\x1b[201~` }, signal);
|
|
122
142
|
await new Promise(resolve => setTimeout(resolve, 150));
|
|
123
143
|
await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] }, signal);
|
|
@@ -37,6 +37,8 @@ export interface TurnEvent {
|
|
|
37
37
|
session: string;
|
|
38
38
|
/** SessionStart / UserPromptSubmit: the dispatch id the worker's hook named. */
|
|
39
39
|
dispatch?: string;
|
|
40
|
+
/** SessionStart only: how the session started, as the harness names it (Claude: startup, resume, clear, compact). */
|
|
41
|
+
start?: string;
|
|
40
42
|
/** Stop only: the harness's count of in-flight background tasks, when it reports one. */
|
|
41
43
|
background?: number;
|
|
42
44
|
/** Stop only: the harness's last assistant message, when it reports one. */
|
|
@@ -67,8 +67,13 @@ export function nextTurn(previous, event) {
|
|
|
67
67
|
record.at = at;
|
|
68
68
|
if (event.dispatch && briefId.safeParse(event.dispatch).success)
|
|
69
69
|
record.dispatch ??= event.dispatch;
|
|
70
|
-
if (event.event === "SessionStart")
|
|
70
|
+
if (event.event === "SessionStart") {
|
|
71
71
|
record.startedAt ??= at;
|
|
72
|
+
// A resumed or cleared conversation in the same terminal no longer runs the background agents its
|
|
73
|
+
// last Stop counted; a compaction keeps them.
|
|
74
|
+
if ((event.start === "resume" || event.start === "clear") && record.stop?.background !== undefined)
|
|
75
|
+
delete record.stop.background;
|
|
76
|
+
}
|
|
72
77
|
else if (event.event === "UserPromptSubmit")
|
|
73
78
|
record.prompt = { seq: record.seq, at };
|
|
74
79
|
else {
|