@phren/cli 0.3.71 → 0.3.73
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.js +11 -1
- package/dist/bridge/browser-env.d.ts +5 -0
- package/dist/bridge/browser-env.js +110 -0
- package/dist/bridge/browser-protocol.d.ts +120 -0
- package/dist/bridge/browser-protocol.js +70 -0
- package/dist/bridge/browser-recordings.d.ts +63 -0
- package/dist/bridge/browser-recordings.js +148 -0
- package/dist/bridge/browser-registry.d.ts +64 -0
- package/dist/bridge/browser-registry.js +262 -0
- package/dist/bridge/browser-routes.d.ts +4 -0
- package/dist/bridge/browser-routes.js +39 -0
- package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
- package/dist/bridge/browser-socket.d.ts +2 -0
- package/dist/bridge/browser-socket.js +10 -0
- package/dist/bridge/browser-stream.d.ts +3 -0
- package/dist/bridge/browser-stream.js +129 -0
- package/dist/bridge/browser-watch.d.ts +12 -0
- package/dist/bridge/browser-watch.js +83 -0
- package/dist/bridge/claude-account-setup.js +3 -1
- package/dist/bridge/claude-accounts.d.ts +5 -1
- package/dist/bridge/claude-accounts.js +36 -6
- package/dist/bridge/codex-servers.d.ts +2 -0
- package/dist/bridge/codex-servers.js +1 -1
- package/dist/bridge/command.js +24 -5
- package/dist/bridge/dispatch-clone.d.ts +33 -0
- package/dist/bridge/dispatch-clone.js +176 -0
- package/dist/bridge/dispatch-command.d.ts +14 -0
- package/dist/bridge/dispatch-command.js +98 -13
- package/dist/bridge/dispatch-idempotency.d.ts +85 -0
- package/dist/bridge/dispatch-idempotency.js +235 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -0
- package/dist/bridge/dispatch-returns.js +131 -1
- package/dist/bridge/dispatch-wait.d.ts +32 -0
- package/dist/bridge/dispatch-wait.js +177 -0
- package/dist/bridge/dispatch.d.ts +78 -2
- package/dist/bridge/dispatch.js +841 -25
- package/dist/bridge/dream-schedule.d.ts +133 -0
- package/dist/bridge/dream-schedule.js +322 -0
- package/dist/bridge/fanouts.js +20 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/git-credential.d.ts +44 -0
- package/dist/bridge/git-credential.js +113 -0
- package/dist/bridge/git-host-auth.d.ts +9 -1
- package/dist/bridge/git-host-auth.js +18 -5
- package/dist/bridge/git-host-gitboy.js +8 -1
- package/dist/bridge/git-hosts.d.ts +12 -1
- package/dist/bridge/git-publish.js +3 -2
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +44 -9
- package/dist/bridge/install.d.ts +1 -1
- package/dist/bridge/install.js +12 -4
- package/dist/bridge/launch-brief.d.ts +11 -0
- package/dist/bridge/launch-brief.js +22 -0
- package/dist/bridge/launch-worktree.d.ts +2 -0
- package/dist/bridge/launch-worktree.js +5 -1
- package/dist/bridge/pane-status.js +1 -1
- package/dist/bridge/protocol.d.ts +7 -0
- package/dist/bridge/schedule-watch.js +13 -2
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +251 -145
- package/dist/bridge/server-routes.d.ts +3 -0
- package/dist/bridge/server-routes.js +33 -17
- package/dist/bridge/server-stream.d.ts +4 -0
- package/dist/bridge/server-stream.js +24 -5
- package/dist/bridge/server.js +35 -4
- package/dist/bridge/session-move.d.ts +10 -4
- package/dist/bridge/session-move.js +65 -34
- package/dist/bridge/simulator-stream.d.ts +2 -0
- package/dist/bridge/simulator-stream.js +2 -0
- package/dist/bridge/status-line-fast.d.ts +9 -0
- package/dist/bridge/status-line-fast.js +56 -0
- package/dist/bridge/tab-activity.d.ts +2 -0
- package/dist/bridge/tab-activity.js +15 -2
- package/dist/bridge/task-routes.d.ts +20 -16
- package/dist/bridge/task-routes.js +1 -1
- package/dist/bridge/terminal-herdr.d.ts +5 -1
- package/dist/bridge/terminal-herdr.js +67 -2
- package/dist/bridge/terminal-tmux.d.ts +2 -0
- package/dist/bridge/terminal-tmux.js +29 -7
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.js +192 -112
- package/dist/bridge/transcript-preview.d.ts +2 -1
- package/dist/bridge/transcript-preview.js +85 -3
- package/dist/bridge/transcripts.js +17 -11
- package/dist/bridge/turn-records.js +16 -4
- package/dist/bridge/usage.d.ts +7 -1
- package/dist/bridge/usage.js +47 -31
- package/dist/bridge/worker-close.d.ts +15 -0
- package/dist/bridge/worker-close.js +304 -3
- package/dist/bridge/worker-identity.d.ts +51 -0
- package/dist/bridge/worker-identity.js +289 -0
- package/dist/bridge/worker-reports.js +15 -3
- package/dist/bridge-hook.mjs +39990 -36152
- package/dist/capabilities/mcp.js +1 -1
- package/dist/cli/browser-hint.d.ts +2 -0
- package/dist/cli/browser-hint.js +21 -0
- package/dist/cli/config-dreaming.d.ts +7 -0
- package/dist/cli/config-dreaming.js +72 -0
- package/dist/cli/config.js +6 -0
- package/dist/cli/dream.d.ts +59 -0
- package/dist/cli/dream.js +315 -0
- package/dist/cli/hooks-context.d.ts +2 -2
- package/dist/cli/hooks-context.js +3 -3
- package/dist/cli/hooks.js +20 -11
- package/dist/cli/namespaces-tasks.js +14 -0
- package/dist/cli-registry.js +28 -3
- package/dist/config/dreaming.d.ts +82 -0
- package/dist/config/dreaming.js +195 -0
- package/dist/config/resolve.js +11 -0
- package/dist/config/schema.d.ts +4 -4
- package/dist/config/schema.js +157 -1
- package/dist/content/citation-freshness.js +6 -0
- package/dist/content/learning.d.ts +1 -0
- package/dist/content/learning.js +2 -0
- package/dist/data/access.d.ts +1 -1
- package/dist/data/access.js +3 -1
- package/dist/data/task-contract.d.ts +5 -4
- package/dist/data/tasks.d.ts +5 -0
- package/dist/data/tasks.js +28 -2
- package/dist/dream/apply.d.ts +69 -0
- package/dist/dream/apply.js +372 -0
- package/dist/dream/budget.d.ts +78 -0
- package/dist/dream/budget.js +180 -0
- package/dist/dream/collect.d.ts +86 -0
- package/dist/dream/collect.js +449 -0
- package/dist/dream/eval/dream-adapter.d.ts +16 -0
- package/dist/dream/eval/dream-adapter.js +21 -0
- package/dist/dream/eval/fixture.d.ts +53 -0
- package/dist/dream/eval/fixture.js +172 -0
- package/dist/dream/eval/index.d.ts +40 -0
- package/dist/dream/eval/index.js +78 -0
- package/dist/dream/eval/score.d.ts +34 -0
- package/dist/dream/eval/score.js +99 -0
- package/dist/dream/eval/scripted-model.d.ts +19 -0
- package/dist/dream/eval/scripted-model.js +70 -0
- package/dist/dream/pages.d.ts +68 -0
- package/dist/dream/pages.js +220 -0
- package/dist/dream/privacy.d.ts +3 -0
- package/dist/dream/privacy.js +18 -0
- package/dist/dream/prompt.d.ts +13 -0
- package/dist/dream/prompt.js +84 -0
- package/dist/dream/run.d.ts +98 -0
- package/dist/dream/run.js +317 -0
- package/dist/dream/types.d.ts +74 -0
- package/dist/dream/types.js +4 -0
- package/dist/finding/lifecycle.d.ts +2 -2
- package/dist/finding/lifecycle.js +5 -2
- package/dist/finding/versions.d.ts +4 -0
- package/dist/finding/versions.js +28 -0
- package/dist/index.js +1 -0
- package/dist/modules/registry.js +10 -8
- package/dist/project-config.d.ts +3 -0
- package/dist/task/merge-links.d.ts +38 -0
- package/dist/task/merge-links.js +45 -0
- package/dist/task/reconcile.d.ts +39 -0
- package/dist/task/reconcile.js +201 -0
- package/dist/task/report-links.d.ts +10 -0
- package/dist/task/report-links.js +47 -0
- package/dist/tools/config.js +46 -4
- package/dist/tools/dispatch.js +2 -1
- package/dist/tools/dream.d.ts +3 -0
- package/dist/tools/dream.js +123 -0
- package/dist/tools/tasks.js +4 -1
- package/package.json +1 -1
|
@@ -1,15 +1,16 @@
|
|
|
1
|
+
import { capacityRoom } from "./usage.js";
|
|
1
2
|
import { targetTranscriptPath } from "./transcripts.js";
|
|
2
3
|
import { CONVERSATION_LIMIT, CONVERSATION_MARKER, ORPHAN_GRACE_MS, pruneContinuationConversations, saveContinuationConversation, saveContinuationIntent } from "./continuation-launch.js";
|
|
3
4
|
import { redactPeerHandoff } from "./peer-handoff.js";
|
|
4
|
-
// Moving a live session to another agent: the
|
|
5
|
-
//
|
|
5
|
+
// Moving a live session to another agent: the Hook saves its history and an
|
|
6
|
+
// optional agent summary, exits the source, and the target harness starts in
|
|
6
7
|
// the same pane by default, or a new chat that keeps the old agent running.
|
|
7
8
|
//
|
|
8
9
|
// The hand-off is asked for through the same durable prompt path `hand_off`
|
|
9
10
|
// uses, as a reply between two marker lines; the Hook reads it from the
|
|
10
11
|
// transcript and saves it. A reply never waits on a permission prompt, which
|
|
11
12
|
// a write outside the checkout would in a supervised session. When the agent
|
|
12
|
-
//
|
|
13
|
+
// cannot answer, the hand-off is built from its saved conversation,
|
|
13
14
|
// the git state and the original brief instead, as a worker continued on
|
|
14
15
|
// another account is (account-failover.ts).
|
|
15
16
|
//
|
|
@@ -48,8 +49,9 @@ export const moveRequestSchema = z.object({
|
|
|
48
49
|
* account's home and the same conversation resumes there (`claude --resume`),
|
|
49
50
|
* so an account at its usage limit can still switch. `summary-by-target` (a move to another computer):
|
|
50
51
|
* the source is not asked for a hand-off; the new agent there builds one from the copied conversation.
|
|
51
|
-
*
|
|
52
|
-
|
|
52
|
+
* `saved-history` continues immediately on this computer or a peer; `agent-summary` asks a healthy
|
|
53
|
+
* source for an optional summary. Omitted/`handoff` automatically skips an exhausted source. */
|
|
54
|
+
continuation: z.enum(["handoff", "resume", "summary-by-target", "agent-summary", "saved-history"]).default("handoff"),
|
|
53
55
|
/** Kept on a retry: the same id returns the move already under way. */
|
|
54
56
|
id: z.string().uuid().optional(),
|
|
55
57
|
/** How long the agent gets to write its hand-off before Phren builds one. */
|
|
@@ -70,7 +72,7 @@ const moveRecordSchema = z.object({
|
|
|
70
72
|
mode: z.enum(["replace", "new-chat"]).optional(),
|
|
71
73
|
/** `resume`: the same conversation under another account here. `summary-by-target`: the source was out of
|
|
72
74
|
* usage, so the agent on the other computer builds the hand-off from the copied conversation. */
|
|
73
|
-
continuation: z.enum(["resume", "summary-by-target"]).optional(),
|
|
75
|
+
continuation: z.enum(["resume", "summary-by-target", "agent-summary", "saved-history"]).optional(),
|
|
74
76
|
modeForced: z.literal("conductor").optional(),
|
|
75
77
|
handedOffTo: z.object({ computer: z.string().optional(), target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
|
|
76
78
|
handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
|
|
@@ -394,10 +396,12 @@ export function fallbackHandoff(input) {
|
|
|
394
396
|
// Written to a file, so the brief is never cut here.
|
|
395
397
|
return input.original ? withOriginalBrief(head, input.original, Number.MAX_SAFE_INTEGER, "the original brief file") : head;
|
|
396
398
|
}
|
|
397
|
-
/** Whether
|
|
398
|
-
* rate-limit row): its agent cannot answer a hand-off request. */
|
|
399
|
+
/** Whether the harness ended its latest turn with a quota error: it cannot answer a hand-off request. */
|
|
399
400
|
export function sourceOutOfUsage(lines, source) {
|
|
400
|
-
|
|
401
|
+
if (source === "phren")
|
|
402
|
+
return false;
|
|
403
|
+
const error = finalTurnFromLines(lines, source).error;
|
|
404
|
+
return isClaudeUsageLimit(error) || /usage.?limit|rate.?limit|quota|insufficient.?credits|429/i.test(error ?? "");
|
|
401
405
|
}
|
|
402
406
|
/** Room left in a cross-computer brief for the copied conversation, once the rest of the hand-off is in. */
|
|
403
407
|
const TRANSCRIPT_MARGIN = 2_000;
|
|
@@ -499,7 +503,7 @@ export function handoffDocument(record, body, observed, at, conductor = false) {
|
|
|
499
503
|
}
|
|
500
504
|
/** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
|
|
501
505
|
export function continuePrompt(document, file) {
|
|
502
|
-
const lead =
|
|
506
|
+
const lead = `Phren moved this session to you. The hand-off from the previous agent follows (saved at ${file}; resolve its history file beside it). Continue from here: check the current state first, keep its uncommitted changes, and do not start over.`;
|
|
503
507
|
const whole = `${lead}\n\n${document}`;
|
|
504
508
|
if (whole.length <= PROMPT_LIMIT)
|
|
505
509
|
return whole;
|
|
@@ -680,7 +684,7 @@ export class SessionMover {
|
|
|
680
684
|
const at = new Date(this.now).toISOString();
|
|
681
685
|
const resume = data.continuation === "resume";
|
|
682
686
|
const record = { id: data.id ?? randomUUID(), state: resume ? "exiting" : "handing-off", createdAt: at, updatedAt: at,
|
|
683
|
-
...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(
|
|
687
|
+
...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(data.continuation !== "handoff" ? { continuation: data.continuation } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
|
|
684
688
|
...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}), ...(workerDispatch ? { workerDispatch } : {}) };
|
|
685
689
|
await assertUnusedLaunchId(record.id);
|
|
686
690
|
if (conductor && peer) {
|
|
@@ -709,18 +713,22 @@ export class SessionMover {
|
|
|
709
713
|
const pids = pane ? (await this.deps.terminal.processes(from.server, from.pane).catch(() => undefined))?.foregroundPids ?? [] : [];
|
|
710
714
|
const [git, processes] = await Promise.all([(this.deps.git ?? readGitState)(record.cwd).catch(() => undefined),
|
|
711
715
|
(this.deps.processesBelow ?? processesBelow)(pids).catch(() => [])]);
|
|
712
|
-
//
|
|
713
|
-
const
|
|
714
|
-
const lines =
|
|
715
|
-
|
|
716
|
-
|
|
716
|
+
// Saved history is available even when the outgoing harness cannot answer or disappears.
|
|
717
|
+
const portable = !!peer || from.source !== record.to.harness || record.continuation === "saved-history";
|
|
718
|
+
const lines = await this.deps.transcript(from).catch(() => []);
|
|
719
|
+
const whole = portable ? await (this.deps.conversation ?? wholeTranscript)(from).catch(() => undefined) : undefined;
|
|
720
|
+
const entries = conversationEntries(whole?.lines ?? lines, from.source);
|
|
721
|
+
const limits = await this.deps.usage?.().catch(() => []);
|
|
722
|
+
const exhausted = sourceOutOfUsage(lines, from.source) || capacityRoom(limits ?? [], this.now)
|
|
723
|
+
.some(row => row.source === from.source && (from.source !== "claude" || (row.account ?? DEFAULT_ACCOUNT) === (record.from.account ?? DEFAULT_ACCOUNT)) && row.exhausted);
|
|
724
|
+
const requested = record.continuation === "summary-by-target" || record.continuation === "saved-history";
|
|
725
|
+
if (record.continuation === "summary-by-target" && !entries.length)
|
|
717
726
|
throw new BridgeError(409, "The conversation could not be read, so the agent on the other computer would have nothing to build a hand-off from; the old chat remains open.");
|
|
718
|
-
const
|
|
719
|
-
const byTarget = !!peer && (requested || exhausted);
|
|
727
|
+
const byTarget = portable && (requested || exhausted);
|
|
720
728
|
if (byTarget && !requested)
|
|
721
|
-
await this.update(record, { continuation: "summary-by-target" });
|
|
722
|
-
const written = byTarget ? { reason: `${exhausted ? "its account is out of usage" : "the owner asked
|
|
723
|
-
: await this.askForHandoff(record, handoffMs);
|
|
729
|
+
await this.update(record, { continuation: peer ? "summary-by-target" : "saved-history" });
|
|
730
|
+
const written = byTarget ? { reason: `${exhausted ? "its account is out of usage" : "the owner asked for immediate continuation"}; continue from saved history.` }
|
|
731
|
+
: await this.askForHandoff(record, handoffMs).catch(error => ({ reason: `the hand-off request failed (${error instanceof Error ? error.message : String(error)}).` }));
|
|
724
732
|
// The wait is over. Its request, if still untyped, is taken back first: typed later it would ask the old
|
|
725
733
|
// agent (left running by a new-chat move) for a hand-off nobody reads. Then an interrupt already checking
|
|
726
734
|
// finishes, and none starts after (the move goes on to exit or launch, where an Escape would hit the exit
|
|
@@ -730,32 +738,30 @@ export class SessionMover {
|
|
|
730
738
|
await this.lifecycle(record.id, async () => { this.asking.delete(record.id); });
|
|
731
739
|
const observed = observedState(git, processes, !peer), at = new Date(this.now).toISOString();
|
|
732
740
|
let body;
|
|
733
|
-
if (byTarget) {
|
|
741
|
+
if (byTarget || (portable && !("text" in written))) {
|
|
734
742
|
const original = record.dispatch ? await this.deps.brief?.(record.dispatch).catch(() => undefined) : undefined;
|
|
735
|
-
const entries = conversationEntries(lines ?? [], from.source);
|
|
736
743
|
const fit = (room) => targetSummaryBody({ from: harnessName({ harness: from.source, account: record.from.account }), exhausted,
|
|
737
|
-
entries, room, prepare: text => redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>"))
|
|
744
|
+
entries, room, prepare: text => peer ? redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>")) : briefText(text),
|
|
745
|
+
original: original ?? entries.find(entry => entry.role === "owner")?.text,
|
|
738
746
|
...(record.dispatch ? { dispatch: record.dispatch } : {}), ...(record.from.label ? { label: record.from.label } : {}) });
|
|
739
747
|
// What fits beside the rest of the hand-off in the one brief the other computer gets, measured as sent:
|
|
740
748
|
// the checkout path replaced and credentials redacted, either of which can lengthen the text. Messages
|
|
741
749
|
// are prepared that way before they are counted; the refit only catches what the rest of the brief adds.
|
|
742
750
|
// The receiving Hook appends where it put the whole conversation, so that line's room is kept free.
|
|
743
751
|
const limit = PROMPT_LIMIT - POINTER_ROOM;
|
|
744
|
-
|
|
752
|
+
const promptFor = (body) => {
|
|
753
|
+
const document = handoffDocument(record, body, observed, at, !!conductor);
|
|
754
|
+
return peer ? peerPrompt(record, document) : `Phren moved this session to you. Inspect the checkout before continuing.\n\n${document}`;
|
|
755
|
+
};
|
|
756
|
+
let room = limit - promptFor("").length - TRANSCRIPT_MARGIN;
|
|
745
757
|
body = fit(room);
|
|
746
758
|
for (let tries = 0; tries < 4; tries++) {
|
|
747
|
-
const over =
|
|
759
|
+
const over = promptFor(body).length - limit;
|
|
748
760
|
if (over <= 0)
|
|
749
761
|
break;
|
|
750
762
|
room -= over + 500;
|
|
751
763
|
body = fit(room);
|
|
752
764
|
}
|
|
753
|
-
// The whole conversation, for the receiving Hook to pull beside the brief (continuation-launch.ts). A copy
|
|
754
|
-
// that cannot be saved leaves the excerpt, which the brief carries anyway.
|
|
755
|
-
// Read whole here: the lines above are the transcript's last 512 KiB, which tool output can fill.
|
|
756
|
-
const whole = await (this.deps.conversation ?? wholeTranscript)(from).catch(() => undefined);
|
|
757
|
-
await saveContinuationConversation(record.id, conversationCopy(whole ? conversationEntries(whole.lines, from.source) : entries, text => briefText(redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>"))), CONVERSATION_LIMIT, whole?.complete ?? false))
|
|
758
|
-
.catch(() => undefined);
|
|
759
765
|
}
|
|
760
766
|
else {
|
|
761
767
|
const fallback = "text" in written ? undefined : await this.fallback(record, written.reason);
|
|
@@ -763,12 +769,37 @@ export class SessionMover {
|
|
|
763
769
|
? `## Goal and current state\n\n${fallback}\n\n## Next steps\n\nContinue the owner's goal above after checking the checkout and the latest agent reply.\n\n## Key files\n\nOpen or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.`
|
|
764
770
|
: fallback;
|
|
765
771
|
}
|
|
772
|
+
if (portable && !peer && record.mode === "new-chat" && !("text" in written)) {
|
|
773
|
+
body = `## Goal and current state\n\n${body}\n\n## Next steps\n\nContinue the owner's goal above after checking the checkout and the latest agent reply.\n\n## Key files\n\nOpen or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.`;
|
|
774
|
+
}
|
|
775
|
+
let savedHistory;
|
|
776
|
+
if (portable) {
|
|
777
|
+
const prepare = (text) => briefText(peer ? redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>")) : text);
|
|
778
|
+
const first = entries.find(entry => entry.role === "owner")?.text;
|
|
779
|
+
const original = record.dispatch ? await this.deps.brief?.(record.dispatch).catch(() => undefined) : undefined;
|
|
780
|
+
const prefix = [original ? `Original dispatch request:\n${prepare(original).slice(0, ORIGINAL_RESERVE)}` : "",
|
|
781
|
+
first ? `Original owner request:\n${prepare(first).slice(0, ORIGINAL_RESERVE)}` : ""].filter(Boolean).join("\n\n");
|
|
782
|
+
const copy = `${prefix}\n\n${conversationCopy(entries, prepare, CONVERSATION_LIMIT - prefix.length - 2, whole?.complete ?? false)}`;
|
|
783
|
+
// Save before exiting the source. This durable local copy outlives intent-copy cleanup.
|
|
784
|
+
// writeLaunchBrief publishes its folder atomically and owns the launch id.
|
|
785
|
+
// Fill in the history only after that publication, still before source exit.
|
|
786
|
+
savedHistory = copy;
|
|
787
|
+
if (peer) {
|
|
788
|
+
await saveContinuationConversation(record.id, copy);
|
|
789
|
+
if (!body.includes(CONVERSATION_MARKER))
|
|
790
|
+
body += `\n\n${CONVERSATION_MARKER}. Read more history from the conversation file supplied beside this brief as needed; inspect the checkout before continuing.`;
|
|
791
|
+
}
|
|
792
|
+
else
|
|
793
|
+
body += "\n\nSaved history: conversation.md, beside this hand-off file. Read more history from this file as needed, including the original request and earlier decisions. Inspect the checkout before continuing; preserve the owner's uncommitted changes.";
|
|
794
|
+
}
|
|
766
795
|
const document = handoffDocument(record, body, observed, at, !!conductor);
|
|
767
796
|
await this.assertNotAborted(record);
|
|
768
797
|
const file = handoffPath(record.id);
|
|
769
798
|
const prompt = briefText(continuePrompt(document, file));
|
|
770
799
|
// The folder is the new agent's brief folder; the hand-off is written into it, whole.
|
|
771
800
|
await writeLaunchBrief({ id: record.id, text: prompt }, this.now, record.from.label);
|
|
801
|
+
if (savedHistory !== undefined)
|
|
802
|
+
await atomic(path.join(path.dirname(file), "conversation.md"), savedHistory);
|
|
772
803
|
await atomic(file, document);
|
|
773
804
|
await this.update(record, { state: record.mode === "new-chat" ? "launching" : "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
|
|
774
805
|
...("reason" in written ? { reason: written.reason.slice(0, 300) } : {}), chars: document.length } });
|
|
@@ -1120,7 +1151,7 @@ export class SessionMover {
|
|
|
1120
1151
|
return `The conductor hand-over ${outcome}, but the new chat's notice could not be delivered: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500);
|
|
1121
1152
|
}
|
|
1122
1153
|
}
|
|
1123
|
-
/** The agent's
|
|
1154
|
+
/** The agent's optional hand-off, or why there is none; run also catches lifecycle failures. */
|
|
1124
1155
|
async askForHandoff(record, handoffMs) {
|
|
1125
1156
|
const from = record.from.target;
|
|
1126
1157
|
const deadline = this.now + handoffMs;
|
|
@@ -1147,7 +1178,7 @@ export class SessionMover {
|
|
|
1147
1178
|
aborted();
|
|
1148
1179
|
const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
|
|
1149
1180
|
if (!pane || pane.agent !== from.source)
|
|
1150
|
-
throw new BridgeError(409, "The session ended before it wrote its hand-off
|
|
1181
|
+
throw new BridgeError(409, "The session ended before it wrote its hand-off.");
|
|
1151
1182
|
const lines = await this.deps.transcript(from).catch(() => []);
|
|
1152
1183
|
const text = extractHandoff(repliesAfterRequest(conversationEntries(lines, from.source), record.id), record.id);
|
|
1153
1184
|
if (!text)
|
|
@@ -84,6 +84,8 @@ export declare class LatestFrame {
|
|
|
84
84
|
offer(frame: Buffer): void;
|
|
85
85
|
/** The phone has a frame; an acknowledgement it owes nothing for is ignored. */
|
|
86
86
|
ack(): void;
|
|
87
|
+
/** Discard a previous page's queued frame without forgiving its outstanding acknowledgements. */
|
|
88
|
+
discardWaiting(): void;
|
|
87
89
|
close(): void;
|
|
88
90
|
private get bytesPerSecond();
|
|
89
91
|
private pump;
|
|
@@ -128,6 +128,8 @@ export class LatestFrame {
|
|
|
128
128
|
this.inFlight--;
|
|
129
129
|
this.pump();
|
|
130
130
|
}
|
|
131
|
+
/** Discard a previous page's queued frame without forgiving its outstanding acknowledgements. */
|
|
132
|
+
discardWaiting() { this.waiting = undefined; }
|
|
131
133
|
close() { this.closed = true; this.waiting = undefined; clearTimeout(this.timer); }
|
|
132
134
|
get bytesPerSecond() { return this.options.bytesPerSecond ?? STREAM_BYTES_PER_SECOND; }
|
|
133
135
|
pump() {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
|
|
2
|
+
export declare const FAST_STATUS_LINE_FILE = "claude-statusline.mjs";
|
|
3
|
+
export declare const fastStatusLinePath: (versionDir: string) => string;
|
|
4
|
+
/** The owner's status line under any number of Phren wrappers: what a status line that is Phren's wraps,
|
|
5
|
+
* down to one that is not. `null` when the innermost wrapped none; a value that is not Phren's is returned as is.
|
|
6
|
+
* Phren's is the quoted node, the quoted bundle or forwarder (whichever node and Hook folder it named),
|
|
7
|
+
* `usage-statusline` and the wrapped status line as base64. Self-contained: the forwarder embeds its source. */
|
|
8
|
+
export declare function unwrapStatusLine(value: unknown): unknown;
|
|
9
|
+
export declare const FAST_STATUS_LINE_SOURCE: string;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Claude Code runs its status line command on every refresh, from every
|
|
2
|
+
// session. Loading the Hook bundle for each one cost about a second of CPU, and
|
|
3
|
+
// installs under a different node wrapped the previous wrapper, so one refresh
|
|
4
|
+
// ran a chain of bundles. Install writes this small script into each version's
|
|
5
|
+
// folder beside the bundle: it posts the status line's input to the running
|
|
6
|
+
// Hook, which records the usage, and runs the owner's own status line, if any.
|
|
7
|
+
//
|
|
8
|
+
// It must stay dependency-free. When no Hook answers, nothing is recorded: the
|
|
9
|
+
// Hook is what serves the usage, and the next refresh after it starts records it.
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
/** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
|
|
12
|
+
export const FAST_STATUS_LINE_FILE = "claude-statusline.mjs";
|
|
13
|
+
export const fastStatusLinePath = (versionDir) => path.join(versionDir, FAST_STATUS_LINE_FILE);
|
|
14
|
+
/** The owner's status line under any number of Phren wrappers: what a status line that is Phren's wraps,
|
|
15
|
+
* down to one that is not. `null` when the innermost wrapped none; a value that is not Phren's is returned as is.
|
|
16
|
+
* Phren's is the quoted node, the quoted bundle or forwarder (whichever node and Hook folder it named),
|
|
17
|
+
* `usage-statusline` and the wrapped status line as base64. Self-contained: the forwarder embeds its source. */
|
|
18
|
+
export function unwrapStatusLine(value) {
|
|
19
|
+
const phren = /^'(?:[^']|'\\'')*' '(?:[^']|'\\'')*\/(?:bridge-hook|claude-statusline)\.mjs' usage-statusline ([A-Za-z0-9+/=]{1,32768})$/;
|
|
20
|
+
for (let depth = 0; depth < 16; depth++) {
|
|
21
|
+
const command = value && typeof value === "object" && !Array.isArray(value) ? value.command : undefined;
|
|
22
|
+
const match = typeof command === "string" ? phren.exec(command) : null;
|
|
23
|
+
if (!match)
|
|
24
|
+
return value;
|
|
25
|
+
value = JSON.parse(Buffer.from(match[1], "base64").toString());
|
|
26
|
+
}
|
|
27
|
+
throw new Error("Invalid Phren status line");
|
|
28
|
+
}
|
|
29
|
+
export const FAST_STATUS_LINE_SOURCE = `// Installed by Phren Hook: Claude Code's status line, reported to the running Hook.
|
|
30
|
+
import { spawn } from "node:child_process";
|
|
31
|
+
import { request } from "node:http";
|
|
32
|
+
import { homedir } from "node:os";
|
|
33
|
+
import path from "node:path";
|
|
34
|
+
const env = process.env, encoded = process.argv[3] ?? "";
|
|
35
|
+
const unwrapStatusLine = ${unwrapStatusLine.toString()};
|
|
36
|
+
if (process.argv[2] === "usage-statusline" && /^[A-Za-z0-9+/=]{1,32768}$/.test(encoded)) {
|
|
37
|
+
let input = "", oversized = false;
|
|
38
|
+
for await (const chunk of process.stdin) { input += chunk.toString(); if (input.length > 262_144) { oversized = true; break; } }
|
|
39
|
+
const data = oversized ? undefined : JSON.stringify({ configDir: env.CLAUDE_CONFIG_DIR, input });
|
|
40
|
+
const socketPath = path.join(env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"), "agent.sock");
|
|
41
|
+
const reported = data === undefined ? undefined : new Promise(resolve => {
|
|
42
|
+
const req = request({ socketPath, path: "/usage-statusline", method: "POST", timeout: 2_000,
|
|
43
|
+
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => { res.resume(); res.on("end", resolve); res.on("error", resolve); });
|
|
44
|
+
req.on("error", resolve); req.on("timeout", () => { req.destroy(); resolve(); }); req.end(data);
|
|
45
|
+
});
|
|
46
|
+
let previous;
|
|
47
|
+
try { previous = unwrapStatusLine(JSON.parse(Buffer.from(encoded, "base64").toString())); } catch { /* Nothing of the owner's to show. */ }
|
|
48
|
+
// The owner's own status line, run just as Claude ran it before the Hook was installed.
|
|
49
|
+
const shown = previous && typeof previous.command === "string" ? new Promise(resolve => {
|
|
50
|
+
const child = spawn("/bin/sh", ["-c", previous.command], { stdio: ["pipe", "inherit", "inherit"] });
|
|
51
|
+
child.on("error", resolve); child.on("exit", resolve);
|
|
52
|
+
child.stdin.on("error", () => {}); child.stdin.end(input);
|
|
53
|
+
}) : undefined;
|
|
54
|
+
await Promise.all([reported, shown]);
|
|
55
|
+
}
|
|
56
|
+
`;
|
|
@@ -16,6 +16,8 @@ export type TabActivityObservation = {
|
|
|
16
16
|
stamps: ReadonlyMap<string, TabActivityStamp>;
|
|
17
17
|
};
|
|
18
18
|
export declare const tabActivityKey: (workspace: unknown, tab: unknown) => string;
|
|
19
|
+
/** Panes grouped once per snapshot, preserving terminal order and workspace scope. */
|
|
20
|
+
export declare function panesByTab(snapshot: Json): Map<string, Json[]>;
|
|
19
21
|
/** A clock for Herdr's clockless state counters. Only successful snapshots
|
|
20
22
|
* prune tabs; each activity pass also prunes missing servers. Writes are ordered
|
|
21
23
|
* and atomic, and an unchanged poll never rewrites the file. */
|
|
@@ -4,6 +4,19 @@ import { createHash } from "node:crypto";
|
|
|
4
4
|
import { atomicInPrivateDir, bridgeRoot, object, objects } from "./protocol.js";
|
|
5
5
|
const digest = (text) => createHash("sha256").update(text).digest("hex");
|
|
6
6
|
export const tabActivityKey = (workspace, tab) => JSON.stringify([workspace, tab]);
|
|
7
|
+
/** Panes grouped once per snapshot, preserving terminal order and workspace scope. */
|
|
8
|
+
export function panesByTab(snapshot) {
|
|
9
|
+
const groups = new Map();
|
|
10
|
+
for (const pane of objects(snapshot.panes)) {
|
|
11
|
+
const key = tabActivityKey(pane.workspace_id, pane.tab_id);
|
|
12
|
+
const panes = groups.get(key);
|
|
13
|
+
if (panes)
|
|
14
|
+
panes.push(pane);
|
|
15
|
+
else
|
|
16
|
+
groups.set(key, [pane]);
|
|
17
|
+
}
|
|
18
|
+
return groups;
|
|
19
|
+
}
|
|
7
20
|
/** A clock for Herdr's clockless state counters. Only successful snapshots
|
|
8
21
|
* prune tabs; each activity pass also prunes missing servers. Writes are ordered
|
|
9
22
|
* and atomic, and an unchanged poll never rewrites the file. */
|
|
@@ -29,13 +42,13 @@ export class TabActivityStore {
|
|
|
29
42
|
const prefix = JSON.stringify(server) + ":";
|
|
30
43
|
const seen = new Set(), stamps = new Map();
|
|
31
44
|
let changed = false;
|
|
45
|
+
const grouped = panesByTab(snapshot);
|
|
32
46
|
for (const tab of objects(snapshot.tabs)) {
|
|
33
47
|
const tabKey = tabActivityKey(tab.workspace_id, tab.tab_id), key = prefix + tabKey;
|
|
34
48
|
seen.add(key);
|
|
35
49
|
// Include every pane: a lower counter changing must count even when
|
|
36
50
|
// another pane still has the tab's maximum state_change_seq.
|
|
37
|
-
const panes =
|
|
38
|
-
.map(p => [p.pane_id, p.agent, p.agent_status, p.state_change_seq, p.title || p.terminal_title_stripped])
|
|
51
|
+
const panes = (grouped.get(tabKey) ?? []).map(p => [p.pane_id, p.agent, p.agent_status, p.state_change_seq, p.title || p.terminal_title_stripped])
|
|
39
52
|
.sort((a, b) => String(a[0]).localeCompare(String(b[0])));
|
|
40
53
|
const signature = digest(JSON.stringify([tab.agent_status, tab.state_change_seq, tab.label, tab.title, panes]));
|
|
41
54
|
const stamp = this.entries.get(key);
|
|
@@ -69,6 +69,10 @@ export declare function getTaskRoute(base: string, url: URL): {
|
|
|
69
69
|
};
|
|
70
70
|
items: {
|
|
71
71
|
[k: string]: {
|
|
72
|
+
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
73
|
+
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
74
|
+
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
75
|
+
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
72
76
|
id: string;
|
|
73
77
|
stableId?: string;
|
|
74
78
|
identityAmbiguous?: boolean;
|
|
@@ -77,6 +81,7 @@ export declare function getTaskRoute(base: string, url: URL): {
|
|
|
77
81
|
checked: boolean;
|
|
78
82
|
priority?: "high" | "medium" | "low";
|
|
79
83
|
context?: string;
|
|
84
|
+
links?: import("../task/merge-links.js").TaskLinks;
|
|
80
85
|
pinned?: boolean;
|
|
81
86
|
githubIssue?: number;
|
|
82
87
|
githubUrl?: string;
|
|
@@ -95,10 +100,6 @@ export declare function getTaskRoute(base: string, url: URL): {
|
|
|
95
100
|
taskContractRecords?: string[];
|
|
96
101
|
taskContractLines?: string[];
|
|
97
102
|
opaqueContinuationLines?: string[];
|
|
98
|
-
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
99
|
-
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
100
|
-
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
101
|
-
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
102
103
|
}[];
|
|
103
104
|
};
|
|
104
105
|
};
|
|
@@ -126,6 +127,10 @@ export declare function updateTaskRoute(base: string, input: unknown): {
|
|
|
126
127
|
};
|
|
127
128
|
items: {
|
|
128
129
|
[k: string]: {
|
|
130
|
+
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
131
|
+
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
132
|
+
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
133
|
+
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
129
134
|
id: string;
|
|
130
135
|
stableId?: string;
|
|
131
136
|
identityAmbiguous?: boolean;
|
|
@@ -134,6 +139,7 @@ export declare function updateTaskRoute(base: string, input: unknown): {
|
|
|
134
139
|
checked: boolean;
|
|
135
140
|
priority?: "high" | "medium" | "low";
|
|
136
141
|
context?: string;
|
|
142
|
+
links?: import("../task/merge-links.js").TaskLinks;
|
|
137
143
|
pinned?: boolean;
|
|
138
144
|
githubIssue?: number;
|
|
139
145
|
githubUrl?: string;
|
|
@@ -152,10 +158,6 @@ export declare function updateTaskRoute(base: string, input: unknown): {
|
|
|
152
158
|
taskContractRecords?: string[];
|
|
153
159
|
taskContractLines?: string[];
|
|
154
160
|
opaqueContinuationLines?: string[];
|
|
155
|
-
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
156
|
-
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
157
|
-
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
158
|
-
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
159
161
|
}[];
|
|
160
162
|
};
|
|
161
163
|
};
|
|
@@ -185,6 +187,10 @@ export declare function createTaskRoute(base: string, input: unknown): {
|
|
|
185
187
|
};
|
|
186
188
|
items: {
|
|
187
189
|
[k: string]: {
|
|
190
|
+
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
191
|
+
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
192
|
+
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
193
|
+
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
188
194
|
id: string;
|
|
189
195
|
stableId?: string;
|
|
190
196
|
identityAmbiguous?: boolean;
|
|
@@ -193,6 +199,7 @@ export declare function createTaskRoute(base: string, input: unknown): {
|
|
|
193
199
|
checked: boolean;
|
|
194
200
|
priority?: "high" | "medium" | "low";
|
|
195
201
|
context?: string;
|
|
202
|
+
links?: import("../task/merge-links.js").TaskLinks;
|
|
196
203
|
pinned?: boolean;
|
|
197
204
|
githubIssue?: number;
|
|
198
205
|
githubUrl?: string;
|
|
@@ -211,10 +218,6 @@ export declare function createTaskRoute(base: string, input: unknown): {
|
|
|
211
218
|
taskContractRecords?: string[];
|
|
212
219
|
taskContractLines?: string[];
|
|
213
220
|
opaqueContinuationLines?: string[];
|
|
214
|
-
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
215
|
-
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
216
|
-
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
217
|
-
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
218
221
|
}[];
|
|
219
222
|
};
|
|
220
223
|
};
|
|
@@ -244,6 +247,10 @@ export declare function saveTaskRoute(base: string, input: unknown): {
|
|
|
244
247
|
};
|
|
245
248
|
items: {
|
|
246
249
|
[k: string]: {
|
|
250
|
+
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
251
|
+
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
252
|
+
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
253
|
+
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
247
254
|
id: string;
|
|
248
255
|
stableId?: string;
|
|
249
256
|
identityAmbiguous?: boolean;
|
|
@@ -252,6 +259,7 @@ export declare function saveTaskRoute(base: string, input: unknown): {
|
|
|
252
259
|
checked: boolean;
|
|
253
260
|
priority?: "high" | "medium" | "low";
|
|
254
261
|
context?: string;
|
|
262
|
+
links?: import("../task/merge-links.js").TaskLinks;
|
|
255
263
|
pinned?: boolean;
|
|
256
264
|
githubIssue?: number;
|
|
257
265
|
githubUrl?: string;
|
|
@@ -270,10 +278,6 @@ export declare function saveTaskRoute(base: string, input: unknown): {
|
|
|
270
278
|
taskContractRecords?: string[];
|
|
271
279
|
taskContractLines?: string[];
|
|
272
280
|
opaqueContinuationLines?: string[];
|
|
273
|
-
responsibility: import("../data/task-contract.js").TaskResponsibility;
|
|
274
|
-
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
275
|
-
prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
|
|
276
|
-
identity: import("../data/task-contract.js").TaskDependency | null;
|
|
277
281
|
}[];
|
|
278
282
|
};
|
|
279
283
|
};
|
|
@@ -152,7 +152,7 @@ export async function launchTaskRoute(base, server, input) {
|
|
|
152
152
|
try {
|
|
153
153
|
const launched = await launchSession(server, { kind: data.kind, model: data.model, effort: data.effort, account: data.account,
|
|
154
154
|
permissionMode: data.permissionMode, role: "agent", cwd, label: task.text.slice(0, 200),
|
|
155
|
-
launchId: task.launchId, brief: { id: task.launchId, text } }, { trustFolder: true });
|
|
155
|
+
launchId: task.launchId, brief: { id: task.launchId, text, task: task.identity } }, { trustFolder: true });
|
|
156
156
|
return { ...launched, task: task.identity, taskRevision: task.revision, launchId: task.launchId, claimPreserved: true,
|
|
157
157
|
state: launched.briefState === "sent" ? "started" : "uncertain" };
|
|
158
158
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Json } from "./protocol.js";
|
|
2
|
-
import type { TerminalPane, TerminalProvider } from "./terminal.js";
|
|
2
|
+
import type { AgentStart, TerminalPane, TerminalProvider } from "./terminal.js";
|
|
3
3
|
/** Who reports phren-agent's lifecycle to Herdr, which does not detect it itself. */
|
|
4
4
|
export declare const PHREN_REPORT_SOURCE = "phren-hook";
|
|
5
5
|
/** A word for a POSIX shell, quoted only when it needs it. */
|
|
@@ -7,6 +7,10 @@ export declare function shellWord(word: string): string;
|
|
|
7
7
|
/** What the Hook types into a Herdr pane's shell to start phren-agent:
|
|
8
8
|
* the agent, then Herdr's report of it released once it exits. */
|
|
9
9
|
export declare function phrenCommandLine(args: string[]): string;
|
|
10
|
+
/** The exact command Herdr types for a keyed launch. */
|
|
11
|
+
export declare function herdrExplicitCommand(agent: AgentStart): string;
|
|
12
|
+
/** sh, bash or zsh only: the keyed wrapper is a POSIX shell command line. */
|
|
13
|
+
export declare function shellFromProcessInfo(info: Json): string | undefined;
|
|
10
14
|
/** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
|
|
11
15
|
export declare function herdrPanes(server: string, s: Json): TerminalPane[];
|
|
12
16
|
export declare const herdrTerminal: TerminalProvider;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { browserEnv } from "./browser-env.js";
|
|
1
2
|
// Herdr as the Hook's terminal provider: each method is one call on Herdr's
|
|
2
3
|
// socket API. It calls herdr.ts's exported `rpc`, the seam the bridge tests
|
|
3
4
|
// fake, so a test that records Herdr requests sees exactly what it did before
|
|
4
5
|
// the provider existed.
|
|
5
6
|
import { herdrSocketPath, rpc, snapshot } from "./herdr.js";
|
|
6
7
|
import { BridgeError, object, objects } from "./protocol.js";
|
|
7
|
-
import { agentFromCommand } from "./terminal-tmux.js";
|
|
8
|
+
import { agentFromCommand, explicitAgentCommand } from "./terminal-tmux.js";
|
|
8
9
|
const text = (value) => typeof value === "string" && value ? value : undefined;
|
|
9
10
|
/** Who reports phren-agent's lifecycle to Herdr, which does not detect it itself. */
|
|
10
11
|
export const PHREN_REPORT_SOURCE = "phren-hook";
|
|
@@ -70,6 +71,66 @@ async function startPhren(server, pane, { name, args, timeoutMs }) {
|
|
|
70
71
|
await rpc(server, "pane.report_agent", { pane_id: pane, source: PHREN_REPORT_SOURCE, agent: "phren", state: "idle" });
|
|
71
72
|
await rpc(server, "agent.rename", { target: pane, name }).catch(() => undefined);
|
|
72
73
|
}
|
|
74
|
+
/** The exact command Herdr types for a keyed launch. */
|
|
75
|
+
export function herdrExplicitCommand(agent) {
|
|
76
|
+
return explicitAgentCommand(agent.kind, agent.args, agent.env ?? {});
|
|
77
|
+
}
|
|
78
|
+
/** sh, bash or zsh only: the keyed wrapper is a POSIX shell command line. */
|
|
79
|
+
export function shellFromProcessInfo(info) {
|
|
80
|
+
const shellPid = info.shell_pid;
|
|
81
|
+
const processes = objects(info.foreground_processes);
|
|
82
|
+
const shell = processes.find(p => p.pid === shellPid) ?? processes[0];
|
|
83
|
+
const command = typeof shell?.cmdline === "string" ? shell.cmdline.trim().split(/\s+/)[0] : "";
|
|
84
|
+
const name = command.split("/").pop()?.replace(/^-/, "");
|
|
85
|
+
return name && ["sh", "bash", "zsh"].includes(name) ? name : undefined;
|
|
86
|
+
}
|
|
87
|
+
/** Keyed launches: type our explicit `env -i` command at the pane's fresh shell. */
|
|
88
|
+
async function startExplicit(server, pane, { kind, args, timeoutMs, env, freshPane }) {
|
|
89
|
+
if (!freshPane)
|
|
90
|
+
throw new BridgeError(409, "A keyed Herdr launch needs a pane this launch just created; refusing to type into a reused pane.");
|
|
91
|
+
const readyBy = Date.now() + Math.min(timeoutMs, 15_000);
|
|
92
|
+
let stable = "", stableSince = 0;
|
|
93
|
+
for (;;) {
|
|
94
|
+
const info = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
|
|
95
|
+
const shellPid = info.shell_pid;
|
|
96
|
+
const processes = objects(info.foreground_processes);
|
|
97
|
+
const pids = processes.map(p => p.pid);
|
|
98
|
+
const foreground = Number.isSafeInteger(shellPid) && info.foreground_process_group_id === shellPid;
|
|
99
|
+
const shell = shellFromProcessInfo(info);
|
|
100
|
+
if (foreground && !shell)
|
|
101
|
+
throw new BridgeError(409, "Herdr: keyed launches support only sh, bash and zsh pane shells; this shell is not supported.");
|
|
102
|
+
const idle = foreground && !!shell && pids.length > 0 && pids.every(pid => pid === shellPid);
|
|
103
|
+
if (idle) {
|
|
104
|
+
const key = JSON.stringify([shellPid, pids]);
|
|
105
|
+
if (key !== stable) {
|
|
106
|
+
stable = key;
|
|
107
|
+
stableSince = Date.now();
|
|
108
|
+
}
|
|
109
|
+
if (Date.now() - stableSince >= 300)
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
stable = "";
|
|
114
|
+
stableSince = 0;
|
|
115
|
+
}
|
|
116
|
+
if (Date.now() >= readyBy)
|
|
117
|
+
throw new BridgeError(409, `Herdr: agent target pane ${pane} did not reach an idle shell prompt.`, { herdrCode: "agent_pane_busy" });
|
|
118
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
119
|
+
}
|
|
120
|
+
await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["ctrl+u"] });
|
|
121
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
122
|
+
await rpc(server, "pane.send_text", { pane_id: pane, text: herdrExplicitCommand({ name: "", kind, args, timeoutMs, env, freshPane }) });
|
|
123
|
+
await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] });
|
|
124
|
+
const deadline = Date.now() + Math.min(timeoutMs, 30_000);
|
|
125
|
+
for (;;) {
|
|
126
|
+
const info = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
|
|
127
|
+
if (objects(info.foreground_processes).some(p => typeof p.cmdline === "string" && agentFromCommand(p.cmdline) === kind))
|
|
128
|
+
return;
|
|
129
|
+
if (Date.now() >= deadline)
|
|
130
|
+
throw new BridgeError(504, `${kind} did not start in the Herdr pane. Check that it is installed and on the login shell's PATH.`);
|
|
131
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
73
134
|
/** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
|
|
74
135
|
export function herdrPanes(server, s) {
|
|
75
136
|
return objects(s.panes).filter(p => typeof p.pane_id === "string" && typeof p.tab_id === "string" && typeof p.workspace_id === "string").map(p => {
|
|
@@ -158,12 +219,16 @@ export const herdrTerminal = {
|
|
|
158
219
|
await startPhren(server, pane, agent);
|
|
159
220
|
return;
|
|
160
221
|
}
|
|
222
|
+
if (agent.envExact) {
|
|
223
|
+
await startExplicit(server, pane, agent);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
161
226
|
// Herdr waits up to `timeout_ms` for the agent to become ready; the socket waits a little longer.
|
|
162
227
|
await rpc(server, "agent.start", { name, kind, pane_id: pane, timeout_ms: timeoutMs, ...(args.length ? { args } : {}) }, undefined, timeoutMs + 5_000);
|
|
163
228
|
},
|
|
164
229
|
// What Herdr sets in its own panes (herdrPaneFromEnv reads them back).
|
|
165
230
|
paneEnv(server, { workspace, tab, pane }) {
|
|
166
|
-
return { HERDR_ENV: "1", HERDR_SOCKET_PATH: herdrSocketPath(server), HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane };
|
|
231
|
+
return { ...browserEnv(pane), HERDR_ENV: "1", HERDR_SOCKET_PATH: herdrSocketPath(server), HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane };
|
|
167
232
|
},
|
|
168
233
|
async reportAgent(server, pane, agent, state) {
|
|
169
234
|
await rpc(server, "pane.report_agent", { pane_id: pane, source: PHREN_REPORT_SOURCE, agent, state });
|
|
@@ -46,6 +46,8 @@ export declare function tmuxSocketFolders(env?: NodeJS.ProcessEnv): string[];
|
|
|
46
46
|
export declare function tmuxSocketsIn(folder: string, strict?: boolean): Promise<string[]>;
|
|
47
47
|
/** For tests: replace how tmux and ps run; the returned function restores them. */
|
|
48
48
|
export declare function setTmuxDeps(replacement: Partial<TmuxDeps>): () => void;
|
|
49
|
+
/** The exact keyed-launch command: shell init, then `env -i` with only the explicit environment. */
|
|
50
|
+
export declare function explicitAgentCommand(kind: string, args: string[], env: Record<string, string>): string;
|
|
49
51
|
declare const SIGILS: {
|
|
50
52
|
readonly s: "$";
|
|
51
53
|
readonly w: "@";
|