@phren/cli 0.3.71 → 0.3.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hooks.js +11 -1
- package/dist/bridge/browser-env.d.ts +5 -0
- package/dist/bridge/browser-env.js +110 -0
- package/dist/bridge/browser-protocol.d.ts +120 -0
- package/dist/bridge/browser-protocol.js +70 -0
- package/dist/bridge/browser-recordings.d.ts +63 -0
- package/dist/bridge/browser-recordings.js +148 -0
- package/dist/bridge/browser-registry.d.ts +64 -0
- package/dist/bridge/browser-registry.js +262 -0
- package/dist/bridge/browser-routes.d.ts +4 -0
- package/dist/bridge/browser-routes.js +39 -0
- package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
- package/dist/bridge/browser-socket.d.ts +2 -0
- package/dist/bridge/browser-socket.js +10 -0
- package/dist/bridge/browser-stream.d.ts +3 -0
- package/dist/bridge/browser-stream.js +129 -0
- package/dist/bridge/browser-watch.d.ts +12 -0
- package/dist/bridge/browser-watch.js +83 -0
- package/dist/bridge/claude-account-setup.js +3 -1
- package/dist/bridge/claude-accounts.d.ts +5 -1
- package/dist/bridge/claude-accounts.js +36 -6
- package/dist/bridge/codex-servers.d.ts +2 -0
- package/dist/bridge/codex-servers.js +1 -1
- package/dist/bridge/command.js +24 -5
- package/dist/bridge/dispatch-clone.d.ts +33 -0
- package/dist/bridge/dispatch-clone.js +176 -0
- package/dist/bridge/dispatch-command.d.ts +14 -0
- package/dist/bridge/dispatch-command.js +98 -13
- package/dist/bridge/dispatch-idempotency.d.ts +85 -0
- package/dist/bridge/dispatch-idempotency.js +235 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -0
- package/dist/bridge/dispatch-returns.js +131 -1
- package/dist/bridge/dispatch-wait.d.ts +32 -0
- package/dist/bridge/dispatch-wait.js +177 -0
- package/dist/bridge/dispatch.d.ts +78 -2
- package/dist/bridge/dispatch.js +841 -25
- package/dist/bridge/dream-schedule.d.ts +133 -0
- package/dist/bridge/dream-schedule.js +322 -0
- package/dist/bridge/fanouts.js +20 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/git-credential.d.ts +44 -0
- package/dist/bridge/git-credential.js +113 -0
- package/dist/bridge/git-host-auth.d.ts +9 -1
- package/dist/bridge/git-host-auth.js +18 -5
- package/dist/bridge/git-host-gitboy.js +8 -1
- package/dist/bridge/git-hosts.d.ts +12 -1
- package/dist/bridge/git-publish.js +3 -2
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +44 -9
- package/dist/bridge/install.d.ts +1 -1
- package/dist/bridge/install.js +12 -4
- package/dist/bridge/launch-brief.d.ts +11 -0
- package/dist/bridge/launch-brief.js +22 -0
- package/dist/bridge/launch-worktree.d.ts +2 -0
- package/dist/bridge/launch-worktree.js +5 -1
- package/dist/bridge/pane-status.js +1 -1
- package/dist/bridge/protocol.d.ts +7 -0
- package/dist/bridge/schedule-watch.js +13 -2
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +251 -145
- package/dist/bridge/server-routes.d.ts +3 -0
- package/dist/bridge/server-routes.js +33 -17
- package/dist/bridge/server-stream.d.ts +4 -0
- package/dist/bridge/server-stream.js +24 -5
- package/dist/bridge/server.js +35 -4
- package/dist/bridge/session-move.d.ts +10 -4
- package/dist/bridge/session-move.js +65 -34
- package/dist/bridge/simulator-stream.d.ts +2 -0
- package/dist/bridge/simulator-stream.js +2 -0
- package/dist/bridge/status-line-fast.d.ts +9 -0
- package/dist/bridge/status-line-fast.js +56 -0
- package/dist/bridge/tab-activity.d.ts +2 -0
- package/dist/bridge/tab-activity.js +15 -2
- package/dist/bridge/task-routes.d.ts +20 -16
- package/dist/bridge/task-routes.js +1 -1
- package/dist/bridge/terminal-herdr.d.ts +5 -1
- package/dist/bridge/terminal-herdr.js +67 -2
- package/dist/bridge/terminal-tmux.d.ts +2 -0
- package/dist/bridge/terminal-tmux.js +29 -7
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.js +192 -112
- package/dist/bridge/transcript-preview.d.ts +2 -1
- package/dist/bridge/transcript-preview.js +85 -3
- package/dist/bridge/transcripts.js +17 -11
- package/dist/bridge/turn-records.js +16 -4
- package/dist/bridge/usage.d.ts +7 -1
- package/dist/bridge/usage.js +47 -31
- package/dist/bridge/worker-close.d.ts +15 -0
- package/dist/bridge/worker-close.js +304 -3
- package/dist/bridge/worker-identity.d.ts +51 -0
- package/dist/bridge/worker-identity.js +289 -0
- package/dist/bridge/worker-reports.js +15 -3
- package/dist/bridge-hook.mjs +39990 -36152
- package/dist/capabilities/mcp.js +1 -1
- package/dist/cli/browser-hint.d.ts +2 -0
- package/dist/cli/browser-hint.js +21 -0
- package/dist/cli/config-dreaming.d.ts +7 -0
- package/dist/cli/config-dreaming.js +72 -0
- package/dist/cli/config.js +6 -0
- package/dist/cli/dream.d.ts +59 -0
- package/dist/cli/dream.js +315 -0
- package/dist/cli/hooks-context.d.ts +2 -2
- package/dist/cli/hooks-context.js +3 -3
- package/dist/cli/hooks.js +20 -11
- package/dist/cli/namespaces-tasks.js +14 -0
- package/dist/cli-registry.js +28 -3
- package/dist/config/dreaming.d.ts +82 -0
- package/dist/config/dreaming.js +195 -0
- package/dist/config/resolve.js +11 -0
- package/dist/config/schema.d.ts +4 -4
- package/dist/config/schema.js +157 -1
- package/dist/content/citation-freshness.js +6 -0
- package/dist/content/learning.d.ts +1 -0
- package/dist/content/learning.js +2 -0
- package/dist/data/access.d.ts +1 -1
- package/dist/data/access.js +3 -1
- package/dist/data/task-contract.d.ts +5 -4
- package/dist/data/tasks.d.ts +5 -0
- package/dist/data/tasks.js +28 -2
- package/dist/dream/apply.d.ts +69 -0
- package/dist/dream/apply.js +372 -0
- package/dist/dream/budget.d.ts +78 -0
- package/dist/dream/budget.js +180 -0
- package/dist/dream/collect.d.ts +86 -0
- package/dist/dream/collect.js +449 -0
- package/dist/dream/eval/dream-adapter.d.ts +16 -0
- package/dist/dream/eval/dream-adapter.js +21 -0
- package/dist/dream/eval/fixture.d.ts +53 -0
- package/dist/dream/eval/fixture.js +172 -0
- package/dist/dream/eval/index.d.ts +40 -0
- package/dist/dream/eval/index.js +78 -0
- package/dist/dream/eval/score.d.ts +34 -0
- package/dist/dream/eval/score.js +99 -0
- package/dist/dream/eval/scripted-model.d.ts +19 -0
- package/dist/dream/eval/scripted-model.js +70 -0
- package/dist/dream/pages.d.ts +68 -0
- package/dist/dream/pages.js +220 -0
- package/dist/dream/privacy.d.ts +3 -0
- package/dist/dream/privacy.js +18 -0
- package/dist/dream/prompt.d.ts +13 -0
- package/dist/dream/prompt.js +84 -0
- package/dist/dream/run.d.ts +98 -0
- package/dist/dream/run.js +317 -0
- package/dist/dream/types.d.ts +74 -0
- package/dist/dream/types.js +4 -0
- package/dist/finding/lifecycle.d.ts +2 -2
- package/dist/finding/lifecycle.js +5 -2
- package/dist/finding/versions.d.ts +4 -0
- package/dist/finding/versions.js +28 -0
- package/dist/index.js +1 -0
- package/dist/modules/registry.js +10 -8
- package/dist/project-config.d.ts +3 -0
- package/dist/task/merge-links.d.ts +38 -0
- package/dist/task/merge-links.js +45 -0
- package/dist/task/reconcile.d.ts +39 -0
- package/dist/task/reconcile.js +201 -0
- package/dist/task/report-links.d.ts +10 -0
- package/dist/task/report-links.js +47 -0
- package/dist/tools/config.js +46 -4
- package/dist/tools/dispatch.js +2 -1
- package/dist/tools/dream.d.ts +3 -0
- package/dist/tools/dream.js +123 -0
- package/dist/tools/tasks.js +4 -1
- package/package.json +1 -1
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { ownerInboxSchema } from "./owner-inbox.js";
|
|
2
2
|
import { prsSchema } from "./return-contract.js";
|
|
3
|
+
import { createReadStream } from "node:fs";
|
|
4
|
+
import { stat } from "node:fs/promises";
|
|
5
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
6
|
import { parseArgs } from "node:util";
|
|
4
7
|
import { hookRequest } from "./client.js";
|
|
5
|
-
import { dispatchSchema } from "./dispatch.js";
|
|
8
|
+
import { DISPATCH_PROMPT_LIMIT, dispatchSchema } from "./dispatch.js";
|
|
9
|
+
import { idempotencyKeySchema } from "./dispatch-idempotency.js";
|
|
10
|
+
import { waitForDispatch } from "./dispatch-wait.js";
|
|
6
11
|
import { handOff, moveSession } from "./hand-off.js";
|
|
7
12
|
import { terminalPaneFromEnv } from "./terminal.js";
|
|
8
13
|
import { dispatchIdFromEnv } from "./launch-brief.js";
|
|
@@ -67,16 +72,86 @@ export async function runDispatch(args) {
|
|
|
67
72
|
console.log(JSON.stringify(await listLiveSessions(), null, 2));
|
|
68
73
|
return 0;
|
|
69
74
|
}
|
|
75
|
+
if (args[0] === "wait") {
|
|
76
|
+
const { values, positionals } = parseArgs({ args: args.slice(1), allowPositionals: true, options: {
|
|
77
|
+
timeout: { type: "string" }, json: { type: "boolean" }, follow: { type: "boolean" },
|
|
78
|
+
} });
|
|
79
|
+
if (positionals.length !== 1)
|
|
80
|
+
throw new Error("Usage: phren dispatch wait <dispatch-id> [--timeout <seconds>] [--json] [--follow]");
|
|
81
|
+
const seconds = values.timeout === undefined ? undefined : Number(values.timeout);
|
|
82
|
+
if (seconds !== undefined && (!Number.isFinite(seconds) || seconds < 0))
|
|
83
|
+
throw new Error("--timeout is a non-negative number of seconds.");
|
|
84
|
+
return waitForDispatch(positionals[0], { timeoutMs: seconds === undefined ? undefined : seconds * 1000 });
|
|
85
|
+
}
|
|
86
|
+
if (args[0] === "close") {
|
|
87
|
+
const result = await hookRequest("/v1/dispatch/cancel", closeRequestFromArgs(args.slice(1)));
|
|
88
|
+
console.log(JSON.stringify({ ...(typeof result.dispatch === "string" ? { dispatch: result.dispatch } : {}), closed: result.closed === true,
|
|
89
|
+
...(result.pending === true ? { pending: true } : {}) }, null, 2));
|
|
90
|
+
return result.pending === true ? 1 : 0;
|
|
91
|
+
}
|
|
92
|
+
const input = await dispatchInputFromArgs(args);
|
|
93
|
+
// Run inside an agent's pane, the dispatch remembers that pane for return notices.
|
|
94
|
+
const origin = await terminalPaneFromEnv();
|
|
95
|
+
const result = await hookRequest("/v1/dispatch", { ...input, ...(origin ? { origin } : {}) }, undefined, 180_000);
|
|
96
|
+
console.log(JSON.stringify(result, null, 2));
|
|
97
|
+
return result.ok === true || result.existing === true ? 0 : 1;
|
|
98
|
+
}
|
|
99
|
+
const DISPATCH_USAGE = "Usage: phren dispatch <computer|anywhere|local> <project> --prompt <brief> | --prompt-file <path|-> [--harness codex|claude|opencode|copilot] [--label <label>] [--idempotency-key <key>] [--worktree [--branch <name>]] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]";
|
|
100
|
+
/** The brief limit shared with dispatchSchema. */
|
|
101
|
+
export const PROMPT_LIMIT = DISPATCH_PROMPT_LIMIT;
|
|
102
|
+
/** A brief from a file, or stdin for `-`. The text never goes through argv. */
|
|
103
|
+
export async function readPromptFile(file, stdin = process.stdin) {
|
|
104
|
+
if (file !== "-") {
|
|
105
|
+
const info = await stat(file);
|
|
106
|
+
if (info.size > PROMPT_LIMIT)
|
|
107
|
+
throw new Error(`Worker brief is too large: ${info.size} bytes; the limit is ${PROMPT_LIMIT} characters.`);
|
|
108
|
+
}
|
|
109
|
+
const stream = file === "-" ? stdin : createReadStream(file);
|
|
110
|
+
const decoder = new StringDecoder("utf8");
|
|
111
|
+
let prompt = "";
|
|
112
|
+
try {
|
|
113
|
+
for await (const chunk of stream) {
|
|
114
|
+
prompt += decoder.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
|
115
|
+
if (prompt.length > PROMPT_LIMIT) {
|
|
116
|
+
throw new Error(`Worker brief is too large: more than ${PROMPT_LIMIT} characters.`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
prompt += decoder.end();
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
if (file !== "-")
|
|
123
|
+
stream.destroy();
|
|
124
|
+
}
|
|
125
|
+
if (prompt.length > PROMPT_LIMIT)
|
|
126
|
+
throw new Error(`Worker brief is too large: ${prompt.length} characters; the limit is ${PROMPT_LIMIT}.`);
|
|
127
|
+
return prompt;
|
|
128
|
+
}
|
|
129
|
+
/** The dispatch form's argv, prompt file/stdin and defaults, without reaching a Hook. */
|
|
130
|
+
export async function dispatchInputFromArgs(args, stdin = process.stdin) {
|
|
70
131
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
|
|
71
132
|
"keep-open": { type: "boolean" },
|
|
72
|
-
harness: { type: "string", default: "codex" }, model: { type: "string" }, effort: { type: "string" }, account: { type: "string" }, "permission-mode": { type: "string" },
|
|
133
|
+
harness: { type: "string", default: "codex" }, model: { type: "string" }, effort: { type: "string" }, account: { type: "string" }, "permission-mode": { type: "string" },
|
|
134
|
+
prompt: { type: "string" }, "prompt-file": { type: "string" }, label: { type: "string" }, "idempotency-key": { type: "string" },
|
|
135
|
+
worktree: { type: "boolean" }, branch: { type: "string" },
|
|
73
136
|
"parent-provider": { type: "string" }, "parent-session": { type: "string" }, "parent-computer": { type: "string" },
|
|
74
137
|
"parent-server": { type: "string" }, "parent-workspace": { type: "string" }, "parent-tab": { type: "string" }, "parent-pane": { type: "string" },
|
|
75
138
|
} });
|
|
76
139
|
if (positionals.length !== 2)
|
|
77
|
-
throw new Error(
|
|
140
|
+
throw new Error(DISPATCH_USAGE);
|
|
141
|
+
const [computer, project] = positionals;
|
|
142
|
+
const promptFile = values["prompt-file"];
|
|
143
|
+
if ((values.prompt === undefined) === (promptFile === undefined))
|
|
144
|
+
throw new Error("Give exactly one of --prompt and --prompt-file.");
|
|
145
|
+
const prompt = promptFile !== undefined ? await readPromptFile(promptFile, stdin) : values.prompt;
|
|
146
|
+
const key = values["idempotency-key"];
|
|
147
|
+
if (key !== undefined && !idempotencyKeySchema.safeParse(key).success) {
|
|
148
|
+
throw new Error(idempotencyKeySchema.safeParse(key).error.issues[0]?.message ?? "Invalid idempotency key.");
|
|
149
|
+
}
|
|
150
|
+
const label = values.label ?? (computer === "local" ? (key ? key.slice(0, 60) : "gitboy agent") : undefined);
|
|
151
|
+
if (values.branch !== undefined && !values.worktree)
|
|
152
|
+
throw new Error("--branch needs --worktree.");
|
|
78
153
|
const parentValues = ["parent-provider", "parent-session", "parent-computer", "parent-server", "parent-workspace", "parent-tab", "parent-pane"];
|
|
79
|
-
const hasParent = parentValues.some(
|
|
154
|
+
const hasParent = parentValues.some(name => values[name] !== undefined);
|
|
80
155
|
const parent = hasParent ? {
|
|
81
156
|
provider: values["parent-provider"], session: values["parent-session"], computer: values["parent-computer"],
|
|
82
157
|
} : undefined;
|
|
@@ -84,21 +159,31 @@ export async function runDispatch(args) {
|
|
|
84
159
|
server: values["parent-server"], workspace: values["parent-workspace"], tab: values["parent-tab"], pane: values["parent-pane"],
|
|
85
160
|
source: values["parent-provider"], session: values["parent-session"],
|
|
86
161
|
} : undefined;
|
|
87
|
-
const { "permission-mode": permissionMode, "keep-open": keepOpen, ...rest } = values;
|
|
88
|
-
const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([
|
|
89
|
-
|
|
162
|
+
const { "permission-mode": permissionMode, "keep-open": keepOpen, prompt: _prompt, "prompt-file": _promptFile, "idempotency-key": _key, worktree, branch, ...rest } = values;
|
|
163
|
+
const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([name]) => !name.startsWith("parent-"))),
|
|
164
|
+
...(permissionMode !== undefined ? { permissionMode } : {}), ...(keepOpen ? { closeOnFinish: false } : {}),
|
|
165
|
+
...(worktree ? { worktree: true } : {}), ...(branch !== undefined ? { branch } : {}), ...(key !== undefined ? { idempotencyKey: key } : {}) };
|
|
166
|
+
const parsed = dispatchSchema.safeParse({ computer, project, prompt, ...(label !== undefined ? { label } : {}), ...ordinary,
|
|
90
167
|
...(parent ? { parent, parentTarget } : {}) });
|
|
91
168
|
if (!parsed.success) {
|
|
92
169
|
// Name the flag, not a schema path: a missing --label or --prompt is the usual slip.
|
|
93
170
|
const flag = (path) => path.length ? (["computer", "project"].includes(String(path[0])) ? `<${String(path[0])}>` : `--${String(path[0]).replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`) : "input";
|
|
94
171
|
throw new Error(`phren dispatch: ${parsed.error.issues.map(issue => `${flag(issue.path)} ${issue.code === "invalid_type" && /received undefined/.test(issue.message) ? "is required" : issue.message}`).join("; ")}. Run phren dispatch for usage.`);
|
|
95
172
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
173
|
+
return parsed.data;
|
|
174
|
+
}
|
|
175
|
+
/** Exactly one of a dispatch id and an idempotency key, for `dispatch close`. */
|
|
176
|
+
export function closeRequestFromArgs(args) {
|
|
177
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { "idempotency-key": { type: "string" } } });
|
|
178
|
+
const key = values["idempotency-key"];
|
|
179
|
+
const id = positionals[0];
|
|
180
|
+
if (positionals.length > 1 || (id === undefined) === (key === undefined)) {
|
|
181
|
+
throw new Error("Usage: phren dispatch close <dispatch-id> | phren dispatch close --idempotency-key <key>");
|
|
182
|
+
}
|
|
183
|
+
if (key !== undefined && !idempotencyKeySchema.safeParse(key).success) {
|
|
184
|
+
throw new Error(idempotencyKeySchema.safeParse(key).error.issues[0]?.message ?? "Invalid idempotency key.");
|
|
185
|
+
}
|
|
186
|
+
return key !== undefined ? { idempotencyKey: key } : { dispatch: id };
|
|
102
187
|
}
|
|
103
188
|
export async function runHandOff(args) {
|
|
104
189
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* Idempotency keys for local dispatches (`phren dispatch local ... --idempotency-key`).
|
|
4
|
+
* A reservation is written to a temp file and published with `link`, which is
|
|
5
|
+
* atomic and fails with EEXIST: an empty or half-written file is never a
|
|
6
|
+
* reservation another caller can reclaim. Every update or delete checks the
|
|
7
|
+
* owner nonce. The per-key mutex is in-process because only the Hook server
|
|
8
|
+
* process mutates key records; the CLI reaches it through Hook routes.
|
|
9
|
+
*/
|
|
10
|
+
export declare const IDEMPOTENCY_TTL_MS: number;
|
|
11
|
+
/** A reservation that has not reached "launched" is interrupted after this. */
|
|
12
|
+
export declare const LAUNCH_INTERRUPTED_MS: number;
|
|
13
|
+
export declare const idempotencyKeySchema: z.ZodString;
|
|
14
|
+
declare const phaseSchema: z.ZodEnum<{
|
|
15
|
+
failed: "failed";
|
|
16
|
+
launched: "launched";
|
|
17
|
+
launching: "launching";
|
|
18
|
+
reserved: "reserved";
|
|
19
|
+
}>;
|
|
20
|
+
declare const recordSchema: z.ZodObject<{
|
|
21
|
+
key: z.ZodString;
|
|
22
|
+
dispatchId: z.ZodString;
|
|
23
|
+
owner: z.ZodString;
|
|
24
|
+
createdAt: z.ZodString;
|
|
25
|
+
phase: z.ZodEnum<{
|
|
26
|
+
failed: "failed";
|
|
27
|
+
launched: "launched";
|
|
28
|
+
launching: "launching";
|
|
29
|
+
reserved: "reserved";
|
|
30
|
+
}>;
|
|
31
|
+
project: z.ZodOptional<z.ZodString>;
|
|
32
|
+
harness: z.ZodOptional<z.ZodString>;
|
|
33
|
+
label: z.ZodOptional<z.ZodString>;
|
|
34
|
+
computer: z.ZodOptional<z.ZodString>;
|
|
35
|
+
cloneDir: z.ZodOptional<z.ZodString>;
|
|
36
|
+
gitConfigFile: z.ZodOptional<z.ZodString>;
|
|
37
|
+
agentTokenFile: z.ZodOptional<z.ZodString>;
|
|
38
|
+
workerFile: z.ZodOptional<z.ZodString>;
|
|
39
|
+
startingToken: z.ZodOptional<z.ZodString>;
|
|
40
|
+
cancelRequestedAt: z.ZodOptional<z.ZodString>;
|
|
41
|
+
}, z.core.$strict>;
|
|
42
|
+
export type IdempotencyRecord = z.infer<typeof recordSchema>;
|
|
43
|
+
export type IdempotencyPhase = z.infer<typeof phaseSchema>;
|
|
44
|
+
export declare const idempotencyKeyFile: (key: string) => string;
|
|
45
|
+
/** Called by the Hook server before it handles dispatches. */
|
|
46
|
+
export declare function markHookServerProcess(): void;
|
|
47
|
+
/** Delete lock and reclaim files left by an older Hook or a crash. */
|
|
48
|
+
export declare function cleanupIdempotencyLocks(): Promise<void>;
|
|
49
|
+
export type KeyReservation = {
|
|
50
|
+
reserved: true;
|
|
51
|
+
record: IdempotencyRecord;
|
|
52
|
+
} | {
|
|
53
|
+
reserved: false;
|
|
54
|
+
record: IdempotencyRecord;
|
|
55
|
+
};
|
|
56
|
+
export interface KeySeed {
|
|
57
|
+
project?: string;
|
|
58
|
+
harness?: string;
|
|
59
|
+
label?: string;
|
|
60
|
+
computer?: string;
|
|
61
|
+
cloneDir?: string;
|
|
62
|
+
gitConfigFile?: string;
|
|
63
|
+
agentTokenFile?: string;
|
|
64
|
+
workerFile?: string;
|
|
65
|
+
startingToken?: string;
|
|
66
|
+
}
|
|
67
|
+
/** Reserve `key` for this caller, with its dispatch id, atomically. */
|
|
68
|
+
export declare function reserveIdempotencyKey(key: string, dispatchId: string, owner: string, seed?: KeySeed, now?: number): Promise<KeyReservation>;
|
|
69
|
+
/** Move the reservation's phase. False when this caller no longer owns it. */
|
|
70
|
+
export declare function updateIdempotencyPhase(key: string, owner: string, phase: IdempotencyPhase): Promise<boolean>;
|
|
71
|
+
/** Run under the key's in-process mutex, with the current reservation record. */
|
|
72
|
+
export declare function withIdempotencyKeyLock<T>(key: string, run: (record: IdempotencyRecord | undefined, save: (record: IdempotencyRecord) => Promise<void>) => Promise<T>): Promise<T>;
|
|
73
|
+
/** Record a cancellation on the reservation itself, under its mutex, before any receipt exists. */
|
|
74
|
+
export declare function requestIdempotencyCancel(key: string, now?: number): Promise<IdempotencyRecord | undefined>;
|
|
75
|
+
/** Release a reservation this caller owns and never launched. */
|
|
76
|
+
export declare function releaseIdempotencyKey(key: string, owner: string): Promise<boolean>;
|
|
77
|
+
/** The live record for a key, or undefined when there is none or it expired. */
|
|
78
|
+
export declare function findIdempotencyKey(key: string): Promise<IdempotencyRecord | undefined>;
|
|
79
|
+
/** Every live reservation, for reconciliation on Hook start. */
|
|
80
|
+
export declare function listIdempotencyRecords(): Promise<IdempotencyRecord[]>;
|
|
81
|
+
/** Wait for the reserving caller to name its dispatch. Undefined when the key disappears or the wait runs out. */
|
|
82
|
+
export declare function waitForIdempotencyKey(key: string, timeoutMs?: number): Promise<IdempotencyRecord | undefined>;
|
|
83
|
+
/** A branch slug for a key: `agent/<key-slug>` or `agent/<dispatch id>` when there is no key. */
|
|
84
|
+
export declare function worktreeBranchFor(key: string | undefined, dispatchId: string): string;
|
|
85
|
+
export {};
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { link, lstat, mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { atomic, BridgeError, bridgeRoot } from "./protocol.js";
|
|
6
|
+
/**
|
|
7
|
+
* Idempotency keys for local dispatches (`phren dispatch local ... --idempotency-key`).
|
|
8
|
+
* A reservation is written to a temp file and published with `link`, which is
|
|
9
|
+
* atomic and fails with EEXIST: an empty or half-written file is never a
|
|
10
|
+
* reservation another caller can reclaim. Every update or delete checks the
|
|
11
|
+
* owner nonce. The per-key mutex is in-process because only the Hook server
|
|
12
|
+
* process mutates key records; the CLI reaches it through Hook routes.
|
|
13
|
+
*/
|
|
14
|
+
export const IDEMPOTENCY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
15
|
+
/** A reservation that has not reached "launched" is interrupted after this. */
|
|
16
|
+
export const LAUNCH_INTERRUPTED_MS = 5 * 60_000;
|
|
17
|
+
export const idempotencyKeySchema = z.string().min(1).max(200).regex(/^[A-Za-z0-9:._@/-]+$/, "An idempotency key is 1 to 200 characters of letters, digits, and : . _ @ / -");
|
|
18
|
+
const phaseSchema = z.enum(["reserved", "launching", "launched", "failed"]);
|
|
19
|
+
const recordSchema = z.object({
|
|
20
|
+
key: z.string().min(1).max(200),
|
|
21
|
+
dispatchId: z.string().uuid(),
|
|
22
|
+
owner: z.string().uuid(),
|
|
23
|
+
createdAt: z.string().datetime(),
|
|
24
|
+
phase: phaseSchema,
|
|
25
|
+
project: z.string().max(100).optional(),
|
|
26
|
+
harness: z.string().max(32).optional(),
|
|
27
|
+
label: z.string().max(200).optional(),
|
|
28
|
+
computer: z.string().max(200).optional(),
|
|
29
|
+
cloneDir: z.string().max(4096).optional(),
|
|
30
|
+
gitConfigFile: z.string().max(4096).optional(),
|
|
31
|
+
agentTokenFile: z.string().max(4096).optional(),
|
|
32
|
+
workerFile: z.string().max(4096).optional(),
|
|
33
|
+
startingToken: z.string().regex(/^[a-f0-9]{64}$/).optional(),
|
|
34
|
+
cancelRequestedAt: z.string().datetime().optional(),
|
|
35
|
+
}).strict();
|
|
36
|
+
const keyRoot = () => path.join(bridgeRoot(), "idempotency");
|
|
37
|
+
const hashOf = (key) => createHash("sha256").update(key).digest("hex");
|
|
38
|
+
export const idempotencyKeyFile = (key) => path.join(keyRoot(), `${hashOf(key)}.json`);
|
|
39
|
+
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
40
|
+
function expired(record, now = Date.now()) {
|
|
41
|
+
const created = Date.parse(record.createdAt);
|
|
42
|
+
return Number.isFinite(created) && now - created > IDEMPOTENCY_TTL_MS;
|
|
43
|
+
}
|
|
44
|
+
async function readKey(file) {
|
|
45
|
+
const info = await lstat(file).catch(error => {
|
|
46
|
+
if (error.code !== "ENOENT")
|
|
47
|
+
throw error;
|
|
48
|
+
return undefined;
|
|
49
|
+
});
|
|
50
|
+
if (!info?.isFile() || info.isSymbolicLink() || info.size > 4096)
|
|
51
|
+
return undefined;
|
|
52
|
+
try {
|
|
53
|
+
return recordSchema.parse(JSON.parse(await readFile(file, "utf8")));
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Publish a full record atomically. False means the key already exists. */
|
|
60
|
+
async function publish(key, record) {
|
|
61
|
+
await mkdir(keyRoot(), { recursive: true, mode: 0o700 });
|
|
62
|
+
const temp = path.join(keyRoot(), `.${hashOf(key)}.${record.owner}.tmp`);
|
|
63
|
+
await writeFile(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" });
|
|
64
|
+
try {
|
|
65
|
+
await link(temp, idempotencyKeyFile(key));
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (error.code === "EEXIST")
|
|
70
|
+
return false;
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
await unlink(temp).catch(() => undefined);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
let hookServerProcess = false;
|
|
78
|
+
/** Called by the Hook server before it handles dispatches. */
|
|
79
|
+
export function markHookServerProcess() { hookServerProcess = true; }
|
|
80
|
+
function assertHookServerProcess() {
|
|
81
|
+
if (!hookServerProcess)
|
|
82
|
+
throw new BridgeError(403, "Idempotency key locks are only available inside the Phren Hook server process.");
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A per-key async mutex. Only the Hook server process mutates key records (the
|
|
86
|
+
* CLI reaches it through Hook routes), so a Map of promise chains serializes
|
|
87
|
+
* every read-modify-write without a lock file or a reclaim race.
|
|
88
|
+
*/
|
|
89
|
+
const keyMutexes = new Map();
|
|
90
|
+
async function withKeyMutex(key, run) {
|
|
91
|
+
const previous = keyMutexes.get(key) ?? Promise.resolve();
|
|
92
|
+
let release;
|
|
93
|
+
const current = new Promise(resolve => { release = resolve; });
|
|
94
|
+
const tail = previous.then(() => current);
|
|
95
|
+
keyMutexes.set(key, tail);
|
|
96
|
+
await previous;
|
|
97
|
+
try {
|
|
98
|
+
return await run();
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
release();
|
|
102
|
+
if (keyMutexes.get(key) === tail)
|
|
103
|
+
keyMutexes.delete(key);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Delete lock and reclaim files left by an older Hook or a crash. */
|
|
107
|
+
export async function cleanupIdempotencyLocks() {
|
|
108
|
+
const root = keyRoot();
|
|
109
|
+
const names = await readdir(root).catch(error => {
|
|
110
|
+
if (error.code !== "ENOENT")
|
|
111
|
+
throw error;
|
|
112
|
+
return [];
|
|
113
|
+
});
|
|
114
|
+
await Promise.all(names.filter(name => name.endsWith(".lock") || name.includes(".lock.reclaim-"))
|
|
115
|
+
.map(name => unlink(path.join(root, name)).catch(() => undefined)));
|
|
116
|
+
}
|
|
117
|
+
async function replaceExpired(key, fresh, now) {
|
|
118
|
+
const current = await readKey(idempotencyKeyFile(key));
|
|
119
|
+
if (current && !expired(current, now))
|
|
120
|
+
return { reserved: false, record: current };
|
|
121
|
+
if (current)
|
|
122
|
+
await unlink(idempotencyKeyFile(key)).catch(() => undefined);
|
|
123
|
+
if (await publish(key, fresh))
|
|
124
|
+
return { reserved: true, record: fresh };
|
|
125
|
+
const raced = await readKey(idempotencyKeyFile(key));
|
|
126
|
+
if (!raced)
|
|
127
|
+
throw new BridgeError(503, "The idempotency key's reservation is unreadable; refusing to start another dispatch.");
|
|
128
|
+
return { reserved: false, record: raced };
|
|
129
|
+
}
|
|
130
|
+
/** Reserve `key` for this caller, with its dispatch id, atomically. */
|
|
131
|
+
export async function reserveIdempotencyKey(key, dispatchId, owner, seed = {}, now = Date.now()) {
|
|
132
|
+
return withKeyMutex(key, async () => {
|
|
133
|
+
const record = { key, dispatchId, owner, createdAt: new Date(now).toISOString(), phase: "reserved", ...seed };
|
|
134
|
+
if (await publish(key, record))
|
|
135
|
+
return { reserved: true, record };
|
|
136
|
+
const existing = await readKey(idempotencyKeyFile(key));
|
|
137
|
+
// An unreadable reservation is not free: never unlink it and start a second agent.
|
|
138
|
+
if (!existing)
|
|
139
|
+
throw new BridgeError(503, "The idempotency key's reservation is unreadable; refusing to start another dispatch.");
|
|
140
|
+
if (!expired(existing, now))
|
|
141
|
+
return { reserved: false, record: existing };
|
|
142
|
+
return replaceExpired(key, record, now);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
/** Move the reservation's phase. False when this caller no longer owns it. */
|
|
146
|
+
export async function updateIdempotencyPhase(key, owner, phase) {
|
|
147
|
+
return withKeyMutex(key, async () => {
|
|
148
|
+
const file = idempotencyKeyFile(key);
|
|
149
|
+
const record = await readKey(file);
|
|
150
|
+
if (!record || record.owner !== owner)
|
|
151
|
+
return false;
|
|
152
|
+
await atomic(file, JSON.stringify({ ...record, phase }), 0o600);
|
|
153
|
+
return true;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/** Run under the key's in-process mutex, with the current reservation record. */
|
|
157
|
+
export async function withIdempotencyKeyLock(key, run) {
|
|
158
|
+
assertHookServerProcess();
|
|
159
|
+
return withKeyMutex(key, async () => {
|
|
160
|
+
const file = idempotencyKeyFile(key);
|
|
161
|
+
const record = await readKey(file);
|
|
162
|
+
return await run(record, async (next) => {
|
|
163
|
+
const current = await readKey(file);
|
|
164
|
+
if (!current)
|
|
165
|
+
throw new BridgeError(409, "The idempotency key no longer exists.");
|
|
166
|
+
if (current.owner !== next.owner)
|
|
167
|
+
throw new BridgeError(409, "This dispatch no longer owns its idempotency key.");
|
|
168
|
+
await atomic(file, JSON.stringify(next), 0o600);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
/** Record a cancellation on the reservation itself, under its mutex, before any receipt exists. */
|
|
173
|
+
export async function requestIdempotencyCancel(key, now = Date.now()) {
|
|
174
|
+
return withKeyMutex(key, async () => {
|
|
175
|
+
const file = idempotencyKeyFile(key);
|
|
176
|
+
const record = await readKey(file);
|
|
177
|
+
if (!record)
|
|
178
|
+
return undefined;
|
|
179
|
+
if (record.cancelRequestedAt)
|
|
180
|
+
return record;
|
|
181
|
+
record.cancelRequestedAt = new Date(now).toISOString();
|
|
182
|
+
await atomic(file, JSON.stringify(record), 0o600);
|
|
183
|
+
return record;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/** Release a reservation this caller owns and never launched. */
|
|
187
|
+
export async function releaseIdempotencyKey(key, owner) {
|
|
188
|
+
return withKeyMutex(key, async () => {
|
|
189
|
+
const file = idempotencyKeyFile(key);
|
|
190
|
+
const record = await readKey(file);
|
|
191
|
+
if (!record || record.owner !== owner)
|
|
192
|
+
return false;
|
|
193
|
+
await unlink(file).catch(() => undefined);
|
|
194
|
+
return true;
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
/** The live record for a key, or undefined when there is none or it expired. */
|
|
198
|
+
export async function findIdempotencyKey(key) {
|
|
199
|
+
const record = await readKey(idempotencyKeyFile(key));
|
|
200
|
+
return record && !expired(record) ? record : undefined;
|
|
201
|
+
}
|
|
202
|
+
/** Every live reservation, for reconciliation on Hook start. */
|
|
203
|
+
export async function listIdempotencyRecords() {
|
|
204
|
+
const names = await readdir(keyRoot()).catch(error => {
|
|
205
|
+
if (error.code !== "ENOENT")
|
|
206
|
+
throw error;
|
|
207
|
+
return [];
|
|
208
|
+
});
|
|
209
|
+
const records = [];
|
|
210
|
+
for (const name of names.filter(name => /^[a-f0-9]{64}\.json$/.test(name))) {
|
|
211
|
+
const record = await readKey(path.join(keyRoot(), name));
|
|
212
|
+
if (record && !expired(record))
|
|
213
|
+
records.push(record);
|
|
214
|
+
}
|
|
215
|
+
return records;
|
|
216
|
+
}
|
|
217
|
+
/** Wait for the reserving caller to name its dispatch. Undefined when the key disappears or the wait runs out. */
|
|
218
|
+
export async function waitForIdempotencyKey(key, timeoutMs = 180_000) {
|
|
219
|
+
const deadline = Date.now() + timeoutMs;
|
|
220
|
+
while (Date.now() < deadline) {
|
|
221
|
+
const record = await findIdempotencyKey(key);
|
|
222
|
+
if (!record)
|
|
223
|
+
return undefined;
|
|
224
|
+
if (record.phase !== "reserved")
|
|
225
|
+
return record;
|
|
226
|
+
await sleep(100);
|
|
227
|
+
}
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
/** A branch slug for a key: `agent/<key-slug>` or `agent/<dispatch id>` when there is no key. */
|
|
231
|
+
export function worktreeBranchFor(key, dispatchId) {
|
|
232
|
+
const slug = (key ?? "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/\.{2,}/g, ".")
|
|
233
|
+
.replace(/^[-.]+|[-.]+$/g, "").slice(0, 80).replace(/[-.]+$/g, "");
|
|
234
|
+
return `agent/${slug || dispatchId}`;
|
|
235
|
+
}
|
|
@@ -338,6 +338,12 @@ export declare class DispatchReturns {
|
|
|
338
338
|
forwardPrs(): Promise<void>;
|
|
339
339
|
cleanup(): Promise<void>;
|
|
340
340
|
private closeRemote;
|
|
341
|
+
/**
|
|
342
|
+
* Mark one dispatch's return read, leaving every other return untouched:
|
|
343
|
+
* `phren dispatch wait` follows one worker and must not consume a
|
|
344
|
+
* conductor's returns on the same Hook.
|
|
345
|
+
*/
|
|
346
|
+
acknowledgeOne(id: string): Promise<Json>;
|
|
341
347
|
/** A remote successor acknowledges only the exact return version it received. */
|
|
342
348
|
acknowledge(rows: Json[]): Promise<void>;
|
|
343
349
|
/** Every unread return, oldest first, marked read as it is handed over. */
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { intentionallyClosed } from "./worker-close.js";
|
|
2
|
+
import { dispatchClonePaths, removeDispatchClone, removeDispatchSecrets } from "./dispatch-clone.js";
|
|
3
|
+
import { removeWorkerFile, workerAlive } from "./worker-identity.js";
|
|
2
4
|
import { workerPrs, readIntegrator } from "./worker-reports.js";
|
|
3
5
|
import { prsSchema } from "./return-contract.js";
|
|
4
6
|
import { sessionStalls } from "./stalls.js";
|
|
@@ -8,7 +10,7 @@ import { setTimeout as sleep } from "node:timers/promises";
|
|
|
8
10
|
import { promisify } from "node:util";
|
|
9
11
|
import { z } from "zod";
|
|
10
12
|
import { logger } from "../logger.js";
|
|
11
|
-
import { arrivalOf, dispatchStatus, updateReceipt } from "./dispatch.js";
|
|
13
|
+
import { arrivalOf, boundWorkerGone, clearWorkerEnded, dispatchStatus, updateReceipt } from "./dispatch.js";
|
|
12
14
|
import { briefArrival, briefId } from "./launch-brief.js";
|
|
13
15
|
import { codexServers, LOST_TURN } from "./codex-servers.js";
|
|
14
16
|
import { findGrant } from "./grants.js";
|
|
@@ -1014,6 +1016,109 @@ export class DispatchReturns {
|
|
|
1014
1016
|
}
|
|
1015
1017
|
async cleanup() {
|
|
1016
1018
|
for (const receipt of await dispatchStatus()) {
|
|
1019
|
+
const paths = receipt.idempotencyKey
|
|
1020
|
+
? dispatchClonePaths(receipt.id)
|
|
1021
|
+
: { cloneDir: receipt.cloneDir, gitConfigFile: receipt.gitConfigFile, agentTokenFile: receipt.agentTokenFile };
|
|
1022
|
+
const state = receipt.returned?.state;
|
|
1023
|
+
// Only the Hook that created the clone/token owns their filesystem.
|
|
1024
|
+
const local = this.isSelf(receipt) || this.isLocal(receipt.computer);
|
|
1025
|
+
// Keyed dispatches are local-only; never use a peer path for one.
|
|
1026
|
+
if (receipt.idempotencyKey && !local)
|
|
1027
|
+
continue;
|
|
1028
|
+
if (local && (state === "failed" || state === "gone")) {
|
|
1029
|
+
if (receipt.idempotencyKey) {
|
|
1030
|
+
// A keyed worker's durable PID/start time decides, not its return.
|
|
1031
|
+
const alive = await workerAlive(receipt.id, receipt.workerFile ?? dispatchClonePaths(receipt.id).workerFile, receipt.submittedAt);
|
|
1032
|
+
if (alive !== "gone") {
|
|
1033
|
+
await clearWorkerEnded(receipt.id);
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
await removeDispatchSecrets(paths);
|
|
1037
|
+
await removeWorkerFile(receipt.id);
|
|
1038
|
+
const at = receipt.closedAt ?? new Date(this.now()).toISOString();
|
|
1039
|
+
const until = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
|
|
1040
|
+
await updateReceipt(receipt.id, value => {
|
|
1041
|
+
if (!value.endedAt)
|
|
1042
|
+
value.endedAt = at;
|
|
1043
|
+
if (!value.retainedUntil)
|
|
1044
|
+
value.retainedUntil = until;
|
|
1045
|
+
return true;
|
|
1046
|
+
}).catch(() => undefined);
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
// A launch that never reached its request has no worker: its secrets
|
|
1050
|
+
// go immediately. Any other outcome waits for confirmed termination.
|
|
1051
|
+
if (!receipt.target && receipt.launchOutcome === "not-started") {
|
|
1052
|
+
await removeDispatchSecrets(paths);
|
|
1053
|
+
const at = receipt.closedAt ?? new Date(this.now()).toISOString();
|
|
1054
|
+
const until = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
|
|
1055
|
+
await updateReceipt(receipt.id, value => {
|
|
1056
|
+
if (!value.endedAt)
|
|
1057
|
+
value.endedAt = at;
|
|
1058
|
+
if (!value.retainedUntil)
|
|
1059
|
+
value.retainedUntil = until;
|
|
1060
|
+
return true;
|
|
1061
|
+
}).catch(() => undefined);
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
// Retention and token removal wait for confirmed termination: a failed
|
|
1065
|
+
// return alone does not prove the pane stopped.
|
|
1066
|
+
if (receipt.endedAt) {
|
|
1067
|
+
const until = receipt.retainedUntil ? Date.parse(receipt.retainedUntil) : NaN;
|
|
1068
|
+
if (!Number.isFinite(until) || this.now() < until)
|
|
1069
|
+
continue;
|
|
1070
|
+
if (!await boundWorkerGone(receipt)) {
|
|
1071
|
+
await clearWorkerEnded(receipt.id);
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
continue;
|
|
1075
|
+
}
|
|
1076
|
+
if (!await boundWorkerGone(receipt)) {
|
|
1077
|
+
await clearWorkerEnded(receipt.id);
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
await removeDispatchSecrets(paths);
|
|
1081
|
+
const at = receipt.closedAt ?? new Date(this.now()).toISOString();
|
|
1082
|
+
const until = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
|
|
1083
|
+
await updateReceipt(receipt.id, value => {
|
|
1084
|
+
if (!value.endedAt)
|
|
1085
|
+
value.endedAt = at;
|
|
1086
|
+
if (!value.retainedUntil)
|
|
1087
|
+
value.retainedUntil = until;
|
|
1088
|
+
return true;
|
|
1089
|
+
}).catch(() => undefined);
|
|
1090
|
+
continue;
|
|
1091
|
+
}
|
|
1092
|
+
if (local && state === "done") {
|
|
1093
|
+
if (receipt.idempotencyKey) {
|
|
1094
|
+
if (receipt.closedAt) {
|
|
1095
|
+
await removeDispatchClone(paths);
|
|
1096
|
+
continue;
|
|
1097
|
+
}
|
|
1098
|
+
if (receipt.closeOnFinish === false) {
|
|
1099
|
+
await clearWorkerEnded(receipt.id);
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
const alive = await workerAlive(receipt.id, receipt.workerFile ?? dispatchClonePaths(receipt.id).workerFile, receipt.submittedAt);
|
|
1103
|
+
if (alive === "gone") {
|
|
1104
|
+
await removeDispatchClone(paths);
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
await clearWorkerEnded(receipt.id);
|
|
1108
|
+
}
|
|
1109
|
+
else {
|
|
1110
|
+
if (receipt.closedAt) {
|
|
1111
|
+
await removeDispatchClone(paths);
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
if (receipt.closeOnFinish === false) {
|
|
1115
|
+
// Keep-open work stays alive; it has no termination time yet.
|
|
1116
|
+
await clearWorkerEnded(receipt.id);
|
|
1117
|
+
continue;
|
|
1118
|
+
}
|
|
1119
|
+
// A done worker's pane may still run: keep its token until the verified close.
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1017
1122
|
if (!receipt.closePending || receipt.closedAt || receipt.returned?.at !== receipt.closePending.at || receipt.returned.state !== "done" || !receipt.returned.read)
|
|
1018
1123
|
continue;
|
|
1019
1124
|
const peer = this.isSelf(receipt) ? undefined : (await this.peers().catch(() => [])).find(peer => peer.name === receipt.computer);
|
|
@@ -1033,11 +1138,36 @@ export class DispatchReturns {
|
|
|
1033
1138
|
}
|
|
1034
1139
|
}
|
|
1035
1140
|
async closeRemote(receipt, verifiedPeer) {
|
|
1141
|
+
// Keyed dispatches are local-only; never close one over a peer path.
|
|
1142
|
+
if (receipt.idempotencyKey)
|
|
1143
|
+
return { closed: false };
|
|
1036
1144
|
const peer = verifiedPeer ?? (await this.peers()).find(peer => peer.name === receipt.computer);
|
|
1037
1145
|
if (!peer)
|
|
1038
1146
|
return { closed: false };
|
|
1039
1147
|
return this.request(peer, "/v1/dispatch/close", { target: receipt.target, dispatch: receipt.moves?.slice().reverse().find(move => move.to.computer)?.id ?? receipt.id, turn: receipt.closePending.turn });
|
|
1040
1148
|
}
|
|
1149
|
+
/**
|
|
1150
|
+
* Mark one dispatch's return read, leaving every other return untouched:
|
|
1151
|
+
* `phren dispatch wait` follows one worker and must not consume a
|
|
1152
|
+
* conductor's returns on the same Hook.
|
|
1153
|
+
*/
|
|
1154
|
+
async acknowledgeOne(id) {
|
|
1155
|
+
let acknowledged = false;
|
|
1156
|
+
await updateReceipt(id, value => {
|
|
1157
|
+
if (!value.returned || value.returned.read)
|
|
1158
|
+
return false;
|
|
1159
|
+
value.returned.read = true;
|
|
1160
|
+
if (value.returned.state === "done" && value.closeOnFinish !== false && !value.returned.background && value.returned.turn && !value.closedAt)
|
|
1161
|
+
value.closePending = { at: value.returned.at, turn: value.returned.turn };
|
|
1162
|
+
acknowledged = true;
|
|
1163
|
+
return true;
|
|
1164
|
+
}).catch(() => undefined);
|
|
1165
|
+
if (acknowledged) {
|
|
1166
|
+
await this.forwardPrs();
|
|
1167
|
+
await this.cleanup();
|
|
1168
|
+
}
|
|
1169
|
+
return { ok: true, dispatch: id, acknowledged };
|
|
1170
|
+
}
|
|
1041
1171
|
/** A remote successor acknowledges only the exact return version it received. */
|
|
1042
1172
|
async acknowledge(rows) {
|
|
1043
1173
|
for (const row of rows)
|