@phren/cli 0.3.56 → 0.3.58
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/claude-suggestion.d.ts +9 -0
- package/dist/bridge/claude-suggestion.js +30 -4
- package/dist/bridge/computer-identity.d.ts +4 -2
- package/dist/bridge/computer-identity.js +7 -3
- package/dist/bridge/conductor-group.d.ts +1 -1
- package/dist/bridge/conductor-group.js +2 -2
- package/dist/bridge/conductor-sets.d.ts +6 -0
- package/dist/bridge/conductor-sets.js +8 -2
- package/dist/bridge/dispatch-command.js +3 -3
- 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 +9 -0
- package/dist/bridge/prompt-deliveries.js +67 -4
- 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 +12 -0
- package/dist/bridge/server-pane-routes.js +112 -0
- package/dist/bridge/server-routes.d.ts +2 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/server.js +8 -2
- package/dist/bridge/session-move.d.ts +25 -0
- package/dist/bridge/session-move.js +128 -9
- package/dist/bridge/simulator-stream.d.ts +118 -0
- package/dist/bridge/simulator-stream.js +284 -0
- package/dist/bridge/simulators.d.ts +12 -0
- package/dist/bridge/simulators.js +32 -26
- package/dist/bridge/speech-transcribe.js +28 -3
- package/dist/bridge/terminal-herdr.js +28 -8
- package/dist/bridge-hook.mjs +1941 -1289
- package/dist/cli-registry.js +2 -2
- package/dist/modules/registry.js +2 -2
- package/dist/tools/dispatch.js +3 -2
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +7 -0
|
@@ -2,6 +2,8 @@ import { EXPECTED_REPOSITORY_REQUIRED, isGitWriteRoute } from "./git-write-polic
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
+
import { TURN_ENDED_WITHOUT_IT } from "./prompt-deliveries.js";
|
|
6
|
+
import { claudeSubagentView } from "./claude-suggestion.js";
|
|
5
7
|
import { gitBranches, gitDiscard, gitLog, gitPulls, gitShow, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
|
|
6
8
|
import { fanoutWorktrees } from "./fanouts.js";
|
|
7
9
|
import { gitWorktrees, resolveWorktree } from "./git-worktrees.js";
|
|
@@ -26,6 +28,7 @@ import { fileSearchSchema, listRepositoryFiles, searchRepository } from "./file-
|
|
|
26
28
|
import { deliveryIdSchema, PromptOnce, promptScope } from "./prompt-once.js";
|
|
27
29
|
import { promptWithStartupRetry } from "./prompt-startup.js";
|
|
28
30
|
import { sendServedPrompt, servedPane } from "./opencode-panes.js";
|
|
31
|
+
import { claudeSuggestionShown } from "./claude-suggestion.js";
|
|
29
32
|
export /** A file from the phone: a plain name and base64 bytes, bounded. */ function uploadBody(data) {
|
|
30
33
|
const name = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_ .()-]{0,199}$/).refine(n => !n.includes("..")).parse(data.name);
|
|
31
34
|
const encoded = z.string().max(11_184_812).regex(/^[A-Za-z0-9+/]*={0,2}$/).parse(data.data);
|
|
@@ -126,6 +129,27 @@ export function promptGuards(agentHooks, target) {
|
|
|
126
129
|
return { held: () => !!(agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)),
|
|
127
130
|
screen: () => terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 }) };
|
|
128
131
|
}
|
|
132
|
+
/** Whether a hand-off would relay the Claude pane's own prompt suggestion: the dim guess at the owner's next message
|
|
133
|
+
* that Claude draws in its empty input box. Read as plain text it looks like an owner message left unsent, Enter does
|
|
134
|
+
* not submit it, and a conductor watching panes relayed three of them as the owner's words, one a merge instruction
|
|
135
|
+
* the owner never gave (2026-10-18). An unreadable screen does not refuse. */
|
|
136
|
+
async function relaysSuggestion(target, text) {
|
|
137
|
+
let screen = "";
|
|
138
|
+
try {
|
|
139
|
+
screen = await terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 });
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
const shown = claudeSuggestionShown(screen);
|
|
145
|
+
// Case is kept (file and branch names differ by it); a leading voice marker says nothing about who wrote the words.
|
|
146
|
+
const plain = (value) => value.replace(/\s+/g, " ").trim().replace(/^\[voice\]\s*/i, "");
|
|
147
|
+
if (shown === undefined)
|
|
148
|
+
return false;
|
|
149
|
+
// A narrow pane cuts a long suggestion with "…": its visible part, with or without the mark, is all a screen read shows.
|
|
150
|
+
const words = plain(text), cut = shown.endsWith("…") ? plain(shown.slice(0, -1)) : undefined;
|
|
151
|
+
return words === plain(shown) || (cut !== undefined && (words === cut || words === `${cut}…` || words === `${cut} …`));
|
|
152
|
+
}
|
|
129
153
|
/** Herdr answered the request with a refusal (a 409 carrying its own error code): it performed nothing. */
|
|
130
154
|
const herdrRefused = (error) => error instanceof BridgeError && error.status === 409 && typeof error.details?.herdrCode === "string";
|
|
131
155
|
/** An idle agent that has not taken typed text within the first wait
|
|
@@ -151,6 +175,88 @@ async function resubmitIfIdle(agentHooks, target, text) {
|
|
|
151
175
|
return outcome;
|
|
152
176
|
return await status() === "working" ? "pending" : "unsubmitted";
|
|
153
177
|
}
|
|
178
|
+
/** A Claude pane showing a subagent's view (its empty input reads "Message
|
|
179
|
+
* @<agent>…") takes typed text for that subagent, so a phone message never
|
|
180
|
+
* reached the turn and failed when it ended (owner, 2026-10-21). Escape returns
|
|
181
|
+
* to the main view. It is pressed once, only while that view shows: in the main
|
|
182
|
+
* view Escape would interrupt the turn, so a view still showing after it is left
|
|
183
|
+
* as it is and logged. True when the view was left. */
|
|
184
|
+
export async function leaveClaudeSubagentView(agentHooks, target, waitMs = 250) {
|
|
185
|
+
if (target.source !== "claude")
|
|
186
|
+
return false;
|
|
187
|
+
const shows = async () => {
|
|
188
|
+
let screen;
|
|
189
|
+
try {
|
|
190
|
+
screen = await agentHooks.paneAnsi?.(target);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
screen = undefined;
|
|
194
|
+
}
|
|
195
|
+
return screen !== undefined && claudeSubagentView(screen);
|
|
196
|
+
};
|
|
197
|
+
if (!await shows())
|
|
198
|
+
return false;
|
|
199
|
+
process.stderr.write(`phren hook: ${target.server}:${target.pane} shows a subagent view; Escape back to the conversation before typing\n`);
|
|
200
|
+
await terminalProvider().sendKeys(target.server, target.pane, ["esc"]);
|
|
201
|
+
await sleep(waitMs);
|
|
202
|
+
if (!await shows())
|
|
203
|
+
return true;
|
|
204
|
+
process.stderr.write(`phren hook: ${target.server}:${target.pane} still shows a subagent view after Escape; not pressing it again\n`);
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
/** A phone message the turn ended without, in a Claude pane that now shows a
|
|
208
|
+
* subagent's view (opened while the message waited): leave the view and type
|
|
209
|
+
* it again under the same delivery id, once. Any other outcome, a changed
|
|
210
|
+
* pane, or ten minutes end the watch. */
|
|
211
|
+
export function retryAfterSubagentView(agentHooks, target, terminal, text, id, intervalMs = 2_000, limitMs = 600_000, escapeWaitMs = 250) {
|
|
212
|
+
const started = Date.now();
|
|
213
|
+
const look = async () => {
|
|
214
|
+
if (Date.now() - started > limitMs)
|
|
215
|
+
return;
|
|
216
|
+
const status = agentHooks.deliveries.status(id, target);
|
|
217
|
+
if (status.state !== "failed") {
|
|
218
|
+
if (status.state !== "delivered")
|
|
219
|
+
schedule();
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (status.reason !== TURN_ENDED_WITHOUT_IT)
|
|
223
|
+
return;
|
|
224
|
+
// The same conversation, as the route checks it: a /clear or /resume in the
|
|
225
|
+
// same terminal is another conversation, never given the old message.
|
|
226
|
+
// A refusal (409: the conversation changed or the pane went) ends the watch;
|
|
227
|
+
// a look that failed for now (a timeout) or an agent busy again waits.
|
|
228
|
+
let pane;
|
|
229
|
+
try {
|
|
230
|
+
pane = await validateTarget(target, true, true);
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
if (error instanceof BridgeError && error.status === 409)
|
|
234
|
+
return;
|
|
235
|
+
schedule();
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (!pane || pane.terminal_id !== terminal)
|
|
239
|
+
return;
|
|
240
|
+
if (!["idle", "done"].includes(String(pane.agent_status))) {
|
|
241
|
+
schedule();
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (!await leaveClaudeSubagentView(agentHooks, target, escapeWaitMs))
|
|
245
|
+
return;
|
|
246
|
+
// Checked again with nothing awaited before the record is replaced: a retry
|
|
247
|
+
// from the phone may have delivered it meanwhile.
|
|
248
|
+
const now = agentHooks.deliveries.status(id, target);
|
|
249
|
+
if (now.state !== "failed" || now.reason !== TURN_ENDED_WITHOUT_IT)
|
|
250
|
+
return;
|
|
251
|
+
process.stderr.write(`phren hook: retrying phone message ${id} in the conversation after leaving the subagent view\n`);
|
|
252
|
+
const expected = agentHooks.deliveries.expect(target, text, 1_500, undefined, id, typeof terminal === "string" ? terminal : undefined);
|
|
253
|
+
await terminalProvider().prompt(target.server, target.pane, text);
|
|
254
|
+
if (await expected === "pending")
|
|
255
|
+
await resubmitIfIdle(agentHooks, target, text);
|
|
256
|
+
};
|
|
257
|
+
const schedule = () => { const timer = setTimeout(() => void look().catch(() => undefined), intervalMs); timer.unref?.(); };
|
|
258
|
+
schedule();
|
|
259
|
+
}
|
|
154
260
|
/** A busy Claude Code queues typed text on Enter, but after a long paste
|
|
155
261
|
* ("paste again to expand") it can swallow that Enter and leave the text in
|
|
156
262
|
* its input line, where it stays after the turn ends. Follow the pane: once
|
|
@@ -402,6 +508,9 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
402
508
|
// A Claude lead waiting on its background agents takes a prompt though Herdr reads it working (`takesPrompt`).
|
|
403
509
|
if (data.hookQueued === true && !await takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)))
|
|
404
510
|
throw new BridgeError(409, "The worker is busy; the hand-off remains queued.", { code: "hand-off-busy" });
|
|
511
|
+
if (data.hookQueued === true && target.source === "claude" && typeof data.text === "string" && await relaysSuggestion(target, data.text)) {
|
|
512
|
+
throw new BridgeError(409, "That text is Claude's own suggested next prompt, drawn dim in the agent's empty input box. The owner did not send it, so it was not typed.", { code: "prompt-suggestion" });
|
|
513
|
+
}
|
|
405
514
|
if (status === "unknown" || (["blocked", "waiting"].includes(status) && (agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)))) {
|
|
406
515
|
throw new BridgeError(409, "This agent needs input in the terminal first.");
|
|
407
516
|
}
|
|
@@ -478,6 +587,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
478
587
|
try {
|
|
479
588
|
await typing();
|
|
480
589
|
typed = true;
|
|
590
|
+
await leaveClaudeSubagentView(agentHooks, target);
|
|
481
591
|
await terminalProvider().prompt(target.server, target.pane, text);
|
|
482
592
|
}
|
|
483
593
|
catch (error) {
|
|
@@ -508,6 +618,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
508
618
|
else
|
|
509
619
|
followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
|
|
510
620
|
}
|
|
621
|
+
if (deliveryId && target.source === "claude" && outcome !== "delivered")
|
|
622
|
+
retryAfterSubagentView(agentHooks, target, pane.terminal_id, text, deliveryId);
|
|
511
623
|
// A bare slash command opens the agent's own menu; the phone may
|
|
512
624
|
// walk it with keys for the next half minute. The command rides
|
|
513
625
|
// along so a Codex /permissions walk can find its confirmation.
|
|
@@ -117,6 +117,7 @@ export declare const capabilities: {
|
|
|
117
117
|
queuedHandOff: boolean;
|
|
118
118
|
approvalPush: string;
|
|
119
119
|
simulators: boolean;
|
|
120
|
+
simulatorStream: boolean;
|
|
120
121
|
code: boolean;
|
|
121
122
|
codeFiles: boolean;
|
|
122
123
|
overviewStream: boolean;
|
|
@@ -144,6 +145,7 @@ export declare const capabilities: {
|
|
|
144
145
|
moveConductor: boolean;
|
|
145
146
|
moveToComputer: boolean;
|
|
146
147
|
moveConductorToComputer: boolean;
|
|
148
|
+
moveResume: boolean;
|
|
147
149
|
claudeAccountAdd: boolean;
|
|
148
150
|
workerRelocation: number;
|
|
149
151
|
projectMemory: boolean;
|
|
@@ -89,7 +89,7 @@ async function childActivity(source, session) {
|
|
|
89
89
|
export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
90
90
|
terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
91
91
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
92
|
-
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, claudeAccountAdd: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
|
|
92
|
+
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, claudeAccountAdd: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
|
|
93
93
|
export function capabilitiesForModules(snapshot) {
|
|
94
94
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
95
95
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
package/dist/bridge/server.js
CHANGED
|
@@ -24,6 +24,7 @@ import { cpus, hostname, loadavg } from "node:os";
|
|
|
24
24
|
import path from "node:path";
|
|
25
25
|
import { WebSocketServer } from "ws";
|
|
26
26
|
import { relayLiveSpeech } from "./speech-live.js";
|
|
27
|
+
import { streamSimulator } from "./simulator-stream.js";
|
|
27
28
|
import { failRelay, relayTranscription } from "./speech-transcribe.js";
|
|
28
29
|
import { ActivityJournal } from "./activity.js";
|
|
29
30
|
import { countTick } from "./metrics.js";
|
|
@@ -56,7 +57,7 @@ import { typedMuxRequest } from "./mux-wire.js";
|
|
|
56
57
|
import { overviewStream } from "./server-overview.js";
|
|
57
58
|
import { transcriptStreams } from "./server-stream.js";
|
|
58
59
|
import { launchSession } from "./server-launch.js";
|
|
59
|
-
import { SessionMover, transcriptTail } from "./session-move.js";
|
|
60
|
+
import { copyClaudeConversation, SessionMover, transcriptTail } from "./session-move.js";
|
|
60
61
|
import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
|
|
61
62
|
import { paneAccount, paneAccountKey } from "./pane-accounts.js";
|
|
62
63
|
import { readTurn } from "./turn-records.js";
|
|
@@ -178,6 +179,7 @@ export async function serve(version, options = {}) {
|
|
|
178
179
|
launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
|
|
179
180
|
inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
|
|
180
181
|
transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
|
|
182
|
+
copyConversation: async (target, home, check) => copyClaudeConversation(await targetTranscriptPath(target), home, process.env, check),
|
|
181
183
|
paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
|
|
182
184
|
paneDispatch: async (server, pane) => {
|
|
183
185
|
const dispatch = (await readTurn(server, String(pane.pane_id)))?.dispatch;
|
|
@@ -279,7 +281,7 @@ export async function serve(version, options = {}) {
|
|
|
279
281
|
http.on("upgrade", (request, socket, head) => {
|
|
280
282
|
try {
|
|
281
283
|
const url = new URL(request.url || "/", "http://phren.local");
|
|
282
|
-
if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live"].includes(url.pathname) || url.origin !== "http://phren.local") {
|
|
284
|
+
if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream"].includes(url.pathname) || url.origin !== "http://phren.local") {
|
|
283
285
|
socket.destroy();
|
|
284
286
|
return;
|
|
285
287
|
}
|
|
@@ -304,6 +306,10 @@ export async function serve(version, options = {}) {
|
|
|
304
306
|
void relayTranscription(client, url.searchParams).catch(() => failRelay(client));
|
|
305
307
|
return;
|
|
306
308
|
}
|
|
309
|
+
if (url.pathname === "/v1/simulators/stream") {
|
|
310
|
+
void streamSimulator(client, url.searchParams).catch(() => client.close(1011, "Simulator stream unavailable"));
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
307
313
|
if (url.pathname === "/v1/speech/live") {
|
|
308
314
|
void relayLiveSpeech(client, url.searchParams).catch(() => client.close(1011, "Spoken replies unavailable"));
|
|
309
315
|
return;
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { Readable } from "node:stream";
|
|
2
|
+
import { type Json } from "./protocol.js";
|
|
3
|
+
/**
|
|
4
|
+
* `WS /v1/simulators/stream?udid=&fps=&size=&quality=`: one booted
|
|
5
|
+
* simulator's screen, live. The native helper (native/simcast.swift) reads the
|
|
6
|
+
* device's framebuffer through CoreSimulator, as `simctl io` does, and writes
|
|
7
|
+
* each changed frame as a length-prefixed JPEG; this side forwards them.
|
|
8
|
+
*
|
|
9
|
+
* Why JPEG frames from the framebuffer, not the alternatives:
|
|
10
|
+
* - `simctl io screenshot` took about 1.1 s a shot (Xcode 27.1, M1 Max),
|
|
11
|
+
* which is today's 1 fps poll and no more.
|
|
12
|
+
* - `simctl io recordVideo` writes a QuickTime movie that is only readable
|
|
13
|
+
* once finalized, so it cannot feed a live socket.
|
|
14
|
+
* - ScreenCaptureKit on the Simulator window needs a Screen Recording grant
|
|
15
|
+
* (which macOS re-asks for monthly), captures the window chrome, and stops
|
|
16
|
+
* when the window is minimized; the framebuffer needs no grant.
|
|
17
|
+
* - H.264 halves the bytes but ties frames together: a dropped frame corrupts
|
|
18
|
+
* the picture until the next keyframe, so "always the latest frame" would
|
|
19
|
+
* need keyframe requests across the socket. Every JPEG stands alone, so a
|
|
20
|
+
* frame the phone can't take yet is simply replaced by the next one.
|
|
21
|
+
* - The helper sends only frames whose framebuffer changed (its IOSurface
|
|
22
|
+
* seed moved): a still screen costs nothing on the wire.
|
|
23
|
+
*
|
|
24
|
+
* Frames: a text `{ type: "start", format: "jpeg", fps, size, quality, ack }`,
|
|
25
|
+
* then one binary message per frame, each a whole JPEG. A phone that asks
|
|
26
|
+
* with `ack=1` sends `{ type: "ack" }` for each frame it receives, and at
|
|
27
|
+
* most two frames are unacknowledged: the SSH channel and TCP buffers between
|
|
28
|
+
* here and the phone then never hold more than that, so what the phone shows
|
|
29
|
+
* is at most two frames old however slow the link. Without it, a frame is
|
|
30
|
+
* done once written to the gateway's socket. When the stream
|
|
31
|
+
* ends, the socket closes with the reason (1008 for a bad request, 1011 when
|
|
32
|
+
* capture failed); the phone then falls back to `/v1/simulators/screenshot`.
|
|
33
|
+
* Closing the socket stops the helper. Taps and keys stay on
|
|
34
|
+
* `/v1/simulators/action`.
|
|
35
|
+
*/
|
|
36
|
+
/** A JPEG larger than this is a broken helper, not a frame. */
|
|
37
|
+
export declare const MAX_FRAME_BYTES: number;
|
|
38
|
+
/** The wire budget: about 24 Mbit/s, so animations at full rate on Wi-Fi, and
|
|
39
|
+
* the phone asks for a smaller `size` on a slower link. */
|
|
40
|
+
export declare const STREAM_BYTES_PER_SECOND: number;
|
|
41
|
+
/** Each stream runs its own helper; a few phones may watch at once. */
|
|
42
|
+
export declare const MAX_STREAMS = 4;
|
|
43
|
+
export interface StreamOptions {
|
|
44
|
+
udid: string;
|
|
45
|
+
fps: number;
|
|
46
|
+
size: number;
|
|
47
|
+
quality: number;
|
|
48
|
+
ack: boolean;
|
|
49
|
+
}
|
|
50
|
+
/** Frames in flight when the phone acknowledges them: one decoding on the
|
|
51
|
+
* phone while the next crosses the network. */
|
|
52
|
+
export declare const ACK_WINDOW = 2;
|
|
53
|
+
/** The query, validated before anything runs. */
|
|
54
|
+
export declare function streamOptions(query: URLSearchParams): StreamOptions;
|
|
55
|
+
/** Splits the helper's stdout into frames: a 4-byte big-endian length, then
|
|
56
|
+
* that many bytes. Pipes deliver arbitrary chunks, so a frame may span many. */
|
|
57
|
+
export declare class FrameReader {
|
|
58
|
+
private buffered;
|
|
59
|
+
private bytes;
|
|
60
|
+
push(chunk: Buffer): Buffer[];
|
|
61
|
+
}
|
|
62
|
+
/** Sends the newest frame only. At most `window` frames are in flight (until
|
|
63
|
+
* written, or until acknowledged when `acked`); frames that arrive meanwhile
|
|
64
|
+
* replace the one waiting, so a slow link sees fewer frames, never older
|
|
65
|
+
* ones. A byte budget, refilled continuously with one second of burst, bounds
|
|
66
|
+
* the bitrate the same way. */
|
|
67
|
+
export declare class LatestFrame {
|
|
68
|
+
private send;
|
|
69
|
+
private options;
|
|
70
|
+
private now;
|
|
71
|
+
private waiting?;
|
|
72
|
+
private inFlight;
|
|
73
|
+
private tokens;
|
|
74
|
+
private refilled;
|
|
75
|
+
private timer?;
|
|
76
|
+
private closed;
|
|
77
|
+
sent: number;
|
|
78
|
+
dropped: number;
|
|
79
|
+
constructor(send: (frame: Buffer, done: (error?: Error) => void) => void, options?: {
|
|
80
|
+
bytesPerSecond?: number;
|
|
81
|
+
window?: number;
|
|
82
|
+
acked?: boolean;
|
|
83
|
+
}, now?: () => number);
|
|
84
|
+
offer(frame: Buffer): void;
|
|
85
|
+
/** The phone has a frame; an acknowledgement it owes nothing for is ignored. */
|
|
86
|
+
ack(): void;
|
|
87
|
+
close(): void;
|
|
88
|
+
private get bytesPerSecond();
|
|
89
|
+
private pump;
|
|
90
|
+
}
|
|
91
|
+
/** The phone's socket, or a test double. */
|
|
92
|
+
export interface StreamClient {
|
|
93
|
+
readonly readyState: number;
|
|
94
|
+
send(data: string | Buffer, options: {
|
|
95
|
+
binary: boolean;
|
|
96
|
+
}, done?: (error?: Error) => void): void;
|
|
97
|
+
close(code?: number, reason?: string): void;
|
|
98
|
+
once(event: "close" | "error", listener: () => void): unknown;
|
|
99
|
+
on(event: "message", listener: (data: Buffer, isBinary: boolean) => void): unknown;
|
|
100
|
+
}
|
|
101
|
+
/** The capture process, or a test double. */
|
|
102
|
+
export interface CaptureProcess {
|
|
103
|
+
readonly stdout: Readable | null;
|
|
104
|
+
readonly stderr: Readable | null;
|
|
105
|
+
kill(signal?: NodeJS.Signals): boolean;
|
|
106
|
+
once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown;
|
|
107
|
+
once(event: "error", listener: (error: Error) => void): unknown;
|
|
108
|
+
}
|
|
109
|
+
export interface StreamDeps {
|
|
110
|
+
booted: () => Promise<Json[]>;
|
|
111
|
+
helper: () => Promise<string>;
|
|
112
|
+
spawn: (binary: string, args: string[]) => CaptureProcess;
|
|
113
|
+
platform: () => NodeJS.Platform;
|
|
114
|
+
bytesPerSecond?: number;
|
|
115
|
+
}
|
|
116
|
+
/** Streams running now, for tests and health. */
|
|
117
|
+
export declare function activeSimulatorStreams(): number;
|
|
118
|
+
export declare function streamSimulator(client: StreamClient, query: URLSearchParams, deps?: StreamDeps): Promise<void>;
|