@indigoai-us/hq-cli 5.345.235 → 5.345.237
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/CHANGELOG.md +49 -0
- package/dist/command-catalog.generated.d.ts +76 -1
- package/dist/command-catalog.generated.js +93 -1
- package/dist/command-registration-plan.d.ts +6 -0
- package/dist/command-registration-plan.js +1 -0
- package/dist/commands/bot.js +9 -0
- package/dist/commands/daemon.d.ts +1 -0
- package/dist/commands/daemon.js +70 -6
- package/dist/commands/deploy-app-db.js +4 -19
- package/dist/commands/deploy-app-upload.js +66 -40
- package/dist/commands/deploy-mutations.js +24 -16
- package/dist/commands/deploy-runtime-bindings.d.ts +3 -0
- package/dist/commands/deploy-runtime-bindings.js +116 -0
- package/dist/commands/deploy-ssr.js +5 -24
- package/dist/commands/mesh.js +6 -2
- package/dist/commands/signals-run.d.ts +43 -2
- package/dist/commands/signals-run.js +85 -7
- package/dist/commands/sync-core.d.ts +7 -0
- package/dist/commands/sync-core.js +52 -3
- package/dist/lib/bot/continuity.d.ts +21 -2
- package/dist/lib/bot/continuity.js +48 -19
- package/dist/lib/bot/fleet-cron.js +6 -0
- package/dist/lib/bot/fleet-local.d.ts +11 -1
- package/dist/lib/bot/fleet-local.js +21 -1
- package/dist/lib/bot/fleet-state.d.ts +129 -0
- package/dist/lib/bot/fleet-state.js +669 -0
- package/dist/lib/bot/promote.d.ts +9 -3
- package/dist/lib/bot/promote.js +115 -16
- package/dist/lib/daemon/catalog.d.ts +13 -0
- package/dist/lib/daemon/catalog.js +32 -6
- package/dist/lib/daemon/lanes-reconcile-status.d.ts +0 -4
- package/dist/lib/daemon/lanes-reconcile-status.js +2 -12
- package/dist/lib/daemon/lanes-reconcile-watcher.d.ts +1 -1
- package/dist/lib/daemon/lanes-reconcile-watcher.js +2 -1
- package/dist/lib/daemon/legacy-handover.d.ts +38 -0
- package/dist/lib/daemon/legacy-handover.js +117 -0
- package/dist/lib/daemon/mesh-owner.js +2 -1
- package/dist/lib/daemon/run.d.ts +18 -1
- package/dist/lib/daemon/run.js +85 -12
- package/dist/lib/daemon/selfcheck.d.ts +28 -0
- package/dist/lib/daemon/selfcheck.js +86 -15
- package/dist/lib/deploy-api.d.ts +2 -2
- package/dist/lib/deploy-api.js +4 -2
- package/dist/lib/deploy-identity.d.ts +18 -0
- package/dist/lib/deploy-identity.js +179 -0
- package/dist/lib/hot-channels/alert.js +13 -6
- package/dist/lib/hot-channels/fleet-complete.d.ts +89 -0
- package/dist/lib/hot-channels/fleet-complete.js +157 -0
- package/dist/lib/hot-channels/run.js +2 -1
- package/dist/lib/hot-channels/signals-claude-login.d.ts +3 -2
- package/dist/lib/hot-channels/signals-claude-login.js +6 -1
- package/dist/lib/hot-channels/signals-pass-failure.d.ts +29 -0
- package/dist/lib/hot-channels/signals-pass-failure.js +36 -0
- package/dist/lib/hot-channels/signals-pass.d.ts +49 -2
- package/dist/lib/hot-channels/signals-pass.js +188 -12
- package/dist/lib/hot-channels/signals-runtime.d.ts +6 -3
- package/dist/lib/hot-channels/signals-runtime.js +11 -2
- package/dist/lib/lanes/reconcile-result.d.ts +5 -0
- package/dist/lib/lanes/reconcile-result.js +20 -2
- package/dist/lib/lanes/reconcile.js +12 -3
- package/dist/lib/mesh/live/emit.js +25 -6
- package/dist/lib/mesh/live/flush.js +119 -15
- package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -0
- package/dist/lib/mesh/live/reporting-privacy.js +147 -1
- package/dist/lib/mesh/live/spool.d.ts +16 -0
- package/dist/lib/mesh/live/spool.js +45 -0
- package/dist/lib/signals/engine.d.ts +17 -3
- package/dist/lib/signals/engine.js +28 -9
- package/dist/lib/signals/failure-alert.d.ts +33 -1
- package/dist/lib/signals/failure-alert.js +72 -5
- package/dist/lib/signals/owner-notice.d.ts +94 -0
- package/dist/lib/signals/owner-notice.js +233 -0
- package/dist/lib/signals/reply.d.ts +7 -0
- package/dist/lib/signals/reply.js +23 -3
- package/dist/lib/signals/steps/adapters.d.ts +51 -2
- package/dist/lib/signals/steps/adapters.js +213 -7
- package/dist/lib/signals/steps/extract.js +18 -4
- package/dist/lib/signals/steps/types.d.ts +63 -1
- package/dist/lib/signals/steps/types.js +32 -0
- package/dist/lib/sync-core/engine-auth.d.ts +35 -0
- package/dist/lib/sync-core/engine-auth.js +96 -0
- package/dist/lib/sync-core/engine-home.d.ts +6 -0
- package/dist/lib/sync-core/engine-home.js +12 -0
- package/dist/lib/sync-core/rollout-state.d.ts +1 -0
- package/dist/lib/sync-core/rollout-state.js +3 -0
- package/dist/lib/vault-sync-switches.d.ts +7 -0
- package/dist/lib/vault-sync-switches.js +56 -0
- package/dist/lib/work-context/errors.d.ts +12 -0
- package/dist/lib/work-context/errors.js +15 -0
- package/dist/lib/work-context/organize.js +6 -1
- package/dist/lib/work-context/reconcile.js +20 -1
- package/dist/utils/resident-package-preload.js +34 -4
- package/docs/anywhere-runtime.md +6 -0
- package/package.json +7 -7
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type BotApi, type BotPromotionBrain, type BotPromotionState } from "./api.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type BotConfig, type BotRuntimeId } from "./config.js";
|
|
3
3
|
import type { BotMachineCreds } from "./creds.js";
|
|
4
|
+
import { type FleetStateManifest } from "./fleet-state.js";
|
|
4
5
|
/** HQ's note on why a move is stuck, as the person should read it; HQ's own text goes to the bot log. */
|
|
5
6
|
export declare function promotionFailureText(dir: string, config: BotConfig, companyUid: string, failure: string, failureCode?: string): string;
|
|
6
7
|
/** Any error from reading a move's details, as a short reason; the raw text goes to the bot log. */
|
|
@@ -45,7 +46,7 @@ export interface LocalBotPromotionRuntime {
|
|
|
45
46
|
model?: string;
|
|
46
47
|
} | null;
|
|
47
48
|
}
|
|
48
|
-
/** The bot's brain as sent at prepare: a known runtime profile provider
|
|
49
|
+
/** The bot's brain as sent at prepare: a known runtime profile provider, and its model, win over bot.json. */
|
|
49
50
|
export declare function promotionBrain(config: BotConfig, runtime?: LocalBotPromotionRuntime): BotPromotionBrain;
|
|
50
51
|
/** Cloud bots run on Codex only for now. A bot already held names the cancel. */
|
|
51
52
|
export declare function promotionBrainRefusal(config: BotConfig, brain: BotPromotionBrain, dir: string): Error | null;
|
|
@@ -63,9 +64,12 @@ export declare function promoteLocalBot(input: {
|
|
|
63
64
|
runtime?: LocalBotPromotionRuntime;
|
|
64
65
|
isRunning?: () => boolean;
|
|
65
66
|
restart?: () => Promise<unknown>;
|
|
67
|
+
fleetHome?: string;
|
|
68
|
+
onSnapshot?: (fleetState: FleetStateManifest | null) => void;
|
|
66
69
|
}): Promise<{
|
|
67
70
|
promotion: BotPromotionState;
|
|
68
71
|
pending: boolean;
|
|
72
|
+
fleetState?: FleetStateManifest | null;
|
|
69
73
|
}>;
|
|
70
74
|
export type PromotionCancelOutcome = "canceled" | "pending" | "active" | "not-found";
|
|
71
75
|
export interface PromotionCancelResult {
|
|
@@ -89,7 +93,8 @@ export declare const PROMOTION_CANCEL_IDENTITY_RETRIES = 3;
|
|
|
89
93
|
* promotion at all. Anything else keeps the hold. A damaged hold may name
|
|
90
94
|
* another company, so only a confirmed cancel releases it. When HQ will not
|
|
91
95
|
* show the move (403, or 404 without a code), a readable hold for this company
|
|
92
|
-
* still asks HQ to cancel its operation: cancel is authorized on the bot alone
|
|
96
|
+
* still asks HQ to cancel its operation: cancel is authorized on the bot alone,
|
|
97
|
+
* and a PROMOTION_NOT_FOUND answer then keeps the hold, since HQ proved nothing.
|
|
93
98
|
*/
|
|
94
99
|
export declare function cancelLocalBotPromotion(input: {
|
|
95
100
|
dir: string;
|
|
@@ -99,6 +104,7 @@ export declare function cancelLocalBotPromotion(input: {
|
|
|
99
104
|
pollMs?: number;
|
|
100
105
|
timeoutMs?: number;
|
|
101
106
|
sleep?: (ms: number) => Promise<void>;
|
|
107
|
+
now?: () => number;
|
|
102
108
|
onWaiting?: () => void;
|
|
103
109
|
signedInPerson?: SignedInPerson;
|
|
104
110
|
}): Promise<PromotionCancelResult>;
|
package/dist/lib/bot/promote.js
CHANGED
|
@@ -3,8 +3,10 @@ import * as fs from "node:fs";
|
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { BotApiError } from "./api.js";
|
|
6
|
+
import { HQ_FLEET_RUNTIME_ENGINE_ID } from "./config.js";
|
|
6
7
|
import { botCredsPath } from "./paths.js";
|
|
7
|
-
import { snapshotBotContinuity, validateBotContinuity } from "./continuity.js";
|
|
8
|
+
import { FLEET_STATE_DIR, planFleetContinuity, snapshotBotContinuity, validateBotContinuity } from "./continuity.js";
|
|
9
|
+
import { collectFleetState, FleetStateLimitError, fleetStateManifestOf } from "./fleet-state.js";
|
|
8
10
|
import { attestPromotionDrain, hasPromotionHold, holdForPromotion, localBotProcessAlive, promotionHoldSummary, readPromotionHoldOrigin, recordPromotionHoldOrigin, waitForPromotionDrain, } from "./promotion-hold.js";
|
|
9
11
|
import { uploadLocalBotPromotion } from "./promotion-upload.js";
|
|
10
12
|
import { appendBotLog, botLogLine } from "./log.js";
|
|
@@ -80,12 +82,14 @@ function otherCompanyError(config, held, asked, cancel) {
|
|
|
80
82
|
(cancel ? "" : `Continue that move with: hq bot promote ${config.name} --company ${held}, or `) +
|
|
81
83
|
`${cancel ? "Cancel" : "cancel"} it with: hq bot promote ${config.name} --company ${held} --cancel`);
|
|
82
84
|
}
|
|
85
|
+
/** Every file a release removes, for a person freeing the bot by hand. */
|
|
86
|
+
const manualRelease = (holdFile) => `delete ${holdFile} and the promotion-hold-origin.json, promotion-active.json and promotion-snapshot-*.json files beside it`;
|
|
83
87
|
function damagedHoldError(dir, config, reason, companyUid) {
|
|
84
88
|
const file = path.join(dir, "promotion-hold.json");
|
|
85
89
|
return new Error(`The promotion hold for ${config.name} on this computer (${file}) is damaged: ${reason}. ` +
|
|
86
90
|
`HQ has no move to the cloud for ${config.name} in company ${companyUid}, but a damaged hold may belong to a move in another company, so it was not removed. ` +
|
|
87
91
|
`Nothing was released: ${config.name} stays held on this computer. If it is moving to another company, cancel there with: hq bot promote ${config.name} --company <uid> --cancel. ` +
|
|
88
|
-
`If you are sure it is not moving to the cloud anywhere,
|
|
92
|
+
`If you are sure it is not moving to the cloud anywhere, ${manualRelease(file)}, then start it with: hq bot start ${config.name}`);
|
|
89
93
|
}
|
|
90
94
|
/** HQ's raw answer goes to the bot's own log only, never to the person. */
|
|
91
95
|
function logRaw(dir, error) {
|
|
@@ -233,10 +237,10 @@ function withCancelHint(error, config, companyUid, dir) {
|
|
|
233
237
|
return new Error(`${reason(error, dir)}. ${config.name} stays stopped on this computer while it is held for the move. ` +
|
|
234
238
|
`Run the same command to continue, or cancel the move with: hq bot promote ${config.name} --company ${companyUid} --cancel`, { cause: error });
|
|
235
239
|
}
|
|
236
|
-
/** The bot's brain as sent at prepare: a known runtime profile provider
|
|
240
|
+
/** The bot's brain as sent at prepare: a known runtime profile provider, and its model, win over bot.json. */
|
|
237
241
|
export function promotionBrain(config, runtime) {
|
|
238
242
|
const profile = runtime?.brain?.() ?? null;
|
|
239
|
-
const model = config.model?.trim() || profile?.model?.trim();
|
|
243
|
+
const model = profile?.runtime ? profile.model?.trim() || config.model?.trim() : config.model?.trim() || profile?.model?.trim();
|
|
240
244
|
const effort = config.effort?.trim();
|
|
241
245
|
return { runtime: profile?.runtime ?? config.runtime, ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
|
|
242
246
|
}
|
|
@@ -256,6 +260,42 @@ export function promotionBrainRefusal(config, brain, dir) {
|
|
|
256
260
|
: `Moving a Grok bot to the cloud is not supported yet. Switch ${name} to Codex first with: hq bot switch-account ${name} --runtime codex, or keep it on this computer. Nothing was changed.`;
|
|
257
261
|
return Object.assign(new Error(text), { expected: true });
|
|
258
262
|
}
|
|
263
|
+
/** Where the cloud computer keeps HQ; the released importer plans against it. */
|
|
264
|
+
const CLOUD_HQ_ROOT = "/home/ec2-user/hq-agent";
|
|
265
|
+
/** Run the cloud importer's own checks here, so a snapshot it would refuse is
|
|
266
|
+
* never frozen, uploaded or announced to the server.
|
|
267
|
+
*/
|
|
268
|
+
function assertCloudImportable(bundle, config) {
|
|
269
|
+
try {
|
|
270
|
+
validateBotContinuity(bundle, { agentUid: config.agentUid, ownerUid: config.ownerUid });
|
|
271
|
+
planFleetContinuity(bundle, { agentUid: config.agentUid, ownerUid: config.ownerUid, hqRoot: CLOUD_HQ_ROOT, ...(config.companySlug ? { companySlug: config.companySlug } : {}) });
|
|
272
|
+
}
|
|
273
|
+
catch (error) {
|
|
274
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
275
|
+
if (!reason.includes("SOUL transfer budget"))
|
|
276
|
+
throw error;
|
|
277
|
+
const skillFiles = bundle.files.filter((file) => file.area === "memory" && file.path.startsWith(`${FLEET_STATE_DIR}/skills/`)).length;
|
|
278
|
+
throw new Error(`the cloud bot's identity file lists every moved file and is limited to 32 KiB, which ${bundle.files.length} files (${skillFiles} of them from learned skills) exceed; nothing was truncated`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const SKILL_LIMIT = /32 KiB|-file transfer limit|MiB transfer limit/;
|
|
282
|
+
/** Learned skills to name in a pre-flight failure: the ones the error points
|
|
283
|
+
* at, or for a size limit every carried skill, largest first.
|
|
284
|
+
*/
|
|
285
|
+
function skillsToRemove(reason, state) {
|
|
286
|
+
const skills = state?.manifest.skills ?? [];
|
|
287
|
+
const named = skills.filter((skill) => reason.includes(`skills/${skill}/`));
|
|
288
|
+
if (named.length || !SKILL_LIMIT.test(reason))
|
|
289
|
+
return named;
|
|
290
|
+
const byBytes = reason.includes("MiB");
|
|
291
|
+
const weight = new Map();
|
|
292
|
+
for (const file of state?.files ?? []) {
|
|
293
|
+
const owner = skills.filter((skill) => file.path.startsWith(`${FLEET_STATE_DIR}/skills/${skill}/`)).sort((a, b) => b.length - a.length)[0];
|
|
294
|
+
if (owner)
|
|
295
|
+
weight.set(owner, (weight.get(owner) ?? 0) + (byBytes ? file.bytes.length : 1));
|
|
296
|
+
}
|
|
297
|
+
return [...weight].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([skill]) => skill);
|
|
298
|
+
}
|
|
259
299
|
/** One recoverable local-to-cloud step, used by CLI and desktop. Never kills the
|
|
260
300
|
* local runtime, recopies provider login files, or changes another bot.
|
|
261
301
|
* When this call creates the hold and fails before the server records the
|
|
@@ -267,6 +307,28 @@ export async function promoteLocalBot(input) {
|
|
|
267
307
|
const refusal = promotionBrainRefusal(config, brain, dir);
|
|
268
308
|
if (refusal)
|
|
269
309
|
throw refusal;
|
|
310
|
+
const fleetBot = config.engine?.id === HQ_FLEET_RUNTIME_ENGINE_ID;
|
|
311
|
+
const stillHeld = `${config.name} is held for this move and stays stopped until it finishes; fix the problem, then rerun hq bot promote ${config.name} --company ${companyUid}, or cancel the move with: hq bot promote ${config.name} --company ${companyUid} --cancel`;
|
|
312
|
+
// The pre-flight and the frozen snapshot scan each unchanged skill file once between them.
|
|
313
|
+
const scanCache = new Map();
|
|
314
|
+
const buildSnapshot = (held) => {
|
|
315
|
+
let state = null;
|
|
316
|
+
try {
|
|
317
|
+
if (!fleetBot)
|
|
318
|
+
return snapshotBotContinuity(config, dir);
|
|
319
|
+
state = collectFleetState(config, dir, { brain, scanCache, ...(input.fleetHome ? { fleetHome: input.fleetHome } : {}) });
|
|
320
|
+
const snapshot = snapshotBotContinuity(config, dir, state?.files);
|
|
321
|
+
assertCloudImportable(snapshot, config);
|
|
322
|
+
return snapshot;
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
if (!fleetBot)
|
|
326
|
+
throw error;
|
|
327
|
+
const reason = sentence(error).replace(/^Bot continuity: /, "");
|
|
328
|
+
const skills = error instanceof FleetStateLimitError ? error.skills : skillsToRemove(reason, state);
|
|
329
|
+
throw new Error(`This bot cannot be moved to the cloud yet: ${reason}.${skills.length ? ` Remove or shrink ${skills.length === 1 ? "this learned skill" : "these learned skills"} in the bot's skills folder, then retry: ${skills.join(", ")}.` : ""} Nothing was uploaded.${held ? ` ${stillHeld}.` : ""}`, { cause: error });
|
|
330
|
+
}
|
|
331
|
+
};
|
|
270
332
|
if (config.kind === "personal")
|
|
271
333
|
throw personalBotError(config);
|
|
272
334
|
const read = readLocalHold(dir, config);
|
|
@@ -277,10 +339,11 @@ export async function promoteLocalBot(input) {
|
|
|
277
339
|
throw otherCompanyError(config, localHold.companyUid, companyUid, false);
|
|
278
340
|
let existing = await readPromotionStatus(api, config, companyUid, dir);
|
|
279
341
|
let priorOrigin = null;
|
|
342
|
+
let canceledHere = false;
|
|
280
343
|
if (existing?.phase === "cancelled") {
|
|
281
344
|
// A canceled operation is finished: no hold, id or frozen snapshot from before is used again.
|
|
282
345
|
priorOrigin = readPromotionHoldOrigin(dir);
|
|
283
|
-
releaseLocalPromotion(dir);
|
|
346
|
+
canceledHere = releaseLocalPromotion(dir);
|
|
284
347
|
localHold = null;
|
|
285
348
|
existing = null;
|
|
286
349
|
}
|
|
@@ -289,6 +352,29 @@ export async function promoteLocalBot(input) {
|
|
|
289
352
|
throw new Error("Invalid saved promotion operation");
|
|
290
353
|
const hold = { agentUid: config.agentUid, ownerUid: config.ownerUid, companyUid, operationId };
|
|
291
354
|
const fresh = !existing && !localHold;
|
|
355
|
+
const file = path.join(dir, `promotion-snapshot-${operationId}.json`);
|
|
356
|
+
// A first attempt that cannot succeed fails here, before the bot is held or stopped.
|
|
357
|
+
if (fleetBot && !existing && !fs.existsSync(file)) {
|
|
358
|
+
try {
|
|
359
|
+
buildSnapshot(localHold !== null);
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
if (!canceledHere)
|
|
363
|
+
throw error;
|
|
364
|
+
// The canceled move's hold is gone, so put the bot back the way it was before that move.
|
|
365
|
+
const freed = `${sentence(error)}. The earlier move was canceled, so ${config.name} is no longer held on this computer`;
|
|
366
|
+
if (!priorOrigin || !input.restart) {
|
|
367
|
+
throw new Error(`${freed}${priorOrigin === false ? "" : `; start it with: hq bot start ${config.name}`}.`, { cause: error });
|
|
368
|
+
}
|
|
369
|
+
try {
|
|
370
|
+
await input.restart();
|
|
371
|
+
}
|
|
372
|
+
catch (restartError) {
|
|
373
|
+
throw new Error(`${freed}, but it did not start again: ${sentence(restartError)}. Start it with: hq bot start ${config.name}`, { cause: error });
|
|
374
|
+
}
|
|
375
|
+
throw new Error(`${freed} and was started again, since it was running before that move.`, { cause: error });
|
|
376
|
+
}
|
|
377
|
+
}
|
|
292
378
|
const wasRunning = fresh ? priorOrigin ?? (input.isRunning ?? (() => localBotProcessAlive(dir)))() : null;
|
|
293
379
|
holdForPromotion(dir, hold);
|
|
294
380
|
let prepared = !fresh;
|
|
@@ -302,11 +388,10 @@ export async function promoteLocalBot(input) {
|
|
|
302
388
|
}
|
|
303
389
|
runtime?.stop();
|
|
304
390
|
await waitForPromotionDrain(dir, input.drainTimeoutMs ?? 60_000);
|
|
305
|
-
const file = path.join(dir, `promotion-snapshot-${operationId}.json`);
|
|
306
391
|
if (!fs.existsSync(file)) {
|
|
307
392
|
if (existing)
|
|
308
393
|
throw new Error("The original frozen snapshot is missing. Restore it before retrying.");
|
|
309
|
-
const snapshot =
|
|
394
|
+
const snapshot = buildSnapshot(false);
|
|
310
395
|
const temp = `${file}.${randomUUID()}.tmp`;
|
|
311
396
|
fs.writeFileSync(temp, JSON.stringify(snapshot), { mode: 0o600, flag: "wx" });
|
|
312
397
|
try {
|
|
@@ -324,6 +409,10 @@ export async function promoteLocalBot(input) {
|
|
|
324
409
|
validateBotContinuity(bundle, { agentUid: config.agentUid, ownerUid: config.ownerUid });
|
|
325
410
|
if (existing && existing.snapshotSha256 !== bundle.digest)
|
|
326
411
|
throw new Error("Frozen snapshot does not match the cloud operation");
|
|
412
|
+
const fleetState = fleetBot ? fleetStateManifestOf(bundle) : null;
|
|
413
|
+
if (fleetBot)
|
|
414
|
+
input.onSnapshot?.(fleetState);
|
|
415
|
+
const carried = fleetBot ? { fleetState } : {};
|
|
327
416
|
let state = existing;
|
|
328
417
|
if (!state || state.phase === "preparing") {
|
|
329
418
|
const machine = runtime ? runtime.machineCredential() : readPrivateJson(botCredsPath(dir), 8192);
|
|
@@ -342,15 +431,15 @@ export async function promoteLocalBot(input) {
|
|
|
342
431
|
const result = await api.resumePromotion(config.agentUid, { companyUid, operationId });
|
|
343
432
|
if (result.promotion.phase === "active")
|
|
344
433
|
recordActivePromotion(dir, hold, result.promotion);
|
|
345
|
-
return result;
|
|
434
|
+
return { ...result, ...carried };
|
|
346
435
|
}
|
|
347
|
-
return { promotion: state, pending: state.phase !== "active" };
|
|
436
|
+
return { promotion: state, pending: state.phase !== "active", ...carried };
|
|
348
437
|
}
|
|
349
438
|
catch (error) {
|
|
350
439
|
if (prepared)
|
|
351
440
|
throw withCancelHint(error, config, companyUid, dir);
|
|
352
441
|
// A prepare whose answer was lost may still have been recorded: ask before releasing.
|
|
353
|
-
if (prepareSent && !(error instanceof BotApiError) && await serverMayKnow(api, config, companyUid, operationId))
|
|
442
|
+
if (prepareSent && (!(error instanceof BotApiError) || error.status >= 500) && await serverMayKnow(api, config, companyUid, operationId))
|
|
354
443
|
throw withCancelHint(error, config, companyUid, dir);
|
|
355
444
|
const refused = serverRefusal(error, config);
|
|
356
445
|
releaseLocalPromotion(dir);
|
|
@@ -384,7 +473,8 @@ export const PROMOTION_CANCEL_IDENTITY_RETRIES = 3;
|
|
|
384
473
|
* promotion at all. Anything else keeps the hold. A damaged hold may name
|
|
385
474
|
* another company, so only a confirmed cancel releases it. When HQ will not
|
|
386
475
|
* show the move (403, or 404 without a code), a readable hold for this company
|
|
387
|
-
* still asks HQ to cancel its operation: cancel is authorized on the bot alone
|
|
476
|
+
* still asks HQ to cancel its operation: cancel is authorized on the bot alone,
|
|
477
|
+
* and a PROMOTION_NOT_FOUND answer then keeps the hold, since HQ proved nothing.
|
|
388
478
|
*/
|
|
389
479
|
export async function cancelLocalBotPromotion(input) {
|
|
390
480
|
const { dir, config, companyUid, api } = input;
|
|
@@ -418,20 +508,23 @@ export async function cancelLocalBotPromotion(input) {
|
|
|
418
508
|
const pollMs = input.pollMs ?? PROMOTION_CANCEL_POLL_MS;
|
|
419
509
|
const timeoutMs = input.timeoutMs ?? PROMOTION_CANCEL_TIMEOUT_MS;
|
|
420
510
|
const sleep = input.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
|
|
511
|
+
const now = input.now ?? Date.now;
|
|
421
512
|
const kept = `Nothing was released: ${config.name} stays held on this computer.`;
|
|
422
513
|
let result;
|
|
423
514
|
try {
|
|
515
|
+
const deadline = now() + timeoutMs;
|
|
424
516
|
result = await api.cancelPromotion(config.agentUid, { companyUid, operationId });
|
|
425
|
-
let
|
|
517
|
+
let announced = false;
|
|
426
518
|
let identityRetries = 0;
|
|
427
519
|
for (;;) {
|
|
428
520
|
if (result.pending) {
|
|
429
|
-
if (
|
|
521
|
+
if (now() >= deadline)
|
|
430
522
|
break;
|
|
431
|
-
if (
|
|
523
|
+
if (!announced) {
|
|
524
|
+
announced = true;
|
|
432
525
|
input.onWaiting?.();
|
|
526
|
+
}
|
|
433
527
|
await sleep(pollMs);
|
|
434
|
-
waited += pollMs;
|
|
435
528
|
}
|
|
436
529
|
else if (result.identityRestored === false && identityRetries < PROMOTION_CANCEL_IDENTITY_RETRIES) {
|
|
437
530
|
identityRetries += 1;
|
|
@@ -449,7 +542,13 @@ export async function cancelLocalBotPromotion(input) {
|
|
|
449
542
|
if (error instanceof BotApiError && error.status === 409 && error.code === "PROMOTION_INSTANCE_NOT_OWNED") {
|
|
450
543
|
throw new Error(`HQ says the cloud copy of ${config.name} does not belong to this move, so it cannot be canceled from here. ${kept}`, { cause: error });
|
|
451
544
|
}
|
|
452
|
-
if (unseen &&
|
|
545
|
+
if (unseen && error instanceof BotApiError && error.status === 404 && error.code === "PROMOTION_NOT_FOUND") {
|
|
546
|
+
logRaw(dir, unseen);
|
|
547
|
+
const file = path.join(dir, "promotion-hold.json");
|
|
548
|
+
throw new Error(`${unseen.status === 403 ? "HQ refused to show" : "HQ could not find"} the move of ${config.name} to company ${companyUid} and says it has no move to cancel, so it could not prove the bot is free. ${kept} ` +
|
|
549
|
+
`Sign in as the bot's owner (hq whoami) and run the same command again. If you are sure ${config.name} is not moving to the cloud anywhere, ${manualRelease(file)}, then start it with: hq bot start ${config.name}`, { cause: error });
|
|
550
|
+
}
|
|
551
|
+
if (unseen) {
|
|
453
552
|
logRaw(dir, unseen);
|
|
454
553
|
const bothMissing = unseen.status === 404 && error instanceof BotApiError && error.status === 404 && !error.code;
|
|
455
554
|
if (bothMissing && await cloudAgentPresence(input) === "gone")
|
|
@@ -23,10 +23,14 @@ export declare const SERVICE_DESCRIPTIONS: Record<ServiceName, string>;
|
|
|
23
23
|
export declare const DEFAULT_SERVICES: Record<MachineType, readonly ServiceName[]>;
|
|
24
24
|
/** Services another enabled service turns on; only an explicit disable keeps them off. */
|
|
25
25
|
export declare const IMPLIED_SERVICES: Partial<Record<ServiceName, ServiceName>>;
|
|
26
|
+
/** Services that run whenever a vault is on the new sync engine here, whatever the config says. */
|
|
27
|
+
export declare const ENGINE_REQUIRED_SERVICES: readonly ServiceName[];
|
|
26
28
|
/** Defaults plus this host's overrides, in catalog order. Unknown names are ignored. */
|
|
27
29
|
export declare function enabledServices(machineType: MachineType, overrides: {
|
|
28
30
|
enable: readonly string[];
|
|
29
31
|
disable: readonly string[];
|
|
32
|
+
}, opts?: {
|
|
33
|
+
engineVaults?: number;
|
|
30
34
|
}): ServiceName[];
|
|
31
35
|
type UnitCommand = {
|
|
32
36
|
type: "hq";
|
|
@@ -141,9 +145,14 @@ export declare const SYNC_CORE_SELFCHECK_UNIT = "sync-core-selfcheck";
|
|
|
141
145
|
export declare const SYNC_CORE_SELFCHECK_INTERVAL_SEC = 3600;
|
|
142
146
|
export declare const SYNC_CORE_MANIFEST_INTERVAL_SEC: number;
|
|
143
147
|
export declare const SYNC_CORE_LEGACY_SETTLE_MS: number;
|
|
148
|
+
/** How long an engine may wait for the old sync to restart before status and the self-check call it stuck. */
|
|
149
|
+
export declare const LEGACY_HANDOVER_STUCK_AFTER_MS: number;
|
|
150
|
+
export declare const LEGACY_HANDOVER_STUCK_PREFIX = "stuck: waiting over 10 minutes for the running sync";
|
|
144
151
|
export type LegacySyncHolder = {
|
|
145
152
|
status: "started";
|
|
146
153
|
startedAt: number;
|
|
154
|
+
pid?: number;
|
|
155
|
+
owner?: string;
|
|
147
156
|
} | {
|
|
148
157
|
status: "missing";
|
|
149
158
|
} | {
|
|
@@ -181,6 +190,8 @@ export interface PlanContext {
|
|
|
181
190
|
syncCoreRunning?: SyncCoreRunning;
|
|
182
191
|
legacySyncReadyForCore?: boolean;
|
|
183
192
|
legacySyncHolder?: LegacySyncHolder;
|
|
193
|
+
/** When the daemon last asked the old sync runner to stop so it restarts with the new skip list. */
|
|
194
|
+
legacyHandoverStopRequestedAt?: number;
|
|
184
195
|
now?: number;
|
|
185
196
|
/** A legacy desktop app or sync unit is still managing sync. */
|
|
186
197
|
desktopAppManagesSync: boolean;
|
|
@@ -247,6 +258,8 @@ export declare const CODEX_RUNNER_SCRIPT = "/usr/local/bin/outpost-codex-runner.
|
|
|
247
258
|
/** The outpost's Claude runner script, read for the session name it uses. */
|
|
248
259
|
export declare const CLAUDE_RUNNER_SCRIPT = "/usr/local/bin/outpost-runner.sh";
|
|
249
260
|
export declare const NOT_SIGNED_IN = "not signed in (run `hq login`)";
|
|
261
|
+
/** True only when an engine unit's one remaining block is an old runner that has to restart. */
|
|
262
|
+
export declare function isLegacyRestartWait(block: UnitPlan["blocked"]): boolean;
|
|
250
263
|
export declare function daemonAloneRunsLegacySync(ctx: PlanContext): boolean;
|
|
251
264
|
/** Turn enabled services into concrete units for this host. */
|
|
252
265
|
export declare function planUnits(services: readonly ServiceName[], ctx: PlanContext): UnitPlan[];
|
|
@@ -83,15 +83,18 @@ export const DEFAULT_SERVICES = {
|
|
|
83
83
|
};
|
|
84
84
|
/** Services another enabled service turns on; only an explicit disable keeps them off. */
|
|
85
85
|
export const IMPLIED_SERVICES = { mesh: "sync-core" };
|
|
86
|
+
/** Services that run whenever a vault is on the new sync engine here, whatever the config says. */
|
|
87
|
+
export const ENGINE_REQUIRED_SERVICES = ["mesh"];
|
|
86
88
|
/** Defaults plus this host's overrides, in catalog order. Unknown names are ignored. */
|
|
87
|
-
export function enabledServices(machineType, overrides) {
|
|
89
|
+
export function enabledServices(machineType, overrides, opts = {}) {
|
|
88
90
|
const defaults = DEFAULT_SERVICES[machineType];
|
|
89
91
|
const wanted = (s) => (defaults.includes(s) || overrides.enable.includes(s)) && !overrides.disable.includes(s);
|
|
90
92
|
const implied = (s) => {
|
|
91
93
|
const by = IMPLIED_SERVICES[s];
|
|
92
94
|
return by !== undefined && wanted(by) && !overrides.disable.includes(s);
|
|
93
95
|
};
|
|
94
|
-
|
|
96
|
+
const engines = (opts.engineVaults ?? 0) > 0 && wanted("sync-core");
|
|
97
|
+
return SERVICE_NAMES.filter((s) => wanted(s) || implied(s) || (engines && ENGINE_REQUIRED_SERVICES.includes(s)));
|
|
95
98
|
}
|
|
96
99
|
/**
|
|
97
100
|
* Why the daemon schedules no search-index pass. The timer never starts `hq`
|
|
@@ -113,6 +116,9 @@ export const SYNC_CORE_SELFCHECK_UNIT = "sync-core-selfcheck";
|
|
|
113
116
|
export const SYNC_CORE_SELFCHECK_INTERVAL_SEC = 3600;
|
|
114
117
|
export const SYNC_CORE_MANIFEST_INTERVAL_SEC = 24 * 3600;
|
|
115
118
|
export const SYNC_CORE_LEGACY_SETTLE_MS = 10 * 60 * 1000;
|
|
119
|
+
/** How long an engine may wait for the old sync to restart before status and the self-check call it stuck. */
|
|
120
|
+
export const LEGACY_HANDOVER_STUCK_AFTER_MS = 10 * 60 * 1000;
|
|
121
|
+
export const LEGACY_HANDOVER_STUCK_PREFIX = "stuck: waiting over 10 minutes for the running sync";
|
|
116
122
|
function base(service, over = {}) {
|
|
117
123
|
return {
|
|
118
124
|
id: service,
|
|
@@ -153,6 +159,26 @@ export const CLAUDE_RUNNER_SCRIPT = "/usr/local/bin/outpost-runner.sh";
|
|
|
153
159
|
const NO_HQ_ROOT = "no HQ folder configured (run `hq daemon install --hq-root <path>`)";
|
|
154
160
|
export const NOT_SIGNED_IN = "not signed in (run `hq login`)";
|
|
155
161
|
const KIT_NOT_SET_UP = "the agent kit is not set up on this machine (run `hq agent kit install`)";
|
|
162
|
+
function isoSeconds(ms) {
|
|
163
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
164
|
+
}
|
|
165
|
+
function legacySyncOffFor(vault, vaultSync) {
|
|
166
|
+
return vault.kind === "personal"
|
|
167
|
+
? vaultSync?.personalOff === true
|
|
168
|
+
: vaultSync?.offCompanies.has(vault.slug ?? "") === true;
|
|
169
|
+
}
|
|
170
|
+
function stuckHandoverReason(what, offSince, holder, stopRequestedAt) {
|
|
171
|
+
const who = `${holder.owner ? `${holder.owner} ` : ""}${holder.pid !== undefined ? `pid ${holder.pid}, ` : ""}started ${isoSeconds(holder.startedAt)}`;
|
|
172
|
+
const asked = stopRequestedAt !== undefined ? `; HQ asked it to stop at ${isoSeconds(stopRequestedAt)}` : "";
|
|
173
|
+
return `${LEGACY_HANDOVER_STUCK_PREFIX} (started before the switch was turned off for ${what} at ${isoSeconds(offSince)}; ${who}) to restart${asked}. ` +
|
|
174
|
+
"Check that the HQ desktop app is open with Auto-sync on, then run `hq daemon status`";
|
|
175
|
+
}
|
|
176
|
+
const LEGACY_RESTART_WAIT_PREFIX = "waiting for the running sync (started before the switch was turned off for ";
|
|
177
|
+
/** True only when an engine unit's one remaining block is an old runner that has to restart. */
|
|
178
|
+
export function isLegacyRestartWait(block) {
|
|
179
|
+
return block?.state === "waiting"
|
|
180
|
+
&& (block.reason.startsWith(LEGACY_RESTART_WAIT_PREFIX) || block.reason.startsWith(LEGACY_HANDOVER_STUCK_PREFIX));
|
|
181
|
+
}
|
|
156
182
|
function syncOwnerBlock(ctx) {
|
|
157
183
|
if (ctx.machineType === "desktop" && ctx.syncOwner === "desktop-app" && ctx.desktopAppManagesSync) {
|
|
158
184
|
return "the desktop app is still managing sync (run `hq daemon sync take-ownership` after it stops its runner)";
|
|
@@ -245,9 +271,7 @@ function planService(service, ctx) {
|
|
|
245
271
|
const now = ctx.now ?? Date.now();
|
|
246
272
|
const engines = (ctx.syncCoreVaults ?? []).map((vault) => {
|
|
247
273
|
const full = vault.phase === "full";
|
|
248
|
-
const legacyOff = vault.
|
|
249
|
-
? ctx.vaultSync?.personalOff === true
|
|
250
|
-
: ctx.vaultSync?.offCompanies.has(vault.slug ?? "") === true;
|
|
274
|
+
const legacyOff = legacySyncOffFor(vault, ctx.vaultSync);
|
|
251
275
|
const offSince = vault.legacyOffSince ? Date.parse(vault.legacyOffSince) : Number.NaN;
|
|
252
276
|
const settled = Number.isFinite(offSince) && now - offSince >= SYNC_CORE_LEGACY_SETTLE_MS;
|
|
253
277
|
const settleNeeded = ctx.legacySyncHolder !== undefined
|
|
@@ -262,7 +286,9 @@ function planService(service, ctx) {
|
|
|
262
286
|
: holder.status === "unreadable"
|
|
263
287
|
? "waiting to learn when the sync that holds the sync lock started (its owner status could not be read)"
|
|
264
288
|
: !Number.isFinite(offSince) || holder.startedAt < offSince
|
|
265
|
-
?
|
|
289
|
+
? Number.isFinite(offSince) && legacyOff && now - offSince >= LEGACY_HANDOVER_STUCK_AFTER_MS
|
|
290
|
+
? stuckHandoverReason(what, offSince, holder, ctx.legacyHandoverStopRequestedAt)
|
|
291
|
+
: `waiting for the running sync (started before the switch was turned off for ${what}) to restart`
|
|
266
292
|
: undefined;
|
|
267
293
|
return base(service, {
|
|
268
294
|
id: syncCoreUnitId(vault.uid),
|
|
@@ -8,10 +8,6 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import type { DaemonState } from "./supervisor.js";
|
|
10
10
|
type Unit = DaemonState["units"][number];
|
|
11
|
-
/** The longest `lastError` written to the state file, in UTF-8 bytes. */
|
|
12
|
-
export declare const LANES_RECONCILE_ERROR_BYTES = 300;
|
|
13
|
-
/** One line, no secrets, no control characters (it is printed to a terminal), at most LANES_RECONCILE_ERROR_BYTES. */
|
|
14
|
-
export declare function lanesReconcileErrorText(error: unknown): string;
|
|
15
11
|
export interface LanesReconcileStatus {
|
|
16
12
|
/** The same reconcile, with its outcome recorded. A failure is rethrown. */
|
|
17
13
|
track(reconcile: () => Promise<void>): () => Promise<void>;
|
|
@@ -6,19 +6,9 @@
|
|
|
6
6
|
* the outcome of each watcher run and adds one unit entry to the state file
|
|
7
7
|
* `hq daemon status` reads.
|
|
8
8
|
*/
|
|
9
|
-
import {
|
|
10
|
-
import { redactSecrets } from "../db/redact.js";
|
|
9
|
+
import { reconcileFailureText } from "../lanes/reconcile-result.js";
|
|
11
10
|
import { NOT_SIGNED_IN, SERVICE_DESCRIPTIONS } from "./catalog.js";
|
|
12
|
-
import { cutUtf8 } from "./state-file.js";
|
|
13
|
-
/** The longest `lastError` written to the state file, in UTF-8 bytes. */
|
|
14
|
-
export const LANES_RECONCILE_ERROR_BYTES = 300;
|
|
15
11
|
const UNIT_ID = "lanes-reconcile";
|
|
16
|
-
/** One line, no secrets, no control characters (it is printed to a terminal), at most LANES_RECONCILE_ERROR_BYTES. */
|
|
17
|
-
export function lanesReconcileErrorText(error) {
|
|
18
|
-
const raw = error instanceof Error ? error.message : String(error);
|
|
19
|
-
const oneLine = redactSecrets(redactForLog(raw)).replace(/\p{Cc}+/gu, " ").replace(/\s+/g, " ").trim();
|
|
20
|
-
return cutUtf8(oneLine, LANES_RECONCILE_ERROR_BYTES);
|
|
21
|
-
}
|
|
22
12
|
export function createLanesReconcileStatus(options = {}) {
|
|
23
13
|
const now = options.now ?? Date.now;
|
|
24
14
|
let lastRunAt;
|
|
@@ -34,7 +24,7 @@ export function createLanesReconcileStatus(options = {}) {
|
|
|
34
24
|
}
|
|
35
25
|
catch (error) {
|
|
36
26
|
lastResult = "failed";
|
|
37
|
-
lastError =
|
|
27
|
+
lastError = reconcileFailureText(error);
|
|
38
28
|
throw error;
|
|
39
29
|
}
|
|
40
30
|
finally {
|
|
@@ -10,7 +10,7 @@ export declare function createLanesReconcileWatcher(options: {
|
|
|
10
10
|
debounceMs?: number;
|
|
11
11
|
intervalMs?: number;
|
|
12
12
|
watch?: (directory: string, listener: (event: string, filename: string | Buffer | null) => void) => Watcher;
|
|
13
|
-
onError?: (error:
|
|
13
|
+
onError?: (error: Error) => void;
|
|
14
14
|
onWatchError?: (error: unknown) => void;
|
|
15
15
|
}): LanesReconcileWatcher;
|
|
16
16
|
export {};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
+
import { reconcileFailureText } from "../lanes/reconcile-result.js";
|
|
2
3
|
/** Reconcile at startup, on lane-store changes, and on a bounded in-process timer. */
|
|
3
4
|
export function createLanesReconcileWatcher(options) {
|
|
4
5
|
const debounceMs = options.debounceMs ?? 250;
|
|
@@ -21,7 +22,7 @@ export function createLanesReconcileWatcher(options) {
|
|
|
21
22
|
await options.reconcile();
|
|
22
23
|
}
|
|
23
24
|
catch (error) {
|
|
24
|
-
options.onError?.(error);
|
|
25
|
+
options.onError?.(new Error(reconcileFailureText(error)));
|
|
25
26
|
}
|
|
26
27
|
finally {
|
|
27
28
|
running = false;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Asks an old sync runner started before a vault's switch changed to stop (SIGTERM, never SIGKILL, never on Windows) so its owner relaunches it with the current skip list. */
|
|
2
|
+
import { type LegacySyncHolder } from "./catalog.js";
|
|
3
|
+
export declare const LEGACY_HANDOVER_RESIGNAL_AFTER_MS: number;
|
|
4
|
+
export declare const LEGACY_HANDOVER_STUCK_FILE = "legacy-handover.json";
|
|
5
|
+
export type LegacyHandoverOutcome = "signalled" | "already-signalled" | "own-runner" | "no-pid" | "not-running" | "not-a-sync-runner" | "unsupported-platform" | "signal-failed";
|
|
6
|
+
export interface LegacyHandoverStuck {
|
|
7
|
+
what: string;
|
|
8
|
+
since: number;
|
|
9
|
+
reason: string;
|
|
10
|
+
}
|
|
11
|
+
export interface LegacyHandoverDeps {
|
|
12
|
+
now: () => number;
|
|
13
|
+
selfPid: number;
|
|
14
|
+
isAlive: (pid: number) => boolean;
|
|
15
|
+
commandLine: (pid: number) => string | null;
|
|
16
|
+
signal: (pid: number, signal: "SIGTERM") => void;
|
|
17
|
+
/** Windows has no graceful SIGTERM: process.kill ends the runner at once, possibly mid-replace. */
|
|
18
|
+
platform?: NodeJS.Platform;
|
|
19
|
+
/** Persist the restore waits that passed the bound, for status and the self-check. */
|
|
20
|
+
writeRestoreStuck?: (stuck: LegacyHandoverStuck[]) => void;
|
|
21
|
+
log: (level: "info" | "warn", message: string) => void;
|
|
22
|
+
}
|
|
23
|
+
export interface LegacyHandover {
|
|
24
|
+
request(holder: Extract<LegacySyncHolder, {
|
|
25
|
+
status: "started";
|
|
26
|
+
}>, vaults: readonly string[]): LegacyHandoverOutcome;
|
|
27
|
+
/** When the current holder was last asked to stop, if it was. */
|
|
28
|
+
requestedAt(holder: LegacySyncHolder | undefined): number | undefined;
|
|
29
|
+
/** Record vaults switched back on that the running old sync still skips. */
|
|
30
|
+
reportRestoreWaits(holder: LegacySyncHolder | undefined, waits: readonly {
|
|
31
|
+
what: string;
|
|
32
|
+
since: number;
|
|
33
|
+
}[]): void;
|
|
34
|
+
}
|
|
35
|
+
export declare function createLegacyHandover(deps: LegacyHandoverDeps): LegacyHandover;
|
|
36
|
+
export declare function writeLegacyHandoverStuck(file: string, stuck: readonly LegacyHandoverStuck[], now?: number): void;
|
|
37
|
+
export declare function readLegacyHandoverStuck(file: string): LegacyHandoverStuck[];
|
|
38
|
+
//# sourceMappingURL=legacy-handover.d.ts.map
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/** Asks an old sync runner started before a vault's switch changed to stop (SIGTERM, never SIGKILL, never on Windows) so its owner relaunches it with the current skip list. */
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { LEGACY_HANDOVER_STUCK_AFTER_MS } from "./catalog.js";
|
|
5
|
+
import { SYNC_RUNNER_OWNER, isSyncRunnerCommandLine } from "./sync-runner.js";
|
|
6
|
+
export const LEGACY_HANDOVER_RESIGNAL_AFTER_MS = 5 * 60_000;
|
|
7
|
+
const FORGET_AFTER_MS = 6 * 60 * 60_000;
|
|
8
|
+
export const LEGACY_HANDOVER_STUCK_FILE = "legacy-handover.json";
|
|
9
|
+
function holderKey(holder) {
|
|
10
|
+
return `${holder.pid ?? "?"}@${holder.startedAt}`;
|
|
11
|
+
}
|
|
12
|
+
function isoSeconds(ms) {
|
|
13
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
14
|
+
}
|
|
15
|
+
export function createLegacyHandover(deps) {
|
|
16
|
+
const sent = new Map();
|
|
17
|
+
const refused = new Map();
|
|
18
|
+
let lastStuck = "[]";
|
|
19
|
+
const prune = (now) => {
|
|
20
|
+
for (const map of [sent, refused]) {
|
|
21
|
+
for (const [key, at] of map)
|
|
22
|
+
if (now - at > FORGET_AFTER_MS)
|
|
23
|
+
map.delete(key);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const requestedAt = (holder) => holder?.status === "started" ? sent.get(holderKey(holder)) : undefined;
|
|
27
|
+
return {
|
|
28
|
+
requestedAt,
|
|
29
|
+
request(holder, vaults) {
|
|
30
|
+
const key = holderKey(holder);
|
|
31
|
+
const now = deps.now();
|
|
32
|
+
prune(now);
|
|
33
|
+
if (holder.owner === SYNC_RUNNER_OWNER)
|
|
34
|
+
return "own-runner";
|
|
35
|
+
if (holder.pid === undefined || !Number.isInteger(holder.pid) || holder.pid <= 1 || holder.pid === deps.selfPid) {
|
|
36
|
+
return "no-pid";
|
|
37
|
+
}
|
|
38
|
+
if (deps.platform === "win32")
|
|
39
|
+
return "unsupported-platform";
|
|
40
|
+
const pid = holder.pid;
|
|
41
|
+
const last = sent.get(key);
|
|
42
|
+
if (last !== undefined && now - last < LEGACY_HANDOVER_RESIGNAL_AFTER_MS)
|
|
43
|
+
return "already-signalled";
|
|
44
|
+
if (!deps.isAlive(pid))
|
|
45
|
+
return "not-running";
|
|
46
|
+
const command = deps.commandLine(pid);
|
|
47
|
+
if (command === null || !isSyncRunnerCommandLine(command)) {
|
|
48
|
+
if (!refused.has(key)) {
|
|
49
|
+
refused.set(key, now);
|
|
50
|
+
deps.log("warn", `the sync lease names pid ${pid}, which is not a sync runner; leaving it alone`);
|
|
51
|
+
}
|
|
52
|
+
return "not-a-sync-runner";
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
deps.signal(pid, "SIGTERM");
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
deps.log("warn", `could not ask the old sync runner (pid ${pid}) to restart: ${error.message}`);
|
|
59
|
+
return "signal-failed";
|
|
60
|
+
}
|
|
61
|
+
sent.set(key, now);
|
|
62
|
+
deps.log("info", `asked the old sync runner (${holder.owner ?? "unknown owner"}, pid ${pid}) to stop so its owner restarts it with the current sync switches for ${vaults.join(", ")}`);
|
|
63
|
+
return "signalled";
|
|
64
|
+
},
|
|
65
|
+
reportRestoreWaits(holder, waits) {
|
|
66
|
+
if (!deps.writeRestoreStuck)
|
|
67
|
+
return;
|
|
68
|
+
const now = deps.now();
|
|
69
|
+
const stuck = holder?.status !== "started"
|
|
70
|
+
? []
|
|
71
|
+
: waits.filter((wait) => now - wait.since >= LEGACY_HANDOVER_STUCK_AFTER_MS).map((wait) => {
|
|
72
|
+
const asked = requestedAt(holder);
|
|
73
|
+
const who = `${holder.owner ? `${holder.owner} ` : ""}${holder.pid !== undefined ? `pid ${holder.pid}, ` : ""}started ${isoSeconds(holder.startedAt)}`;
|
|
74
|
+
return {
|
|
75
|
+
what: wait.what,
|
|
76
|
+
since: wait.since,
|
|
77
|
+
reason: `stuck: the running sync (${who}) still skips ${wait.what}, whose switch HQ turned back on at ${isoSeconds(wait.since)}, so ${wait.what} has no sync until it restarts` +
|
|
78
|
+
`${asked !== undefined ? `; HQ asked it to stop at ${isoSeconds(asked)}` : ""}. Check that the HQ desktop app is open with Auto-sync on, or restart the app`,
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
const text = JSON.stringify(stuck);
|
|
82
|
+
if (text === lastStuck)
|
|
83
|
+
return;
|
|
84
|
+
try {
|
|
85
|
+
deps.writeRestoreStuck(stuck);
|
|
86
|
+
lastStuck = text;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
deps.log("warn", `could not record the stuck sync handover: ${error.message}`);
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export function writeLegacyHandoverStuck(file, stuck, now = Date.now()) {
|
|
95
|
+
if (stuck.length === 0) {
|
|
96
|
+
fs.rmSync(file, { force: true });
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
100
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
101
|
+
fs.writeFileSync(tmp, `${JSON.stringify({ checkedAt: now, stuck })}\n`, { mode: 0o600 });
|
|
102
|
+
fs.renameSync(tmp, file);
|
|
103
|
+
}
|
|
104
|
+
export function readLegacyHandoverStuck(file) {
|
|
105
|
+
let parsed;
|
|
106
|
+
try {
|
|
107
|
+
parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
const stuck = parsed?.stuck;
|
|
113
|
+
if (!Array.isArray(stuck))
|
|
114
|
+
return [];
|
|
115
|
+
return stuck.filter((entry) => !!entry && typeof entry.what === "string" && typeof entry.reason === "string" && typeof entry.since === "number");
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=legacy-handover.js.map
|