@phren/cli 0.3.58 → 0.3.59
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/README.md +1 -1
- package/dist/bridge/account-add.d.ts +30 -0
- package/dist/bridge/account-add.js +125 -19
- package/dist/bridge/account-failover.d.ts +9 -2
- package/dist/bridge/account-failover.js +1 -1
- package/dist/bridge/account-policy.d.ts +44 -0
- package/dist/bridge/account-policy.js +103 -0
- package/dist/bridge/account-pools.d.ts +35 -0
- package/dist/bridge/account-pools.js +171 -0
- package/dist/bridge/account-usage.d.ts +18 -0
- package/dist/bridge/account-usage.js +57 -1
- package/dist/bridge/agent-hook-callback.d.ts +6 -0
- package/dist/bridge/agent-hook-callback.js +10 -2
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +13 -0
- package/dist/bridge/agent-hooks.d.ts +12 -2
- package/dist/bridge/agent-hooks.js +41 -4
- package/dist/bridge/claude-account-setup.d.ts +16 -0
- package/dist/bridge/claude-account-setup.js +46 -2
- package/dist/bridge/claude-accounts.d.ts +9 -0
- package/dist/bridge/claude-accounts.js +53 -15
- package/dist/bridge/claude-credits.d.ts +5 -1
- package/dist/bridge/claude-credits.js +37 -29
- package/dist/bridge/command.js +12 -3
- package/dist/bridge/dispatch-command.js +22 -0
- package/dist/bridge/dispatch-returns.d.ts +23 -0
- package/dist/bridge/dispatch-returns.js +57 -0
- package/dist/bridge/dispatch.d.ts +26 -4
- package/dist/bridge/dispatch.js +100 -11
- package/dist/bridge/git-host-gitlab.js +2 -1
- package/dist/bridge/hand-off-queue.d.ts +71 -0
- package/dist/bridge/hand-off-queue.js +38 -0
- package/dist/bridge/harnesses.d.ts +12 -0
- package/dist/bridge/harnesses.js +20 -4
- package/dist/bridge/helper.d.ts +54 -0
- package/dist/bridge/helper.js +186 -0
- package/dist/bridge/herdr.js +6 -2
- package/dist/bridge/hook-fast.d.ts +3 -0
- package/dist/bridge/hook-fast.js +10 -2
- package/dist/bridge/move-computers.d.ts +15 -1
- package/dist/bridge/move-computers.js +123 -26
- package/dist/bridge/prompt-deliveries.d.ts +29 -1
- package/dist/bridge/prompt-deliveries.js +146 -10
- package/dist/bridge/schedule-watch.js +17 -3
- package/dist/bridge/server-routes.d.ts +3 -0
- package/dist/bridge/server-routes.js +66 -6
- package/dist/bridge/server.js +2 -1
- package/dist/bridge/session-move.d.ts +59 -1
- package/dist/bridge/session-move.js +266 -18
- package/dist/bridge/simulators.d.ts +19 -0
- package/dist/bridge/simulators.js +93 -13
- package/dist/bridge/speech-live.js +132 -22
- package/dist/bridge/task-routes.d.ts +16 -16
- package/dist/bridge/terminal-herdr.js +6 -1
- package/dist/bridge/terminal-tmux.js +9 -5
- package/dist/bridge/terminal.d.ts +9 -2
- package/dist/bridge/transcript-claude.d.ts +3 -0
- package/dist/bridge/transcript-claude.js +175 -29
- package/dist/bridge/transcript-preview.d.ts +11 -2
- package/dist/bridge/transcript-preview.js +90 -8
- package/dist/bridge/turn-records.d.ts +19 -0
- package/dist/bridge/turn-records.js +78 -3
- package/dist/bridge-hook.mjs +11394 -9961
- package/dist/cli-registry.js +2 -2
- package/dist/content/citation.d.ts +4 -0
- package/dist/content/citation.js +21 -21
- package/dist/data/task-contract.d.ts +4 -4
- package/dist/governance/policy.js +5 -2
- package/dist/index.js +1 -1
- package/dist/modules/registry.js +3 -3
- package/dist/project-config.d.ts +14 -0
- package/dist/project-config.js +40 -1
- package/dist/tools/helper.d.ts +3 -0
- package/dist/tools/helper.js +44 -0
- package/package.json +1 -1
|
@@ -35,7 +35,7 @@ import { hasUsable } from "./harnesses.js";
|
|
|
35
35
|
import { findPane } from "./herdr.js";
|
|
36
36
|
import { briefArrival, briefId, briefRoot, assertUnusedLaunchId, writeLaunchBrief } from "./launch-brief.js";
|
|
37
37
|
import { atomic, BridgeError, bridgeRoot, object, startingTargetSchema, targetSchema } from "./protocol.js";
|
|
38
|
-
import { publicAssistant } from "./schedule-watch.js";
|
|
38
|
+
import { finalTurnFromLines, isClaudeUsageLimit, publicAssistant } from "./schedule-watch.js";
|
|
39
39
|
const run = promisify(execFile);
|
|
40
40
|
export { moveToSchema };
|
|
41
41
|
export const moveRequestSchema = z.object({
|
|
@@ -45,8 +45,10 @@ export const moveRequestSchema = z.object({
|
|
|
45
45
|
/** `resume` switches a Claude conversation to another account on this
|
|
46
46
|
* computer without a hand-off: the transcript is copied into the target
|
|
47
47
|
* account's home and the same conversation resumes there (`claude --resume`),
|
|
48
|
-
* so an account at its usage limit can still switch.
|
|
49
|
-
|
|
48
|
+
* so an account at its usage limit can still switch. `summary-by-target` (a move to another computer):
|
|
49
|
+
* the source is not asked for a hand-off; the new agent there builds one from the copied conversation.
|
|
50
|
+
* A source whose last turn ended on its usage limit is moved this way without asking. */
|
|
51
|
+
continuation: z.enum(["handoff", "resume", "summary-by-target"]).default("handoff"),
|
|
50
52
|
/** Kept on a retry: the same id returns the move already under way. */
|
|
51
53
|
id: z.string().uuid().optional(),
|
|
52
54
|
/** How long the agent gets to write its hand-off before Phren builds one. */
|
|
@@ -65,7 +67,9 @@ const moveRecordSchema = z.object({
|
|
|
65
67
|
accountChoice: z.string().max(400).optional(),
|
|
66
68
|
project: projectName.optional(),
|
|
67
69
|
mode: z.enum(["replace", "new-chat"]).optional(),
|
|
68
|
-
|
|
70
|
+
/** `resume`: the same conversation under another account here. `summary-by-target`: the source was out of
|
|
71
|
+
* usage, so the agent on the other computer builds the hand-off from the copied conversation. */
|
|
72
|
+
continuation: z.enum(["resume", "summary-by-target"]).optional(),
|
|
69
73
|
modeForced: z.literal("conductor").optional(),
|
|
70
74
|
handedOffTo: z.object({ computer: z.string().optional(), target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
|
|
71
75
|
handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
|
|
@@ -88,6 +92,15 @@ const moveRecordSchema = z.object({
|
|
|
88
92
|
/** The slash command each harness ends its interactive session with. */
|
|
89
93
|
const EXIT_COMMANDS = { claude: "/exit", codex: "/quit", copilot: "/exit", opencode: "/exit", phren: "/exit" };
|
|
90
94
|
const HARNESS_NAMES = { claude: "Claude", codex: "Codex", opencode: "OpenCode", copilot: "Copilot", phren: "phren agent" };
|
|
95
|
+
/** Refuses a Claude account on this computer that the pools of the pane's project or this computer rule out. */
|
|
96
|
+
async function refuseOutsidePools(pane, account) {
|
|
97
|
+
const cwd = String(pane.foreground_cwd || pane.cwd || "");
|
|
98
|
+
if (!path.isAbsolute(cwd))
|
|
99
|
+
return;
|
|
100
|
+
const refused = await (await import("./move-computers.js")).localPoolRefusal(cwd, account);
|
|
101
|
+
if (refused)
|
|
102
|
+
throw new BridgeError(409, `Claude account ${account} may not take this session: ${refused}.`, { code: "account_pool" });
|
|
103
|
+
}
|
|
91
104
|
const MOVE_KEEP_MS = 7 * 24 * 60 * 60 * 1000;
|
|
92
105
|
const MAX_MOVES = 256;
|
|
93
106
|
const MAX_RECORD_BYTES = 32_768;
|
|
@@ -110,6 +123,16 @@ async function saveMove(record) {
|
|
|
110
123
|
writes = run.catch(() => undefined);
|
|
111
124
|
return run;
|
|
112
125
|
}
|
|
126
|
+
/** The mark that a move's agent was sent its one Escape, beside the move's record, so a Hook restart does not
|
|
127
|
+
* send a second. Written before the key goes: a crash between the two counts as sent. */
|
|
128
|
+
const interruptFile = (id) => path.join(movesRoot(), `${z.string().uuid().parse(id)}.interrupted`);
|
|
129
|
+
async function markInterrupted(id) {
|
|
130
|
+
await mkdir(movesRoot(), { recursive: true, mode: 0o700 });
|
|
131
|
+
await atomic(interruptFile(id), { at: new Date().toISOString() });
|
|
132
|
+
}
|
|
133
|
+
const interruptMarked = (id) => lstat(interruptFile(id)).then(info => info.isFile(), () => false);
|
|
134
|
+
/** How long after the interrupt's Escape the move's own exit waits before sending another. */
|
|
135
|
+
const INTERRUPT_SETTLE_MS = 5_000;
|
|
113
136
|
export async function readMove(id) {
|
|
114
137
|
const file = recordFile(id);
|
|
115
138
|
if (landedMoves.has(file))
|
|
@@ -131,7 +154,7 @@ export async function listMoves(now = Date.now()) {
|
|
|
131
154
|
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
132
155
|
const settled = (record) => record.state === "moved" || record.state === "failed";
|
|
133
156
|
const stale = records.filter((record, index) => settled(record) && (index >= MAX_MOVES || now - Date.parse(record.updatedAt) > MOVE_KEEP_MS));
|
|
134
|
-
await Promise.all(stale.
|
|
157
|
+
await Promise.all(stale.flatMap(record => [recordFile(record.id), interruptFile(record.id)].map(file => rm(file, { force: true }).catch(() => undefined))));
|
|
135
158
|
return records.filter(record => !stale.includes(record));
|
|
136
159
|
}
|
|
137
160
|
/** The move that took the agent out of `target`'s pane: a target with a
|
|
@@ -364,6 +387,70 @@ export function fallbackHandoff(input) {
|
|
|
364
387
|
// Written to a file, so the brief is never cut here.
|
|
365
388
|
return input.original ? withOriginalBrief(head, input.original, Number.MAX_SAFE_INTEGER, "the original brief file") : head;
|
|
366
389
|
}
|
|
390
|
+
/** Whether a Claude conversation's last turn ended on its subscription's usage limit (Claude's own
|
|
391
|
+
* rate-limit row): its agent cannot answer a hand-off request. */
|
|
392
|
+
export function sourceOutOfUsage(lines, source) {
|
|
393
|
+
return source === "claude" && isClaudeUsageLimit(finalTurnFromLines(lines, "claude").error);
|
|
394
|
+
}
|
|
395
|
+
/** Room left in a cross-computer brief for the copied conversation, once the rest of the hand-off is in. */
|
|
396
|
+
const TRANSCRIPT_MARGIN = 2_000;
|
|
397
|
+
/** What of the original dispatch brief is kept ahead of the conversation: the oldest turns, which state the task, go first. */
|
|
398
|
+
const ORIGINAL_RESERVE = 8_000;
|
|
399
|
+
/**
|
|
400
|
+
* The hand-off for a source that does not write one (its account is out of usage, or the owner asked), for a
|
|
401
|
+
* fresh agent on the target computer to build itself: what happened, then as much of the conversation as fits
|
|
402
|
+
* in `room` characters, newest messages kept, oldest first. The target agent writes its own summary from it first.
|
|
403
|
+
*/
|
|
404
|
+
export function targetSummaryBody(input) {
|
|
405
|
+
const head = [
|
|
406
|
+
input.exhausted
|
|
407
|
+
? `The previous agent (${input.from}) is out of usage on its account, so it could not write a hand-off. Phren copied its conversation instead, below, for you to build one from.`
|
|
408
|
+
: `The owner moved the previous agent (${input.from}) here without asking it for a hand-off. Phren copied its conversation instead, below, for you to build one from.`,
|
|
409
|
+
"",
|
|
410
|
+
"First, from this conversation, write yourself a short hand-off: the owner's goal, what is done, what is half done, and the next steps. Then check this checkout against it and continue from there; do not start over.",
|
|
411
|
+
"",
|
|
412
|
+
...(input.dispatch ? [`It was working on dispatch ${input.dispatch}${input.label ? ` ("${input.label}")` : ""}.`, ""] : []),
|
|
413
|
+
];
|
|
414
|
+
const summary = (kept) => `The last ${kept} of its ${input.entries.length} messages, oldest first:`;
|
|
415
|
+
const kept = [];
|
|
416
|
+
// The original brief as it will be sent (redacted, paths replaced) and only then cut to its share, so a cut
|
|
417
|
+
// never lands inside a credential the redaction had to see whole.
|
|
418
|
+
const sentOriginal = input.original === undefined ? undefined : input.prepare ? input.prepare(input.original) : input.original;
|
|
419
|
+
const capNote = `\n[The original brief was cut to ${ORIGINAL_RESERVE} characters; the full text is in the dispatching computer's brief.]`;
|
|
420
|
+
const original = sentOriginal === undefined || sentOriginal.length <= ORIGINAL_RESERVE ? sentOriginal
|
|
421
|
+
: `${sentOriginal.slice(0, ORIGINAL_RESERVE - capNote.length)}${capNote}`;
|
|
422
|
+
// The list's own heading, and room for the original brief and its cut note, are counted up front.
|
|
423
|
+
const reserve = original ? original.length + 200 : 0;
|
|
424
|
+
let used = head.join("\n").length + summary(input.entries.length).length + 2 + reserve;
|
|
425
|
+
for (const entry of [...input.entries].reverse()) {
|
|
426
|
+
// One long message never takes the whole room: its end is what was said last.
|
|
427
|
+
const sent = input.prepare ? input.prepare(entry.text) : entry.text;
|
|
428
|
+
const text = sent.length > 6_000 ? `…${sent.slice(-6_000)}` : sent;
|
|
429
|
+
const block = quoted(entry.role === "owner" ? "Prompt to it" : "Its reply", text);
|
|
430
|
+
const size = block.join("\n").length + 1;
|
|
431
|
+
if (used + size > input.room)
|
|
432
|
+
break;
|
|
433
|
+
kept.unshift(block);
|
|
434
|
+
used += size;
|
|
435
|
+
}
|
|
436
|
+
const lines = [...head];
|
|
437
|
+
if (!kept.length)
|
|
438
|
+
lines.push(input.entries.length ? "Its conversation did not fit beside the rest of this hand-off; ask the owner where it stood." : "Its conversation could not be read; ask the owner where it stood.", "");
|
|
439
|
+
else
|
|
440
|
+
lines.push(summary(kept.length), "", ...kept.flat());
|
|
441
|
+
const body = lines.join("\n");
|
|
442
|
+
// The original brief takes what room is left, cut with a note when it doesn't fit.
|
|
443
|
+
return original ? withOriginalBrief(body, original, input.room, "the dispatching computer's brief") : body;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* The prompt another computer gets: full inline text only, since the peer cannot read this Hook's brief path.
|
|
447
|
+
* Commit ids and the complete hand-off are kept, credentials redacted in place rather than through the lossy
|
|
448
|
+
* approval/log summarizer.
|
|
449
|
+
*/
|
|
450
|
+
function peerPrompt(record, document) {
|
|
451
|
+
const safeDocument = document.replaceAll(record.cwd, "<source checkout>");
|
|
452
|
+
return redactPeerHandoff(briefText(`Continue the owner's work from this hand-off. This is a different checkout: local uncommitted files and running processes were not copied. Check its branch and files before proceeding.\n\n${safeDocument}`));
|
|
453
|
+
}
|
|
367
454
|
/** The hand-off file: who moved where and when, the body, then what Phren saw. */
|
|
368
455
|
export function handoffDocument(record, body, observed, at, conductor = false) {
|
|
369
456
|
return [
|
|
@@ -399,11 +486,26 @@ const DEFAULT_HANDOFF_MS = 240_000;
|
|
|
399
486
|
export class SessionMover {
|
|
400
487
|
deps;
|
|
401
488
|
cancelled = new Set();
|
|
489
|
+
/** Moves this process is waiting on: their hand-off request was handed to the queue, and the wait for the
|
|
490
|
+
* agent's answer is not over (it answered, the wait ran out, or the owner aborted). Only these are interrupted:
|
|
491
|
+
* a move whose request was never sent (summary-by-target, or not yet), or one this process no longer runs
|
|
492
|
+
* (the Hook restarted), has no request an Escape would let in. */
|
|
493
|
+
asking = new Set();
|
|
494
|
+
/** Per move, the hand-off's end and an interrupt's check-and-send, one at a time. */
|
|
495
|
+
lifecycles = new Map();
|
|
402
496
|
admissions = new Set();
|
|
403
497
|
running = new Map();
|
|
404
498
|
constructor(deps) {
|
|
405
499
|
this.deps = deps;
|
|
406
500
|
}
|
|
501
|
+
lifecycle(id, work) {
|
|
502
|
+
const result = (this.lifecycles.get(id) ?? Promise.resolve()).then(work);
|
|
503
|
+
const tail = result.catch(() => undefined);
|
|
504
|
+
this.lifecycles.set(id, tail);
|
|
505
|
+
void tail.then(() => { if (this.lifecycles.get(id) === tail)
|
|
506
|
+
this.lifecycles.delete(id); });
|
|
507
|
+
return result;
|
|
508
|
+
}
|
|
407
509
|
get now() { return (this.deps.now ?? Date.now)(); }
|
|
408
510
|
sleep(ms) { return (this.deps.sleep ?? (value => new Promise(resolve => setTimeout(resolve, value))))(ms); }
|
|
409
511
|
get poll() { return this.deps.pollMs ?? 2_000; }
|
|
@@ -445,6 +547,9 @@ export class SessionMover {
|
|
|
445
547
|
const to = { ...data.to };
|
|
446
548
|
if (!peer)
|
|
447
549
|
delete to.computer;
|
|
550
|
+
// Another computer's agent builds the hand-off; on this one, an exhausted account switches with `resume`.
|
|
551
|
+
if (data.continuation === "summary-by-target" && !peer)
|
|
552
|
+
throw new BridgeError(409, "summary-by-target continues on another computer; on this one, switch accounts with continuation resume.");
|
|
448
553
|
const active = (await listMoves(this.now)).find(record => record.from.target.server === target.server && record.from.target.pane === target.pane
|
|
449
554
|
&& record.state !== "moved" && record.state !== "failed");
|
|
450
555
|
if (active || [...this.running.keys()].some(key => key === `${target.server}\0${target.pane}`))
|
|
@@ -489,6 +594,7 @@ export class SessionMover {
|
|
|
489
594
|
throw new BridgeError(400, "Choose another Claude account to switch to.");
|
|
490
595
|
if (!claudeHome(to.account))
|
|
491
596
|
throw new BridgeError(409, `No Claude account "${to.account}" on this computer.`, { code: "account_unavailable" });
|
|
597
|
+
await refuseOutsidePools(pane, to.account);
|
|
492
598
|
if (!this.deps.copyConversation)
|
|
493
599
|
throw new BridgeError(503, "This Hook cannot switch accounts.");
|
|
494
600
|
await this.deps.copyConversation(target, claudeHome(to.account), true);
|
|
@@ -505,6 +611,10 @@ export class SessionMover {
|
|
|
505
611
|
const cwd = String(pane.foreground_cwd || pane.cwd || "");
|
|
506
612
|
if (!path.isAbsolute(cwd))
|
|
507
613
|
throw new BridgeError(409, "The pane's folder is unknown, so the new agent could not start there.");
|
|
614
|
+
// A Claude account named on this computer keeps to the pools too (a peer's is checked by checkMovePeer).
|
|
615
|
+
// Unnamed, the new Claude runs under the pane's own account (relaunch), else default: that one is checked.
|
|
616
|
+
if (!peer && data.continuation !== "resume" && to.harness === "claude")
|
|
617
|
+
await refuseOutsidePools(pane, to.account ?? account ?? DEFAULT_ACCOUNT);
|
|
508
618
|
let project;
|
|
509
619
|
let accountChoice;
|
|
510
620
|
let computerId;
|
|
@@ -541,7 +651,7 @@ export class SessionMover {
|
|
|
541
651
|
const at = new Date(this.now).toISOString();
|
|
542
652
|
const resume = data.continuation === "resume";
|
|
543
653
|
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 } : {}),
|
|
654
|
+
...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(resume ? { continuation: "resume" } : data.continuation === "summary-by-target" ? { continuation: "summary-by-target" } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
|
|
545
655
|
...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}), ...(workerDispatch ? { workerDispatch } : {}) };
|
|
546
656
|
await assertUnusedLaunchId(record.id);
|
|
547
657
|
if (conductor && peer) {
|
|
@@ -570,12 +680,53 @@ export class SessionMover {
|
|
|
570
680
|
const pids = pane ? (await this.deps.terminal.processes(from.server, from.pane).catch(() => undefined))?.foregroundPids ?? [] : [];
|
|
571
681
|
const [git, processes] = await Promise.all([(this.deps.git ?? readGitState)(record.cwd).catch(() => undefined),
|
|
572
682
|
(this.deps.processesBelow ?? processesBelow)(pids).catch(() => [])]);
|
|
573
|
-
|
|
574
|
-
const
|
|
575
|
-
const
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
683
|
+
// A source out of usage cannot answer a hand-off request: on another computer, the new agent builds it.
|
|
684
|
+
const requested = record.continuation === "summary-by-target";
|
|
685
|
+
const lines = peer ? await this.deps.transcript(from).catch(() => undefined) : [];
|
|
686
|
+
// Asked for by name, the move never launches an agent with no conversation to build from.
|
|
687
|
+
if (requested && !lines?.length)
|
|
688
|
+
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.");
|
|
689
|
+
const exhausted = !!peer && sourceOutOfUsage(lines ?? [], from.source);
|
|
690
|
+
const byTarget = !!peer && (requested || exhausted);
|
|
691
|
+
if (byTarget && !requested)
|
|
692
|
+
await this.update(record, { continuation: "summary-by-target" });
|
|
693
|
+
const written = byTarget ? { reason: `${exhausted ? "its account is out of usage" : "the owner asked"}, so the agent on ${peer.name} builds the hand-off from the copied conversation.` }
|
|
694
|
+
: await this.askForHandoff(record, handoffMs);
|
|
695
|
+
// The wait is over. Its request, if still untyped, is taken back first: typed later it would ask the old
|
|
696
|
+
// agent (left running by a new-chat move) for a hand-off nobody reads. Then an interrupt already checking
|
|
697
|
+
// finishes, and none starts after (the move goes on to exit or launch, where an Escape would hit the exit
|
|
698
|
+
// command or the agent's last turn).
|
|
699
|
+
if (this.asking.has(record.id))
|
|
700
|
+
await this.withdrawRequest(record, "The move stopped waiting for this hand-off.");
|
|
701
|
+
await this.lifecycle(record.id, async () => { this.asking.delete(record.id); });
|
|
702
|
+
const observed = observedState(git, processes, !peer), at = new Date(this.now).toISOString();
|
|
703
|
+
let body;
|
|
704
|
+
if (byTarget) {
|
|
705
|
+
const original = record.dispatch ? await this.deps.brief?.(record.dispatch).catch(() => undefined) : undefined;
|
|
706
|
+
const entries = conversationEntries(lines ?? [], from.source);
|
|
707
|
+
const fit = (room) => targetSummaryBody({ from: harnessName({ harness: from.source, account: record.from.account }), exhausted,
|
|
708
|
+
entries, room, prepare: text => redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>")), ...(original ? { original } : {}),
|
|
709
|
+
...(record.dispatch ? { dispatch: record.dispatch } : {}), ...(record.from.label ? { label: record.from.label } : {}) });
|
|
710
|
+
// What fits beside the rest of the hand-off in the one brief the other computer gets, measured as sent:
|
|
711
|
+
// the checkout path replaced and credentials redacted, either of which can lengthen the text. Messages
|
|
712
|
+
// are prepared that way before they are counted; the refit only catches what the rest of the brief adds.
|
|
713
|
+
let room = PROMPT_LIMIT - peerPrompt(record, handoffDocument(record, "", observed, at, !!conductor)).length - TRANSCRIPT_MARGIN;
|
|
714
|
+
body = fit(room);
|
|
715
|
+
for (let tries = 0; tries < 4; tries++) {
|
|
716
|
+
const over = peerPrompt(record, handoffDocument(record, body, observed, at, !!conductor)).length - PROMPT_LIMIT;
|
|
717
|
+
if (over <= 0)
|
|
718
|
+
break;
|
|
719
|
+
room -= over + 500;
|
|
720
|
+
body = fit(room);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
const fallback = "text" in written ? undefined : await this.fallback(record, written.reason);
|
|
725
|
+
body = "text" in written ? written.text : record.mode === "new-chat"
|
|
726
|
+
? `## 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.`
|
|
727
|
+
: fallback;
|
|
728
|
+
}
|
|
729
|
+
const document = handoffDocument(record, body, observed, at, !!conductor);
|
|
579
730
|
await this.assertNotAborted(record);
|
|
580
731
|
const file = handoffPath(record.id);
|
|
581
732
|
const prompt = briefText(continuePrompt(document, file));
|
|
@@ -653,6 +804,12 @@ export class SessionMover {
|
|
|
653
804
|
}
|
|
654
805
|
catch (error) {
|
|
655
806
|
const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
|
|
807
|
+
// A wait that failed (the pane went missing for a moment, Herdr did not answer) leaves the old agent running
|
|
808
|
+
// with the request still queued for it: taken back, as when the wait ends, and no interrupt after.
|
|
809
|
+
if (this.asking.has(record.id)) {
|
|
810
|
+
await this.withdrawRequest(record, "The move failed before the agent wrote its hand-off.");
|
|
811
|
+
await this.lifecycle(record.id, async () => { this.asking.delete(record.id); });
|
|
812
|
+
}
|
|
656
813
|
if (roleTransferred) {
|
|
657
814
|
// update() has already populated the complete moved record. The role
|
|
658
815
|
// and worker routes committed; a later status save cannot undo them.
|
|
@@ -684,6 +841,72 @@ export class SessionMover {
|
|
|
684
841
|
logger.warn("move", `Moving pane ${from.pane} to ${record.to.harness} failed: ${message}`);
|
|
685
842
|
}
|
|
686
843
|
}
|
|
844
|
+
/**
|
|
845
|
+
* "Stop <agent> and hand off now": Escape to the old agent only while the move's hand-off request is
|
|
846
|
+
* still held for it (queued behind the step it is on, not yet typed), so the step stops and the request
|
|
847
|
+
* goes in, and never into the hand-off the agent is writing. Checked and sent under the hand-off queue's
|
|
848
|
+
* lock (`whileQueued`), which is what types the request, and under the move's own lifecycle lock, which is
|
|
849
|
+
* what ends the hand-off wait: the move cannot go on to exit or launch between the check and the key.
|
|
850
|
+
* `state` says why it did not: the request is being or was typed (`typed`), the agent is writing its
|
|
851
|
+
* hand-off (`writing`), the move is past it, or the pane runs another agent now (`replaced`).
|
|
852
|
+
*/
|
|
853
|
+
async interrupt(id, queue, escape) {
|
|
854
|
+
const record = await readMove(id);
|
|
855
|
+
if (!record)
|
|
856
|
+
throw new BridgeError(404, "No move with that id is recorded.");
|
|
857
|
+
if (record.state !== "handing-off" || !this.asking.has(id))
|
|
858
|
+
return { interrupted: false, state: "finished" };
|
|
859
|
+
// Without the queue the request was typed the moment it was sent: it is never held.
|
|
860
|
+
if (!queue)
|
|
861
|
+
return { interrupted: false, state: "typed" };
|
|
862
|
+
const from = record.from.target;
|
|
863
|
+
let answer = { interrupted: true };
|
|
864
|
+
const result = await queue.whileQueued(`move-${id}`, from, row => this.lifecycle(id, async () => {
|
|
865
|
+
// A move that left the hand-off (it answered, timed out and is exiting, or was aborted) needs no Escape.
|
|
866
|
+
if ((await readMove(id))?.state !== "handing-off" || !this.asking.has(id)) {
|
|
867
|
+
answer = { interrupted: false, state: "finished" };
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
// No request waiting yet: there is nothing an Escape would let in.
|
|
871
|
+
if (!row) {
|
|
872
|
+
answer = { interrupted: false, state: "idle" };
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
// One Escape per move, across Hook restarts: a second (a double tap, a retry) would land on the stopped
|
|
876
|
+
// agent's empty input, where Claude and Codex take Esc Esc as "go back to an earlier message".
|
|
877
|
+
if (await interruptMarked(id))
|
|
878
|
+
return;
|
|
879
|
+
// An agent not on a step has nothing to stop: its request goes in at the queue's next look.
|
|
880
|
+
const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
|
|
881
|
+
if (!pane || !["working", "blocked", "waiting", "unknown"].includes(String(pane.agent_status))) {
|
|
882
|
+
answer = { interrupted: false, state: "idle" };
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
// Only the agent the request is for: the same harness, terminal and conversation (the one the queued row
|
|
886
|
+
// followed to, when the pane's conversation changed in the same terminal). The owner may have started
|
|
887
|
+
// another in the pane since; one whose conversation can't be read is not taken for it.
|
|
888
|
+
const session = await this.deps.identity(from.server, pane).catch(() => undefined);
|
|
889
|
+
const wanted = row.session ?? from.session;
|
|
890
|
+
if (pane.agent !== from.source || (wanted && session !== wanted)
|
|
891
|
+
|| (typeof pane.terminal_id === "string" && pane.terminal_id !== row.terminal)) {
|
|
892
|
+
answer = { interrupted: false, state: "replaced" };
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
// Marked before it goes, so a crash after the key counts as sent; an Escape known to have failed
|
|
896
|
+
// clears the mark, leaving the next tap free to try again.
|
|
897
|
+
await markInterrupted(id);
|
|
898
|
+
try {
|
|
899
|
+
await (escape ?? (target => this.deps.terminal.sendKeys(target.server, target.pane, ["esc"])))(from);
|
|
900
|
+
}
|
|
901
|
+
catch (error) {
|
|
902
|
+
await rm(interruptFile(id), { force: true }).catch(() => undefined);
|
|
903
|
+
throw error;
|
|
904
|
+
}
|
|
905
|
+
}));
|
|
906
|
+
if (!result.ran)
|
|
907
|
+
return { interrupted: false, state: result.state === "delivered" ? "writing" : result.state === "failed" ? "finished" : "typed" };
|
|
908
|
+
return answer;
|
|
909
|
+
}
|
|
687
910
|
async abort(id) {
|
|
688
911
|
const record = await readMove(id);
|
|
689
912
|
if (!record)
|
|
@@ -697,20 +920,29 @@ export class SessionMover {
|
|
|
697
920
|
}
|
|
698
921
|
else if (record.state !== "handing-off" && record.state !== "failed")
|
|
699
922
|
throw new BridgeError(409, "This launch may already exist; reconcile it before aborting.");
|
|
923
|
+
// Marked first, so a move not yet at its request never sends it (askForHandoff checks). Its request, if
|
|
924
|
+
// already queued and still untyped, is taken back (even one a restarted Hook no longer waits on); then, after
|
|
925
|
+
// an interrupt already checking and before any other, no Escape goes for an aborted move.
|
|
700
926
|
this.cancelled.add(id);
|
|
927
|
+
if (record.state === "handing-off")
|
|
928
|
+
await this.withdrawRequest(record, "The owner aborted the move.");
|
|
929
|
+
await this.lifecycle(id, async () => { this.asking.delete(id); });
|
|
701
930
|
await this.update(record, { state: "failed", error: "The owner aborted this uncommitted move; the original chat keeps its role." });
|
|
702
931
|
return record;
|
|
703
932
|
}
|
|
933
|
+
/** Takes the move's hand-off request back while it is still queued. Outside the move's lifecycle lock: an
|
|
934
|
+
* interrupt holds the queue's lock while it waits for that one, so this must not wait the other way round. */
|
|
935
|
+
async withdrawRequest(record, reason) {
|
|
936
|
+
await this.deps.withdraw?.(record.from.target, `move-${record.id}`, reason).catch(error => {
|
|
937
|
+
logger.warn("move", `Taking back the hand-off request of move ${record.id} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
938
|
+
});
|
|
939
|
+
}
|
|
704
940
|
async assertNotAborted(record) {
|
|
705
941
|
if (this.cancelled.has(record.id) || (await readMove(record.id))?.state === "failed" || record.modeForced === "conductor" && record.to.computer && (await this.deps.succession.status(record.id)).phase === "aborted")
|
|
706
942
|
throw new BridgeError(409, "This uncommitted move was aborted; no conductor role was transferred.");
|
|
707
943
|
}
|
|
708
944
|
async continueOnPeer(record, peer, project, document) {
|
|
709
|
-
|
|
710
|
-
// Preserve commit ids and the complete hand-off, redacting credentials
|
|
711
|
-
// in place instead of applying the lossy approval/log summarizer to it.
|
|
712
|
-
const safeDocument = document.replaceAll(record.cwd, "<source checkout>");
|
|
713
|
-
const remotePrompt = redactPeerHandoff(briefText(`Continue the owner's work from this hand-off. This is a different checkout: local uncommitted files and running processes were not copied. Check its branch and files before proceeding.\n\n${safeDocument}`));
|
|
945
|
+
const remotePrompt = peerPrompt(record, document);
|
|
714
946
|
if (remotePrompt.length > PROMPT_LIMIT)
|
|
715
947
|
throw new BridgeError(409, "The hand-off is too long to send in full to another computer; the old chat remains open.");
|
|
716
948
|
const checked = await (await import("./move-computers.js")).checkMovePeer(peer, project, record.to, record.modeForced === "conductor");
|
|
@@ -855,18 +1087,27 @@ export class SessionMover {
|
|
|
855
1087
|
async askForHandoff(record, handoffMs) {
|
|
856
1088
|
const from = record.from.target;
|
|
857
1089
|
const deadline = this.now + handoffMs;
|
|
1090
|
+
// An abort before, during or after the request was sent: it is not sent, or taken back (run's catch).
|
|
1091
|
+
const aborted = () => { if (this.cancelled.has(record.id))
|
|
1092
|
+
throw new BridgeError(409, "This uncommitted move was aborted; no conductor role was transferred."); };
|
|
1093
|
+
aborted();
|
|
858
1094
|
try {
|
|
859
1095
|
const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to, record.mode), `move-${record.id}`);
|
|
860
1096
|
// A lost delivery acknowledgement can still have reached the agent;
|
|
861
1097
|
// its marked transcript reply is authoritative for the normal window.
|
|
862
1098
|
if (sent.state !== "uncertain" && sent.ok !== true && sent.queued !== true)
|
|
863
1099
|
return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
|
|
1100
|
+
// From here the owner may stop the agent's step so the request goes in (`interrupt`, which the queue
|
|
1101
|
+
// answers `typed` or `writing` once it went).
|
|
1102
|
+
this.asking.add(record.id);
|
|
864
1103
|
}
|
|
865
1104
|
catch (error) {
|
|
866
1105
|
return { reason: `the request could not be delivered (${error instanceof Error ? error.message : String(error)}).` };
|
|
867
1106
|
}
|
|
868
1107
|
while (this.now < deadline) {
|
|
1108
|
+
aborted();
|
|
869
1109
|
await this.sleep(this.poll);
|
|
1110
|
+
aborted();
|
|
870
1111
|
const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
|
|
871
1112
|
if (!pane || pane.agent !== from.source)
|
|
872
1113
|
throw new BridgeError(409, "The session ended before it wrote its hand-off; nothing was started.");
|
|
@@ -943,7 +1184,14 @@ export class SessionMover {
|
|
|
943
1184
|
await this.sleep(Math.min(this.poll, 500));
|
|
944
1185
|
}
|
|
945
1186
|
};
|
|
946
|
-
|
|
1187
|
+
let pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
|
|
1188
|
+
// Just after the owner's interrupt sent its Escape, the pane can still read working: wait that out and look
|
|
1189
|
+
// again, rather than a second Escape at once, which Claude and Codex take as "go back to an earlier message".
|
|
1190
|
+
const since = await readFile(interruptFile(record.id), "utf8").then(text => Date.now() - Date.parse(String(JSON.parse(text).at)), () => Infinity);
|
|
1191
|
+
if (pane?.agent_status === "working" && since < INTERRUPT_SETTLE_MS) {
|
|
1192
|
+
await this.sleep(INTERRUPT_SETTLE_MS - since);
|
|
1193
|
+
pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
|
|
1194
|
+
}
|
|
947
1195
|
// A turn still running (a hand-off that ran late) is stopped first, as Esc in the terminal would.
|
|
948
1196
|
if (pane?.agent_status === "working") {
|
|
949
1197
|
await this.checkPromotion(record);
|
|
@@ -2,6 +2,14 @@ import { type Json } from "./protocol.js";
|
|
|
2
2
|
export declare const SIMULATOR_UDID: RegExp;
|
|
3
3
|
/** The iOS simulators booted on this Mac, from `simctl`; none elsewhere. */
|
|
4
4
|
export declare function bootedSimulators(): Promise<Json[]>;
|
|
5
|
+
/** Most devices `GET /v1/simulators?all=1` lists. */
|
|
6
|
+
export declare const SIMULATOR_DEVICE_LIMIT = 64;
|
|
7
|
+
/**
|
|
8
|
+
* Every iOS simulator this Mac can run (`simctl list devices available`), booted or not, with its `state`
|
|
9
|
+
* (`Booted`, `Shutdown`, `Booting`, `Shutting Down`): booted ones first, then the newest runtime, then by
|
|
10
|
+
* name, at most SIMULATOR_DEVICE_LIMIT. For the phone's device picker, which boots one from here.
|
|
11
|
+
*/
|
|
12
|
+
export declare function simulatorDevices(): Promise<Json[]>;
|
|
5
13
|
/** A PNG of one booted simulator's screen. */
|
|
6
14
|
export declare function simulatorScreenshot(udid: string): Promise<Buffer>;
|
|
7
15
|
/** What the phone may ask a simulator to do. Boot, shutdown, launch and
|
|
@@ -19,11 +27,22 @@ export type SimulatorAction = {
|
|
|
19
27
|
action: "tap";
|
|
20
28
|
x: number;
|
|
21
29
|
y: number;
|
|
30
|
+
}
|
|
31
|
+
/** A swipe or scroll: press at (x1, y1), move to (x2, y2) over `durationMs` (default 300), release. */
|
|
32
|
+
| {
|
|
33
|
+
action: "drag";
|
|
34
|
+
x1: number;
|
|
35
|
+
y1: number;
|
|
36
|
+
x2: number;
|
|
37
|
+
y2: number;
|
|
38
|
+
durationMs?: number;
|
|
22
39
|
} | {
|
|
23
40
|
action: "type";
|
|
24
41
|
text: string;
|
|
25
42
|
submit?: boolean;
|
|
26
43
|
};
|
|
44
|
+
/** A drag's duration bounds, in ms. */
|
|
45
|
+
export declare const DRAG_DEFAULT_MS = 300, DRAG_MIN_MS = 50, DRAG_MAX_MS = 5000;
|
|
27
46
|
/** The native helpers, compiled once per Hook version with swiftc, which any
|
|
28
47
|
* Mac with the simulators has. simtap (native/simtap.swift) finds the
|
|
29
48
|
* Simulator window through the Accessibility API and posts touches and keys
|
|
@@ -11,22 +11,29 @@ const execFileAsync = promisify(execFile);
|
|
|
11
11
|
* slot, for good. */
|
|
12
12
|
const exec = (file, args, options) => execFileAsync(file, args, { ...options, killSignal: "SIGKILL", encoding: "utf8" });
|
|
13
13
|
export const SIMULATOR_UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
|
|
14
|
-
/**
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
/** `simctl list devices [filter] -j`, parsed (every device without a filter); undefined when simctl failed, timed
|
|
15
|
+
* out or answered nonsense. */
|
|
16
|
+
async function listDevices(filter) {
|
|
17
|
+
const listed = await exec("/usr/bin/xcrun", ["simctl", "list", "devices", ...(filter ? [filter] : []), "-j"], { timeout: 8_000, maxBuffer: 8_388_608 }).catch(() => undefined);
|
|
18
|
+
if (!listed)
|
|
19
|
+
return undefined;
|
|
20
20
|
try {
|
|
21
|
-
|
|
21
|
+
return JSON.parse(listed.stdout);
|
|
22
22
|
}
|
|
23
23
|
catch {
|
|
24
|
-
return
|
|
24
|
+
return undefined;
|
|
25
25
|
}
|
|
26
|
+
}
|
|
27
|
+
/** com.apple.CoreSimulator.SimRuntime.iOS-26-1 → iOS 26.1 */
|
|
28
|
+
const runtimeName = (runtimeID) => runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
|
|
29
|
+
/** The iOS simulators booted on this Mac, from `simctl`; none elsewhere. */
|
|
30
|
+
export async function bootedSimulators() {
|
|
31
|
+
if (process.platform !== "darwin")
|
|
32
|
+
return [];
|
|
33
|
+
const parsed = await listDevices("booted") ?? {};
|
|
26
34
|
const list = [];
|
|
27
35
|
for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
|
|
28
|
-
|
|
29
|
-
const runtime = runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
|
|
36
|
+
const runtime = runtimeName(runtimeID);
|
|
30
37
|
for (const device of devices ?? []) {
|
|
31
38
|
if (device.state !== "Booted" || !device.udid || !SIMULATOR_UDID.test(device.udid))
|
|
32
39
|
continue;
|
|
@@ -37,6 +44,46 @@ export async function bootedSimulators() {
|
|
|
37
44
|
}
|
|
38
45
|
return list;
|
|
39
46
|
}
|
|
47
|
+
/** Most devices `GET /v1/simulators?all=1` lists. */
|
|
48
|
+
export const SIMULATOR_DEVICE_LIMIT = 64;
|
|
49
|
+
/**
|
|
50
|
+
* Every iOS simulator this Mac can run (`simctl list devices available`), booted or not, with its `state`
|
|
51
|
+
* (`Booted`, `Shutdown`, `Booting`, `Shutting Down`): booted ones first, then the newest runtime, then by
|
|
52
|
+
* name, at most SIMULATOR_DEVICE_LIMIT. For the phone's device picker, which boots one from here.
|
|
53
|
+
*/
|
|
54
|
+
export async function simulatorDevices() {
|
|
55
|
+
if (process.platform !== "darwin")
|
|
56
|
+
return [];
|
|
57
|
+
const parsed = await listDevices("available") ?? {};
|
|
58
|
+
const list = [];
|
|
59
|
+
for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
|
|
60
|
+
if (!/SimRuntime\.iOS-/.test(runtimeID))
|
|
61
|
+
continue;
|
|
62
|
+
const version = (/iOS-(\d+)-(\d+)/.exec(runtimeID) ?? []).slice(1).map(Number);
|
|
63
|
+
for (const device of devices ?? []) {
|
|
64
|
+
if (device.isAvailable === false || !device.udid || !SIMULATOR_UDID.test(device.udid))
|
|
65
|
+
continue;
|
|
66
|
+
const state = typeof device.state === "string" && /^[A-Za-z ]{1,32}$/.test(device.state) ? device.state : "Unknown";
|
|
67
|
+
list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime: runtimeName(runtimeID), state, version });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const newer = (a, b) => (b[0] ?? 0) - (a[0] ?? 0) || (b[1] ?? 0) - (a[1] ?? 0);
|
|
71
|
+
return list.sort((a, b) => Number(b.state === "Booted") - Number(a.state === "Booted") || newer(a.version, b.version) || a.name.localeCompare(b.name))
|
|
72
|
+
.slice(0, SIMULATOR_DEVICE_LIMIT).map(({ version: _version, ...device }) => device);
|
|
73
|
+
}
|
|
74
|
+
/** A simulator's state as `simctl` reports it now, from every device it has (a booted device whose runtime is no
|
|
75
|
+
* longer available still shuts down): `missing` when simctl lists no such device, undefined when it couldn't say. */
|
|
76
|
+
async function deviceState(udid) {
|
|
77
|
+
const listed = await listDevices();
|
|
78
|
+
if (!listed)
|
|
79
|
+
return undefined;
|
|
80
|
+
for (const devices of Object.values(listed.devices ?? {})) {
|
|
81
|
+
const device = devices?.find(d => d.udid?.toUpperCase() === udid.toUpperCase());
|
|
82
|
+
if (device)
|
|
83
|
+
return String(device.state ?? "");
|
|
84
|
+
}
|
|
85
|
+
return "missing";
|
|
86
|
+
}
|
|
40
87
|
/** A PNG of one booted simulator's screen. */
|
|
41
88
|
export async function simulatorScreenshot(udid) {
|
|
42
89
|
if (!SIMULATOR_UDID.test(udid))
|
|
@@ -57,6 +104,8 @@ export async function simulatorScreenshot(udid) {
|
|
|
57
104
|
await unlink(file).catch(() => undefined);
|
|
58
105
|
}
|
|
59
106
|
}
|
|
107
|
+
/** A drag's duration bounds, in ms. */
|
|
108
|
+
export const DRAG_DEFAULT_MS = 300, DRAG_MIN_MS = 50, DRAG_MAX_MS = 5_000;
|
|
60
109
|
const HELPER_LABEL = { simtap: "simulator input helper", simcast: "simulator stream helper" };
|
|
61
110
|
const building = new Map();
|
|
62
111
|
function helper(name) {
|
|
@@ -156,17 +205,37 @@ const KEY_H = "4", KEY_L = "37";
|
|
|
156
205
|
export async function simulatorAct(udid, request) {
|
|
157
206
|
if (!SIMULATOR_UDID.test(udid))
|
|
158
207
|
throw new BridgeError(400, "Invalid simulator identifier.");
|
|
159
|
-
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready", "accessibility-settings"].includes(request.action))
|
|
208
|
+
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "drag", "screenshot-ready", "accessibility-settings"].includes(request.action))
|
|
160
209
|
throw new BridgeError(400, "Unknown simulator action.");
|
|
161
210
|
if (process.platform !== "darwin")
|
|
162
211
|
throw new BridgeError(404, "Simulators run on macOS only.");
|
|
163
212
|
const simctl = (...args) => exec("/usr/bin/xcrun", ["simctl", ...args], { timeout: 30_000 }).catch(() => { throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`); });
|
|
213
|
+
// Boot and shutdown take any device, booted or not, and a device already in (or on its way to) the asked-for
|
|
214
|
+
// state is not a failure: the phone's picker may be a moment behind. A list that failed (simctl slow to start)
|
|
215
|
+
// is no reason to refuse; simctl itself then says.
|
|
216
|
+
const settle = async (verb, done) => {
|
|
217
|
+
const state = await deviceState(udid);
|
|
218
|
+
if (state === "missing")
|
|
219
|
+
throw new BridgeError(404, "No such simulator on this Mac.");
|
|
220
|
+
if (state !== undefined && done.includes(state))
|
|
221
|
+
return;
|
|
222
|
+
try {
|
|
223
|
+
await simctl(verb, udid);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
const now = await deviceState(udid);
|
|
227
|
+
if (now === undefined || !done.includes(now))
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
};
|
|
164
231
|
switch (request.action) {
|
|
165
232
|
case "boot":
|
|
166
|
-
await
|
|
233
|
+
await settle("boot", ["Booted", "Booting"]);
|
|
234
|
+
// Taps, drags and keys go to the device's window in the Simulator app, which booting alone doesn't open.
|
|
235
|
+
await exec("/usr/bin/open", ["-a", "Simulator", "--args", "-CurrentDeviceUDID", udid.toUpperCase()], { timeout: 15_000 }).catch(() => undefined);
|
|
167
236
|
break;
|
|
168
237
|
case "shutdown":
|
|
169
|
-
await
|
|
238
|
+
await settle("shutdown", ["Shutdown", "Shutting Down"]);
|
|
170
239
|
break;
|
|
171
240
|
case "launch":
|
|
172
241
|
if (typeof request.bundleId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9.-]{2,199}$/.test(request.bundleId))
|
|
@@ -199,6 +268,17 @@ export async function simulatorAct(udid, request) {
|
|
|
199
268
|
await simtap(await deviceName(udid), "tap", String(x), String(y));
|
|
200
269
|
break;
|
|
201
270
|
}
|
|
271
|
+
case "drag": {
|
|
272
|
+
// From and to are fractions of the screenshot, as a tap's are.
|
|
273
|
+
const { x1, y1, x2, y2 } = request, durationMs = request.durationMs ?? DRAG_DEFAULT_MS;
|
|
274
|
+
if (![x1, y1, x2, y2].every(v => typeof v === "number" && v >= 0 && v <= 1))
|
|
275
|
+
throw new BridgeError(400, "Drag outside the screen.");
|
|
276
|
+
if (typeof durationMs !== "number" || !Number.isInteger(durationMs) || durationMs < DRAG_MIN_MS || durationMs > DRAG_MAX_MS) {
|
|
277
|
+
throw new BridgeError(400, `A drag takes ${DRAG_MIN_MS} to ${DRAG_MAX_MS} ms.`);
|
|
278
|
+
}
|
|
279
|
+
await simtap(await deviceName(udid), "drag", String(x1), String(y1), String(x2), String(y2), String(durationMs));
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
202
282
|
case "screenshot-ready": break;
|
|
203
283
|
case "accessibility-settings": {
|
|
204
284
|
// The phone's "Open Accessibility settings": ask for the grant again and
|