@phren/cli 0.3.71 → 0.3.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hooks.js +11 -1
- package/dist/bridge/browser-env.d.ts +5 -0
- package/dist/bridge/browser-env.js +110 -0
- package/dist/bridge/browser-protocol.d.ts +120 -0
- package/dist/bridge/browser-protocol.js +70 -0
- package/dist/bridge/browser-recordings.d.ts +63 -0
- package/dist/bridge/browser-recordings.js +148 -0
- package/dist/bridge/browser-registry.d.ts +64 -0
- package/dist/bridge/browser-registry.js +262 -0
- package/dist/bridge/browser-routes.d.ts +4 -0
- package/dist/bridge/browser-routes.js +39 -0
- package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
- package/dist/bridge/browser-socket.d.ts +2 -0
- package/dist/bridge/browser-socket.js +10 -0
- package/dist/bridge/browser-stream.d.ts +3 -0
- package/dist/bridge/browser-stream.js +129 -0
- package/dist/bridge/browser-watch.d.ts +12 -0
- package/dist/bridge/browser-watch.js +83 -0
- package/dist/bridge/claude-account-setup.js +3 -1
- package/dist/bridge/claude-accounts.d.ts +5 -1
- package/dist/bridge/claude-accounts.js +36 -6
- package/dist/bridge/codex-servers.d.ts +2 -0
- package/dist/bridge/codex-servers.js +1 -1
- package/dist/bridge/command.js +24 -5
- package/dist/bridge/dispatch-clone.d.ts +33 -0
- package/dist/bridge/dispatch-clone.js +176 -0
- package/dist/bridge/dispatch-command.d.ts +14 -0
- package/dist/bridge/dispatch-command.js +98 -13
- package/dist/bridge/dispatch-idempotency.d.ts +85 -0
- package/dist/bridge/dispatch-idempotency.js +235 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -0
- package/dist/bridge/dispatch-returns.js +131 -1
- package/dist/bridge/dispatch-wait.d.ts +32 -0
- package/dist/bridge/dispatch-wait.js +177 -0
- package/dist/bridge/dispatch.d.ts +78 -2
- package/dist/bridge/dispatch.js +841 -25
- package/dist/bridge/dream-schedule.d.ts +133 -0
- package/dist/bridge/dream-schedule.js +322 -0
- package/dist/bridge/fanouts.js +20 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/git-credential.d.ts +44 -0
- package/dist/bridge/git-credential.js +113 -0
- package/dist/bridge/git-host-auth.d.ts +9 -1
- package/dist/bridge/git-host-auth.js +18 -5
- package/dist/bridge/git-host-gitboy.js +8 -1
- package/dist/bridge/git-hosts.d.ts +12 -1
- package/dist/bridge/git-publish.js +3 -2
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +44 -9
- package/dist/bridge/install.d.ts +1 -1
- package/dist/bridge/install.js +12 -4
- package/dist/bridge/launch-brief.d.ts +11 -0
- package/dist/bridge/launch-brief.js +22 -0
- package/dist/bridge/launch-worktree.d.ts +2 -0
- package/dist/bridge/launch-worktree.js +5 -1
- package/dist/bridge/pane-status.js +1 -1
- package/dist/bridge/protocol.d.ts +7 -0
- package/dist/bridge/schedule-watch.js +13 -2
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +251 -145
- package/dist/bridge/server-routes.d.ts +3 -0
- package/dist/bridge/server-routes.js +33 -17
- package/dist/bridge/server-stream.d.ts +4 -0
- package/dist/bridge/server-stream.js +24 -5
- package/dist/bridge/server.js +35 -4
- package/dist/bridge/session-move.d.ts +10 -4
- package/dist/bridge/session-move.js +65 -34
- package/dist/bridge/simulator-stream.d.ts +2 -0
- package/dist/bridge/simulator-stream.js +2 -0
- package/dist/bridge/status-line-fast.d.ts +9 -0
- package/dist/bridge/status-line-fast.js +56 -0
- package/dist/bridge/tab-activity.d.ts +2 -0
- package/dist/bridge/tab-activity.js +15 -2
- package/dist/bridge/task-routes.d.ts +20 -16
- package/dist/bridge/task-routes.js +1 -1
- package/dist/bridge/terminal-herdr.d.ts +5 -1
- package/dist/bridge/terminal-herdr.js +67 -2
- package/dist/bridge/terminal-tmux.d.ts +2 -0
- package/dist/bridge/terminal-tmux.js +29 -7
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.js +192 -112
- package/dist/bridge/transcript-preview.d.ts +2 -1
- package/dist/bridge/transcript-preview.js +85 -3
- package/dist/bridge/transcripts.js +17 -11
- package/dist/bridge/turn-records.js +16 -4
- package/dist/bridge/usage.d.ts +7 -1
- package/dist/bridge/usage.js +47 -31
- package/dist/bridge/worker-close.d.ts +15 -0
- package/dist/bridge/worker-close.js +304 -3
- package/dist/bridge/worker-identity.d.ts +51 -0
- package/dist/bridge/worker-identity.js +289 -0
- package/dist/bridge/worker-reports.js +15 -3
- package/dist/bridge-hook.mjs +39990 -36152
- package/dist/capabilities/mcp.js +1 -1
- package/dist/cli/browser-hint.d.ts +2 -0
- package/dist/cli/browser-hint.js +21 -0
- package/dist/cli/config-dreaming.d.ts +7 -0
- package/dist/cli/config-dreaming.js +72 -0
- package/dist/cli/config.js +6 -0
- package/dist/cli/dream.d.ts +59 -0
- package/dist/cli/dream.js +315 -0
- package/dist/cli/hooks-context.d.ts +2 -2
- package/dist/cli/hooks-context.js +3 -3
- package/dist/cli/hooks.js +20 -11
- package/dist/cli/namespaces-tasks.js +14 -0
- package/dist/cli-registry.js +28 -3
- package/dist/config/dreaming.d.ts +82 -0
- package/dist/config/dreaming.js +195 -0
- package/dist/config/resolve.js +11 -0
- package/dist/config/schema.d.ts +4 -4
- package/dist/config/schema.js +157 -1
- package/dist/content/citation-freshness.js +6 -0
- package/dist/content/learning.d.ts +1 -0
- package/dist/content/learning.js +2 -0
- package/dist/data/access.d.ts +1 -1
- package/dist/data/access.js +3 -1
- package/dist/data/task-contract.d.ts +5 -4
- package/dist/data/tasks.d.ts +5 -0
- package/dist/data/tasks.js +28 -2
- package/dist/dream/apply.d.ts +69 -0
- package/dist/dream/apply.js +372 -0
- package/dist/dream/budget.d.ts +78 -0
- package/dist/dream/budget.js +180 -0
- package/dist/dream/collect.d.ts +86 -0
- package/dist/dream/collect.js +449 -0
- package/dist/dream/eval/dream-adapter.d.ts +16 -0
- package/dist/dream/eval/dream-adapter.js +21 -0
- package/dist/dream/eval/fixture.d.ts +53 -0
- package/dist/dream/eval/fixture.js +172 -0
- package/dist/dream/eval/index.d.ts +40 -0
- package/dist/dream/eval/index.js +78 -0
- package/dist/dream/eval/score.d.ts +34 -0
- package/dist/dream/eval/score.js +99 -0
- package/dist/dream/eval/scripted-model.d.ts +19 -0
- package/dist/dream/eval/scripted-model.js +70 -0
- package/dist/dream/pages.d.ts +68 -0
- package/dist/dream/pages.js +220 -0
- package/dist/dream/privacy.d.ts +3 -0
- package/dist/dream/privacy.js +18 -0
- package/dist/dream/prompt.d.ts +13 -0
- package/dist/dream/prompt.js +84 -0
- package/dist/dream/run.d.ts +98 -0
- package/dist/dream/run.js +317 -0
- package/dist/dream/types.d.ts +74 -0
- package/dist/dream/types.js +4 -0
- package/dist/finding/lifecycle.d.ts +2 -2
- package/dist/finding/lifecycle.js +5 -2
- package/dist/finding/versions.d.ts +4 -0
- package/dist/finding/versions.js +28 -0
- package/dist/index.js +1 -0
- package/dist/modules/registry.js +10 -8
- package/dist/project-config.d.ts +3 -0
- package/dist/task/merge-links.d.ts +38 -0
- package/dist/task/merge-links.js +45 -0
- package/dist/task/reconcile.d.ts +39 -0
- package/dist/task/reconcile.js +201 -0
- package/dist/task/report-links.d.ts +10 -0
- package/dist/task/report-links.js +47 -0
- package/dist/tools/config.js +46 -4
- package/dist/tools/dispatch.js +2 -1
- package/dist/tools/dream.d.ts +3 -0
- package/dist/tools/dream.js +123 -0
- package/dist/tools/tasks.js +4 -1
- package/package.json +1 -1
package/dist/bridge/dispatch.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { mergeTaskIdentitySchema } from "../task/merge-links.js";
|
|
1
2
|
import { redactPeerHandoff } from "./peer-handoff.js";
|
|
2
3
|
import { integratorSchema, prsSchema } from "./return-contract.js";
|
|
3
|
-
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
4
5
|
import { lstat, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
import { z } from "zod";
|
|
@@ -18,20 +19,27 @@ import { prepareDispatchOriginHandover, trackDispatchOrigin } from "./dispatch-o
|
|
|
18
19
|
import { readRoleState, recordedConductor } from "./conductor-role.js";
|
|
19
20
|
import { linkedComputer } from "./computer-identity.js";
|
|
20
21
|
import { isLocalComputer, localHost, peerHost } from "./dispatch-hosts.js";
|
|
21
|
-
import { object, atomic, BridgeError, bridgeRoot, id, launchEfforts, PERMISSION_MODES, PROTOCOL, provider, serverName, startingTargetSchema, targetSchema } from "./protocol.js";
|
|
22
|
+
import { object, objects, atomic, BridgeError, bridgeRoot, id, launchEfforts, PERMISSION_MODES, PROTOCOL, provider, serverName, startingTargetSchema, targetSchema } from "./protocol.js";
|
|
22
23
|
import { phrenStoreRoot } from "./transcripts.js";
|
|
23
24
|
import { isAccountSlug } from "./claude-accounts.js";
|
|
24
25
|
import { hasUsable } from "./harnesses.js";
|
|
25
26
|
import { limitedBy, limitKey, readAccountLimits } from "./account-choice.js";
|
|
26
27
|
import { allowedRooms, choosePolicyAccount, computerRule, openRoom, policyApplies, poolRefusal, projectRule, withPolicy } from "./account-policy.js";
|
|
27
|
-
import { arrivalSchema } from "./launch-brief.js";
|
|
28
|
+
import { arrivalSchema, briefArrival } from "./launch-brief.js";
|
|
29
|
+
import { worktreeBranch } from "./launch-worktree.js";
|
|
30
|
+
import { dispatchClonePaths, removeDispatchClone, removeDispatchSecrets } from "./dispatch-clone.js";
|
|
31
|
+
import { launchInProgress, markSubmitted, removeWorkerFile, workerAlive } from "./worker-identity.js";
|
|
32
|
+
import { findIdempotencyKey, idempotencyKeySchema, LAUNCH_INTERRUPTED_MS, listIdempotencyRecords, releaseIdempotencyKey, reserveIdempotencyKey, updateIdempotencyPhase, waitForIdempotencyKey, withIdempotencyKeyLock, worktreeBranchFor } from "./dispatch-idempotency.js";
|
|
28
33
|
const text = (max) => z.string().min(1).max(max).refine(value => !!value.trim() && !/[\x00-\x1f\x7f]/.test(value));
|
|
29
34
|
export const projectName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/);
|
|
35
|
+
/** The longest worker brief a dispatch takes, in characters. */
|
|
36
|
+
export const DISPATCH_PROMPT_LIMIT = 32768;
|
|
30
37
|
/** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
|
|
31
38
|
export const PEER_COPILOT_REASON = "Copilot cannot continue on another computer: its harness does not confirm launch-brief arrival. Continue locally or choose another harness.";
|
|
32
39
|
export const DISPATCH_HARNESSES = ["codex", "claude", "opencode", "copilot"];
|
|
33
40
|
export const dispatchSchema = z.object({
|
|
34
|
-
computer: z.union([z.literal("anywhere"), computerName]).describe("Enrolled computer name, or anywhere for the least busy connected computer."),
|
|
41
|
+
computer: z.union([z.literal("anywhere"), computerName]).describe("Enrolled computer name, local for this computer, or anywhere for the least busy connected computer."),
|
|
42
|
+
task: mergeTaskIdentitySchema.optional().describe("Private task identity for merge reconciliation. Never put it in commits or GitHub."),
|
|
35
43
|
project: projectName.describe("Project slug registered on the receiving computer."),
|
|
36
44
|
harness: z.enum(DISPATCH_HARNESSES).describe("Agent harness on the receiving computer."),
|
|
37
45
|
model: text(200).optional().describe("Explicit model, otherwise the remote harness default."),
|
|
@@ -41,8 +49,12 @@ export const dispatchSchema = z.object({
|
|
|
41
49
|
permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude, Codex and Copilot; not OpenCode); otherwise the receiving computer's own default."),
|
|
42
50
|
releaseActions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length).optional()
|
|
43
51
|
.describe("Release-type actions the brief asks the worker to do (merge, publish, deploy, app-store, github-admin). Ask-first projects refuse them from an agent unless the owner confirmed."),
|
|
44
|
-
prompt: z.string().min(1).max(
|
|
52
|
+
prompt: z.string().min(1).max(DISPATCH_PROMPT_LIMIT).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)).describe(`Worker brief, at most ${DISPATCH_PROMPT_LIMIT} characters.`),
|
|
45
53
|
label: text(200).describe("Short task label."),
|
|
54
|
+
idempotencyKey: idempotencyKeySchema.optional()
|
|
55
|
+
.describe("Caller-supplied key (1 to 200 characters of letters, digits and : . _ @ / -). The Hook returns the dispatch this key already started instead of starting another, for 30 days. Dispatches with a key run in their harness's standard permission mode."),
|
|
56
|
+
worktree: z.boolean().optional().describe("Start the worker in a fresh git worktree of the project's checkout, on a new branch. Never reused."),
|
|
57
|
+
branch: worktreeBranch.optional().describe("Branch for the worktree; defaults to agent/<key-slug or dispatch id>. Needs worktree."),
|
|
46
58
|
closeOnFinish: z.boolean().optional().describe("Close the finished worker pane after its done return is read. Defaults to true; false keeps it open."),
|
|
47
59
|
integrator: integratorSchema.optional().describe("Forward structured PR reports to this integrator, overriding the Hook default."),
|
|
48
60
|
parent: dispatchParentSchema.optional().describe("Explicit local conversation parent for work-tree attachment."),
|
|
@@ -89,7 +101,21 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
|
|
|
89
101
|
origin: originPaneSchema.extend({ agent: provider, terminal: z.string().min(1).max(200) }).strict().optional()
|
|
90
102
|
.describe("The local agent pane that placed this dispatch; return notices go there."),
|
|
91
103
|
closedAt: timestamp.optional(),
|
|
104
|
+
cancelRequestedAt: timestamp.optional(),
|
|
92
105
|
closePending: z.object({ at: timestamp, turn: z.string().optional() }).strict().optional(),
|
|
106
|
+
agentTokenFile: z.string().max(4096).optional().describe("Private file holding the keyed worker's gitboy agent token; removed when it closes or finishes."),
|
|
107
|
+
cloneDir: z.string().max(4096).optional().describe("The keyed dispatch's isolated clone; removed when it closes or finishes, or after its retention date."),
|
|
108
|
+
gitConfigFile: z.string().max(4096).optional().describe("The keyed dispatch's managed global Git config; removed with the clone or as soon as a failed/cancelled worker ends."),
|
|
109
|
+
workerFile: z.string().max(4096).optional().describe("The keyed worker's PID and start-time record, written before the harness execs."),
|
|
110
|
+
retainedUntil: timestamp.optional().describe("When a failed, cancelled or keep-open clone may be removed by reconciliation."),
|
|
111
|
+
endedAt: timestamp.optional().describe("When the worker was observed gone or closed; retention is measured from here."),
|
|
112
|
+
launchOutcome: z.enum(["not-started", "ambiguous", "started"]).optional()
|
|
113
|
+
.describe("Whether the launch request was never sent, was sent with an unknown outcome, or produced a target or arrival."),
|
|
114
|
+
startingToken: z.string().regex(/^[a-f0-9]{64}$/).optional()
|
|
115
|
+
.describe("The launch's own starting token, recorded before the request and carried by its pane."),
|
|
116
|
+
launchServer: z.string().max(200).optional().describe("The terminal server the launch request targeted."),
|
|
117
|
+
scanSince: timestamp.optional().describe("When a successful snapshot first found no pane carrying this launch's starting token."),
|
|
118
|
+
submittedAt: timestamp.optional().describe("When the launch command was submitted; a missing worker file is only gone after its grace period."),
|
|
93
119
|
worker: z.object({ state: z.enum(workerStates), since: timestamp, checkedAt: timestamp, sawWorking: z.boolean(),
|
|
94
120
|
background: z.number().int().min(0).max(999).optional().describe("The most background tasks seen running while the worker was working."),
|
|
95
121
|
waitingSince: timestamp.optional().describe("When the dispatching Hook first saw the worker's finished turn waiting on background tasks; bounds that wait.") }).strict().optional()
|
|
@@ -153,6 +179,32 @@ function save(receipt, originWindow) {
|
|
|
153
179
|
await saveReceipt(receipt);
|
|
154
180
|
});
|
|
155
181
|
}
|
|
182
|
+
const PLACEMENT_FIELDS = ["state", "error", "brief", "target", "account", "accountChoice", "agentTokenFile", "cloneDir", "gitConfigFile", "workerFile", "returned", "closedAt", "launchOutcome", "submittedAt"];
|
|
183
|
+
/** Every placement write re-reads the receipt under the lock, so a concurrent cancelRequestedAt is never lost. */
|
|
184
|
+
async function persistReceipt(receipt, originWindow, change = () => undefined) {
|
|
185
|
+
const updated = await updateReceipt(receipt.id, value => {
|
|
186
|
+
// A concurrent close finalizes the receipt; a placement write must not
|
|
187
|
+
// resurrect it with a stale state or return.
|
|
188
|
+
if (value.closedAt || value.error === "cancelled")
|
|
189
|
+
return false;
|
|
190
|
+
const origin = originWindow.rewrite(value.origin);
|
|
191
|
+
if (origin !== value.origin && !value.closedAt) {
|
|
192
|
+
value.origin = origin;
|
|
193
|
+
if (value.returned && !value.returned.read)
|
|
194
|
+
delete value.returned.notifiedAt;
|
|
195
|
+
}
|
|
196
|
+
for (const key of PLACEMENT_FIELDS) {
|
|
197
|
+
const next = receipt[key];
|
|
198
|
+
if (next !== undefined)
|
|
199
|
+
value[key] = next;
|
|
200
|
+
}
|
|
201
|
+
change(value);
|
|
202
|
+
value.updatedAt = new Date().toISOString();
|
|
203
|
+
return true;
|
|
204
|
+
}, { duringPlacement: true });
|
|
205
|
+
if (updated)
|
|
206
|
+
Object.assign(receipt, updated);
|
|
207
|
+
}
|
|
156
208
|
async function saveReceipt(receipt) {
|
|
157
209
|
const root = path.join(bridgeRoot(), "dispatches");
|
|
158
210
|
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
@@ -166,8 +218,8 @@ let receiptUpdates = Promise.resolve();
|
|
|
166
218
|
* when `change` returns true. Updates run one at a time in this process, and a
|
|
167
219
|
* receipt still being placed (launching or sending) is never touched.
|
|
168
220
|
*/
|
|
169
|
-
export function updateReceipt(receiptID, change) {
|
|
170
|
-
return serializeReceiptUpdate(() => changeReceipt(receiptID, change));
|
|
221
|
+
export function updateReceipt(receiptID, change, options = {}) {
|
|
222
|
+
return serializeReceiptUpdate(() => changeReceipt(receiptID, change, options.duringPlacement === true));
|
|
171
223
|
}
|
|
172
224
|
function serializeReceiptUpdate(change) {
|
|
173
225
|
const run = receiptUpdates.then(change);
|
|
@@ -186,9 +238,9 @@ async function readReceipt(receiptID) {
|
|
|
186
238
|
return receiptSchema.parse(JSON.parse(await readFile(file, "utf8")));
|
|
187
239
|
}
|
|
188
240
|
/** Caller holds receiptUpdates; ordinary polling never edits a placing receipt. */
|
|
189
|
-
async function changeReceipt(receiptID, change) {
|
|
241
|
+
async function changeReceipt(receiptID, change, duringPlacement = false) {
|
|
190
242
|
const receipt = await readReceipt(receiptID);
|
|
191
|
-
if (!receipt || ["launching", "sending"].includes(receipt.state))
|
|
243
|
+
if (!receipt || (!duringPlacement && ["launching", "sending"].includes(receipt.state)))
|
|
192
244
|
return undefined;
|
|
193
245
|
if (!change(receipt))
|
|
194
246
|
return receipt;
|
|
@@ -279,6 +331,589 @@ export function failureReason(error) {
|
|
|
279
331
|
const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
|
|
280
332
|
return `${typeof code === "string" && !(error instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
|
|
281
333
|
}
|
|
334
|
+
/** A fresh terminal snapshot proves the bound worker gone; a failed snapshot does not. */
|
|
335
|
+
export async function boundWorkerGone(receipt) {
|
|
336
|
+
const target = receipt.target;
|
|
337
|
+
if (!target)
|
|
338
|
+
return false;
|
|
339
|
+
try {
|
|
340
|
+
const { findPane } = await import("./herdr.js");
|
|
341
|
+
const { terminalProvider } = await import("./terminal.js");
|
|
342
|
+
const snapshot = await terminalProvider().snapshot(target.server);
|
|
343
|
+
// A launch token binds the pane itself; without one, the agent must match.
|
|
344
|
+
const address = "starting" in target && target.starting === true
|
|
345
|
+
? { workspace: target.workspace, tab: target.tab, pane: target.pane }
|
|
346
|
+
: target;
|
|
347
|
+
return !findPane(snapshot, address);
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** A worker that may still run has no termination time; drop any stale retention clock. */
|
|
354
|
+
export async function clearWorkerEnded(id) {
|
|
355
|
+
await updateReceipt(id, value => {
|
|
356
|
+
if (!value.endedAt && !value.retainedUntil)
|
|
357
|
+
return false;
|
|
358
|
+
delete value.endedAt;
|
|
359
|
+
delete value.retainedUntil;
|
|
360
|
+
return true;
|
|
361
|
+
}).catch(() => undefined);
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* A successful terminal snapshot on the launch's server, and the pane carrying
|
|
365
|
+
* this launch's starting token. `ok: false` means the snapshot or an identity
|
|
366
|
+
* read failed, so no conclusion can be drawn.
|
|
367
|
+
*/
|
|
368
|
+
export async function scanStartingToken(receipt) {
|
|
369
|
+
const token = receipt.startingToken;
|
|
370
|
+
const server = receipt.launchServer ?? receipt.target?.server;
|
|
371
|
+
if (!token || !server)
|
|
372
|
+
return { ok: false };
|
|
373
|
+
try {
|
|
374
|
+
const { paneChatState, paneStartingToken } = await import("./herdr.js");
|
|
375
|
+
const { terminalProvider } = await import("./terminal.js");
|
|
376
|
+
const snapshot = await terminalProvider().snapshot(server);
|
|
377
|
+
const panes = objects(snapshot.panes);
|
|
378
|
+
for (const pane of panes) {
|
|
379
|
+
if (pane.startingToken === token || paneStartingToken(server, pane) === token)
|
|
380
|
+
return { ok: true, pane };
|
|
381
|
+
}
|
|
382
|
+
for (const pane of panes) {
|
|
383
|
+
if (typeof pane.agent === "string" && pane.agent) {
|
|
384
|
+
const chat = await paneChatState(server, pane).catch(() => undefined);
|
|
385
|
+
if (!chat)
|
|
386
|
+
return { ok: false };
|
|
387
|
+
if (chat.startingToken === token)
|
|
388
|
+
return { ok: true, pane };
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return { ok: true };
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
return { ok: false };
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/** The exact binding for a pane that carries the launch's starting token. */
|
|
398
|
+
export function startingTargetFromPane(receipt, pane) {
|
|
399
|
+
const server = receipt.launchServer ?? receipt.target?.server;
|
|
400
|
+
const source = provider.safeParse(pane.agent);
|
|
401
|
+
if (!server || !source.success || !id.safeParse(pane.workspace_id).success || !id.safeParse(pane.tab_id).success || !id.safeParse(pane.pane_id).success)
|
|
402
|
+
return undefined;
|
|
403
|
+
const binding = { server, workspace: String(pane.workspace_id), tab: String(pane.tab_id), pane: String(pane.pane_id), source: source.data };
|
|
404
|
+
const session = typeof pane.sessionId === "string" ? pane.sessionId : typeof pane.session_id === "string" ? pane.session_id : undefined;
|
|
405
|
+
if (session)
|
|
406
|
+
return { ...binding, session };
|
|
407
|
+
const token = typeof pane.startingToken === "string" ? pane.startingToken : receipt.startingToken;
|
|
408
|
+
return token ? { ...binding, starting: true, startingToken: token } : undefined;
|
|
409
|
+
}
|
|
410
|
+
/** A launch error before any target: an explicit 4xx refusal is not-started;
|
|
411
|
+
* timeouts, 5xx and transport errors leave the outcome unknown. */
|
|
412
|
+
function launchFailureOutcome(error) {
|
|
413
|
+
if (!(error instanceof BridgeError))
|
|
414
|
+
return "ambiguous";
|
|
415
|
+
if (error.status === 504 || error.status >= 500)
|
|
416
|
+
return "ambiguous";
|
|
417
|
+
if (error.status >= 400 && error.status < 500) {
|
|
418
|
+
const code = typeof error.details?.code === "string" ? error.details.code : undefined;
|
|
419
|
+
if (code === "harness_unavailable" || code === "account_unavailable" || code === "outside_set" || code === "account_pool")
|
|
420
|
+
return "not-started";
|
|
421
|
+
if ([400, 401, 403, 404, 422].includes(error.status))
|
|
422
|
+
return "not-started";
|
|
423
|
+
return "ambiguous";
|
|
424
|
+
}
|
|
425
|
+
return "ambiguous";
|
|
426
|
+
}
|
|
427
|
+
/** A keyed lookup, after reconciling a launch that was interrupted. */
|
|
428
|
+
async function lookupKeyedDispatch(key) {
|
|
429
|
+
const record = await findIdempotencyKey(key);
|
|
430
|
+
if (!record)
|
|
431
|
+
return undefined;
|
|
432
|
+
await reconcileIdempotencyRecord(record);
|
|
433
|
+
let receipt = await readReceipt(record.dispatchId).catch(() => undefined);
|
|
434
|
+
if (!receipt)
|
|
435
|
+
return undefined;
|
|
436
|
+
if (record.cancelRequestedAt && !receipt.cancelRequestedAt) {
|
|
437
|
+
await withIdempotencyKeyLock(record.key, async (current) => {
|
|
438
|
+
if (!current?.cancelRequestedAt)
|
|
439
|
+
return;
|
|
440
|
+
await updateReceipt(record.dispatchId, value => {
|
|
441
|
+
if (value.cancelRequestedAt)
|
|
442
|
+
return false;
|
|
443
|
+
value.cancelRequestedAt = current.cancelRequestedAt;
|
|
444
|
+
return true;
|
|
445
|
+
}, { duringPlacement: true }).catch(() => undefined);
|
|
446
|
+
});
|
|
447
|
+
const reread = await readReceipt(record.dispatchId).catch(() => undefined);
|
|
448
|
+
if (reread)
|
|
449
|
+
receipt = reread;
|
|
450
|
+
}
|
|
451
|
+
const settled = receipt;
|
|
452
|
+
return { ok: settled.state === "accepted", ...settled, dispatch: settled.id, existing: true };
|
|
453
|
+
}
|
|
454
|
+
/** A key cancelled before its receipt existed: settle it as failed/cancelled without launching. */
|
|
455
|
+
export async function settleCancelledReservation(record) {
|
|
456
|
+
if (await launchInProgress(record.dispatchId)) {
|
|
457
|
+
throw new BridgeError(409, "This dispatch's launch is in progress; its cancel is recorded and will be applied.");
|
|
458
|
+
}
|
|
459
|
+
const existing = await readReceipt(record.dispatchId).catch(() => undefined);
|
|
460
|
+
if (existing)
|
|
461
|
+
return existing;
|
|
462
|
+
const at = new Date().toISOString();
|
|
463
|
+
const receipt = {
|
|
464
|
+
id: record.dispatchId,
|
|
465
|
+
computer: record.computer ?? "local",
|
|
466
|
+
project: record.project ?? "unknown",
|
|
467
|
+
harness: record.harness ?? "claude",
|
|
468
|
+
label: record.label ?? "gitboy agent",
|
|
469
|
+
createdAt: record.createdAt,
|
|
470
|
+
updatedAt: at,
|
|
471
|
+
state: "failed",
|
|
472
|
+
error: "cancelled",
|
|
473
|
+
returned: { state: "failed", at, error: "cancelled", read: false },
|
|
474
|
+
idempotencyKey: record.key,
|
|
475
|
+
launchOutcome: "not-started",
|
|
476
|
+
...(record.startingToken ? { startingToken: record.startingToken } : {}),
|
|
477
|
+
endedAt: at,
|
|
478
|
+
retainedUntil: new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString(),
|
|
479
|
+
...(record.cloneDir ? { cloneDir: record.cloneDir } : {}),
|
|
480
|
+
...(record.gitConfigFile ? { gitConfigFile: record.gitConfigFile } : {}),
|
|
481
|
+
...(record.agentTokenFile ? { agentTokenFile: record.agentTokenFile } : {}),
|
|
482
|
+
...(record.workerFile ? { workerFile: record.workerFile } : {}),
|
|
483
|
+
};
|
|
484
|
+
await saveReceipt(receipt);
|
|
485
|
+
await removeDispatchSecrets({ cloneDir: record.cloneDir, gitConfigFile: record.gitConfigFile, agentTokenFile: record.agentTokenFile });
|
|
486
|
+
await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
|
|
487
|
+
return receipt;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* An interrupted launch is resolved by durable proof: a keyed worker's PID and
|
|
491
|
+
* start time, or (for unkeyed work) the launch's starting token. A live launch
|
|
492
|
+
* lock means the launch is still placing, so nothing is final.
|
|
493
|
+
*/
|
|
494
|
+
async function confirmInterruptedLaunch(receipt) {
|
|
495
|
+
const paths = { cloneDir: receipt.cloneDir, gitConfigFile: receipt.gitConfigFile, agentTokenFile: receipt.agentTokenFile, workerFile: receipt.workerFile };
|
|
496
|
+
const clearSeed = async () => {
|
|
497
|
+
if (receipt.startingToken)
|
|
498
|
+
(await import("./herdr.js")).clearStartingTokenByToken(receipt.startingToken);
|
|
499
|
+
};
|
|
500
|
+
const finish = async () => {
|
|
501
|
+
const at = new Date().toISOString();
|
|
502
|
+
await updateReceipt(receipt.id, value => {
|
|
503
|
+
if (!value.endedAt)
|
|
504
|
+
value.endedAt = at;
|
|
505
|
+
if (!value.retainedUntil)
|
|
506
|
+
value.retainedUntil = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
|
|
507
|
+
return true;
|
|
508
|
+
}, { duringPlacement: true }).catch(() => undefined);
|
|
509
|
+
const until = receipt.retainedUntil ? Date.parse(receipt.retainedUntil) : NaN;
|
|
510
|
+
if (Number.isFinite(until) && Date.now() >= until)
|
|
511
|
+
await removeDispatchClone(paths);
|
|
512
|
+
};
|
|
513
|
+
if (receipt.idempotencyKey) {
|
|
514
|
+
const alive = await workerAlive(receipt.id, receipt.workerFile ?? dispatchClonePaths(receipt.id).workerFile, receipt.submittedAt);
|
|
515
|
+
if (alive === "unknown")
|
|
516
|
+
return;
|
|
517
|
+
if (alive === "alive") {
|
|
518
|
+
await updateReceipt(receipt.id, value => {
|
|
519
|
+
value.launchOutcome = "started";
|
|
520
|
+
return true;
|
|
521
|
+
}, { duringPlacement: true }).catch(() => undefined);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
await removeDispatchSecrets(paths);
|
|
525
|
+
await removeWorkerFile(receipt.id);
|
|
526
|
+
await finish();
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (receipt.launchOutcome === "not-started") {
|
|
530
|
+
await removeDispatchSecrets(paths);
|
|
531
|
+
await clearSeed();
|
|
532
|
+
await finish();
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (!receipt.startingToken)
|
|
536
|
+
return;
|
|
537
|
+
const scan = await scanStartingToken(receipt);
|
|
538
|
+
if (!scan.ok)
|
|
539
|
+
return;
|
|
540
|
+
if (scan.pane) {
|
|
541
|
+
const target = startingTargetFromPane(receipt, scan.pane);
|
|
542
|
+
if (!target)
|
|
543
|
+
return;
|
|
544
|
+
await updateReceipt(receipt.id, value => {
|
|
545
|
+
if (!value.target)
|
|
546
|
+
value.target = target;
|
|
547
|
+
value.launchOutcome = "started";
|
|
548
|
+
return true;
|
|
549
|
+
}, { duringPlacement: true }).catch(() => undefined);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const since = receipt.scanSince;
|
|
553
|
+
if (!since) {
|
|
554
|
+
await updateReceipt(receipt.id, value => {
|
|
555
|
+
if (!value.scanSince)
|
|
556
|
+
value.scanSince = new Date().toISOString();
|
|
557
|
+
return true;
|
|
558
|
+
}, { duringPlacement: true }).catch(() => undefined);
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
if (!Number.isFinite(Date.parse(since)) || Date.now() - Date.parse(since) < 24 * 60 * 60_000)
|
|
562
|
+
return;
|
|
563
|
+
await removeDispatchSecrets(paths);
|
|
564
|
+
await clearSeed();
|
|
565
|
+
await finish();
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* A reservation stuck in `reserved` or `launching` for five minutes with no
|
|
569
|
+
* target and no live worker is an interrupted launch. It becomes a failed
|
|
570
|
+
* receipt with "launch interrupted"; nothing is relaunched automatically.
|
|
571
|
+
*/
|
|
572
|
+
export async function reconcileIdempotencyRecord(record) {
|
|
573
|
+
const terminal = await readReceipt(record.dispatchId).catch(() => undefined);
|
|
574
|
+
if (terminal && isLocalComputer(terminal.computer)) {
|
|
575
|
+
const state = terminal.returned?.state;
|
|
576
|
+
const done = state === "done";
|
|
577
|
+
const keepOpen = terminal.closeOnFinish === false;
|
|
578
|
+
const paths = {
|
|
579
|
+
cloneDir: record.cloneDir ?? terminal.cloneDir,
|
|
580
|
+
gitConfigFile: record.gitConfigFile ?? terminal.gitConfigFile,
|
|
581
|
+
agentTokenFile: record.agentTokenFile ?? terminal.agentTokenFile,
|
|
582
|
+
workerFile: record.workerFile ?? terminal.workerFile,
|
|
583
|
+
};
|
|
584
|
+
// Failed, cancelled and interrupted work keeps its clone (recoverable).
|
|
585
|
+
// Retention starts only once durable proof confirms the worker gone;
|
|
586
|
+
// a failed return alone never removes its token.
|
|
587
|
+
if (state === "failed" || state === "gone" || (terminal.closedAt && !done)) {
|
|
588
|
+
if (terminal.idempotencyKey) {
|
|
589
|
+
const alive = await workerAlive(terminal.id, terminal.workerFile ?? paths.workerFile, terminal.submittedAt);
|
|
590
|
+
if (alive !== "gone") {
|
|
591
|
+
await clearWorkerEnded(terminal.id);
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
await removeDispatchSecrets(paths);
|
|
595
|
+
await removeWorkerFile(terminal.id);
|
|
596
|
+
let endedAt = terminal.endedAt;
|
|
597
|
+
let retainedUntil = terminal.retainedUntil;
|
|
598
|
+
if (!endedAt) {
|
|
599
|
+
const at = terminal.closedAt ?? new Date().toISOString();
|
|
600
|
+
const until = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
|
|
601
|
+
endedAt = at;
|
|
602
|
+
retainedUntil = until;
|
|
603
|
+
await updateReceipt(terminal.id, value => {
|
|
604
|
+
if (!value.endedAt)
|
|
605
|
+
value.endedAt = at;
|
|
606
|
+
if (!value.retainedUntil)
|
|
607
|
+
value.retainedUntil = until;
|
|
608
|
+
return true;
|
|
609
|
+
}).catch(() => undefined);
|
|
610
|
+
}
|
|
611
|
+
else if (!retainedUntil) {
|
|
612
|
+
const until = new Date(Date.parse(endedAt) + 7 * 24 * 60 * 60_000).toISOString();
|
|
613
|
+
retainedUntil = until;
|
|
614
|
+
await updateReceipt(terminal.id, value => {
|
|
615
|
+
if (!value.retainedUntil)
|
|
616
|
+
value.retainedUntil = until;
|
|
617
|
+
return true;
|
|
618
|
+
}).catch(() => undefined);
|
|
619
|
+
}
|
|
620
|
+
if (retainedUntil && Number.isFinite(Date.parse(retainedUntil)) && Date.now() >= Date.parse(retainedUntil)) {
|
|
621
|
+
if (await workerAlive(terminal.id, terminal.workerFile ?? paths.workerFile, terminal.submittedAt) === "gone")
|
|
622
|
+
await removeDispatchClone(paths);
|
|
623
|
+
}
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (!terminal.target) {
|
|
627
|
+
// An ambiguous launch has no binding to snapshot: its own starting
|
|
628
|
+
// token decides whether a worker runs.
|
|
629
|
+
await confirmInterruptedLaunch(terminal);
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
if (!await boundWorkerGone(terminal)) {
|
|
633
|
+
await clearWorkerEnded(terminal.id);
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
await removeDispatchSecrets(paths);
|
|
637
|
+
let endedAt = terminal.endedAt;
|
|
638
|
+
let retainedUntil = terminal.retainedUntil;
|
|
639
|
+
if (!endedAt) {
|
|
640
|
+
const at = terminal.closedAt ?? new Date().toISOString();
|
|
641
|
+
const until = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
|
|
642
|
+
endedAt = at;
|
|
643
|
+
retainedUntil = until;
|
|
644
|
+
await updateReceipt(terminal.id, value => {
|
|
645
|
+
if (!value.endedAt)
|
|
646
|
+
value.endedAt = at;
|
|
647
|
+
if (!value.retainedUntil)
|
|
648
|
+
value.retainedUntil = until;
|
|
649
|
+
return true;
|
|
650
|
+
}).catch(() => undefined);
|
|
651
|
+
}
|
|
652
|
+
else if (!retainedUntil) {
|
|
653
|
+
const until = new Date(Date.parse(endedAt) + 7 * 24 * 60 * 60_000).toISOString();
|
|
654
|
+
retainedUntil = until;
|
|
655
|
+
await updateReceipt(terminal.id, value => {
|
|
656
|
+
if (!value.retainedUntil)
|
|
657
|
+
value.retainedUntil = until;
|
|
658
|
+
return true;
|
|
659
|
+
}).catch(() => undefined);
|
|
660
|
+
}
|
|
661
|
+
if (retainedUntil && Number.isFinite(Date.parse(retainedUntil)) && Date.now() >= Date.parse(retainedUntil)) {
|
|
662
|
+
// Confirm again at the moment of deletion; a live worker keeps its clone.
|
|
663
|
+
if (!await boundWorkerGone(terminal)) {
|
|
664
|
+
await clearWorkerEnded(terminal.id);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
await removeDispatchClone(paths);
|
|
668
|
+
}
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (done) {
|
|
672
|
+
if (terminal.idempotencyKey) {
|
|
673
|
+
if (terminal.closedAt) {
|
|
674
|
+
await removeDispatchClone(paths);
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
if (keepOpen) {
|
|
678
|
+
await clearWorkerEnded(terminal.id);
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const alive = await workerAlive(terminal.id, terminal.workerFile ?? paths.workerFile, terminal.submittedAt);
|
|
682
|
+
if (alive === "gone") {
|
|
683
|
+
await removeDispatchClone(paths);
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
await clearWorkerEnded(terminal.id);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
if (terminal.closedAt) {
|
|
690
|
+
await removeDispatchClone(paths);
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
if (keepOpen) {
|
|
694
|
+
// Keep-open work is never deleted before it is closed.
|
|
695
|
+
await clearWorkerEnded(terminal.id);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (await boundWorkerGone(terminal)) {
|
|
699
|
+
await removeDispatchClone(paths);
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
await clearWorkerEnded(terminal.id);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const closeIfCancelled = async () => {
|
|
706
|
+
const current = await updateReceipt(record.dispatchId, () => false, { duringPlacement: true }).catch(() => undefined);
|
|
707
|
+
if (!current?.cancelRequestedAt || !current.target)
|
|
708
|
+
return false;
|
|
709
|
+
const { closeVerifiedWorker } = await import("./worker-close.js");
|
|
710
|
+
await closeVerifiedWorker(current);
|
|
711
|
+
return true;
|
|
712
|
+
};
|
|
713
|
+
if (await closeIfCancelled())
|
|
714
|
+
return;
|
|
715
|
+
if (record.phase !== "reserved" && record.phase !== "launching")
|
|
716
|
+
return;
|
|
717
|
+
if (Date.now() - Date.parse(record.createdAt) < LAUNCH_INTERRUPTED_MS)
|
|
718
|
+
return;
|
|
719
|
+
let receipt;
|
|
720
|
+
try {
|
|
721
|
+
receipt = await readReceipt(record.dispatchId);
|
|
722
|
+
}
|
|
723
|
+
catch {
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (receipt) {
|
|
727
|
+
if (receipt.target) {
|
|
728
|
+
if (receipt.state === "launching" || receipt.state === "sending") {
|
|
729
|
+
await updateReceipt(receipt.id, value => {
|
|
730
|
+
if (value.state === "launching" || value.state === "sending")
|
|
731
|
+
value.state = "uncertain";
|
|
732
|
+
return true;
|
|
733
|
+
}, { duringPlacement: true }).catch(() => undefined);
|
|
734
|
+
}
|
|
735
|
+
await updateIdempotencyPhase(record.key, record.owner, "launched").catch(() => undefined);
|
|
736
|
+
await closeIfCancelled();
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
// The launch's own arrival record names the pane or session it created,
|
|
740
|
+
// even when the receipt died before saving the target.
|
|
741
|
+
const arrival = await briefArrival(record.dispatchId).catch(() => undefined);
|
|
742
|
+
const arrived = arrival?.accepted?.target ?? arrival?.started?.target;
|
|
743
|
+
if (arrived) {
|
|
744
|
+
await serializeReceiptUpdate(async () => {
|
|
745
|
+
const current = await readReceipt(record.dispatchId);
|
|
746
|
+
if (!current || current.target)
|
|
747
|
+
return;
|
|
748
|
+
current.target = remoteTarget.parse(arrived);
|
|
749
|
+
current.state = arrival?.accepted ? "accepted" : "uncertain";
|
|
750
|
+
if (!current.cloneDir && record.cloneDir)
|
|
751
|
+
current.cloneDir = record.cloneDir;
|
|
752
|
+
if (!current.gitConfigFile && record.gitConfigFile)
|
|
753
|
+
current.gitConfigFile = record.gitConfigFile;
|
|
754
|
+
if (!current.agentTokenFile && record.agentTokenFile)
|
|
755
|
+
current.agentTokenFile = record.agentTokenFile;
|
|
756
|
+
current.updatedAt = new Date().toISOString();
|
|
757
|
+
await saveReceipt(current);
|
|
758
|
+
}).catch(() => undefined);
|
|
759
|
+
await updateIdempotencyPhase(record.key, record.owner, "launched").catch(() => undefined);
|
|
760
|
+
await closeIfCancelled();
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
const worker = receipt.worker;
|
|
764
|
+
const workerLive = worker && ["working", "blocked", "needs-you"].includes(worker.state)
|
|
765
|
+
&& Number.isFinite(Date.parse(worker.checkedAt)) && Date.now() - Date.parse(worker.checkedAt) < LAUNCH_INTERRUPTED_MS;
|
|
766
|
+
if (workerLive) {
|
|
767
|
+
if (receipt.state === "launching" || receipt.state === "sending") {
|
|
768
|
+
await updateReceipt(receipt.id, value => {
|
|
769
|
+
if (value.state === "launching" || value.state === "sending")
|
|
770
|
+
value.state = "uncertain";
|
|
771
|
+
return true;
|
|
772
|
+
}, { duringPlacement: true }).catch(() => undefined);
|
|
773
|
+
}
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
if (receipt.returned && ["done", "failed", "gone"].includes(receipt.returned.state)) {
|
|
777
|
+
if (receipt.returned.state !== "done" && !receipt.target)
|
|
778
|
+
await confirmInterruptedLaunch(receipt);
|
|
779
|
+
await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
// Never publish an interrupted-launch failure while a launch lock is live
|
|
783
|
+
// or the durable process proof says the worker may still run.
|
|
784
|
+
let lockLive = false;
|
|
785
|
+
try {
|
|
786
|
+
lockLive = await launchInProgress(record.dispatchId);
|
|
787
|
+
}
|
|
788
|
+
catch {
|
|
789
|
+
lockLive = true;
|
|
790
|
+
}
|
|
791
|
+
if (lockLive)
|
|
792
|
+
return;
|
|
793
|
+
let alive = "unknown";
|
|
794
|
+
try {
|
|
795
|
+
alive = await workerAlive(record.dispatchId, receipt.workerFile ?? record.workerFile ?? dispatchClonePaths(record.dispatchId).workerFile, receipt.submittedAt);
|
|
796
|
+
}
|
|
797
|
+
catch {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
if (alive !== "gone")
|
|
801
|
+
return;
|
|
802
|
+
// A stale receipt can still say launching/sending; the ordinary writer
|
|
803
|
+
// refuses those, so reconcile it under the receipt lock directly.
|
|
804
|
+
const interrupted = await serializeReceiptUpdate(async () => {
|
|
805
|
+
const current = await readReceipt(receipt.id);
|
|
806
|
+
if (!current || current.target || current.closedAt)
|
|
807
|
+
return undefined;
|
|
808
|
+
if (current.returned && ["done", "failed", "gone"].includes(current.returned.state))
|
|
809
|
+
return current;
|
|
810
|
+
current.state = "failed";
|
|
811
|
+
current.error = "launch interrupted";
|
|
812
|
+
current.updatedAt = new Date().toISOString();
|
|
813
|
+
current.returned = { state: "failed", at: current.updatedAt, error: "launch interrupted", read: false };
|
|
814
|
+
if (!current.startingToken && record.startingToken)
|
|
815
|
+
current.startingToken = record.startingToken;
|
|
816
|
+
if (!current.workerFile && record.workerFile)
|
|
817
|
+
current.workerFile = record.workerFile;
|
|
818
|
+
if (!current.launchServer)
|
|
819
|
+
current.launchServer = localHost().server;
|
|
820
|
+
current.launchOutcome = current.launchOutcome ?? (record.phase === "reserved" ? "not-started" : "ambiguous");
|
|
821
|
+
if (current.launchOutcome === "not-started") {
|
|
822
|
+
current.endedAt = current.updatedAt;
|
|
823
|
+
current.retainedUntil = new Date(Date.now() + 7 * 24 * 60 * 60_000).toISOString();
|
|
824
|
+
}
|
|
825
|
+
await saveReceipt(current);
|
|
826
|
+
return current;
|
|
827
|
+
}).catch(() => undefined);
|
|
828
|
+
if (interrupted)
|
|
829
|
+
await confirmInterruptedLaunch(interrupted);
|
|
830
|
+
await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
// The launch may have recorded its arrival even if the receipt write was lost.
|
|
834
|
+
const arrival = await briefArrival(record.dispatchId).catch(() => undefined);
|
|
835
|
+
const arrived = arrival?.accepted?.target ?? arrival?.started?.target;
|
|
836
|
+
if (arrived) {
|
|
837
|
+
const at = new Date().toISOString();
|
|
838
|
+
const recovered = {
|
|
839
|
+
id: record.dispatchId,
|
|
840
|
+
computer: record.computer ?? "local",
|
|
841
|
+
project: record.project ?? "unknown",
|
|
842
|
+
harness: record.harness ?? "claude",
|
|
843
|
+
label: record.label ?? "gitboy agent",
|
|
844
|
+
createdAt: record.createdAt,
|
|
845
|
+
updatedAt: at,
|
|
846
|
+
state: "accepted",
|
|
847
|
+
target: remoteTarget.parse(arrived),
|
|
848
|
+
...(record.cloneDir ? { cloneDir: record.cloneDir } : {}),
|
|
849
|
+
...(record.gitConfigFile ? { gitConfigFile: record.gitConfigFile } : {}),
|
|
850
|
+
...(record.agentTokenFile ? { agentTokenFile: record.agentTokenFile } : {}),
|
|
851
|
+
};
|
|
852
|
+
await saveReceipt(recovered);
|
|
853
|
+
await updateIdempotencyPhase(record.key, record.owner, "launched").catch(() => undefined);
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
// The process died after reserving but before its first receipt write.
|
|
857
|
+
const at = new Date().toISOString();
|
|
858
|
+
// A no-receipt reservation is only an interrupted launch once the lock is
|
|
859
|
+
// over and the durable process proof says no worker is running.
|
|
860
|
+
let lockLive = false;
|
|
861
|
+
try {
|
|
862
|
+
lockLive = await launchInProgress(record.dispatchId);
|
|
863
|
+
}
|
|
864
|
+
catch {
|
|
865
|
+
lockLive = true;
|
|
866
|
+
}
|
|
867
|
+
if (lockLive)
|
|
868
|
+
return;
|
|
869
|
+
let alive = "unknown";
|
|
870
|
+
try {
|
|
871
|
+
alive = await workerAlive(record.dispatchId, record.workerFile ?? dispatchClonePaths(record.dispatchId).workerFile);
|
|
872
|
+
}
|
|
873
|
+
catch {
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
if (alive !== "gone")
|
|
877
|
+
return;
|
|
878
|
+
const outcome = record.phase === "reserved" ? "not-started" : "ambiguous";
|
|
879
|
+
const fallback = {
|
|
880
|
+
id: record.dispatchId,
|
|
881
|
+
computer: record.computer ?? "local",
|
|
882
|
+
project: record.project ?? "unknown",
|
|
883
|
+
harness: record.harness ?? "claude",
|
|
884
|
+
label: record.label ?? "gitboy agent",
|
|
885
|
+
createdAt: record.createdAt,
|
|
886
|
+
updatedAt: at,
|
|
887
|
+
state: "failed",
|
|
888
|
+
error: "launch interrupted",
|
|
889
|
+
returned: { state: "failed", at, error: "launch interrupted", read: false },
|
|
890
|
+
idempotencyKey: record.key,
|
|
891
|
+
launchOutcome: outcome,
|
|
892
|
+
launchServer: localHost().server,
|
|
893
|
+
...(record.startingToken ? { startingToken: record.startingToken } : {}),
|
|
894
|
+
...(outcome === "not-started" ? { endedAt: at, retainedUntil: new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString() } : {}),
|
|
895
|
+
...(record.cloneDir ? { cloneDir: record.cloneDir } : {}),
|
|
896
|
+
...(record.gitConfigFile ? { gitConfigFile: record.gitConfigFile } : {}),
|
|
897
|
+
...(record.agentTokenFile ? { agentTokenFile: record.agentTokenFile } : {}),
|
|
898
|
+
...(record.workerFile ? { workerFile: record.workerFile } : {}),
|
|
899
|
+
};
|
|
900
|
+
await saveReceipt(fallback);
|
|
901
|
+
await confirmInterruptedLaunch(fallback);
|
|
902
|
+
await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
|
|
903
|
+
}
|
|
904
|
+
/** Reconcile every live reservation; called on Hook start. */
|
|
905
|
+
export async function reconcileInterruptedDispatches() {
|
|
906
|
+
for (const record of await listIdempotencyRecords()) {
|
|
907
|
+
await reconcileIdempotencyRecord(record).catch(error => logger.warn("dispatch", `Could not reconcile idempotency key ${record.key}: ${failureReason(error)}`));
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
/** The durable record for a key after reconciliation, for cancel-by-key and dispatch retries. */
|
|
911
|
+
export async function reconcileIdempotencyKey(key) {
|
|
912
|
+
const record = await findIdempotencyKey(key);
|
|
913
|
+
if (record)
|
|
914
|
+
await reconcileIdempotencyRecord(record);
|
|
915
|
+
return record;
|
|
916
|
+
}
|
|
282
917
|
export function dispatchStatus() {
|
|
283
918
|
return serializeReceiptUpdate(readDispatchStatus);
|
|
284
919
|
}
|
|
@@ -601,6 +1236,77 @@ export class DispatchService {
|
|
|
601
1236
|
* `continues` names the dispatch whose worker hit its usage limit (account-failover.ts). */
|
|
602
1237
|
async dispatch(input, originValue, continues) {
|
|
603
1238
|
const data = dispatchSchema.parse(input);
|
|
1239
|
+
if (data.idempotencyKey && data.worktree !== true) {
|
|
1240
|
+
throw new BridgeError(400, "A dispatch with an idempotency key requires --worktree: keyed workers run only in a Phren-managed clone.");
|
|
1241
|
+
}
|
|
1242
|
+
if (data.idempotencyKey)
|
|
1243
|
+
return this.dispatchKeyed(data, randomUUID(), originValue, continues);
|
|
1244
|
+
return this.place(data, randomUUID(), originValue, continues);
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* The gitboy path: a caller that may retry after a crash names a key and
|
|
1248
|
+
* gets the dispatch that key already started. The dispatch id is generated
|
|
1249
|
+
* before the reservation, and the reservation is published atomically, so
|
|
1250
|
+
* two concurrent calls start one agent; the loser returns the winner's
|
|
1251
|
+
* receipt.
|
|
1252
|
+
*/
|
|
1253
|
+
async dispatchKeyed(data, dispatchId, originValue, continues) {
|
|
1254
|
+
const key = data.idempotencyKey;
|
|
1255
|
+
const existing = await lookupKeyedDispatch(key);
|
|
1256
|
+
if (existing)
|
|
1257
|
+
return existing;
|
|
1258
|
+
const known = await findIdempotencyKey(key);
|
|
1259
|
+
if (known?.cancelRequestedAt) {
|
|
1260
|
+
if (await launchInProgress(known.dispatchId))
|
|
1261
|
+
return { ok: false, dispatch: known.dispatchId, pending: true, existing: true };
|
|
1262
|
+
const receipt = await settleCancelledReservation(known);
|
|
1263
|
+
return { ok: false, ...receipt, dispatch: receipt.id, existing: true };
|
|
1264
|
+
}
|
|
1265
|
+
const owner = randomUUID();
|
|
1266
|
+
const paths = data.worktree === true ? dispatchClonePaths(dispatchId) : undefined;
|
|
1267
|
+
const startingToken = randomBytes(32).toString("hex");
|
|
1268
|
+
const reservation = await reserveIdempotencyKey(key, dispatchId, owner, { project: data.project, harness: data.harness, label: data.label, computer: data.computer, startingToken, ...(paths ?? {}) });
|
|
1269
|
+
if (!reservation.reserved) {
|
|
1270
|
+
const record = await waitForIdempotencyKey(key);
|
|
1271
|
+
if (!record)
|
|
1272
|
+
throw new BridgeError(503, "Another dispatch with this idempotency key did not settle; try again.");
|
|
1273
|
+
const receipt = await lookupKeyedDispatch(key);
|
|
1274
|
+
if (!receipt)
|
|
1275
|
+
throw new BridgeError(503, "The dispatch for this idempotency key has no receipt.");
|
|
1276
|
+
return receipt;
|
|
1277
|
+
}
|
|
1278
|
+
try {
|
|
1279
|
+
const result = await this.place(data, dispatchId, originValue, continues, { key, owner, startingToken, ...(paths ? { paths } : {}) });
|
|
1280
|
+
return { ...result, existing: false };
|
|
1281
|
+
}
|
|
1282
|
+
catch (error) {
|
|
1283
|
+
// A placement that never saved a receipt gives the key back; once a
|
|
1284
|
+
// receipt exists the key stays, so a retry returns that dispatch. A
|
|
1285
|
+
// receipt read failure is not proof that none exists.
|
|
1286
|
+
let receipt;
|
|
1287
|
+
try {
|
|
1288
|
+
receipt = await readReceipt(dispatchId);
|
|
1289
|
+
}
|
|
1290
|
+
catch {
|
|
1291
|
+
throw error;
|
|
1292
|
+
}
|
|
1293
|
+
if (!receipt)
|
|
1294
|
+
await releaseIdempotencyKey(key, owner).catch(() => undefined);
|
|
1295
|
+
throw error;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
async place(data, dispatchId, originValue, continues, keyed) {
|
|
1299
|
+
if (data.idempotencyKey) {
|
|
1300
|
+
if (data.harness !== "claude" && data.harness !== "codex") {
|
|
1301
|
+
throw new BridgeError(400, "A dispatch with an idempotency key may run only claude or codex; copilot, opencode and other harnesses are refused.");
|
|
1302
|
+
}
|
|
1303
|
+
if (data.permissionMode && data.permissionMode !== "supervised") {
|
|
1304
|
+
throw new BridgeError(400, `A dispatch with an idempotency key runs supervised; --permission-mode ${data.permissionMode} is refused.`);
|
|
1305
|
+
}
|
|
1306
|
+
data.permissionMode = "supervised";
|
|
1307
|
+
}
|
|
1308
|
+
if (data.branch && data.worktree !== true)
|
|
1309
|
+
throw new BridgeError(400, "--branch needs --worktree.");
|
|
604
1310
|
if (data.permissionMode && data.harness === "opencode")
|
|
605
1311
|
throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
|
|
606
1312
|
if (this.active)
|
|
@@ -626,6 +1332,9 @@ export class DispatchService {
|
|
|
626
1332
|
// An alias or hostname (`Mac`, `Sams-Mac-mini.local`) names the same computer as its hooks.yaml name.
|
|
627
1333
|
const named = data.computer === "anywhere" || isLocalComputer(data.computer, here.names) ? undefined : await linkedComputer(data.computer).catch(() => undefined);
|
|
628
1334
|
const toLocal = data.computer !== "anywhere" && (isLocalComputer(data.computer, here.names) || (named !== undefined && "local" in named));
|
|
1335
|
+
if (data.idempotencyKey && data.computer !== "anywhere" && !toLocal) {
|
|
1336
|
+
throw new BridgeError(400, "Keyed dispatches run on this computer only.");
|
|
1337
|
+
}
|
|
629
1338
|
const peerName = named && "peer" in named ? named.peer : data.computer;
|
|
630
1339
|
const enrolled = await hookPeers().catch(error => { if (toLocal || data.computer === "anywhere")
|
|
631
1340
|
return []; throw error; });
|
|
@@ -718,6 +1427,9 @@ export class DispatchService {
|
|
|
718
1427
|
throw new BridgeError(409, `${peer.name}: ${refused}`, { code: "account_pool" });
|
|
719
1428
|
}
|
|
720
1429
|
// Chosen here by pools and roles, the account goes in the launch; otherwise that computer picks, as before.
|
|
1430
|
+
// Keyed work is gitboy's runner: its clone and token never leave this Hook.
|
|
1431
|
+
if (data.idempotencyKey && !peer.local)
|
|
1432
|
+
throw new BridgeError(400, "Keyed dispatches run on this computer only.");
|
|
721
1433
|
const policyChoice = data.account ? undefined : pooled.get(peer.name);
|
|
722
1434
|
const grant = await findGrant({ action: "dispatch", project: data.project, computer: peer.name });
|
|
723
1435
|
// An agent (a call that names its pane) may start a worker only up to its grant's
|
|
@@ -731,21 +1443,112 @@ export class DispatchService {
|
|
|
731
1443
|
const checked = agent ? await checkAgentDispatch(data, grant?.maxPermissionMode ?? DEFAULT_MAX_PERMISSION_MODE) : undefined;
|
|
732
1444
|
if (checked?.permissionMode)
|
|
733
1445
|
data.permissionMode = checked.permissionMode;
|
|
1446
|
+
// A keyed dispatch never leaves supervised, whatever a grant or policy says.
|
|
1447
|
+
if (data.idempotencyKey)
|
|
1448
|
+
data.permissionMode = "supervised";
|
|
734
1449
|
const authority = checked?.authority ?? await readAuthority().then(policy => projectAuthority(policy, data.project)).catch(() => undefined);
|
|
735
1450
|
const origin = await this.origin(originValue);
|
|
736
1451
|
// Prompts are sent over the pipe, never stored in the dispatch ledger.
|
|
737
1452
|
const { prompt: originalPrompt, ...metadata } = data;
|
|
738
1453
|
const prompt = peer.local ? originalPrompt : redactPeerHandoff(originalPrompt);
|
|
739
|
-
|
|
1454
|
+
// A fresh worktree per dispatch: the caller may name its branch (gitboy's
|
|
1455
|
+
// brief does), otherwise it is derived from the idempotency key or the id.
|
|
1456
|
+
const worktree = data.worktree === true ? (data.branch ?? worktreeBranchFor(data.idempotencyKey, dispatchId)) : undefined;
|
|
1457
|
+
const startingToken = keyed?.startingToken ?? randomBytes(32).toString("hex");
|
|
1458
|
+
const receipt = { ...metadata, computer: peer.name, computerId: remoteComputerID, id: dispatchId,
|
|
740
1459
|
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), state: "launching",
|
|
1460
|
+
startingToken, launchServer: peer.server, launchOutcome: "not-started",
|
|
1461
|
+
...(worktree ? { branch: worktree } : {}),
|
|
741
1462
|
...(grant ? { granted: grantLabel(grant) } : {}), ...(authority?.listed ? { authority: authority.line.slice(0, 600) } : {}),
|
|
742
1463
|
...(checked?.confirmation ? { authorityConfirmed: checked.confirmation.confirmedAt } : {}),
|
|
743
|
-
...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}), ...(continues ? { continues } : {})
|
|
744
|
-
|
|
1464
|
+
...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}), ...(continues ? { continues } : {}),
|
|
1465
|
+
...(keyed?.paths ? { cloneDir: keyed.paths.cloneDir, gitConfigFile: keyed.paths.gitConfigFile, agentTokenFile: keyed.paths.agentTokenFile, ...(keyed.paths.workerFile ? { workerFile: keyed.paths.workerFile } : {}) } : {}) };
|
|
1466
|
+
if (keyed) {
|
|
1467
|
+
await withIdempotencyKeyLock(keyed.key, async (record) => {
|
|
1468
|
+
if (record?.cancelRequestedAt) {
|
|
1469
|
+
receipt.cancelRequestedAt = record.cancelRequestedAt;
|
|
1470
|
+
receipt.state = "failed";
|
|
1471
|
+
receipt.error = "cancelled";
|
|
1472
|
+
receipt.returned = { state: "failed", at: new Date().toISOString(), error: "cancelled", read: false };
|
|
1473
|
+
}
|
|
1474
|
+
await save(receipt, originWindow);
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1477
|
+
else
|
|
1478
|
+
await save(receipt, originWindow);
|
|
1479
|
+
const keyCancelled = async () => {
|
|
1480
|
+
if (!keyed)
|
|
1481
|
+
return false;
|
|
1482
|
+
const durable = await updateReceipt(receipt.id, () => false, { duringPlacement: true });
|
|
1483
|
+
const record = await findIdempotencyKey(keyed.key);
|
|
1484
|
+
if (!durable?.cancelRequestedAt && !record?.cancelRequestedAt)
|
|
1485
|
+
return false;
|
|
1486
|
+
receipt.state = "failed";
|
|
1487
|
+
receipt.error = "cancelled";
|
|
1488
|
+
receipt.returned = { state: "failed", at: new Date().toISOString(), error: "cancelled", read: false };
|
|
1489
|
+
await persistReceipt(receipt, originWindow);
|
|
1490
|
+
await updateIdempotencyPhase(keyed.key, keyed.owner, "failed").catch(() => undefined);
|
|
1491
|
+
return true;
|
|
1492
|
+
};
|
|
1493
|
+
if (await keyCancelled())
|
|
1494
|
+
return { ok: false, ...receipt, dispatch: receipt.id, existing: false };
|
|
1495
|
+
const cancelIfRequested = async () => {
|
|
1496
|
+
const durable = await updateReceipt(receipt.id, () => false, { duringPlacement: true });
|
|
1497
|
+
if (!durable?.cancelRequestedAt)
|
|
1498
|
+
return undefined;
|
|
1499
|
+
const { closeVerifiedWorker } = await import("./worker-close.js");
|
|
1500
|
+
const result = await closeVerifiedWorker(durable);
|
|
1501
|
+
if (result.pending && (durable.state === "launching" || durable.state === "sending")) {
|
|
1502
|
+
await persistReceipt(receipt, originWindow, value => {
|
|
1503
|
+
if (value.state === "launching" || value.state === "sending")
|
|
1504
|
+
value.state = "uncertain";
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
// A cancelled placement settles its key, so a repeated key reports it.
|
|
1508
|
+
if (keyed && !result.pending)
|
|
1509
|
+
await updateIdempotencyPhase(keyed.key, keyed.owner, "failed").catch(() => undefined);
|
|
1510
|
+
// The caller gets the dispatch's receipt, settled as cancelled (or
|
|
1511
|
+
// still pending), not the close result alone.
|
|
1512
|
+
const settled = await updateReceipt(receipt.id, () => false, { duringPlacement: true });
|
|
1513
|
+
return { ok: true, ...(settled ?? {}), ...(result.pending ? { pending: true } : {}), dispatch: receipt.id, existing: false };
|
|
1514
|
+
};
|
|
745
1515
|
try {
|
|
1516
|
+
if (keyed && !await updateIdempotencyPhase(keyed.key, keyed.owner, "launching")) {
|
|
1517
|
+
throw new BridgeError(409, "This dispatch no longer owns its idempotency key.");
|
|
1518
|
+
}
|
|
1519
|
+
if (await keyCancelled())
|
|
1520
|
+
return { ok: false, ...receipt, dispatch: receipt.id, existing: false };
|
|
1521
|
+
// The request is about to be sent: from here its outcome may be unknown.
|
|
1522
|
+
if (data.idempotencyKey) {
|
|
1523
|
+
const submittedAt = new Date().toISOString();
|
|
1524
|
+
await markSubmitted(dispatchId, new Date(submittedAt));
|
|
1525
|
+
receipt.submittedAt = submittedAt;
|
|
1526
|
+
}
|
|
1527
|
+
receipt.launchOutcome = "ambiguous";
|
|
1528
|
+
await persistReceipt(receipt, originWindow);
|
|
746
1529
|
// The brief goes with the launch: a Hook that can start the harness
|
|
747
1530
|
// with it says so, and any other types it below.
|
|
748
|
-
const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ?? policyChoice?.account ? { account: data.account ?? policyChoice.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), label: peer.local ? data.label : redactPeerHandoff(data.label), brief: { id: receipt.id, text: prompt } });
|
|
1531
|
+
const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ?? policyChoice?.account ? { account: data.account ?? policyChoice.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), ...(worktree ? { worktree: { branch: worktree } } : {}), startingToken, ...(data.idempotencyKey ? { idempotencyKey: data.idempotencyKey, dispatchId: receipt.id, ...(keyed?.paths ? { phrenPaths: keyed.paths } : {}) } : {}), label: peer.local ? data.label : redactPeerHandoff(data.label), brief: { id: receipt.id, text: prompt, ...(data.task ? { task: data.task } : {}) } });
|
|
1532
|
+
const parsedLaunched = remoteTarget.safeParse(launched.target);
|
|
1533
|
+
if (typeof launched.cloneDir === "string")
|
|
1534
|
+
receipt.cloneDir = launched.cloneDir;
|
|
1535
|
+
if (typeof launched.gitConfigFile === "string")
|
|
1536
|
+
receipt.gitConfigFile = launched.gitConfigFile;
|
|
1537
|
+
if (typeof launched.agentTokenFile === "string")
|
|
1538
|
+
receipt.agentTokenFile = launched.agentTokenFile;
|
|
1539
|
+
if (typeof launched.workerFile === "string")
|
|
1540
|
+
receipt.workerFile = launched.workerFile;
|
|
1541
|
+
// Persist the binding and cleanup paths before any snapshot or arrival wait.
|
|
1542
|
+
if (parsedLaunched.success && parsedLaunched.data.source === data.harness && parsedLaunched.data.server === peer.server) {
|
|
1543
|
+
receipt.target = parsedLaunched.data;
|
|
1544
|
+
receipt.launchOutcome = "started";
|
|
1545
|
+
await persistReceipt(receipt, originWindow);
|
|
1546
|
+
}
|
|
1547
|
+
if (keyed)
|
|
1548
|
+
await updateIdempotencyPhase(keyed.key, keyed.owner, "launched").catch(() => undefined);
|
|
1549
|
+
const cancelledAfterLaunch = await cancelIfRequested();
|
|
1550
|
+
if (cancelledAfterLaunch)
|
|
1551
|
+
return cancelledAfterLaunch;
|
|
749
1552
|
// Placed: the brief is confirmed outside the lock.
|
|
750
1553
|
placed = peer.name;
|
|
751
1554
|
this.placing.set(placed, this.inFlight(placed) + 1);
|
|
@@ -770,9 +1573,11 @@ export class DispatchService {
|
|
|
770
1573
|
await this.confirmLaunched(peer, receipt, launched, originWindow);
|
|
771
1574
|
if (ignored)
|
|
772
1575
|
receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
|
|
773
|
-
receipt
|
|
774
|
-
await
|
|
775
|
-
|
|
1576
|
+
await persistReceipt(receipt, originWindow);
|
|
1577
|
+
const cancelledAfterConfirm = await cancelIfRequested();
|
|
1578
|
+
if (cancelledAfterConfirm)
|
|
1579
|
+
return cancelledAfterConfirm;
|
|
1580
|
+
return { ok: receipt.state === "accepted", ...receipt, dispatch: receipt.id, existing: false };
|
|
776
1581
|
}
|
|
777
1582
|
receipt.brief = "typed";
|
|
778
1583
|
const settled = launched.target ? { target: launched.target } : await settledTarget(peer, launched, data.harness, this.settleIntervalMs);
|
|
@@ -785,15 +1590,18 @@ export class DispatchService {
|
|
|
785
1590
|
if (target.source !== data.harness || target.server !== peer.server)
|
|
786
1591
|
throw new BridgeError(502, "The remote Hook returned a different launch target.");
|
|
787
1592
|
receipt.target = target;
|
|
1593
|
+
receipt.launchOutcome = "started";
|
|
788
1594
|
receipt.state = "sending";
|
|
789
|
-
receipt
|
|
790
|
-
await save(receipt, originWindow);
|
|
1595
|
+
await persistReceipt(receipt, originWindow);
|
|
791
1596
|
if (!("starting" in target)) {
|
|
792
1597
|
const result = await sendBrief(peer, target, prompt, `dispatch-${receipt.id}`);
|
|
793
1598
|
receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
|
|
794
1599
|
}
|
|
795
1600
|
else
|
|
796
1601
|
await this.typeIntoStarting(peer, receipt, target, prompt);
|
|
1602
|
+
const cancelledAfterSend = await cancelIfRequested();
|
|
1603
|
+
if (cancelledAfterSend)
|
|
1604
|
+
return cancelledAfterSend;
|
|
797
1605
|
if (ignored)
|
|
798
1606
|
receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
|
|
799
1607
|
}
|
|
@@ -801,19 +1609,23 @@ export class DispatchService {
|
|
|
801
1609
|
if (error instanceof StartupScreen) {
|
|
802
1610
|
// Known, not uncertain: the brief never reached the pane. Say where
|
|
803
1611
|
// the owner answers, and let the returns loop tell the conductor once.
|
|
1612
|
+
receipt.launchOutcome = "started";
|
|
804
1613
|
const question = `${data.harness} in "${data.label}" on ${peer.name} is waiting on a startup screen (folder trust or sign-in).`.slice(0, 200);
|
|
805
1614
|
receipt.state = "failed";
|
|
806
1615
|
receipt.error = `${question} The brief was not sent. Answer that screen in the pane (the phone can), then hand the brief off to the new session.`.slice(0, 500);
|
|
807
1616
|
receipt.returned = { state: "needs-you", at: new Date().toISOString(), question, read: false };
|
|
808
1617
|
}
|
|
809
1618
|
else {
|
|
1619
|
+
if (receipt.target)
|
|
1620
|
+
receipt.launchOutcome = "started";
|
|
1621
|
+
else
|
|
1622
|
+
receipt.launchOutcome = launchFailureOutcome(error);
|
|
810
1623
|
receipt.state = receipt.state === "launching" && error instanceof BridgeError && [400, 404, 429, 504].includes(error.status) ? "failed" : "uncertain";
|
|
811
1624
|
receipt.error = error instanceof BridgeError ? error.message.slice(0, 500) : "Remote delivery was not confirmed. Inspect this dispatch before retrying.";
|
|
812
1625
|
}
|
|
813
1626
|
}
|
|
814
|
-
receipt
|
|
815
|
-
|
|
816
|
-
return { ok: receipt.state === "accepted", ...receipt };
|
|
1627
|
+
await persistReceipt(receipt, originWindow);
|
|
1628
|
+
return { ok: receipt.state === "accepted", ...receipt, dispatch: receipt.id, existing: false };
|
|
817
1629
|
}
|
|
818
1630
|
finally {
|
|
819
1631
|
originWindow.finish();
|
|
@@ -901,6 +1713,7 @@ export class DispatchService {
|
|
|
901
1713
|
const full = session ? targetSchema.safeParse({ server: target.server, workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source, session }) : undefined;
|
|
902
1714
|
if (full?.success)
|
|
903
1715
|
receipt.target = full.data;
|
|
1716
|
+
receipt.launchOutcome = "started";
|
|
904
1717
|
receipt.state = "accepted";
|
|
905
1718
|
};
|
|
906
1719
|
for (let attempt = 1;; attempt++) {
|
|
@@ -949,17 +1762,20 @@ export class DispatchService {
|
|
|
949
1762
|
*/
|
|
950
1763
|
async confirmLaunched(peer, receipt, launched, originWindow) {
|
|
951
1764
|
const known = remoteTarget.safeParse(launched.target);
|
|
952
|
-
if (known.success && known.data.source === receipt.harness && known.data.server === peer.server)
|
|
1765
|
+
if (known.success && known.data.source === receipt.harness && known.data.server === peer.server) {
|
|
953
1766
|
receipt.target = known.data;
|
|
1767
|
+
receipt.launchOutcome = "started";
|
|
1768
|
+
}
|
|
954
1769
|
receipt.state = "sending";
|
|
955
|
-
receipt
|
|
956
|
-
await save(receipt, originWindow);
|
|
1770
|
+
await persistReceipt(receipt, originWindow);
|
|
957
1771
|
const held = (status) => ["blocked", "waiting"].includes(String(status));
|
|
958
1772
|
const arrival = held(launched.agentStatus) ? await arrivalOf(peer, receipt.id).catch(() => undefined) ?? {}
|
|
959
1773
|
: await awaitArrival(peer, receipt.id, this.settleIntervalMs);
|
|
960
1774
|
const named = arrival.accepted?.target ?? arrival.started?.target;
|
|
961
|
-
if (named && named.source === receipt.harness && named.server === peer.server)
|
|
1775
|
+
if (named && named.source === receipt.harness && named.server === peer.server) {
|
|
962
1776
|
receipt.target = named;
|
|
1777
|
+
receipt.launchOutcome = "started";
|
|
1778
|
+
}
|
|
963
1779
|
if (arrival.accepted) {
|
|
964
1780
|
receipt.state = "accepted";
|
|
965
1781
|
return;
|