@peakflo/agent-harness 0.2.32 → 0.2.33
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/cli.js +25 -0
- package/dist/contract.d.ts +2 -0
- package/dist/contract.js +2 -0
- package/dist/control-plane.d.ts +7 -0
- package/dist/control-plane.js +12 -0
- package/dist/harness.d.ts +22 -0
- package/dist/harness.js +61 -1
- package/dist/service.d.ts +11 -0
- package/dist/service.js +58 -9
- package/dist/types.d.ts +12 -0
- package/dist/updater/coordinator.d.ts +62 -0
- package/dist/updater/coordinator.js +194 -0
- package/dist/updater/launcher.d.ts +24 -0
- package/dist/updater/launcher.js +157 -0
- package/dist/updater/layout.d.ts +53 -0
- package/dist/updater/layout.js +68 -0
- package/dist/updater/stage.d.ts +41 -0
- package/dist/updater/stage.js +169 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -42,6 +42,7 @@ const harness_1 = require("./harness");
|
|
|
42
42
|
const node_floor_1 = require("./node-floor");
|
|
43
43
|
const options_1 = require("./options");
|
|
44
44
|
const service_1 = require("./service");
|
|
45
|
+
const coordinator_1 = require("./updater/coordinator");
|
|
45
46
|
const version_1 = require("./version");
|
|
46
47
|
const USAGE = `pf-agent-harness — headless Peakflo coding-agent harness
|
|
47
48
|
|
|
@@ -268,7 +269,26 @@ async function main() {
|
|
|
268
269
|
}).assertNoDuplicateRunner(options);
|
|
269
270
|
const handedOffCredential = (0, credential_store_1.takeHandedOffCredential)(startEnv);
|
|
270
271
|
const resolveAdapter = (0, adapter_resolver_1.createAdapterResolver)(options.runtime, options.workspaceRoot, { claudePath: options.claudePath });
|
|
272
|
+
// Self-update only for service installs on macOS/Linux, under the launcher
|
|
273
|
+
// (which sets PF_UPDATE_ROOT). A terminal runner never restarts itself.
|
|
274
|
+
const updateRoot = process.env.PF_UPDATE_ROOT;
|
|
275
|
+
let updater;
|
|
276
|
+
const reporters = {};
|
|
277
|
+
if (serviceStart &&
|
|
278
|
+
updateRoot &&
|
|
279
|
+
(process.platform === 'darwin' || process.platform === 'linux')) {
|
|
280
|
+
updater = new coordinator_1.RunnerUpdater({
|
|
281
|
+
root: updateRoot,
|
|
282
|
+
currentVersion: (0, version_1.getHarnessVersion)(),
|
|
283
|
+
report: (r) => reporters.report?.(r) ?? Promise.resolve(),
|
|
284
|
+
log: (message, fields) => process.stderr.write(`${JSON.stringify({ event: 'runner_update', message, ...fields })}\n`),
|
|
285
|
+
...(process.env.PF_UPDATE_MAX_DRAIN_MS
|
|
286
|
+
? { maxDrainMs: Number(process.env.PF_UPDATE_MAX_DRAIN_MS) }
|
|
287
|
+
: {})
|
|
288
|
+
});
|
|
289
|
+
}
|
|
271
290
|
const harness = new harness_1.Harness(options, {
|
|
291
|
+
...(updater ? { updater } : {}),
|
|
272
292
|
getAdapter: (backend, ports) => resolveAdapter(backend, ports),
|
|
273
293
|
...(handedOffCredential
|
|
274
294
|
? { credentialStore: new credential_store_1.MemoryCredentialStore(handedOffCredential) }
|
|
@@ -279,6 +299,7 @@ async function main() {
|
|
|
279
299
|
}
|
|
280
300
|
}
|
|
281
301
|
});
|
|
302
|
+
reporters.report = (r) => harness.reportUpdate(r);
|
|
282
303
|
let shuttingDown = false;
|
|
283
304
|
const shutdown = (signal) => {
|
|
284
305
|
if (shuttingDown) {
|
|
@@ -306,6 +327,10 @@ async function main() {
|
|
|
306
327
|
process.exit(75);
|
|
307
328
|
}
|
|
308
329
|
catch (error) {
|
|
330
|
+
// A switched service install: a non-zero exit makes launchd/systemd
|
|
331
|
+
// restart the launcher, which then runs the new version.
|
|
332
|
+
if (error instanceof harness_1.UpdateRestartError)
|
|
333
|
+
process.exit(75);
|
|
309
334
|
if (error instanceof harness_1.UpgradeRequestedError) {
|
|
310
335
|
if (serviceStart)
|
|
311
336
|
stopPermanentServiceFailure('harness upgrade required', 78);
|
package/dist/contract.d.ts
CHANGED
|
@@ -187,6 +187,8 @@ export declare const ROUTES: {
|
|
|
187
187
|
readonly register: () => string;
|
|
188
188
|
/** Bearer: runner credential. 30s period. */
|
|
189
189
|
readonly heartbeat: (runnerId: string) => string;
|
|
190
|
+
/** Bearer: runner credential. Result of a self-update (updating/updated/failed/rolled_back/refused). */
|
|
191
|
+
readonly updateReport: (runnerId: string) => string;
|
|
190
192
|
/** Bearer: runner credential. Best-effort timing events of one turn, batched; no transcript data. */
|
|
191
193
|
readonly coldStart: (runnerId: string) => string;
|
|
192
194
|
/**
|
package/dist/contract.js
CHANGED
|
@@ -229,6 +229,8 @@ exports.ROUTES = {
|
|
|
229
229
|
register: () => '/api/runners/register',
|
|
230
230
|
/** Bearer: runner credential. 30s period. */
|
|
231
231
|
heartbeat: (runnerId) => `/api/runners/${encodeURIComponent(runnerId)}/heartbeat`,
|
|
232
|
+
/** Bearer: runner credential. Result of a self-update (updating/updated/failed/rolled_back/refused). */
|
|
233
|
+
updateReport: (runnerId) => `/api/runners/${encodeURIComponent(runnerId)}/update-report`,
|
|
232
234
|
/** Bearer: runner credential. Best-effort timing events of one turn, batched; no transcript data. */
|
|
233
235
|
coldStart: (runnerId) => `/api/runners/${encodeURIComponent(runnerId)}/cold-start`,
|
|
234
236
|
/**
|
package/dist/control-plane.d.ts
CHANGED
|
@@ -89,6 +89,13 @@ export declare class ControlPlaneClient {
|
|
|
89
89
|
* This replaced one POST per step. The control plane accepts both shapes,
|
|
90
90
|
* so an older harness on an existing sandbox keeps working.
|
|
91
91
|
*/
|
|
92
|
+
/** Best-effort report of a self-update result. */
|
|
93
|
+
reportUpdate(body: {
|
|
94
|
+
state: string;
|
|
95
|
+
fromVersion: string;
|
|
96
|
+
toVersion: string;
|
|
97
|
+
reason?: string;
|
|
98
|
+
}): Promise<void>;
|
|
92
99
|
reportColdStartBatch(body: ColdStartBatchBody): Promise<void>;
|
|
93
100
|
/**
|
|
94
101
|
* Give the lease-renewal worker the minimum information it needs.
|
package/dist/control-plane.js
CHANGED
|
@@ -121,6 +121,18 @@ class ControlPlaneClient {
|
|
|
121
121
|
* This replaced one POST per step. The control plane accepts both shapes,
|
|
122
122
|
* so an older harness on an existing sandbox keeps working.
|
|
123
123
|
*/
|
|
124
|
+
/** Best-effort report of a self-update result. */
|
|
125
|
+
async reportUpdate(body) {
|
|
126
|
+
if (!this.runnerId || !this.runnerCredential)
|
|
127
|
+
return;
|
|
128
|
+
await this.send({
|
|
129
|
+
method: 'POST',
|
|
130
|
+
path: contract_1.ROUTES.updateReport(this.runnerId),
|
|
131
|
+
token: this.runnerCredential,
|
|
132
|
+
body,
|
|
133
|
+
timeoutMs: 5_000
|
|
134
|
+
});
|
|
135
|
+
}
|
|
124
136
|
async reportColdStartBatch(body) {
|
|
125
137
|
if (!this.runnerId || !this.runnerCredential)
|
|
126
138
|
return;
|
package/dist/harness.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { ControlPlaneClient } from './control-plane';
|
|
|
4
4
|
import { CredentialStore } from './credential-store';
|
|
5
5
|
import { type DiscoverHarnessesOptions } from './harness-discovery';
|
|
6
6
|
import { ArtifactInspector, EventSink, Notifier, SecretProvider, Telemetry, ConversationStore, TranscriptStore, WorkspaceProvider } from './ports';
|
|
7
|
+
import type { RunnerUpdater } from './updater/coordinator';
|
|
7
8
|
import { HarnessOptions, HealthReport, RunnerHarness } from './types';
|
|
8
9
|
/**
|
|
9
10
|
* How often the installed harnesses are looked for again.
|
|
@@ -58,6 +59,11 @@ export declare class UpgradeRequestedError extends Error {
|
|
|
58
59
|
readonly harnessVersion: string;
|
|
59
60
|
constructor(harnessVersion: string);
|
|
60
61
|
}
|
|
62
|
+
/** A service install switched to a new version; the manager restarts it. */
|
|
63
|
+
export declare class UpdateRestartError extends Error {
|
|
64
|
+
readonly toVersion: string;
|
|
65
|
+
constructor(toVersion: string);
|
|
66
|
+
}
|
|
61
67
|
export interface HarnessUpgradeRequest {
|
|
62
68
|
harnessVersion: string;
|
|
63
69
|
/**
|
|
@@ -116,6 +122,11 @@ export interface HarnessDeps {
|
|
|
116
122
|
leaseRenewIntervalMs?: number;
|
|
117
123
|
/** Pass the live runner identity to the sandbox supervisor over IPC. */
|
|
118
124
|
onUpgradeRequested?: (request: HarnessUpgradeRequest) => void;
|
|
125
|
+
/**
|
|
126
|
+
* Self-updater for personal runners that run as a launchd/systemd service.
|
|
127
|
+
* Absent for terminal runners and Windows: those only show the local command.
|
|
128
|
+
*/
|
|
129
|
+
updater?: RunnerUpdater;
|
|
119
130
|
/**
|
|
120
131
|
* How often the lease is renewed WHILE A PERMISSION PROMPT IS OUTSTANDING.
|
|
121
132
|
* Defaults to `APPROVAL_RENEW_INTERVAL_MS` (2 s).
|
|
@@ -480,6 +491,17 @@ export declare class Harness {
|
|
|
480
491
|
*/
|
|
481
492
|
private recoverFailedAnswer;
|
|
482
493
|
private runLeaseLoop;
|
|
494
|
+
/** Used by the self-updater to tell the control plane what happened. */
|
|
495
|
+
reportUpdate(body: {
|
|
496
|
+
state: string;
|
|
497
|
+
fromVersion: string;
|
|
498
|
+
toVersion: string;
|
|
499
|
+
reason?: string;
|
|
500
|
+
}): Promise<void>;
|
|
501
|
+
private heartbeatSucceeded;
|
|
502
|
+
private announcedLocalUpdate;
|
|
503
|
+
/** Offer from the control plane. Service installs stage it; others only tell. */
|
|
504
|
+
private observeRunnerUpdate;
|
|
483
505
|
/**
|
|
484
506
|
* Record a changed pin. Only managed sandboxes have the baked supervisor
|
|
485
507
|
* that can service the distinguished exit code.
|
package/dist/harness.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Harness = exports.UpgradeRequestedError = exports.StoredCredentialUnavailableError = exports.VersionRefusedError = exports.HARNESS_DISCOVERY_FEATURE = exports.HARNESS_RETRY_DELAYS_MS = exports.HARNESS_DISCOVERY_REFRESH_MS = void 0;
|
|
3
|
+
exports.Harness = exports.UpdateRestartError = exports.UpgradeRequestedError = exports.StoredCredentialUnavailableError = exports.VersionRefusedError = exports.HARNESS_DISCOVERY_FEATURE = exports.HARNESS_RETRY_DELAYS_MS = exports.HARNESS_DISCOVERY_REFRESH_MS = void 0;
|
|
4
4
|
exports.mergeHarnessReports = mergeHarnessReports;
|
|
5
5
|
exports.harnessContentKey = harnessContentKey;
|
|
6
6
|
const node_crypto_1 = require("node:crypto");
|
|
@@ -135,6 +135,16 @@ class UpgradeRequestedError extends Error {
|
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
137
|
exports.UpgradeRequestedError = UpgradeRequestedError;
|
|
138
|
+
/** A service install switched to a new version; the manager restarts it. */
|
|
139
|
+
class UpdateRestartError extends Error {
|
|
140
|
+
toVersion;
|
|
141
|
+
constructor(toVersion) {
|
|
142
|
+
super(`Runner update installed: ${toVersion}`);
|
|
143
|
+
this.toVersion = toVersion;
|
|
144
|
+
this.name = 'UpdateRestartError';
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
exports.UpdateRestartError = UpdateRestartError;
|
|
138
148
|
function log(message, extra) {
|
|
139
149
|
process.stdout.write(`${JSON.stringify({
|
|
140
150
|
ts: new Date().toISOString(),
|
|
@@ -610,6 +620,8 @@ class Harness {
|
|
|
610
620
|
/* ------------------------------------------------------------------ */
|
|
611
621
|
async register() {
|
|
612
622
|
const capabilities = this.capabilities ?? (await (0, capabilities_1.probeCapabilities)());
|
|
623
|
+
if (this.deps.updater)
|
|
624
|
+
capabilities.selfUpdate = true;
|
|
613
625
|
// 1. REUSE A PERSISTED CREDENTIAL when there is a valid one.
|
|
614
626
|
//
|
|
615
627
|
// This is the whole fix for "a crashed harness can never rejoin": a
|
|
@@ -1279,6 +1291,8 @@ class Harness {
|
|
|
1279
1291
|
this.refreshCapabilities();
|
|
1280
1292
|
this.applyModelCatalog(capabilities);
|
|
1281
1293
|
this.applyHarnessReport(capabilities);
|
|
1294
|
+
if (this.deps.updater)
|
|
1295
|
+
capabilities.selfUpdate = true;
|
|
1282
1296
|
this.capabilities = capabilities;
|
|
1283
1297
|
// Not awaited: the answer is attached to a LATER heartbeat. Only the
|
|
1284
1298
|
// cached report is ever sent, so a slow CLI cannot delay a heartbeat.
|
|
@@ -1325,6 +1339,8 @@ class Harness {
|
|
|
1325
1339
|
: null;
|
|
1326
1340
|
this.observeHarnessPin(response.harnessVersion);
|
|
1327
1341
|
this.observeSandboxToolsPin(response.sandboxToolsVersion);
|
|
1342
|
+
this.heartbeatSucceeded = true;
|
|
1343
|
+
this.observeRunnerUpdate(response.runnerUpdate);
|
|
1328
1344
|
this.applyCommandsSafely(response.sessionCommands ?? []);
|
|
1329
1345
|
if (response.action === 'drain') {
|
|
1330
1346
|
this.status = 'draining';
|
|
@@ -1636,6 +1652,18 @@ class Harness {
|
|
|
1636
1652
|
// re-invoke the supervisor exactly like a harness bump does, because
|
|
1637
1653
|
// pf-bootstrap's re-dial of /harness/bootstrap is what actually
|
|
1638
1654
|
// resyncs BOTH layers, not just the one that changed.
|
|
1655
|
+
if (this.deps.updater) {
|
|
1656
|
+
// Stop taking new leases once the update is staged; never kill a turn.
|
|
1657
|
+
if (await this.deps.updater.tick(this.active.size)) {
|
|
1658
|
+
this.fatal = new UpdateRestartError('');
|
|
1659
|
+
await this.stop({ preserveRegistration: true });
|
|
1660
|
+
break;
|
|
1661
|
+
}
|
|
1662
|
+
if (this.deps.updater.draining) {
|
|
1663
|
+
await sleep(500);
|
|
1664
|
+
continue;
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1639
1667
|
if (this.pendingHarnessVersion || this.pendingSandboxToolsVersion) {
|
|
1640
1668
|
if (this.active.size === 0) {
|
|
1641
1669
|
await this.requestUpgrade(this.pendingHarnessVersion ?? (0, version_1.getHarnessVersion)(), this.pendingSandboxToolsVersion ?? undefined);
|
|
@@ -1685,6 +1713,11 @@ class Harness {
|
|
|
1685
1713
|
await sleep(LEASE_ERROR_BACKOFF_MS);
|
|
1686
1714
|
continue;
|
|
1687
1715
|
}
|
|
1716
|
+
// Health check of a freshly switched version: registered, heartbeating,
|
|
1717
|
+
// and a lease call answered (a dry check: 204 or a normal lease).
|
|
1718
|
+
if (this.heartbeatSucceeded && this.deps.updater?.awaitingHealth) {
|
|
1719
|
+
void this.deps.updater.confirmHealthy();
|
|
1720
|
+
}
|
|
1688
1721
|
if (!lease) {
|
|
1689
1722
|
// The server normally long-polls. A 204 returned immediately during
|
|
1690
1723
|
// a fence or by a faulty proxy must not make this process spin.
|
|
@@ -1744,6 +1777,33 @@ class Harness {
|
|
|
1744
1777
|
}
|
|
1745
1778
|
await this.stop();
|
|
1746
1779
|
}
|
|
1780
|
+
/** Used by the self-updater to tell the control plane what happened. */
|
|
1781
|
+
async reportUpdate(body) {
|
|
1782
|
+
await this.client.reportUpdate(body);
|
|
1783
|
+
}
|
|
1784
|
+
heartbeatSucceeded = false;
|
|
1785
|
+
announcedLocalUpdate = null;
|
|
1786
|
+
/** Offer from the control plane. Service installs stage it; others only tell. */
|
|
1787
|
+
observeRunnerUpdate(offer) {
|
|
1788
|
+
if (this.options.runtime === 'sandbox' || !offer)
|
|
1789
|
+
return;
|
|
1790
|
+
if (this.deps.updater) {
|
|
1791
|
+
this.deps.updater.observe(offer);
|
|
1792
|
+
void this.deps.updater.reportLastResult();
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
const target = offer.recommendedVersion;
|
|
1796
|
+
if (target &&
|
|
1797
|
+
target !== (0, version_1.getHarnessVersion)() &&
|
|
1798
|
+
this.announcedLocalUpdate !== target) {
|
|
1799
|
+
this.announcedLocalUpdate = target;
|
|
1800
|
+
log('Update available (run in a terminal, not a service)', {
|
|
1801
|
+
current: (0, version_1.getHarnessVersion)(),
|
|
1802
|
+
available: target,
|
|
1803
|
+
command: `npx --yes @peakflo/agent-harness@${target} service install`
|
|
1804
|
+
});
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1747
1807
|
/**
|
|
1748
1808
|
* Record a changed pin. Only managed sandboxes have the baked supervisor
|
|
1749
1809
|
* that can service the distinguished exit code.
|
package/dist/service.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ interface ServiceConfig {
|
|
|
5
5
|
nodePath: string;
|
|
6
6
|
cliPath: string;
|
|
7
7
|
path: string;
|
|
8
|
+
/** Stable launcher + updater state dir. Absent on services installed before auto-update. */
|
|
9
|
+
launcherPath?: string;
|
|
10
|
+
updateRoot?: string;
|
|
11
|
+
fallbackVersion?: string;
|
|
8
12
|
}
|
|
9
13
|
export interface ServiceContext {
|
|
10
14
|
nodePath: string;
|
|
@@ -41,6 +45,11 @@ export declare function permanentStartupFailure(error: unknown): string | null;
|
|
|
41
45
|
export declare function isServiceStart(argv: string[]): boolean;
|
|
42
46
|
/** Parse only documented start options. A token can never enter service state. */
|
|
43
47
|
export declare function serviceStartArgs(input: string[], env: NodeJS.ProcessEnv, home: string): string[];
|
|
48
|
+
/**
|
|
49
|
+
* With the launcher, the service runs a stable script that picks the active
|
|
50
|
+
* harness version and rolls back a bad update; without it, the harness itself.
|
|
51
|
+
*/
|
|
52
|
+
export declare function programArguments(config: ServiceConfig): string[];
|
|
44
53
|
export declare function renderLaunchAgent(config: ServiceConfig, logDir: string, label?: string): string;
|
|
45
54
|
export declare function renderSystemdUnit(config: ServiceConfig): string;
|
|
46
55
|
export declare function recordServiceFailure(reason: string, home?: string): void;
|
|
@@ -63,6 +72,8 @@ export declare class ServiceManager {
|
|
|
63
72
|
private readConfig;
|
|
64
73
|
private checkCredential;
|
|
65
74
|
private writeAndStart;
|
|
75
|
+
/** Copy the stable launcher and seed active.json. Called by install and repair. */
|
|
76
|
+
private prepareUpdater;
|
|
66
77
|
install(input: string[]): Promise<void>;
|
|
67
78
|
private vendorFlag;
|
|
68
79
|
private checkNodeVersion;
|
package/dist/service.js
CHANGED
|
@@ -6,6 +6,7 @@ exports.permanentServiceExitCode = permanentServiceExitCode;
|
|
|
6
6
|
exports.permanentStartupFailure = permanentStartupFailure;
|
|
7
7
|
exports.isServiceStart = isServiceStart;
|
|
8
8
|
exports.serviceStartArgs = serviceStartArgs;
|
|
9
|
+
exports.programArguments = programArguments;
|
|
9
10
|
exports.renderLaunchAgent = renderLaunchAgent;
|
|
10
11
|
exports.renderSystemdUnit = renderSystemdUnit;
|
|
11
12
|
exports.recordServiceFailure = recordServiceFailure;
|
|
@@ -17,6 +18,8 @@ const node_net_1 = require("node:net");
|
|
|
17
18
|
const node_os_1 = require("node:os");
|
|
18
19
|
const node_path_1 = require("node:path");
|
|
19
20
|
const credential_store_1 = require("./credential-store");
|
|
21
|
+
const layout_1 = require("./updater/layout");
|
|
22
|
+
const stage_1 = require("./updater/stage");
|
|
20
23
|
const node_floor_1 = require("./node-floor");
|
|
21
24
|
const options_1 = require("./options");
|
|
22
25
|
const vendor_backends_1 = require("./vendor-backends");
|
|
@@ -202,22 +205,36 @@ function serviceStartArgs(input, env, home) {
|
|
|
202
205
|
result.push(flag);
|
|
203
206
|
return result;
|
|
204
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* With the launcher, the service runs a stable script that picks the active
|
|
210
|
+
* harness version and rolls back a bad update; without it, the harness itself.
|
|
211
|
+
*/
|
|
212
|
+
function programArguments(config) {
|
|
213
|
+
if (config.launcherPath && config.updateRoot)
|
|
214
|
+
return [
|
|
215
|
+
config.nodePath,
|
|
216
|
+
config.launcherPath,
|
|
217
|
+
'--root',
|
|
218
|
+
config.updateRoot,
|
|
219
|
+
'--fallback-cli',
|
|
220
|
+
config.cliPath,
|
|
221
|
+
...(config.fallbackVersion
|
|
222
|
+
? ['--fallback-version', config.fallbackVersion]
|
|
223
|
+
: []),
|
|
224
|
+
'--',
|
|
225
|
+
...config.startArgs
|
|
226
|
+
];
|
|
227
|
+
return [config.nodePath, config.cliPath, 'start', ...config.startArgs];
|
|
228
|
+
}
|
|
205
229
|
function renderLaunchAgent(config, logDir, label = LABEL) {
|
|
206
|
-
const args =
|
|
230
|
+
const args = programArguments(config);
|
|
207
231
|
const array = args
|
|
208
232
|
.map((arg) => ` <string>${xml(arg)}</string>`)
|
|
209
233
|
.join('\n');
|
|
210
234
|
return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key><string>${xml(label)}</string>\n <key>ProgramArguments</key><array>\n${array}\n </array>\n <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n <key>ThrottleInterval</key><integer>30</integer>\n <key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(config.path)}</string></dict>\n <key>StandardOutPath</key><string>${xml((0, node_path_1.join)(logDir, 'stdout.log'))}</string>\n <key>StandardErrorPath</key><string>${xml((0, node_path_1.join)(logDir, 'stderr.log'))}</string>\n</dict>\n</plist>\n`;
|
|
211
235
|
}
|
|
212
236
|
function renderSystemdUnit(config) {
|
|
213
|
-
const command =
|
|
214
|
-
config.nodePath,
|
|
215
|
-
config.cliPath,
|
|
216
|
-
'start',
|
|
217
|
-
...config.startArgs
|
|
218
|
-
]
|
|
219
|
-
.map(systemd)
|
|
220
|
-
.join(' ');
|
|
237
|
+
const command = programArguments(config).map(systemd).join(' ');
|
|
221
238
|
return `[Unit]\nDescription=Peakflo agent harness\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nExecStart=${command}\nEnvironment=${systemdEnvironment(`PATH=${config.path}`)}\nRestart=always\nRestartSec=30s\nRestartPreventExitStatus=2 78\n\n[Install]\nWantedBy=default.target\n`;
|
|
222
239
|
}
|
|
223
240
|
function defaultRun(file, args) {
|
|
@@ -320,6 +337,7 @@ class ServiceManager {
|
|
|
320
337
|
throw new Error('Node.js or the harness CLI is missing. Reinstall the package and run service repair.');
|
|
321
338
|
}
|
|
322
339
|
(0, node_fs_1.mkdirSync)(this.logDir, { recursive: true, mode: 0o700 });
|
|
340
|
+
this.prepareUpdater(config);
|
|
323
341
|
writePrivate(this.stateFile, `${JSON.stringify(config, null, 2)}\n`);
|
|
324
342
|
if (this.platform === 'darwin') {
|
|
325
343
|
writePrivate(this.serviceFile, renderLaunchAgent(config, this.logDir, this.label));
|
|
@@ -359,6 +377,33 @@ class ServiceManager {
|
|
|
359
377
|
this.run('systemctl', ['--user', 'restart', this.unit]);
|
|
360
378
|
}
|
|
361
379
|
}
|
|
380
|
+
/** Copy the stable launcher and seed active.json. Called by install and repair. */
|
|
381
|
+
prepareUpdater(config) {
|
|
382
|
+
const source = (0, node_path_1.join)(__dirname, 'updater', 'launcher.js');
|
|
383
|
+
if (!(0, node_fs_1.existsSync)(source))
|
|
384
|
+
return; // e.g. a source checkout; run without auto-update
|
|
385
|
+
const root = (0, node_path_1.join)(this.home, '.pf-agent-harness', 'updater', this.context.instance ?? 'default');
|
|
386
|
+
(0, node_fs_1.mkdirSync)(root, { recursive: true, mode: 0o700 });
|
|
387
|
+
const launcher = (0, node_path_1.join)(root, 'launcher.js');
|
|
388
|
+
writePrivate(launcher, (0, node_fs_1.readFileSync)(source, 'utf8'));
|
|
389
|
+
const version = (0, version_1.getHarnessVersion)();
|
|
390
|
+
const files = (0, layout_1.paths)(root);
|
|
391
|
+
const active = (0, layout_1.readJson)(files.active);
|
|
392
|
+
// Keep a newer already-installed version; never downgrade on repair.
|
|
393
|
+
const keepActive = active?.version &&
|
|
394
|
+
(0, node_fs_1.existsSync)(active.cli) &&
|
|
395
|
+
(0, stage_1.compareVersions)(active.version, version) > 0;
|
|
396
|
+
if (!keepActive)
|
|
397
|
+
(0, layout_1.writeJsonAtomic)(files.active, {
|
|
398
|
+
version,
|
|
399
|
+
cli: config.cliPath,
|
|
400
|
+
previous: null
|
|
401
|
+
});
|
|
402
|
+
(0, node_fs_1.rmSync)(files.pending, { force: true }); // a repair ends any half-done switch
|
|
403
|
+
config.launcherPath = launcher;
|
|
404
|
+
config.updateRoot = root;
|
|
405
|
+
config.fallbackVersion = version;
|
|
406
|
+
}
|
|
362
407
|
async install(input) {
|
|
363
408
|
this.supported();
|
|
364
409
|
this.checkNodeVersion();
|
|
@@ -679,6 +724,10 @@ class ServiceManager {
|
|
|
679
724
|
}
|
|
680
725
|
(0, node_fs_1.rmSync)(this.serviceFile, { force: true });
|
|
681
726
|
(0, node_fs_1.rmSync)(this.stateFile, { force: true });
|
|
727
|
+
(0, node_fs_1.rmSync)((0, node_path_1.join)(this.home, '.pf-agent-harness', 'updater', this.context.instance ?? 'default'), {
|
|
728
|
+
recursive: true,
|
|
729
|
+
force: true
|
|
730
|
+
});
|
|
682
731
|
clearServiceFailure(this.home);
|
|
683
732
|
if (this.platform === 'linux') {
|
|
684
733
|
try {
|
package/dist/types.d.ts
CHANGED
|
@@ -200,6 +200,8 @@ export interface RunnerCapabilities {
|
|
|
200
200
|
/** `process.arch` — 'x64' | 'arm64' | ... */
|
|
201
201
|
arch: string;
|
|
202
202
|
harnessVersion: string;
|
|
203
|
+
/** True when this runner is a macOS/Linux service that can update itself. */
|
|
204
|
+
selfUpdate?: boolean;
|
|
203
205
|
/**
|
|
204
206
|
* The sandbox TOOLS layer (gh, @peculiar/x509, ...) currently installed,
|
|
205
207
|
* synced by pf-bootstrap independently of the harness. Absent on
|
|
@@ -406,6 +408,16 @@ export interface RunnerHeartbeatResponse {
|
|
|
406
408
|
ok: boolean;
|
|
407
409
|
/** Exact harness pin currently selected by the control plane. */
|
|
408
410
|
harnessVersion?: string;
|
|
411
|
+
/**
|
|
412
|
+
* Update offer for personal service runners: exact versions and an optional
|
|
413
|
+
* expected sha512 integrity. Never a URL. Additive; absent on older servers.
|
|
414
|
+
*/
|
|
415
|
+
runnerUpdate?: {
|
|
416
|
+
minVersion?: string;
|
|
417
|
+
recommendedVersion?: string;
|
|
418
|
+
integrity?: string;
|
|
419
|
+
updateNow?: boolean;
|
|
420
|
+
};
|
|
409
421
|
/**
|
|
410
422
|
* Exact sandbox-tools pin, when the control plane has the tools layer
|
|
411
423
|
* turned on. Additive and independent of harnessVersion — either can
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type StageDeps } from './stage';
|
|
2
|
+
/** What the control plane may send. Never a URL, never a command. */
|
|
3
|
+
export interface RunnerUpdateOffer {
|
|
4
|
+
minVersion?: string;
|
|
5
|
+
recommendedVersion?: string;
|
|
6
|
+
integrity?: string;
|
|
7
|
+
updateNow?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export type UpdateReportState = 'updating' | 'updated' | 'failed' | 'rolled_back' | 'refused';
|
|
10
|
+
export type UpdateReporter = (r: {
|
|
11
|
+
state: UpdateReportState;
|
|
12
|
+
fromVersion: string;
|
|
13
|
+
toVersion: string;
|
|
14
|
+
reason?: string;
|
|
15
|
+
}) => Promise<void>;
|
|
16
|
+
export interface UpdaterOptions {
|
|
17
|
+
root: string;
|
|
18
|
+
currentVersion: string;
|
|
19
|
+
report: UpdateReporter;
|
|
20
|
+
log: (message: string, fields?: Record<string, unknown>) => void;
|
|
21
|
+
/** Longest to wait for an active turn to finish. Default 2 h. */
|
|
22
|
+
maxDrainMs?: number;
|
|
23
|
+
stageDeps?: StageDeps;
|
|
24
|
+
now?: () => number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Runs inside the service harness. observe() → stage in the background (the
|
|
28
|
+
* runner keeps working) → once staged the lease loop stops taking leases
|
|
29
|
+
* (drain) and, when idle, switchAndExit() flips active.json atomically and
|
|
30
|
+
* exits so launchd/systemd restarts into the new version.
|
|
31
|
+
*/
|
|
32
|
+
export declare class RunnerUpdater {
|
|
33
|
+
private readonly options;
|
|
34
|
+
private phase;
|
|
35
|
+
private staged;
|
|
36
|
+
private drainStartedAt;
|
|
37
|
+
private busyMessage;
|
|
38
|
+
/** A version we already gave up on in this process. */
|
|
39
|
+
private abandoned;
|
|
40
|
+
private readonly now;
|
|
41
|
+
constructor(options: UpdaterOptions);
|
|
42
|
+
/** Called with every heartbeat's `runnerUpdate`. */
|
|
43
|
+
observe(offer: RunnerUpdateOffer | undefined): void;
|
|
44
|
+
private stage;
|
|
45
|
+
/** The lease loop must not open new polls while this is true. */
|
|
46
|
+
get draining(): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Called from the lease loop. Returns true when the process should exit
|
|
49
|
+
* because the switch was made. Never interrupts a running turn: after
|
|
50
|
+
* maxDrainMs it gives the update up for this process instead.
|
|
51
|
+
*/
|
|
52
|
+
tick(activeTurns: number): Promise<boolean>;
|
|
53
|
+
private switchNow;
|
|
54
|
+
/**
|
|
55
|
+
* Boot: the process came up on a version that was just switched to. It may
|
|
56
|
+
* only confirm once it registered, heartbeated and made a lease call.
|
|
57
|
+
*/
|
|
58
|
+
get awaitingHealth(): boolean;
|
|
59
|
+
confirmHealthy(): Promise<void>;
|
|
60
|
+
/** Report an outcome left by the previous process (success or rollback). */
|
|
61
|
+
reportLastResult(): Promise<void>;
|
|
62
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RunnerUpdater = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const layout_1 = require("./layout");
|
|
6
|
+
const stage_1 = require("./stage");
|
|
7
|
+
/**
|
|
8
|
+
* Runs inside the service harness. observe() → stage in the background (the
|
|
9
|
+
* runner keeps working) → once staged the lease loop stops taking leases
|
|
10
|
+
* (drain) and, when idle, switchAndExit() flips active.json atomically and
|
|
11
|
+
* exits so launchd/systemd restarts into the new version.
|
|
12
|
+
*/
|
|
13
|
+
class RunnerUpdater {
|
|
14
|
+
options;
|
|
15
|
+
phase = 'idle';
|
|
16
|
+
staged = null;
|
|
17
|
+
drainStartedAt = 0;
|
|
18
|
+
busyMessage = false;
|
|
19
|
+
/** A version we already gave up on in this process. */
|
|
20
|
+
abandoned = new Set();
|
|
21
|
+
now;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.options = options;
|
|
24
|
+
this.now = options.now ?? Date.now;
|
|
25
|
+
}
|
|
26
|
+
/** Called with every heartbeat's `runnerUpdate`. */
|
|
27
|
+
observe(offer) {
|
|
28
|
+
const target = offer?.recommendedVersion;
|
|
29
|
+
if (!target || this.phase !== 'idle' || this.abandoned.has(target))
|
|
30
|
+
return;
|
|
31
|
+
const { root, currentVersion } = this.options;
|
|
32
|
+
if ((0, stage_1.compareVersions)(target, currentVersion) <= 0)
|
|
33
|
+
return;
|
|
34
|
+
const blocked = (0, layout_1.attemptBlocked)(root, target, this.now());
|
|
35
|
+
// An owner pressing "Update now" overrides a backoff, not the 3-strike stop.
|
|
36
|
+
if (blocked && !(offer?.updateNow && !blocked.startsWith('stopped'))) {
|
|
37
|
+
this.options.log('Update not attempted', { target, reason: blocked });
|
|
38
|
+
this.abandoned.add(target);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
this.phase = 'staging';
|
|
42
|
+
void this.stage(target, offer?.integrity);
|
|
43
|
+
}
|
|
44
|
+
async stage(target, integrity) {
|
|
45
|
+
const { root, currentVersion, log } = this.options;
|
|
46
|
+
try {
|
|
47
|
+
log('Staging runner update', { from: currentVersion, to: target });
|
|
48
|
+
this.staged = await (0, stage_1.stageVersion)({
|
|
49
|
+
root,
|
|
50
|
+
current: currentVersion,
|
|
51
|
+
version: target,
|
|
52
|
+
expectedIntegrity: integrity
|
|
53
|
+
}, this.options.stageDeps);
|
|
54
|
+
this.phase = 'staged';
|
|
55
|
+
this.drainStartedAt = this.now();
|
|
56
|
+
log('Update staged; draining', { to: target });
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
this.phase = 'idle';
|
|
60
|
+
this.abandoned.add(target);
|
|
61
|
+
const refused = error instanceof stage_1.UpdateRefused;
|
|
62
|
+
const reason = refused
|
|
63
|
+
? `${error.code}: ${error.message}`
|
|
64
|
+
: `stage_failed: ${error.message.split('\n')[0]}`;
|
|
65
|
+
(0, layout_1.recordFailure)(root, target, this.now());
|
|
66
|
+
log('Update refused or failed before switching', { to: target, reason });
|
|
67
|
+
await this.options
|
|
68
|
+
.report({
|
|
69
|
+
state: refused ? 'refused' : 'failed',
|
|
70
|
+
fromVersion: currentVersion,
|
|
71
|
+
toVersion: target,
|
|
72
|
+
reason
|
|
73
|
+
})
|
|
74
|
+
.catch(() => undefined);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** The lease loop must not open new polls while this is true. */
|
|
78
|
+
get draining() {
|
|
79
|
+
return this.phase === 'staged' || this.phase === 'drained';
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Called from the lease loop. Returns true when the process should exit
|
|
83
|
+
* because the switch was made. Never interrupts a running turn: after
|
|
84
|
+
* maxDrainMs it gives the update up for this process instead.
|
|
85
|
+
*/
|
|
86
|
+
async tick(activeTurns) {
|
|
87
|
+
if (!this.draining || !this.staged)
|
|
88
|
+
return false;
|
|
89
|
+
if (activeTurns > 0) {
|
|
90
|
+
if (!this.busyMessage) {
|
|
91
|
+
this.busyMessage = true;
|
|
92
|
+
this.options.log('Update waiting for the running turn to finish', {
|
|
93
|
+
activeTurns
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
if (this.now() - this.drainStartedAt >
|
|
97
|
+
(this.options.maxDrainMs ?? 2 * 3600_000)) {
|
|
98
|
+
const to = this.staged.version;
|
|
99
|
+
this.options.log('Update postponed: the turn is still running after the maximum wait', { to });
|
|
100
|
+
this.abandoned.add(to);
|
|
101
|
+
this.phase = 'idle';
|
|
102
|
+
this.staged = null;
|
|
103
|
+
await this.options
|
|
104
|
+
.report({
|
|
105
|
+
state: 'failed',
|
|
106
|
+
fromVersion: this.options.currentVersion,
|
|
107
|
+
toVersion: to,
|
|
108
|
+
reason: 'postponed: a turn was still running after the maximum drain wait'
|
|
109
|
+
})
|
|
110
|
+
.catch(() => undefined);
|
|
111
|
+
}
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
await this.switchNow();
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
async switchNow() {
|
|
118
|
+
const { root, currentVersion, log } = this.options;
|
|
119
|
+
const staged = this.staged;
|
|
120
|
+
const files = (0, layout_1.paths)(root);
|
|
121
|
+
const current = (0, layout_1.readJson)(files.active);
|
|
122
|
+
const cliNow = process.env.PF_UPDATE_CLI ?? current?.cli ?? '';
|
|
123
|
+
const pending = {
|
|
124
|
+
from: currentVersion,
|
|
125
|
+
to: staged.version,
|
|
126
|
+
startedAt: new Date(this.now()).toISOString()
|
|
127
|
+
};
|
|
128
|
+
// Order matters: pending first, then the atomic active.json flip. A crash
|
|
129
|
+
// in between leaves a stale pending that the launcher discards.
|
|
130
|
+
(0, layout_1.writeJsonAtomic)(files.pending, pending);
|
|
131
|
+
(0, layout_1.writeJsonAtomic)(files.active, {
|
|
132
|
+
version: staged.version,
|
|
133
|
+
cli: staged.cli,
|
|
134
|
+
previous: { version: currentVersion, cli: cliNow }
|
|
135
|
+
});
|
|
136
|
+
log('Switched to the new version; restarting', { to: staged.version });
|
|
137
|
+
await this.options
|
|
138
|
+
.report({
|
|
139
|
+
state: 'updating',
|
|
140
|
+
fromVersion: currentVersion,
|
|
141
|
+
toVersion: staged.version
|
|
142
|
+
})
|
|
143
|
+
.catch(() => undefined);
|
|
144
|
+
this.phase = 'drained';
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Boot: the process came up on a version that was just switched to. It may
|
|
148
|
+
* only confirm once it registered, heartbeated and made a lease call.
|
|
149
|
+
*/
|
|
150
|
+
get awaitingHealth() {
|
|
151
|
+
const pending = (0, layout_1.readJson)((0, layout_1.paths)(this.options.root).pending);
|
|
152
|
+
return !!pending && pending.to === this.options.currentVersion;
|
|
153
|
+
}
|
|
154
|
+
async confirmHealthy() {
|
|
155
|
+
const { root, currentVersion } = this.options;
|
|
156
|
+
const pending = (0, layout_1.readJson)((0, layout_1.paths)(root).pending);
|
|
157
|
+
if (!pending || pending.to !== currentVersion)
|
|
158
|
+
return;
|
|
159
|
+
const result = {
|
|
160
|
+
state: 'updated',
|
|
161
|
+
from: pending.from,
|
|
162
|
+
to: pending.to,
|
|
163
|
+
at: new Date(this.now()).toISOString()
|
|
164
|
+
};
|
|
165
|
+
(0, layout_1.writeJsonAtomic)((0, layout_1.paths)(root).lastResult, result);
|
|
166
|
+
(0, node_fs_1.rmSync)((0, layout_1.paths)(root).pending, { force: true });
|
|
167
|
+
(0, stage_1.pruneVersions)(root);
|
|
168
|
+
await this.reportLastResult();
|
|
169
|
+
}
|
|
170
|
+
/** Report an outcome left by the previous process (success or rollback). */
|
|
171
|
+
async reportLastResult() {
|
|
172
|
+
const file = (0, layout_1.paths)(this.options.root).lastResult;
|
|
173
|
+
const result = (0, layout_1.readJson)(file);
|
|
174
|
+
if (!result || !result.to)
|
|
175
|
+
return;
|
|
176
|
+
try {
|
|
177
|
+
await this.options.report({
|
|
178
|
+
state: result.state,
|
|
179
|
+
fromVersion: result.from ?? this.options.currentVersion,
|
|
180
|
+
toVersion: result.to,
|
|
181
|
+
reason: result.reason
|
|
182
|
+
});
|
|
183
|
+
(0, node_fs_1.rmSync)(file, { force: true });
|
|
184
|
+
this.options.log('Update result reported', {
|
|
185
|
+
state: result.state,
|
|
186
|
+
to: result.to
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
/* kept on disk; reported after the next successful registration */
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
exports.RunnerUpdater = RunnerUpdater;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
export declare const UPDATE_RESTART_EXIT = 75;
|
|
3
|
+
interface Active {
|
|
4
|
+
version: string | null;
|
|
5
|
+
cli: string;
|
|
6
|
+
previous?: {
|
|
7
|
+
version: string | null;
|
|
8
|
+
cli: string;
|
|
9
|
+
} | null;
|
|
10
|
+
}
|
|
11
|
+
export declare function resolveActive(root: string, fallbackCli: string, fallbackVersion: string | null): Active;
|
|
12
|
+
/** Point the service back at the previous executable and record why. */
|
|
13
|
+
export declare function rollback(root: string, fallbackCli: string, fallbackVersion: string | null, reason: string): Active;
|
|
14
|
+
export interface LauncherOptions {
|
|
15
|
+
root: string;
|
|
16
|
+
fallbackCli: string;
|
|
17
|
+
fallbackVersion: string | null;
|
|
18
|
+
args: string[];
|
|
19
|
+
healthTimeoutMs?: number;
|
|
20
|
+
node?: string;
|
|
21
|
+
}
|
|
22
|
+
/** Returns the exit code the service manager should see. */
|
|
23
|
+
export declare function runLauncher(options: LauncherOptions): Promise<number>;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.UPDATE_RESTART_EXIT = void 0;
|
|
5
|
+
exports.resolveActive = resolveActive;
|
|
6
|
+
exports.rollback = rollback;
|
|
7
|
+
exports.runLauncher = runLauncher;
|
|
8
|
+
/**
|
|
9
|
+
* Stable service entrypoint. Written to be tiny and version independent: it
|
|
10
|
+
* only picks which installed harness to run, and rolls back when a freshly
|
|
11
|
+
* switched version dies or never passes its health check. It is copied to the
|
|
12
|
+
* updater root by `service install|repair`, so a bad harness release cannot
|
|
13
|
+
* break it.
|
|
14
|
+
*
|
|
15
|
+
* Usage: launcher.js --root <dir> --fallback-cli <path> [--fallback-version v] -- <harness start args>
|
|
16
|
+
*/
|
|
17
|
+
const node_child_process_1 = require("node:child_process");
|
|
18
|
+
const node_fs_1 = require("node:fs");
|
|
19
|
+
const node_path_1 = require("node:path");
|
|
20
|
+
exports.UPDATE_RESTART_EXIT = 75;
|
|
21
|
+
function readJson(file) {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse((0, node_fs_1.readFileSync)(file, 'utf8'));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function writeJson(file, value) {
|
|
30
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(file), { recursive: true, mode: 0o700 });
|
|
31
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
32
|
+
(0, node_fs_1.writeFileSync)(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
33
|
+
(0, node_fs_1.renameSync)(temp, file);
|
|
34
|
+
}
|
|
35
|
+
function resolveActive(root, fallbackCli, fallbackVersion) {
|
|
36
|
+
const active = readJson((0, node_path_1.join)(root, 'active.json'));
|
|
37
|
+
if (active && typeof active.cli === 'string' && (0, node_fs_1.existsSync)(active.cli))
|
|
38
|
+
return active;
|
|
39
|
+
return { version: fallbackVersion, cli: fallbackCli };
|
|
40
|
+
}
|
|
41
|
+
/** Point the service back at the previous executable and record why. */
|
|
42
|
+
function rollback(root, fallbackCli, fallbackVersion, reason) {
|
|
43
|
+
const pending = readJson((0, node_path_1.join)(root, 'pending.json'));
|
|
44
|
+
const active = resolveActive(root, fallbackCli, fallbackVersion);
|
|
45
|
+
const target = active.previous && (0, node_fs_1.existsSync)(active.previous.cli)
|
|
46
|
+
? active.previous
|
|
47
|
+
: { version: fallbackVersion, cli: fallbackCli };
|
|
48
|
+
const restored = {
|
|
49
|
+
version: target.version,
|
|
50
|
+
cli: target.cli,
|
|
51
|
+
previous: null
|
|
52
|
+
};
|
|
53
|
+
writeJson((0, node_path_1.join)(root, 'active.json'), restored);
|
|
54
|
+
(0, node_fs_1.rmSync)((0, node_path_1.join)(root, 'pending.json'), { force: true });
|
|
55
|
+
if (pending) {
|
|
56
|
+
writeJson((0, node_path_1.join)(root, 'last-result.json'), {
|
|
57
|
+
state: 'rolled_back',
|
|
58
|
+
from: pending.from,
|
|
59
|
+
to: pending.to,
|
|
60
|
+
reason,
|
|
61
|
+
at: new Date().toISOString()
|
|
62
|
+
});
|
|
63
|
+
// backoff counter (same shape as state.json in layout.ts)
|
|
64
|
+
const stateFile = (0, node_path_1.join)(root, 'state.json');
|
|
65
|
+
const state = readJson(stateFile) ?? { failures: {} };
|
|
66
|
+
const count = (state.failures[pending.to]?.count ?? 0) + 1;
|
|
67
|
+
state.failures[pending.to] = {
|
|
68
|
+
count,
|
|
69
|
+
lastAt: new Date().toISOString(),
|
|
70
|
+
nextAttemptAt: new Date(Date.now() + Math.min(24 * 3600_000, 3600_000 * 4 ** (count - 1))).toISOString()
|
|
71
|
+
};
|
|
72
|
+
writeJson(stateFile, state);
|
|
73
|
+
}
|
|
74
|
+
return restored;
|
|
75
|
+
}
|
|
76
|
+
/** Returns the exit code the service manager should see. */
|
|
77
|
+
async function runLauncher(options) {
|
|
78
|
+
const { root, fallbackCli, fallbackVersion, args } = options;
|
|
79
|
+
const healthTimeoutMs = options.healthTimeoutMs ?? 180_000;
|
|
80
|
+
let stopping = false;
|
|
81
|
+
let child = null;
|
|
82
|
+
const forward = (signal) => {
|
|
83
|
+
stopping = true;
|
|
84
|
+
child?.kill(signal);
|
|
85
|
+
};
|
|
86
|
+
process.on('SIGTERM', () => forward('SIGTERM'));
|
|
87
|
+
process.on('SIGINT', () => forward('SIGINT'));
|
|
88
|
+
for (;;) {
|
|
89
|
+
let active = resolveActive(root, fallbackCli, fallbackVersion);
|
|
90
|
+
let pending = readJson((0, node_path_1.join)(root, 'pending.json'));
|
|
91
|
+
// A pending file for a version that is not the active one is stale.
|
|
92
|
+
if (pending && pending.to !== active.version) {
|
|
93
|
+
(0, node_fs_1.rmSync)((0, node_path_1.join)(root, 'pending.json'), { force: true });
|
|
94
|
+
pending = null;
|
|
95
|
+
}
|
|
96
|
+
const startedAt = Date.now();
|
|
97
|
+
child = (0, node_child_process_1.spawn)(options.node ?? process.execPath, [active.cli, 'start', ...args], {
|
|
98
|
+
stdio: 'inherit',
|
|
99
|
+
env: { ...process.env, PF_UPDATE_ROOT: root, PF_UPDATE_CLI: active.cli }
|
|
100
|
+
});
|
|
101
|
+
let timedOut = false;
|
|
102
|
+
const timer = pending
|
|
103
|
+
? setTimeout(() => {
|
|
104
|
+
if ((0, node_fs_1.existsSync)((0, node_path_1.join)(root, 'pending.json'))) {
|
|
105
|
+
timedOut = true;
|
|
106
|
+
child?.kill('SIGKILL');
|
|
107
|
+
}
|
|
108
|
+
}, healthTimeoutMs)
|
|
109
|
+
: null;
|
|
110
|
+
const code = await new Promise((resolve) => {
|
|
111
|
+
child.once('exit', (c, s) => resolve(c ?? (s ? 128 : 1)));
|
|
112
|
+
child.once('error', () => resolve(1));
|
|
113
|
+
});
|
|
114
|
+
if (timer)
|
|
115
|
+
clearTimeout(timer);
|
|
116
|
+
child = null;
|
|
117
|
+
if (stopping)
|
|
118
|
+
return code;
|
|
119
|
+
const stillPending = (0, node_fs_1.existsSync)((0, node_path_1.join)(root, 'pending.json'));
|
|
120
|
+
if (pending && stillPending) {
|
|
121
|
+
rollback(root, fallbackCli, fallbackVersion, timedOut
|
|
122
|
+
? `The new version did not pass its health check within ${Math.round(healthTimeoutMs / 1000)}s`
|
|
123
|
+
: `The new version exited with code ${code} before it passed its health check`);
|
|
124
|
+
if (Date.now() - startedAt < 1000)
|
|
125
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
126
|
+
continue; // start the previous version right away
|
|
127
|
+
}
|
|
128
|
+
return code;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function parseArgs(argv) {
|
|
132
|
+
const sep = argv.indexOf('--');
|
|
133
|
+
const own = sep >= 0 ? argv.slice(0, sep) : argv;
|
|
134
|
+
const value = (flag) => {
|
|
135
|
+
const at = own.indexOf(flag);
|
|
136
|
+
return at >= 0 ? own[at + 1] : undefined;
|
|
137
|
+
};
|
|
138
|
+
const root = value('--root');
|
|
139
|
+
const fallbackCli = value('--fallback-cli');
|
|
140
|
+
if (!root || !fallbackCli)
|
|
141
|
+
throw new Error('--root and --fallback-cli are required');
|
|
142
|
+
return {
|
|
143
|
+
root,
|
|
144
|
+
fallbackCli,
|
|
145
|
+
fallbackVersion: value('--fallback-version') ?? null,
|
|
146
|
+
args: sep >= 0 ? argv.slice(sep + 1) : [],
|
|
147
|
+
healthTimeoutMs: process.env.PF_UPDATE_HEALTH_TIMEOUT_MS
|
|
148
|
+
? Number(process.env.PF_UPDATE_HEALTH_TIMEOUT_MS)
|
|
149
|
+
: undefined
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
if (require.main === module) {
|
|
153
|
+
runLauncher(parseArgs(process.argv.slice(2))).then((code) => process.exit(code), (error) => {
|
|
154
|
+
process.stderr.write(`launcher failed: ${error.message}\n`);
|
|
155
|
+
process.exit(1);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-disk state of the self-updater. Everything is a small JSON file written
|
|
3
|
+
* by temp-file + rename, so a crash never leaves a half-written file.
|
|
4
|
+
*
|
|
5
|
+
* active.json which executable the service runs (+ the previous one)
|
|
6
|
+
* pending.json a switch that has not yet passed its health check
|
|
7
|
+
* state.json backoff / failure counters per version
|
|
8
|
+
* last-result.json outcome the next process must report to the server
|
|
9
|
+
* versions/<v>/ side-by-side installs; the previous one is kept
|
|
10
|
+
*/
|
|
11
|
+
export interface ActiveRecord {
|
|
12
|
+
version: string | null;
|
|
13
|
+
cli: string;
|
|
14
|
+
previous?: {
|
|
15
|
+
version: string | null;
|
|
16
|
+
cli: string;
|
|
17
|
+
} | null;
|
|
18
|
+
}
|
|
19
|
+
export interface PendingRecord {
|
|
20
|
+
from: string | null;
|
|
21
|
+
to: string;
|
|
22
|
+
startedAt: string;
|
|
23
|
+
}
|
|
24
|
+
export interface LastResult {
|
|
25
|
+
state: 'updated' | 'rolled_back' | 'failed' | 'refused';
|
|
26
|
+
from: string | null;
|
|
27
|
+
to: string;
|
|
28
|
+
reason?: string;
|
|
29
|
+
at: string;
|
|
30
|
+
}
|
|
31
|
+
export interface UpdateState {
|
|
32
|
+
failures: Record<string, {
|
|
33
|
+
count: number;
|
|
34
|
+
lastAt: string;
|
|
35
|
+
nextAttemptAt: string;
|
|
36
|
+
}>;
|
|
37
|
+
}
|
|
38
|
+
export declare const PACKAGE_NAME = "@peakflo/agent-harness";
|
|
39
|
+
export declare const paths: (root: string) => {
|
|
40
|
+
active: string;
|
|
41
|
+
pending: string;
|
|
42
|
+
state: string;
|
|
43
|
+
lastResult: string;
|
|
44
|
+
versions: string;
|
|
45
|
+
};
|
|
46
|
+
export declare function readJson<T>(file: string): T | null;
|
|
47
|
+
export declare function writeJsonAtomic(file: string, value: unknown): void;
|
|
48
|
+
/** Failed versions back off 1h, 4h, 16h (cap 24h); 3 failures stop for good. */
|
|
49
|
+
export declare const MAX_LOCAL_FAILURES = 3;
|
|
50
|
+
export declare function backoffMs(count: number): number;
|
|
51
|
+
export declare function recordFailure(root: string, version: string, now?: number): void;
|
|
52
|
+
/** null when an attempt is allowed, otherwise why not. */
|
|
53
|
+
export declare function attemptBlocked(root: string, version: string, now?: number): string | null;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MAX_LOCAL_FAILURES = exports.paths = exports.PACKAGE_NAME = void 0;
|
|
4
|
+
exports.readJson = readJson;
|
|
5
|
+
exports.writeJsonAtomic = writeJsonAtomic;
|
|
6
|
+
exports.backoffMs = backoffMs;
|
|
7
|
+
exports.recordFailure = recordFailure;
|
|
8
|
+
exports.attemptBlocked = attemptBlocked;
|
|
9
|
+
const node_fs_1 = require("node:fs");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
exports.PACKAGE_NAME = '@peakflo/agent-harness';
|
|
12
|
+
const paths = (root) => ({
|
|
13
|
+
active: (0, node_path_1.join)(root, 'active.json'),
|
|
14
|
+
pending: (0, node_path_1.join)(root, 'pending.json'),
|
|
15
|
+
state: (0, node_path_1.join)(root, 'state.json'),
|
|
16
|
+
lastResult: (0, node_path_1.join)(root, 'last-result.json'),
|
|
17
|
+
versions: (0, node_path_1.join)(root, 'versions')
|
|
18
|
+
});
|
|
19
|
+
exports.paths = paths;
|
|
20
|
+
function readJson(file) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse((0, node_fs_1.readFileSync)(file, 'utf8'));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function writeJsonAtomic(file, value) {
|
|
29
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(file), { recursive: true, mode: 0o700 });
|
|
30
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
31
|
+
try {
|
|
32
|
+
(0, node_fs_1.writeFileSync)(temp, `${JSON.stringify(value, null, 2)}\n`, {
|
|
33
|
+
mode: 0o600
|
|
34
|
+
});
|
|
35
|
+
(0, node_fs_1.renameSync)(temp, file);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
(0, node_fs_1.rmSync)(temp, { force: true });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Failed versions back off 1h, 4h, 16h (cap 24h); 3 failures stop for good. */
|
|
42
|
+
exports.MAX_LOCAL_FAILURES = 3;
|
|
43
|
+
function backoffMs(count) {
|
|
44
|
+
return Math.min(24 * 3600_000, 3600_000 * 4 ** Math.max(0, count - 1));
|
|
45
|
+
}
|
|
46
|
+
function recordFailure(root, version, now = Date.now()) {
|
|
47
|
+
const file = (0, exports.paths)(root).state;
|
|
48
|
+
const state = readJson(file) ?? { failures: {} };
|
|
49
|
+
const count = (state.failures[version]?.count ?? 0) + 1;
|
|
50
|
+
state.failures[version] = {
|
|
51
|
+
count,
|
|
52
|
+
lastAt: new Date(now).toISOString(),
|
|
53
|
+
nextAttemptAt: new Date(now + backoffMs(count)).toISOString()
|
|
54
|
+
};
|
|
55
|
+
writeJsonAtomic(file, state);
|
|
56
|
+
}
|
|
57
|
+
/** null when an attempt is allowed, otherwise why not. */
|
|
58
|
+
function attemptBlocked(root, version, now = Date.now()) {
|
|
59
|
+
const entry = (readJson((0, exports.paths)(root).state) ?? { failures: {} })
|
|
60
|
+
.failures[version];
|
|
61
|
+
if (!entry)
|
|
62
|
+
return null;
|
|
63
|
+
if (entry.count >= exports.MAX_LOCAL_FAILURES)
|
|
64
|
+
return `stopped after ${entry.count} failed attempts`;
|
|
65
|
+
return Date.parse(entry.nextAttemptAt) > now
|
|
66
|
+
? `backing off until ${entry.nextAttemptAt}`
|
|
67
|
+
: null;
|
|
68
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export declare const REGISTRY = "https://registry.npmjs.org";
|
|
2
|
+
/**
|
|
3
|
+
* The registry is fixed. The ONLY override is a loopback http URL set in the
|
|
4
|
+
* local environment of the machine (never by the control plane); it exists so
|
|
5
|
+
* the end-to-end test can use a fake registry without publishing anything.
|
|
6
|
+
*/
|
|
7
|
+
export declare function registryBase(env?: NodeJS.ProcessEnv): string;
|
|
8
|
+
export declare class UpdateRefused extends Error {
|
|
9
|
+
readonly code: 'invalid_version' | 'not_newer' | 'integrity_mismatch' | 'integrity_missing' | 'untrusted_tarball' | 'install_failed' | 'verify_failed';
|
|
10
|
+
constructor(code: 'invalid_version' | 'not_newer' | 'integrity_mismatch' | 'integrity_missing' | 'untrusted_tarball' | 'install_failed' | 'verify_failed', message: string);
|
|
11
|
+
}
|
|
12
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
13
|
+
export interface StageDeps {
|
|
14
|
+
fetchJson: (url: string) => Promise<unknown>;
|
|
15
|
+
fetchBytes: (url: string) => Promise<Buffer>;
|
|
16
|
+
/** Installs the tarball + its dependencies into `dir`. */
|
|
17
|
+
install: (dir: string, tarball: string) => Promise<void>;
|
|
18
|
+
/** Runs `<cli> version`; returns trimmed stdout. */
|
|
19
|
+
smoke: (cli: string) => Promise<string>;
|
|
20
|
+
}
|
|
21
|
+
export declare const defaultStageDeps: () => StageDeps;
|
|
22
|
+
export declare const cliFor: (versionDir: string) => string;
|
|
23
|
+
export interface StageInput {
|
|
24
|
+
root: string;
|
|
25
|
+
current: string;
|
|
26
|
+
version: string;
|
|
27
|
+
/** Integrity the control plane expects, when it has one. */
|
|
28
|
+
expectedIntegrity?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Download, verify and install ONE exact version side by side. Nothing here
|
|
32
|
+
* touches the running install. The only inputs from the server are the exact
|
|
33
|
+
* version and an expected hash; the tarball URL comes from the npm registry.
|
|
34
|
+
*/
|
|
35
|
+
export declare function stageVersion(input: StageInput, deps?: StageDeps): Promise<{
|
|
36
|
+
version: string;
|
|
37
|
+
cli: string;
|
|
38
|
+
integrity: string;
|
|
39
|
+
}>;
|
|
40
|
+
/** Keep the active and previous installs; delete other side-by-side copies. */
|
|
41
|
+
export declare function pruneVersions(root: string): void;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.cliFor = exports.defaultStageDeps = exports.UpdateRefused = exports.REGISTRY = void 0;
|
|
4
|
+
exports.registryBase = registryBase;
|
|
5
|
+
exports.compareVersions = compareVersions;
|
|
6
|
+
exports.stageVersion = stageVersion;
|
|
7
|
+
exports.pruneVersions = pruneVersions;
|
|
8
|
+
const node_child_process_1 = require("node:child_process");
|
|
9
|
+
const node_crypto_1 = require("node:crypto");
|
|
10
|
+
const node_fs_1 = require("node:fs");
|
|
11
|
+
const node_path_1 = require("node:path");
|
|
12
|
+
const node_util_1 = require("node:util");
|
|
13
|
+
const layout_1 = require("./layout");
|
|
14
|
+
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
|
|
15
|
+
exports.REGISTRY = 'https://registry.npmjs.org';
|
|
16
|
+
/**
|
|
17
|
+
* The registry is fixed. The ONLY override is a loopback http URL set in the
|
|
18
|
+
* local environment of the machine (never by the control plane); it exists so
|
|
19
|
+
* the end-to-end test can use a fake registry without publishing anything.
|
|
20
|
+
*/
|
|
21
|
+
function registryBase(env = process.env) {
|
|
22
|
+
const override = env.PF_UPDATE_REGISTRY;
|
|
23
|
+
if (override && /^http:\/\/(127\.0\.0\.1|localhost):\d{2,5}$/.test(override))
|
|
24
|
+
return override;
|
|
25
|
+
return exports.REGISTRY;
|
|
26
|
+
}
|
|
27
|
+
const VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
28
|
+
const SRI = /^sha512-[A-Za-z0-9+/]{86}==$/;
|
|
29
|
+
class UpdateRefused extends Error {
|
|
30
|
+
code;
|
|
31
|
+
constructor(code, message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.code = code;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
exports.UpdateRefused = UpdateRefused;
|
|
37
|
+
function compareVersions(a, b) {
|
|
38
|
+
const pa = a.split('-')[0].split('.').map(Number);
|
|
39
|
+
const pb = b.split('-')[0].split('.').map(Number);
|
|
40
|
+
for (let i = 0; i < 3; i++)
|
|
41
|
+
if (pa[i] !== pb[i])
|
|
42
|
+
return pa[i] - pb[i];
|
|
43
|
+
return Number(!a.includes('-')) - Number(!b.includes('-'));
|
|
44
|
+
}
|
|
45
|
+
const defaultStageDeps = () => ({
|
|
46
|
+
fetchJson: async (url) => {
|
|
47
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(30_000) });
|
|
48
|
+
if (!res.ok)
|
|
49
|
+
throw new Error(`registry answered ${res.status}`);
|
|
50
|
+
return res.json();
|
|
51
|
+
},
|
|
52
|
+
fetchBytes: async (url) => {
|
|
53
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(120_000) });
|
|
54
|
+
if (!res.ok)
|
|
55
|
+
throw new Error(`registry answered ${res.status}`);
|
|
56
|
+
return Buffer.from(await res.arrayBuffer());
|
|
57
|
+
},
|
|
58
|
+
install: async (dir, tarball) => {
|
|
59
|
+
const npm = [(0, node_path_1.join)((0, node_path_1.dirname)(process.execPath), 'npm'), 'npm'].find((candidate) => candidate === 'npm' || (0, node_fs_1.existsSync)(candidate));
|
|
60
|
+
(0, node_fs_1.mkdirSync)(dir, { recursive: true });
|
|
61
|
+
// Minimal manifest so npm installs into `dir`, not a parent project.
|
|
62
|
+
(0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'package.json'), '{"name":"pf-harness-install","private":true}\n');
|
|
63
|
+
await execFileAsync(npm, [
|
|
64
|
+
'install',
|
|
65
|
+
'--prefix',
|
|
66
|
+
dir,
|
|
67
|
+
'--ignore-scripts',
|
|
68
|
+
'--no-audit',
|
|
69
|
+
'--no-fund',
|
|
70
|
+
'--no-package-lock',
|
|
71
|
+
tarball
|
|
72
|
+
], {
|
|
73
|
+
timeout: 600_000,
|
|
74
|
+
env: { ...process.env, npm_config_update_notifier: 'false' }
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
smoke: async (cli) => (await execFileAsync(process.execPath, [cli, 'version'], {
|
|
78
|
+
timeout: 30_000
|
|
79
|
+
})).stdout.trim()
|
|
80
|
+
});
|
|
81
|
+
exports.defaultStageDeps = defaultStageDeps;
|
|
82
|
+
const cliFor = (versionDir) => (0, node_path_1.join)(versionDir, 'node_modules', ...layout_1.PACKAGE_NAME.split('/'), 'dist', 'cli.js');
|
|
83
|
+
exports.cliFor = cliFor;
|
|
84
|
+
/**
|
|
85
|
+
* Download, verify and install ONE exact version side by side. Nothing here
|
|
86
|
+
* touches the running install. The only inputs from the server are the exact
|
|
87
|
+
* version and an expected hash; the tarball URL comes from the npm registry.
|
|
88
|
+
*/
|
|
89
|
+
async function stageVersion(input, deps = (0, exports.defaultStageDeps)()) {
|
|
90
|
+
const { root, version } = input;
|
|
91
|
+
if (!VERSION.test(version))
|
|
92
|
+
throw new UpdateRefused('invalid_version', 'Not an exact version');
|
|
93
|
+
if (compareVersions(version, input.current) <= 0)
|
|
94
|
+
throw new UpdateRefused('not_newer', 'Never downgrades or reinstalls');
|
|
95
|
+
if (input.expectedIntegrity !== undefined &&
|
|
96
|
+
!SRI.test(input.expectedIntegrity))
|
|
97
|
+
throw new UpdateRefused('integrity_mismatch', 'Malformed expected integrity');
|
|
98
|
+
const finalDir = (0, node_path_1.join)((0, layout_1.paths)(root).versions, version);
|
|
99
|
+
const cached = (0, exports.cliFor)(finalDir);
|
|
100
|
+
const marker = (0, node_path_1.join)(finalDir, '.verified-integrity');
|
|
101
|
+
if ((0, node_fs_1.existsSync)(cached) && (0, node_fs_1.existsSync)(marker)) {
|
|
102
|
+
const integrity = (0, node_fs_1.readFileSync)(marker, 'utf8').trim();
|
|
103
|
+
if (!input.expectedIntegrity || input.expectedIntegrity === integrity)
|
|
104
|
+
return { version, cli: cached, integrity };
|
|
105
|
+
(0, node_fs_1.rmSync)(finalDir, { recursive: true, force: true });
|
|
106
|
+
}
|
|
107
|
+
const meta = (await deps.fetchJson(`${registryBase()}/${layout_1.PACKAGE_NAME.replace('/', '%2f')}/${version}`));
|
|
108
|
+
if (meta.name !== layout_1.PACKAGE_NAME || meta.version !== version)
|
|
109
|
+
throw new UpdateRefused('untrusted_tarball', 'Registry answered for another package');
|
|
110
|
+
const registryIntegrity = meta.dist?.integrity;
|
|
111
|
+
if (!registryIntegrity || !SRI.test(registryIntegrity))
|
|
112
|
+
throw new UpdateRefused('integrity_missing', 'Registry gave no sha512 integrity');
|
|
113
|
+
if (input.expectedIntegrity && input.expectedIntegrity !== registryIntegrity)
|
|
114
|
+
throw new UpdateRefused('integrity_mismatch', 'Registry integrity differs from the one the control plane expects');
|
|
115
|
+
const tarballUrl = new URL(meta.dist?.tarball ?? 'invalid:');
|
|
116
|
+
if (tarballUrl.origin !== new URL(registryBase()).origin ||
|
|
117
|
+
!tarballUrl.pathname.endsWith('.tgz'))
|
|
118
|
+
throw new UpdateRefused('untrusted_tarball', 'Tarball is not on the npm registry');
|
|
119
|
+
const bytes = await deps.fetchBytes(tarballUrl.href);
|
|
120
|
+
const actual = `sha512-${(0, node_crypto_1.createHash)('sha512').update(bytes).digest('base64')}`;
|
|
121
|
+
if (actual !== registryIntegrity)
|
|
122
|
+
throw new UpdateRefused('integrity_mismatch', 'Downloaded package does not match its sha512 integrity');
|
|
123
|
+
(0, node_fs_1.mkdirSync)((0, layout_1.paths)(root).versions, { recursive: true, mode: 0o700 });
|
|
124
|
+
const tmp = (0, node_path_1.join)((0, layout_1.paths)(root).versions, `.tmp-${version}-${process.pid}`);
|
|
125
|
+
(0, node_fs_1.rmSync)(tmp, { recursive: true, force: true });
|
|
126
|
+
try {
|
|
127
|
+
(0, node_fs_1.mkdirSync)(tmp, { recursive: true });
|
|
128
|
+
const tarball = (0, node_path_1.join)(tmp, 'package.tgz');
|
|
129
|
+
(0, node_fs_1.writeFileSync)(tarball, bytes);
|
|
130
|
+
try {
|
|
131
|
+
await deps.install(tmp, tarball);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
throw new UpdateRefused('install_failed', `Install failed: ${error.message.split('\n')[0]}`);
|
|
135
|
+
}
|
|
136
|
+
(0, node_fs_1.rmSync)(tarball, { force: true });
|
|
137
|
+
const cli = (0, exports.cliFor)(tmp);
|
|
138
|
+
const installed = (0, layout_1.readJson)((0, node_path_1.join)(tmp, 'node_modules', ...layout_1.PACKAGE_NAME.split('/'), 'package.json'));
|
|
139
|
+
if (installed?.name !== layout_1.PACKAGE_NAME || installed.version !== version)
|
|
140
|
+
throw new UpdateRefused('verify_failed', 'Installed package is not the requested version');
|
|
141
|
+
const said = await deps.smoke(cli).catch(() => '');
|
|
142
|
+
if (!said.includes(version))
|
|
143
|
+
throw new UpdateRefused('verify_failed', 'The new harness did not start (version check failed)');
|
|
144
|
+
(0, node_fs_1.writeFileSync)((0, node_path_1.join)(tmp, '.verified-integrity'), `${registryIntegrity}\n`);
|
|
145
|
+
(0, node_fs_1.rmSync)(finalDir, { recursive: true, force: true });
|
|
146
|
+
(0, node_fs_1.renameSync)(tmp, finalDir); // atomic: the version dir appears complete or not at all
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
(0, node_fs_1.rmSync)(tmp, { recursive: true, force: true });
|
|
150
|
+
}
|
|
151
|
+
return { version, cli: (0, exports.cliFor)(finalDir), integrity: registryIntegrity };
|
|
152
|
+
}
|
|
153
|
+
/** Keep the active and previous installs; delete other side-by-side copies. */
|
|
154
|
+
function pruneVersions(root) {
|
|
155
|
+
const active = (0, layout_1.readJson)((0, layout_1.paths)(root).active);
|
|
156
|
+
const keep = new Set([active?.version, active?.previous?.version].filter((v) => !!v));
|
|
157
|
+
const dir = (0, layout_1.paths)(root).versions;
|
|
158
|
+
if (!(0, node_fs_1.existsSync)(dir))
|
|
159
|
+
return;
|
|
160
|
+
for (const name of (0, node_fs_1.readdirSync)(dir)) {
|
|
161
|
+
const full = (0, node_path_1.join)(dir, name);
|
|
162
|
+
if (name.startsWith('.tmp-')) {
|
|
163
|
+
if (Date.now() - (0, node_fs_1.statSync)(full).mtimeMs > 3600_000)
|
|
164
|
+
(0, node_fs_1.rmSync)(full, { recursive: true, force: true });
|
|
165
|
+
}
|
|
166
|
+
else if (!keep.has(name))
|
|
167
|
+
(0, node_fs_1.rmSync)(full, { recursive: true, force: true });
|
|
168
|
+
}
|
|
169
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@peakflo/agent-harness",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.33",
|
|
4
4
|
"description": "Headless Peakflo coding-agent harness. One codebase, three hosting modes: a Daytona cloud sandbox, a customer VM, and the 20x desktop.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "commonjs",
|