pi-better-server 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +615 -2
- package/codex-plugin/.agents/plugins/marketplace.json +17 -0
- package/codex-plugin/plugins/pi-remote/.codex-plugin/plugin.json +20 -0
- package/codex-plugin/plugins/pi-remote/.mcp.json +13 -0
- package/codex-plugin/plugins/pi-remote/server.mjs +118 -0
- package/codex-plugin/plugins/pi-remote/skills/pi-remote/SKILL.md +19 -0
- package/package.json +60 -4
- package/scripts/bootstrap-host.sh +107 -0
- package/scripts/private-runtime/format.ts +65 -0
- package/scripts/private-runtime/installer.ts +166 -0
- package/scripts/private-runtime/package-lock.json +1491 -0
- package/scripts/private-runtime/package.json +17 -0
- package/scripts/test-on-pi.sh +34 -0
- package/src/cli-args.ts +38 -0
- package/src/cli.ts +90 -0
- package/src/client.ts +152 -0
- package/src/codex/adapter.ts +299 -0
- package/src/codex/app-server.ts +112 -0
- package/src/codex/daemon.ts +232 -0
- package/src/codex/deliver.ts +103 -0
- package/src/codex/preflight.ts +15 -0
- package/src/codex/provider.ts +55 -0
- package/src/codex/return.ts +110 -0
- package/src/codex/rollout.ts +160 -0
- package/src/codex/runtime.ts +126 -0
- package/src/codex/ws-unix.ts +112 -0
- package/src/companion.ts +96 -0
- package/src/control.ts +85 -0
- package/src/core/adapter.ts +109 -0
- package/src/core/bundle.ts +764 -0
- package/src/core/exclusions.ts +53 -0
- package/src/core/move-host.ts +268 -0
- package/src/core/ownership.ts +135 -0
- package/src/core/transfer.ts +73 -0
- package/src/daemon-owner.ts +130 -0
- package/src/detach/detach.ts +150 -0
- package/src/detach/extension.ts +244 -0
- package/src/detach/local-sink.ts +203 -0
- package/src/detach/local-source.ts +133 -0
- package/src/detach/local-state.ts +87 -0
- package/src/detach/recover.ts +53 -0
- package/src/event-log.ts +163 -0
- package/src/git.ts +35 -0
- package/src/handshake.ts +57 -0
- package/src/hosted-session.ts +576 -0
- package/src/index.ts +31 -0
- package/src/lifecycle-config.ts +29 -0
- package/src/maintenance.ts +317 -0
- package/src/move/auth.ts +16 -0
- package/src/move/orchestrate.ts +163 -0
- package/src/move/pi-adapter.ts +181 -0
- package/src/move/preflight.ts +197 -0
- package/src/move/service.ts +16 -0
- package/src/paths.ts +52 -0
- package/src/protocol.ts +212 -0
- package/src/registry.ts +559 -0
- package/src/remote/answer.ts +95 -0
- package/src/remote/attach-codex.ts +41 -0
- package/src/remote/attach.ts +41 -0
- package/src/remote/console.ts +126 -0
- package/src/remote/context.ts +75 -0
- package/src/remote/cursors.ts +36 -0
- package/src/remote/ls.ts +44 -0
- package/src/remote/move.ts +85 -0
- package/src/remote/new.ts +37 -0
- package/src/remote/process-runner.ts +51 -0
- package/src/remote/recover.ts +35 -0
- package/src/remote/return.ts +49 -0
- package/src/remote/sessions.ts +33 -0
- package/src/remote/steer.ts +40 -0
- package/src/remote/tail.ts +91 -0
- package/src/remote/target.ts +313 -0
- package/src/remote-cli.ts +73 -0
- package/src/remote-client/connection-progress.ts +62 -0
- package/src/remote-client/extension.ts +368 -0
- package/src/remote-client/folder-browser.ts +165 -0
- package/src/remote-client/host.ts +127 -0
- package/src/remote-client/local-work.ts +62 -0
- package/src/remote-client/menu.ts +68 -0
- package/src/remote-client/packages.ts +331 -0
- package/src/remote-client/pi-1.2-bridge.ts +482 -0
- package/src/remote-client/profiles.ts +38 -0
- package/src/remote-client/remote-progress.ts +39 -0
- package/src/remote-client/session-browser.ts +267 -0
- package/src/remote-client/session.ts +1205 -0
- package/src/remote-client/ssh-hosts.ts +185 -0
- package/src/remote-client/transfer-command.ts +189 -0
- package/src/remote-client/upgrade-transport.ts +105 -0
- package/src/server.ts +398 -0
- package/src/session-activity.ts +173 -0
- package/src/shared-ssh-core/index.ts +950 -0
- package/src/startup/activation.ts +621 -0
- package/src/startup/admission.ts +98 -0
- package/src/startup/artifact.ts +65 -0
- package/src/startup/commands.ts +37 -0
- package/src/startup/ensure.ts +137 -0
- package/src/startup/install.ts +115 -0
- package/src/startup/managed-types.ts +61 -0
- package/src/startup/runtime.ts +138 -0
- package/src/ui-bridge.ts +124 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a session bundle must never carry. Agent-agnostic: no Pi imports in this directory.
|
|
3
|
+
*
|
|
4
|
+
* Untracked files come from `git ls-files --exclude-standard`, which already drops
|
|
5
|
+
* anything the repo ignores (including ignored `.env` files). These rules are the
|
|
6
|
+
* second wall for credentials that are NOT ignored, and for heavy generated output.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Directories that hold dependencies, build output, or caches. Never bundled, never part of the worktree digest. */
|
|
10
|
+
const GENERATED_DIRS: ReadonlySet<string> = new Set([
|
|
11
|
+
"node_modules",
|
|
12
|
+
"dist",
|
|
13
|
+
"build",
|
|
14
|
+
"out",
|
|
15
|
+
".next",
|
|
16
|
+
".nuxt",
|
|
17
|
+
".turbo",
|
|
18
|
+
".cache",
|
|
19
|
+
".parcel-cache",
|
|
20
|
+
"coverage",
|
|
21
|
+
"target",
|
|
22
|
+
"__pycache__",
|
|
23
|
+
".pytest_cache",
|
|
24
|
+
".tox",
|
|
25
|
+
".venv",
|
|
26
|
+
"venv",
|
|
27
|
+
".gradle",
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
/** Directories whose whole content is credentials or credential-adjacent. */
|
|
31
|
+
const SECRET_DIRS: ReadonlySet<string> = new Set([".ssh", ".aws", ".gnupg", ".kube", ".docker", ".gcloud", ".azure"]);
|
|
32
|
+
|
|
33
|
+
const SECRET_FILE_PATTERNS: readonly RegExp[] = [
|
|
34
|
+
/^\.env/i, // any name starting with .env: .env, .env.local, .envrc, .env-prod, .env_local
|
|
35
|
+
/^\.(npmrc|netrc|pypirc|git-credentials|dockercfg)$/i,
|
|
36
|
+
/^(auth|credentials?|secrets?)(\..+)?\.(json|ya?ml|toml|ini)$/i,
|
|
37
|
+
/^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
|
|
38
|
+
/\.(pem|key|p12|pfx|keystore|jks)$/i,
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/** Why a repo-relative path is left out of a bundle, or undefined when it may travel. */
|
|
42
|
+
export function exclusionReason(relativePath: string): "credential" | "generated" | undefined {
|
|
43
|
+
const segments = relativePath.split("/");
|
|
44
|
+
const name = segments[segments.length - 1] ?? "";
|
|
45
|
+
for (const segment of segments.slice(0, -1)) {
|
|
46
|
+
if (SECRET_DIRS.has(segment)) return "credential";
|
|
47
|
+
}
|
|
48
|
+
if (SECRET_FILE_PATTERNS.some((pattern) => pattern.test(name))) return "credential";
|
|
49
|
+
for (const segment of segments.slice(0, -1)) {
|
|
50
|
+
if (GENERATED_DIRS.has(segment)) return "generated";
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daemon side of `pi-remote move`, agent-agnostic: the command handlers for both
|
|
3
|
+
* ends of a move, built on the bundle, transfer and ownership core. Everything
|
|
4
|
+
* specific to one agent goes through an AgentMoveAdapter (adapter.ts).
|
|
5
|
+
*
|
|
6
|
+
* Source: fence (at a safe boundary) -> export -> serve chunks -> retire | unfence.
|
|
7
|
+
* Target: begin -> write* -> commit (verify, rebuild workspace, import session) | abort.
|
|
8
|
+
* The CLI drives both ends; see move/orchestrate.ts for the order and failure handling.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
11
|
+
import { basename, join, resolve } from "node:path";
|
|
12
|
+
import { createBundle, materializeWorkspace, sha256File, verifyBundle } from "./bundle.ts";
|
|
13
|
+
import { assertExistingDirectory, type AgentMoveAdapter } from "./adapter.ts";
|
|
14
|
+
import { InboundTransfer, readChunk } from "./transfer.ts";
|
|
15
|
+
import type { MoveCommand } from "../protocol.ts";
|
|
16
|
+
|
|
17
|
+
const MAX_READ_BYTES = 4 * 1024 * 1024;
|
|
18
|
+
const DEFAULT_FENCE_WAIT_MS = 30_000;
|
|
19
|
+
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{5,127}$/;
|
|
20
|
+
|
|
21
|
+
export interface CommitAck {
|
|
22
|
+
sessionId: string;
|
|
23
|
+
daemonId: string;
|
|
24
|
+
cwd: string;
|
|
25
|
+
epoch: number;
|
|
26
|
+
worktreeFiles: number;
|
|
27
|
+
worktreeBytes: number;
|
|
28
|
+
/** The rebuilt workspace matched the manifest's per-file checksums. */
|
|
29
|
+
verified: true;
|
|
30
|
+
sessionFile?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface Inbound {
|
|
34
|
+
sessionId: string;
|
|
35
|
+
sourceSessionId: string;
|
|
36
|
+
includeWorkspace?: boolean;
|
|
37
|
+
committing?: Promise<CommitAck>;
|
|
38
|
+
cwd?: string;
|
|
39
|
+
rebindProvider?: string;
|
|
40
|
+
transfer: InboundTransfer;
|
|
41
|
+
ack?: CommitAck;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function checkId(label: string, value: unknown): string {
|
|
45
|
+
if (typeof value !== "string" || !SAFE_ID.test(value)) throw new Error(`${label} must be 6-128 letters, digits, "-" or "_"`);
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class MoveHost {
|
|
50
|
+
private readonly adapter: AgentMoveAdapter;
|
|
51
|
+
private readonly serverDir: string;
|
|
52
|
+
private readonly movesDir: string;
|
|
53
|
+
private readonly inbound = new Map<string, Inbound>();
|
|
54
|
+
private readonly aborted = new Set<string>();
|
|
55
|
+
|
|
56
|
+
constructor(adapter: AgentMoveAdapter, serverDir: string, movesDir: string) {
|
|
57
|
+
this.adapter = adapter;
|
|
58
|
+
this.serverDir = serverDir;
|
|
59
|
+
this.movesDir = movesDir;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async handle(command: MoveCommand): Promise<Record<string, unknown>> {
|
|
63
|
+
switch (command.type) {
|
|
64
|
+
case "move_fence":
|
|
65
|
+
return { sessionId: command.sessionId, data: await this.fence(command.sessionId, checkId("moveId", command.moveId), command.waitMs ?? DEFAULT_FENCE_WAIT_MS) };
|
|
66
|
+
case "move_export":
|
|
67
|
+
return { sessionId: command.sessionId, data: this.export(command.sessionId, checkId("moveId", command.moveId), command.includeWorkspace, command.compression) };
|
|
68
|
+
case "move_read":
|
|
69
|
+
return { data: this.read(checkId("moveId", command.moveId), command.offset, command.length) };
|
|
70
|
+
case "move_retire":
|
|
71
|
+
await this.retire(command.sessionId, checkId("moveId", command.moveId), command.movedTo);
|
|
72
|
+
return { sessionId: command.sessionId };
|
|
73
|
+
case "move_unfence":
|
|
74
|
+
await this.unfence(command.sessionId, command.moveId);
|
|
75
|
+
return { sessionId: command.sessionId };
|
|
76
|
+
case "move_begin":
|
|
77
|
+
await this.begin(command);
|
|
78
|
+
return { sessionId: command.sessionId };
|
|
79
|
+
case "move_write":
|
|
80
|
+
return { data: { received: this.write(checkId("moveId", command.moveId), command.offset, command.data) } };
|
|
81
|
+
case "move_commit":
|
|
82
|
+
return { data: await this.commit(checkId("moveId", command.moveId)) };
|
|
83
|
+
case "move_abort":
|
|
84
|
+
return { data: await this.abort(checkId("moveId", command.moveId), command.sessionId) };
|
|
85
|
+
case "move_preflight": {
|
|
86
|
+
if (command.includeWorkspace === false && command.dir !== undefined) assertExistingDirectory(command.dir);
|
|
87
|
+
const report = (await this.adapter.readiness?.(command)) ?? { checks: [] };
|
|
88
|
+
return { data: { daemonId: this.adapter.ownership.daemonId, ...report } };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ---- source side ----
|
|
94
|
+
|
|
95
|
+
private async fence(sessionId: string, moveId: string, waitMs: number): Promise<{ daemonId: string; epoch: number }> {
|
|
96
|
+
const { adapter } = this;
|
|
97
|
+
if (!adapter.hasSession(sessionId)) throw new Error(`Unknown session: ${sessionId}`);
|
|
98
|
+
await adapter.preflight?.({ side: "source", sessionId, moveId });
|
|
99
|
+
// Safe boundary: no turn running or starting. Waiting here is harmless; nothing is fenced yet.
|
|
100
|
+
const deadline = Date.now() + waitMs;
|
|
101
|
+
while (adapter.isBusy(sessionId)) {
|
|
102
|
+
if (Date.now() >= deadline) throw new Error(`Session ${sessionId} is mid-turn; wait for it to finish (or steer it) and retry the move`);
|
|
103
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 50));
|
|
104
|
+
}
|
|
105
|
+
// No await between the last check and the fence, so no prompt can slip in.
|
|
106
|
+
const record = adapter.ownership.fence(sessionId, moveId);
|
|
107
|
+
try {
|
|
108
|
+
await adapter.stop(sessionId);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
adapter.ownership.unfence(sessionId, moveId);
|
|
111
|
+
await adapter.resume(sessionId);
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
return { daemonId: adapter.ownership.daemonId, epoch: record.epoch };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private export(sessionId: string, moveId: string, includeWorkspace?: boolean, compression?: "gzip" | "none"): { size: number; sha256: string; files: number; worktreeFiles: number; excluded: number } {
|
|
118
|
+
const { adapter } = this;
|
|
119
|
+
const record = adapter.ownership.get(sessionId);
|
|
120
|
+
if (record.state !== "fenced" || record.moveId !== moveId) throw new Error(`Session ${sessionId} is not fenced by move ${moveId}`);
|
|
121
|
+
if (!adapter.hasSession(sessionId)) throw new Error(`Unknown session: ${sessionId}`);
|
|
122
|
+
const dir = join(this.movesDir, moveId);
|
|
123
|
+
rmSync(dir, { recursive: true, force: true });
|
|
124
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
125
|
+
const outFile = join(dir, "bundle.tar");
|
|
126
|
+
const manifest = createBundle({
|
|
127
|
+
...adapter.bundleSession(sessionId),
|
|
128
|
+
...(includeWorkspace !== undefined ? { includeWorkspace } : {}),
|
|
129
|
+
...(compression !== undefined ? { compression } : {}),
|
|
130
|
+
outFile,
|
|
131
|
+
ownership: { epoch: record.epoch, from: adapter.ownership.daemonId, moveId },
|
|
132
|
+
});
|
|
133
|
+
return { size: statSync(outFile).size, sha256: sha256File(outFile), files: manifest.totals.files, worktreeFiles: manifest.totals.worktreeFiles, excluded: manifest.excluded.length };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private read(moveId: string, offset: number, length: number): { data: string; eof: boolean } {
|
|
137
|
+
const file = join(this.movesDir, moveId, "bundle.tar");
|
|
138
|
+
if (!existsSync(file)) throw new Error(`No exported bundle for move ${moveId}`);
|
|
139
|
+
if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(length) || length <= 0) throw new Error("move_read needs a non-negative integer offset and a positive length");
|
|
140
|
+
const { data, eof } = readChunk(file, offset, Math.min(length, MAX_READ_BYTES));
|
|
141
|
+
return { data: data.toString("base64"), eof };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private async retire(sessionId: string, moveId: string, movedTo: string): Promise<void> {
|
|
145
|
+
this.adapter.ownership.retire(sessionId, moveId, movedTo);
|
|
146
|
+
await this.adapter.retire(sessionId);
|
|
147
|
+
rmSync(join(this.movesDir, moveId), { recursive: true, force: true });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private async unfence(sessionId: string, moveId: string | undefined): Promise<void> {
|
|
151
|
+
const fencedBy = this.adapter.ownership.get(sessionId).moveId;
|
|
152
|
+
this.adapter.ownership.unfence(sessionId, moveId);
|
|
153
|
+
if (fencedBy) rmSync(join(this.movesDir, fencedBy), { recursive: true, force: true });
|
|
154
|
+
await this.adapter.resume(sessionId);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---- target side ----
|
|
158
|
+
|
|
159
|
+
private async begin(command: Extract<MoveCommand, { type: "move_begin" }>): Promise<void> {
|
|
160
|
+
const moveId = checkId("moveId", command.moveId);
|
|
161
|
+
const sessionId = checkId("sessionId", command.sessionId);
|
|
162
|
+
const sourceSessionId = command.sourceSessionId === undefined ? sessionId : checkId("sourceSessionId", command.sourceSessionId);
|
|
163
|
+
if ((command.copy === true) !== (sourceSessionId !== sessionId)) throw new Error("Copy requires a different destination session id; handoff must preserve the source id");
|
|
164
|
+
if (command.includeWorkspace === false) assertExistingDirectory(command.cwd);
|
|
165
|
+
if (this.aborted.has(moveId)) throw new Error(`Move ${moveId} was aborted`);
|
|
166
|
+
if (this.inbound.has(moveId)) throw new Error(`Move ${moveId} already started`);
|
|
167
|
+
if (!Number.isInteger(command.size) || command.size < 0 || typeof command.sha256 !== "string") throw new Error("move_begin needs size and sha256");
|
|
168
|
+
this.adapter.assertCanImport(sessionId);
|
|
169
|
+
if (command.cwd !== undefined && !command.cwd.startsWith("/")) throw new Error("move_begin cwd must be an absolute path");
|
|
170
|
+
await this.adapter.preflight?.({ side: "target", sessionId, moveId, ...(command.cwd ? { cwd: command.cwd } : {}) });
|
|
171
|
+
// Preflight is async: a duplicate or an abort may have landed while it ran.
|
|
172
|
+
if (this.aborted.has(moveId)) throw new Error(`Move ${moveId} was aborted`);
|
|
173
|
+
if (this.inbound.has(moveId)) throw new Error(`Move ${moveId} already started`);
|
|
174
|
+
if ([...this.inbound.values()].some((item) => item.sessionId === sessionId && !item.ack)) throw new Error(`Session ${sessionId} already has an inbound transfer`);
|
|
175
|
+
this.adapter.assertCanImport(sessionId);
|
|
176
|
+
const transfer = new InboundTransfer(join(this.movesDir, moveId, "bundle.tar"), command.size, command.sha256);
|
|
177
|
+
this.inbound.set(moveId, { sessionId, sourceSessionId, ...(command.includeWorkspace !== undefined ? { includeWorkspace: command.includeWorkspace } : {}), ...(command.cwd ? { cwd: command.cwd } : {}), ...(command.rebindProvider ? { rebindProvider: command.rebindProvider } : {}), transfer });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private write(moveId: string, offset: number, data: string): number {
|
|
181
|
+
const inbound = this.inbound.get(moveId);
|
|
182
|
+
if (!inbound) throw new Error(`Move ${moveId} was not started or was aborted`);
|
|
183
|
+
if (inbound.committing || inbound.ack) throw new Error(`Move ${moveId} is already committing or committed`);
|
|
184
|
+
return inbound.transfer.write(offset, Buffer.from(data, "base64"));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private async commit(moveId: string): Promise<CommitAck> {
|
|
188
|
+
const inbound = this.inbound.get(moveId);
|
|
189
|
+
if (!inbound || this.aborted.has(moveId)) throw new Error(`Move ${moveId} was not started or was aborted`);
|
|
190
|
+
if (inbound.ack) return inbound.ack;
|
|
191
|
+
inbound.committing ??= this.commitOnce(moveId, inbound);
|
|
192
|
+
return inbound.committing;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private async commitOnce(moveId: string, inbound: Inbound): Promise<CommitAck> {
|
|
196
|
+
const { adapter } = this;
|
|
197
|
+
const moveDir = join(this.movesDir, moveId);
|
|
198
|
+
const { sessionId } = inbound;
|
|
199
|
+
|
|
200
|
+
inbound.transfer.finish(); // size + sha256 of the whole archive
|
|
201
|
+
const extracted = verifyBundle(inbound.transfer.path, join(moveDir, "work"));
|
|
202
|
+
let dest: string | undefined;
|
|
203
|
+
let workspaceBuilt = false;
|
|
204
|
+
let destExisted = false;
|
|
205
|
+
const previousOwnership = adapter.ownership.peek(sessionId);
|
|
206
|
+
const snapshot = adapter.snapshot(sessionId);
|
|
207
|
+
let acquired = false;
|
|
208
|
+
try {
|
|
209
|
+
const { manifest } = extracted;
|
|
210
|
+
if (manifest.session.id !== inbound.sourceSessionId) throw new Error(`Bundle is for session ${manifest.session.id}, not ${inbound.sourceSessionId}`);
|
|
211
|
+
if (manifest.ownership.moveId !== moveId) throw new Error("Bundle ownership moveId does not match the transfer");
|
|
212
|
+
const includeWorkspace = manifest.workspaceIncluded !== false;
|
|
213
|
+
if (inbound.includeWorkspace !== undefined && inbound.includeWorkspace !== includeWorkspace) throw new Error("Bundle workspace mode does not match the transfer request");
|
|
214
|
+
adapter.assertCanImport(sessionId);
|
|
215
|
+
if (previousOwnership?.state === "moved" && (previousOwnership.movedTo !== manifest.ownership.from || manifest.ownership.epoch <= previousOwnership.epoch)) {
|
|
216
|
+
throw new Error(`Session ${sessionId} is not returning from its known owner at a newer epoch`);
|
|
217
|
+
}
|
|
218
|
+
adapter.checkBundle(manifest);
|
|
219
|
+
const cwdName = typeof manifest.session.metadata?.cwdName === "string" ? manifest.session.metadata.cwdName : "workspace";
|
|
220
|
+
if (basename(cwdName) !== cwdName || cwdName === "." || cwdName === "..") throw new Error("Invalid workspace name in bundle");
|
|
221
|
+
dest = resolve(inbound.cwd ?? join(this.serverDir, "workspaces", sessionId, cwdName));
|
|
222
|
+
let built;
|
|
223
|
+
if (includeWorkspace) {
|
|
224
|
+
destExisted = existsSync(dest);
|
|
225
|
+
built = materializeWorkspace(extracted, dest);
|
|
226
|
+
workspaceBuilt = true;
|
|
227
|
+
} else {
|
|
228
|
+
assertExistingDirectory(inbound.cwd);
|
|
229
|
+
built = { cwd: inbound.cwd, files: 0, bytes: 0 };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const record = adapter.ownership.acquire(sessionId, manifest.ownership.epoch + 1, moveId);
|
|
233
|
+
acquired = true;
|
|
234
|
+
const imported = await adapter.importSession({ sessionId, sourceSessionId: inbound.sourceSessionId, moveId, manifest, extractedDir: extracted.dir, cwd: built.cwd, ...(inbound.rebindProvider ? { rebindProvider: inbound.rebindProvider } : {}) });
|
|
235
|
+
inbound.ack = { sessionId, daemonId: adapter.ownership.daemonId, cwd: built.cwd, epoch: record.epoch, worktreeFiles: built.files, worktreeBytes: built.bytes, verified: true, ...(imported?.sessionFile ? { sessionFile: imported.sessionFile } : {}) };
|
|
236
|
+
return inbound.ack;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (acquired) {
|
|
239
|
+
await adapter.restore(sessionId, snapshot);
|
|
240
|
+
adapter.ownership.release(sessionId, previousOwnership);
|
|
241
|
+
}
|
|
242
|
+
if (dest && workspaceBuilt) {
|
|
243
|
+
if (destExisted) for (const name of readdirSync(dest)) rmSync(join(dest, name), { recursive: true, force: true });
|
|
244
|
+
else rmSync(dest, { recursive: true, force: true });
|
|
245
|
+
}
|
|
246
|
+
throw error;
|
|
247
|
+
} finally {
|
|
248
|
+
rmSync(extracted.dir, { recursive: true, force: true });
|
|
249
|
+
rmSync(moveDir, { recursive: true, force: true });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Cancel an inbound move. If it already committed, say so instead of undoing it: the target owns the session. */
|
|
254
|
+
private async abort(moveId: string, sessionId: string): Promise<{ committed: boolean }> {
|
|
255
|
+
const inbound = this.inbound.get(moveId);
|
|
256
|
+
if (inbound && inbound.sessionId !== sessionId) throw new Error("Abort sessionId does not match the transfer");
|
|
257
|
+
// An import may be awaiting provider startup. Do not report failure while it can still commit.
|
|
258
|
+
await inbound?.committing?.catch(() => undefined);
|
|
259
|
+
const record = this.adapter.ownership.get(sessionId);
|
|
260
|
+
const committed = inbound?.ack !== undefined || (record.state === "owned" && record.moveId === moveId);
|
|
261
|
+
if (committed) return { committed: true };
|
|
262
|
+
this.aborted.add(moveId);
|
|
263
|
+
inbound?.transfer.abort();
|
|
264
|
+
this.inbound.delete(moveId);
|
|
265
|
+
rmSync(join(this.movesDir, moveId), { recursive: true, force: true });
|
|
266
|
+
return { committed: false };
|
|
267
|
+
}
|
|
268
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exclusive ownership of each logical session, kept in one small JSON file per
|
|
3
|
+
* daemon. A session is writable here only while this daemon holds it ("owned").
|
|
4
|
+
* `epoch` rises every time ownership changes hands, so a stale holder can be told
|
|
5
|
+
* apart from the current one.
|
|
6
|
+
*
|
|
7
|
+
* owned --fence--> fenced --retire--> moved
|
|
8
|
+
* ^ |
|
|
9
|
+
* +----unfence-----+ (a later import back here: acquire -> owned, epoch + 1)
|
|
10
|
+
*
|
|
11
|
+
* A fenced or moved session refuses every command and is not resumed on boot, so a
|
|
12
|
+
* crash mid-move can never leave two live writers; only an explicit unfence or
|
|
13
|
+
* acquire changes that. A session with no record is owned at epoch 0.
|
|
14
|
+
*/
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
17
|
+
|
|
18
|
+
export type OwnershipState = "owned" | "fenced" | "moved";
|
|
19
|
+
|
|
20
|
+
export interface OwnershipRecord {
|
|
21
|
+
sessionId: string;
|
|
22
|
+
state: OwnershipState;
|
|
23
|
+
epoch: number;
|
|
24
|
+
/** Move that fenced or retired the session. */
|
|
25
|
+
moveId?: string;
|
|
26
|
+
/** Daemon that took the session over (state "moved"). */
|
|
27
|
+
movedTo?: string;
|
|
28
|
+
updatedAt: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface OwnershipFile {
|
|
32
|
+
version: 1;
|
|
33
|
+
/** Stable identity of this daemon's state directory. */
|
|
34
|
+
daemonId: string;
|
|
35
|
+
sessions: Record<string, OwnershipRecord>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class OwnershipError extends Error {
|
|
39
|
+
constructor(message: string) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.name = "OwnershipError";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class OwnershipStore {
|
|
46
|
+
readonly daemonId: string;
|
|
47
|
+
private readonly path: string;
|
|
48
|
+
private readonly records = new Map<string, OwnershipRecord>();
|
|
49
|
+
|
|
50
|
+
constructor(path: string) {
|
|
51
|
+
this.path = path;
|
|
52
|
+
let daemonId: string = randomUUID();
|
|
53
|
+
if (existsSync(path)) {
|
|
54
|
+
const parsed = JSON.parse(readFileSync(path, "utf8")) as OwnershipFile;
|
|
55
|
+
daemonId = parsed.daemonId;
|
|
56
|
+
for (const record of Object.values(parsed.sessions)) this.records.set(record.sessionId, record);
|
|
57
|
+
}
|
|
58
|
+
this.daemonId = daemonId;
|
|
59
|
+
this.save();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get(sessionId: string): OwnershipRecord {
|
|
63
|
+
return this.records.get(sessionId) ?? { sessionId, state: "owned", epoch: 0, updatedAt: new Date(0).toISOString() };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Every session this daemon has a record for (owned, fenced or moved). */
|
|
67
|
+
list(): OwnershipRecord[] {
|
|
68
|
+
return [...this.records.values()];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Why the session cannot take commands here, or undefined when this daemon owns it. */
|
|
72
|
+
blockedReason(sessionId: string): string | undefined {
|
|
73
|
+
const record = this.get(sessionId);
|
|
74
|
+
if (record.state === "fenced") return `Session ${sessionId} is fenced for a move${record.moveId ? ` (${record.moveId})` : ""}`;
|
|
75
|
+
if (record.state === "moved") return `Session ${sessionId} moved to another daemon${record.movedTo ? ` (${record.movedTo})` : ""}`;
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
fence(sessionId: string, moveId: string): OwnershipRecord {
|
|
80
|
+
const current = this.get(sessionId);
|
|
81
|
+
if (current.state !== "owned") throw new OwnershipError(this.blockedReason(sessionId) ?? `Session ${sessionId} is not owned here`);
|
|
82
|
+
return this.set({ ...current, state: "fenced", moveId });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Give the session back to this daemon after a failed move. Only the fencing move may do it. */
|
|
86
|
+
unfence(sessionId: string, moveId?: string): OwnershipRecord {
|
|
87
|
+
const current = this.get(sessionId);
|
|
88
|
+
if (current.state !== "fenced") throw new OwnershipError(`Session ${sessionId} is not fenced`);
|
|
89
|
+
if (moveId && current.moveId !== moveId) throw new OwnershipError(`Session ${sessionId} is fenced by move ${current.moveId}, not ${moveId}`);
|
|
90
|
+
const { moveId: _done, ...rest } = current;
|
|
91
|
+
return this.set({ ...rest, state: "owned" });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The target acknowledged: this daemon no longer owns the session. */
|
|
95
|
+
retire(sessionId: string, moveId: string, movedTo: string): OwnershipRecord {
|
|
96
|
+
const current = this.get(sessionId);
|
|
97
|
+
if (current.state === "moved" && current.moveId === moveId) return current; // retry after a lost reply
|
|
98
|
+
if (current.state !== "fenced" || current.moveId !== moveId) throw new OwnershipError(`Session ${sessionId} is not fenced by move ${moveId}`);
|
|
99
|
+
return this.set({ ...current, state: "moved", movedTo });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** This daemon takes the session at `epoch`; used by the import side. */
|
|
103
|
+
acquire(sessionId: string, epoch: number, moveId: string): OwnershipRecord {
|
|
104
|
+
const current = this.get(sessionId);
|
|
105
|
+
if (current.state === "owned" && this.records.has(sessionId)) throw new OwnershipError(`Session ${sessionId} is already owned by this daemon`);
|
|
106
|
+
if (current.state === "fenced") throw new OwnershipError(`Session ${sessionId} is fenced here; unfence it before importing`);
|
|
107
|
+
return this.set({ sessionId, state: "owned", epoch: Math.max(epoch, current.epoch + 1), moveId, updatedAt: "" });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Forget an acquisition that was rolled back. */
|
|
111
|
+
release(sessionId: string, previous: OwnershipRecord | undefined): void {
|
|
112
|
+
if (previous) this.records.set(sessionId, previous);
|
|
113
|
+
else this.records.delete(sessionId);
|
|
114
|
+
this.save();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Raw record or undefined (for rollback). */
|
|
118
|
+
peek(sessionId: string): OwnershipRecord | undefined {
|
|
119
|
+
return this.records.get(sessionId);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private set(record: OwnershipRecord): OwnershipRecord {
|
|
123
|
+
const next = { ...record, updatedAt: new Date().toISOString() };
|
|
124
|
+
this.records.set(record.sessionId, next);
|
|
125
|
+
this.save();
|
|
126
|
+
return next;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private save(): void {
|
|
130
|
+
const file: OwnershipFile = { version: 1, daemonId: this.daemonId, sessions: Object.fromEntries(this.records) };
|
|
131
|
+
const temp = `${this.path}.${process.pid}.tmp`;
|
|
132
|
+
writeFileSync(temp, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
|
|
133
|
+
renameSync(temp, this.path);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resumable-by-offset chunked file transfer, used to move a bundle over the
|
|
3
|
+
* daemon's own socket (which an SSH forward carries between machines). The
|
|
4
|
+
* receiver checks the total size and sha256 before it calls the file complete.
|
|
5
|
+
*/
|
|
6
|
+
import { closeSync, mkdirSync, openSync, readSync, statSync, writeSync } from "node:fs";
|
|
7
|
+
import { dirname } from "node:path";
|
|
8
|
+
import { sha256File } from "./bundle.ts";
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_CHUNK_BYTES = 1024 * 1024;
|
|
11
|
+
|
|
12
|
+
export class TransferError extends Error {
|
|
13
|
+
constructor(message: string) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "TransferError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function readChunk(path: string, offset: number, length: number): { data: Buffer; eof: boolean } {
|
|
20
|
+
const size = statSync(path).size;
|
|
21
|
+
const want = Math.max(0, Math.min(length, size - offset));
|
|
22
|
+
const buffer = Buffer.alloc(want);
|
|
23
|
+
const fd = openSync(path, "r");
|
|
24
|
+
try {
|
|
25
|
+
let read = 0;
|
|
26
|
+
while (read < want) {
|
|
27
|
+
const n = readSync(fd, buffer, read, want - read, offset + read);
|
|
28
|
+
if (n === 0) break;
|
|
29
|
+
read += n;
|
|
30
|
+
}
|
|
31
|
+
} finally {
|
|
32
|
+
closeSync(fd);
|
|
33
|
+
}
|
|
34
|
+
return { data: buffer, eof: offset + want >= size };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Receives one file by sequential writes; `finish` proves it arrived whole. */
|
|
38
|
+
export class InboundTransfer {
|
|
39
|
+
readonly path: string;
|
|
40
|
+
private readonly size: number;
|
|
41
|
+
private readonly sha256: string;
|
|
42
|
+
private received = 0;
|
|
43
|
+
private fd: number | undefined;
|
|
44
|
+
|
|
45
|
+
constructor(path: string, size: number, sha256: string) {
|
|
46
|
+
this.path = path;
|
|
47
|
+
this.size = size;
|
|
48
|
+
this.sha256 = sha256;
|
|
49
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
50
|
+
this.fd = openSync(path, "w", 0o600);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
write(offset: number, data: Buffer): number {
|
|
54
|
+
if (this.fd === undefined) throw new TransferError("transfer already finished");
|
|
55
|
+
if (offset !== this.received) throw new TransferError(`out-of-order chunk: expected offset ${this.received}, got ${offset}`);
|
|
56
|
+
if (this.received + data.length > this.size) throw new TransferError("transfer is larger than announced");
|
|
57
|
+
writeSync(this.fd, data);
|
|
58
|
+
this.received += data.length;
|
|
59
|
+
return this.received;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
finish(): void {
|
|
63
|
+
if (this.fd !== undefined) closeSync(this.fd);
|
|
64
|
+
this.fd = undefined;
|
|
65
|
+
if (this.received !== this.size) throw new TransferError(`transfer incomplete: got ${this.received} of ${this.size} bytes`);
|
|
66
|
+
if (sha256File(this.path) !== this.sha256) throw new TransferError("checksum mismatch: the archive changed in transit");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
abort(): void {
|
|
70
|
+
if (this.fd !== undefined) closeSync(this.fd);
|
|
71
|
+
this.fd = undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export interface DaemonOwnerIdentity {
|
|
6
|
+
pid: number;
|
|
7
|
+
token: string;
|
|
8
|
+
boot?: string;
|
|
9
|
+
start?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type Owner = DaemonOwnerIdentity;
|
|
13
|
+
|
|
14
|
+
export function currentOwnerIdentity(token = randomUUID()): DaemonOwnerIdentity {
|
|
15
|
+
return { pid: process.pid, token, ...linuxIdentity(process.pid) };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function ownerIsAlive(owner: DaemonOwnerIdentity): boolean {
|
|
19
|
+
return alive(owner);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type OwnerInspection =
|
|
23
|
+
| { status: "missing" | "ambiguous"; reason?: string }
|
|
24
|
+
| { status: "live" | "dead"; owner: DaemonOwnerIdentity };
|
|
25
|
+
|
|
26
|
+
/** Read-only, fail-closed inspection using the same PID-reuse checks as claiming. */
|
|
27
|
+
export function inspectDaemonOwner(serverDir: string, lockName = "daemon-owner"): OwnerInspection {
|
|
28
|
+
const lock = join(serverDir, lockName);
|
|
29
|
+
try {
|
|
30
|
+
const names = readdirSync(lock);
|
|
31
|
+
if (names.length !== 1) return { status: "ambiguous", reason: "Ownership directory is empty or has multiple entries" };
|
|
32
|
+
const owner: Owner = JSON.parse(readFileSync(join(lock, names[0]!), "utf8"));
|
|
33
|
+
validateOwner(owner, names[0]!, lock);
|
|
34
|
+
return { status: alive(owner) ? "live" : "dead", owner };
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
37
|
+
// A disappearing file inside a published directory is not proof of no owner.
|
|
38
|
+
try { readdirSync(lock); } catch (again) {
|
|
39
|
+
if ((again as NodeJS.ErrnoException).code === "ENOENT") return { status: "missing" };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return { status: "ambiguous", reason: String(error) };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function validateDaemonOwnerIdentity(value: unknown): asserts value is DaemonOwnerIdentity {
|
|
47
|
+
const owner = value as Owner;
|
|
48
|
+
validateOwner(owner, `owner-${owner?.token}.json`, "activation journal");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function validateOwner(previous: Owner, name: string, lock: string): void {
|
|
52
|
+
if (!previous || typeof previous !== "object" || Array.isArray(previous)
|
|
53
|
+
|| !Number.isSafeInteger(previous.pid) || previous.pid <= 0 || previous.pid > 2_147_483_647
|
|
54
|
+
|| typeof previous.token !== "string" || !UUID.test(previous.token) || name !== `owner-${previous.token}.json`
|
|
55
|
+
|| (previous.boot !== undefined && (typeof previous.boot !== "string" || !UUID.test(previous.boot)))
|
|
56
|
+
|| (previous.start !== undefined && (typeof previous.start !== "string" || !/^\d+$/.test(previous.start)))) throw new Error(`Invalid daemon ownership in ${lock}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
60
|
+
|
|
61
|
+
function linuxIdentity(pid: number): Pick<Owner, "boot" | "start"> {
|
|
62
|
+
if (process.platform !== "linux") return {};
|
|
63
|
+
try {
|
|
64
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
65
|
+
return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] };
|
|
66
|
+
} catch { return {}; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function alive(owner: Owner): boolean {
|
|
70
|
+
const identity = linuxIdentity(owner.pid);
|
|
71
|
+
if (owner.boot && identity.boot && owner.boot !== identity.boot) return false;
|
|
72
|
+
if (owner.start && identity.start && owner.start !== identity.start) return false;
|
|
73
|
+
try { process.kill(owner.pid, 0); return true; }
|
|
74
|
+
catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Claim ownership before reading the index. A live owner is never reclaimed on a timer. */
|
|
78
|
+
export function claimDaemonOwner(serverDir: string, lockName = "daemon-owner"): () => void {
|
|
79
|
+
const token = randomUUID();
|
|
80
|
+
const owner = currentOwnerIdentity(token);
|
|
81
|
+
const lock = join(serverDir, lockName);
|
|
82
|
+
const candidate = join(serverDir, `.${lockName}-${token}`);
|
|
83
|
+
const name = `owner-${token}.json`;
|
|
84
|
+
mkdirSync(candidate, { mode: 0o700 });
|
|
85
|
+
let claimed = false;
|
|
86
|
+
try {
|
|
87
|
+
writeFileSync(join(candidate, name), `${JSON.stringify(owner)}\n`, { mode: 0o600 });
|
|
88
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
89
|
+
try {
|
|
90
|
+
// Publishing a fully populated directory avoids an ownerless mkdir/write window.
|
|
91
|
+
renameSync(candidate, lock);
|
|
92
|
+
claimed = true;
|
|
93
|
+
let released = false;
|
|
94
|
+
return () => {
|
|
95
|
+
if (released) return;
|
|
96
|
+
try { unlinkSync(join(lock, name)); }
|
|
97
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
98
|
+
try { rmdirSync(lock); }
|
|
99
|
+
catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
|
|
100
|
+
released = true;
|
|
101
|
+
};
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (!["EEXIST", "ENOTEMPTY"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
|
|
104
|
+
}
|
|
105
|
+
let names: string[];
|
|
106
|
+
try { names = readdirSync(lock); }
|
|
107
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
108
|
+
if (names.length === 0) continue;
|
|
109
|
+
if (names.length !== 1 || !/^owner-[a-f0-9-]+\.json$/.test(names[0]!)) throw new Error(`Unrecognized daemon ownership in ${lock}; refusing to remove it`);
|
|
110
|
+
const path = join(lock, names[0]!);
|
|
111
|
+
let previous: Owner;
|
|
112
|
+
try { previous = JSON.parse(readFileSync(path, "utf8")); }
|
|
113
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
114
|
+
validateOwner(previous, names[0]!, lock);
|
|
115
|
+
if (alive(previous)) throw new Error(`Daemon owner ${previous.pid} is already running for ${serverDir}; refusing another writer`);
|
|
116
|
+
// Remove only the exact stale owner's file. A competing claimant publishes a different token.
|
|
117
|
+
try { unlinkSync(path); }
|
|
118
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
119
|
+
try { rmdirSync(lock); }
|
|
120
|
+
catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
|
|
121
|
+
}
|
|
122
|
+
throw new Error(`Daemon ownership changed repeatedly for ${serverDir}; retry connecting`);
|
|
123
|
+
} finally {
|
|
124
|
+
if (!claimed) {
|
|
125
|
+
try { unlinkSync(join(candidate, name)); }
|
|
126
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
127
|
+
rmdirSync(candidate);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|