@agentchatme/agent-core 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -4
- package/dist/{chunk-TH6XOVA3.js → chunk-AFDD53DD.js} +234 -10
- package/dist/chunk-AFDD53DD.js.map +1 -0
- package/dist/{chunk-W3LYBKIV.js → chunk-NAAHIK7Z.js} +468 -95
- package/dist/chunk-NAAHIK7Z.js.map +1 -0
- package/dist/chunk-UE7DKW3C.js +97 -0
- package/dist/chunk-UE7DKW3C.js.map +1 -0
- package/dist/daemon-entry.d.ts +58 -3
- package/dist/daemon-entry.js +290 -30
- package/dist/daemon-entry.js.map +1 -1
- package/dist/index.d.ts +134 -27
- package/dist/index.js +317 -149
- package/dist/index.js.map +1 -1
- package/dist/presets.d.ts +380 -22
- package/dist/presets.js +717 -115
- package/dist/presets.js.map +1 -1
- package/dist/{runner-BzgsiS3V.d.ts → runner-DYVqz_9P.d.ts} +49 -5
- package/dist/{served-manual-DZmEak4_.d.ts → served-manual-2rjsjJFD.d.ts} +153 -3
- package/package.json +1 -1
- package/dist/chunk-HOY2FERJ.js +0 -26
- package/dist/chunk-HOY2FERJ.js.map +0 -1
- package/dist/chunk-NCSF3CCV.js +0 -139
- package/dist/chunk-NCSF3CCV.js.map +0 -1
- package/dist/chunk-TH6XOVA3.js.map +0 -1
- package/dist/chunk-W3LYBKIV.js.map +0 -1
package/dist/daemon-entry.js
CHANGED
|
@@ -1,29 +1,36 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MANUAL,
|
|
3
|
+
acquireAgentLock,
|
|
3
4
|
acquireLeaderLock,
|
|
5
|
+
agentLockPath,
|
|
6
|
+
agentLockRefusal,
|
|
4
7
|
beat,
|
|
8
|
+
clearStandby,
|
|
5
9
|
credentialsPath,
|
|
6
10
|
describeManualSync,
|
|
7
11
|
idle,
|
|
8
|
-
integrationDisabledBy,
|
|
9
12
|
isRunnerFactory,
|
|
13
|
+
markStandby,
|
|
10
14
|
resolveIdentity,
|
|
11
|
-
|
|
12
|
-
resolveRunProfile,
|
|
15
|
+
standbyWaiting,
|
|
13
16
|
textsCachePath,
|
|
14
17
|
writeIntegrationStatus
|
|
15
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-NAAHIK7Z.js";
|
|
16
19
|
import {
|
|
20
|
+
INTEGRATION_ENV,
|
|
21
|
+
INTEGRATION_ENV_LEGACY,
|
|
22
|
+
INTEGRATION_ENV_LEGACY_REMOVAL,
|
|
17
23
|
WINDOWS_SWEEP_TIMEOUT_MS,
|
|
24
|
+
clientIdentityOf,
|
|
18
25
|
describeWindowsSweep,
|
|
26
|
+
integrationDisabledBy,
|
|
27
|
+
log,
|
|
19
28
|
redactDiagnostic,
|
|
29
|
+
resolveRunBudgetMs,
|
|
30
|
+
resolveRunProfile,
|
|
20
31
|
spawnRun,
|
|
21
32
|
sweepWindowsDescendants
|
|
22
|
-
} from "./chunk-
|
|
23
|
-
import {
|
|
24
|
-
clientIdentityOf,
|
|
25
|
-
log
|
|
26
|
-
} from "./chunk-NCSF3CCV.js";
|
|
33
|
+
} from "./chunk-AFDD53DD.js";
|
|
27
34
|
|
|
28
35
|
// src/integration/run.ts
|
|
29
36
|
import * as path2 from "path";
|
|
@@ -101,6 +108,7 @@ var HEARTBEAT_MS = 3e4;
|
|
|
101
108
|
var STATUS_MS = 3e4;
|
|
102
109
|
var HTTP_TIMEOUT_MS = 1e4;
|
|
103
110
|
var RUNNER_DEADLINE_SLACK_MS = 6e4;
|
|
111
|
+
var RUNTIME_RECHECK_MS = 5 * 6e4;
|
|
104
112
|
var PREFLIGHT_DEADLINE_MS = 6e4;
|
|
105
113
|
var CYCLE_FAILURE_CHARS = 240;
|
|
106
114
|
function reasonOf(source, frameReason) {
|
|
@@ -228,6 +236,16 @@ var Integration = class {
|
|
|
228
236
|
statusTimer = null;
|
|
229
237
|
socket = "idle";
|
|
230
238
|
lastError = null;
|
|
239
|
+
/** When the first run that did not get done since the last good one ended; null while runs succeed. */
|
|
240
|
+
failingSince = null;
|
|
241
|
+
/** Runs that did not get done since then. */
|
|
242
|
+
failingRuns = 0;
|
|
243
|
+
/** What the runtime's own check says while runs fail (status `runs_failing`); null when it has not failed one. */
|
|
244
|
+
runsFailing = null;
|
|
245
|
+
lastRecheckAt = 0;
|
|
246
|
+
recheckInFlight = null;
|
|
247
|
+
/** Aborts a runtime check in flight when the integration stops (its probes are killed, not left running). */
|
|
248
|
+
recheckAbort = new AbortController();
|
|
231
249
|
stopping = false;
|
|
232
250
|
stopped = null;
|
|
233
251
|
invites = 0;
|
|
@@ -273,7 +291,8 @@ var Integration = class {
|
|
|
273
291
|
this.stopping = true;
|
|
274
292
|
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
275
293
|
if (this.statusTimer) clearInterval(this.statusTimer);
|
|
276
|
-
this.
|
|
294
|
+
this.recheckAbort.abort();
|
|
295
|
+
this.stopped = Promise.all([this.loop.stop(), this.recheckInFlight ?? Promise.resolve()]).then(() => void 0);
|
|
277
296
|
this.texts.stop();
|
|
278
297
|
this.manual?.stop();
|
|
279
298
|
this.socket = "closed";
|
|
@@ -313,6 +332,11 @@ var Integration = class {
|
|
|
313
332
|
runtime: this.options.runner.name,
|
|
314
333
|
handle: this.options.cfg.handle,
|
|
315
334
|
profile: this.options.profile,
|
|
335
|
+
workdir: this.options.cfg.workdir,
|
|
336
|
+
standby: null,
|
|
337
|
+
runs_failing: this.runsFailing,
|
|
338
|
+
unservable: null,
|
|
339
|
+
...this.options.statusExtra?.() ?? {},
|
|
316
340
|
socket: this.stopping ? "closed" : this.socket,
|
|
317
341
|
wakes: status.coalescer.wakes,
|
|
318
342
|
wakes_absorbed: status.coalescer.absorbed,
|
|
@@ -361,16 +385,19 @@ var Integration = class {
|
|
|
361
385
|
const onAbort = () => controller.abort();
|
|
362
386
|
if (request.signal.aborted) controller.abort();
|
|
363
387
|
else request.signal.addEventListener("abort", onAbort, { once: true });
|
|
388
|
+
const identityLine = this.texts.current()?.identity_line;
|
|
364
389
|
let outcome;
|
|
365
390
|
try {
|
|
366
391
|
outcome = await withDeadline(
|
|
367
392
|
this.options.runner.start({
|
|
368
393
|
kind,
|
|
369
394
|
wake,
|
|
370
|
-
|
|
395
|
+
// No pointer, no trailing blank lines.
|
|
396
|
+
prompt: this.options.manualPointer.trim().length > 0 ? `${request.prompt}
|
|
371
397
|
|
|
372
|
-
${this.options.manualPointer}
|
|
398
|
+
${this.options.manualPointer}` : request.prompt,
|
|
373
399
|
runId,
|
|
400
|
+
...identityLine !== void 0 && identityLine.trim().length > 0 ? { identityLine } : {},
|
|
374
401
|
budgetMs,
|
|
375
402
|
signal: controller.signal
|
|
376
403
|
}),
|
|
@@ -417,9 +444,71 @@ ${this.options.manualPointer}`,
|
|
|
417
444
|
if (outcome.state !== "ok") {
|
|
418
445
|
log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""} \u2014 the cards stay on the tray; the next wake (or the server's re-wake) finds them`);
|
|
419
446
|
}
|
|
447
|
+
this.noteRunHealth(outcome, this.lastRun.ended_at);
|
|
420
448
|
this.writeStatus();
|
|
421
449
|
return outcome.state === "ok" ? { status: "completed" } : { status: outcome.state === "not_started" ? "not_started" : "failed", ...outcome.detail !== void 0 ? { detail: outcome.detail } : {} };
|
|
422
450
|
}
|
|
451
|
+
/**
|
|
452
|
+
* A run that did not get done may be the runtime itself (signed out, the
|
|
453
|
+
* binary gone, a flag an upgrade dropped): checked again, at most once per
|
|
454
|
+
* `RUNTIME_RECHECK_MS`, and said in status until a run succeeds. Wakes keep
|
|
455
|
+
* starting runs meanwhile — each is the quickest way back — and are counted.
|
|
456
|
+
*/
|
|
457
|
+
noteRunHealth(outcome, endedAt) {
|
|
458
|
+
if (outcome.state === "ok") {
|
|
459
|
+
if (this.runsFailing !== null) log.info(`runs work again (${this.failingRuns} run(s) missed since ${this.failingSince})`);
|
|
460
|
+
this.failingSince = null;
|
|
461
|
+
this.failingRuns = 0;
|
|
462
|
+
this.runsFailing = null;
|
|
463
|
+
this.lastRecheckAt = 0;
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
this.failingSince ??= endedAt;
|
|
467
|
+
this.failingRuns += 1;
|
|
468
|
+
if (this.runsFailing !== null) this.runsFailing = { ...this.runsFailing, runs_missed: this.failingRuns };
|
|
469
|
+
const recheckMs = this.options.runtimeRecheckMs ?? RUNTIME_RECHECK_MS;
|
|
470
|
+
if (this.recheckInFlight === null && !this.stopping && (this.lastRecheckAt === 0 || Date.now() - this.lastRecheckAt >= recheckMs)) {
|
|
471
|
+
this.recheckInFlight = this.recheckRuntime().finally(() => {
|
|
472
|
+
this.recheckInFlight = null;
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
async recheckRuntime() {
|
|
477
|
+
this.lastRecheckAt = Date.now();
|
|
478
|
+
const pre = await withDeadline(this.options.runner.preflight({ signal: this.recheckAbort.signal }), PREFLIGHT_DEADLINE_MS, () => ({
|
|
479
|
+
ok: false,
|
|
480
|
+
detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1e3)} s`
|
|
481
|
+
})).catch((err) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` }));
|
|
482
|
+
if (this.failingSince === null || this.stopping) return;
|
|
483
|
+
const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
484
|
+
if (!pre.ok) {
|
|
485
|
+
const reason = `${this.options.runner.name}: ${pre.detail ?? "its check failed"}`;
|
|
486
|
+
if (this.runsFailing?.reason !== reason) log.warn(`runs failing \u2014 ${reason} (since ${this.failingSince}, ${this.failingRuns} run(s) missed); status says so until a run succeeds`);
|
|
487
|
+
this.runsFailing = { reason, since: this.failingSince, runs_missed: this.failingRuns, checked_at: checkedAt };
|
|
488
|
+
} else if (this.runsFailing !== null) {
|
|
489
|
+
this.runsFailing = {
|
|
490
|
+
...this.runsFailing,
|
|
491
|
+
reason: `${this.options.runner.name} checks out now, but runs still fail${this.lastRun?.detail ? ` (last: ${this.lastRun.detail})` : ""}`,
|
|
492
|
+
checked_at: checkedAt
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
this.writeStatus();
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Whether this integration can serve its agent: not while the server refuses
|
|
499
|
+
* its key (socket `blocked`: rotated by `recover` elsewhere, revoked), nor
|
|
500
|
+
* while runs fail for a runtime reason (`runs_failing`). The supervisor then
|
|
501
|
+
* gives the agent up so a healthy listener for it can serve.
|
|
502
|
+
*/
|
|
503
|
+
health() {
|
|
504
|
+
if (this.socket === "blocked") return { ok: false, reason: `the server refuses this home's key${this.lastError ? ` (${this.lastError})` : ""}`, runsFailing: null };
|
|
505
|
+
if (this.runsFailing !== null) return { ok: false, reason: `runs failing: ${this.runsFailing.reason}`, runsFailing: this.runsFailing };
|
|
506
|
+
return { ok: true };
|
|
507
|
+
}
|
|
508
|
+
/** Test seam: resolves when a runtime check started by a failed run has finished. */
|
|
509
|
+
async runtimeCheckDone() {
|
|
510
|
+
await this.recheckInFlight;
|
|
511
|
+
}
|
|
423
512
|
onEvent(event) {
|
|
424
513
|
switch (event.type) {
|
|
425
514
|
case "wake": {
|
|
@@ -464,10 +553,24 @@ ${this.options.manualPointer}`,
|
|
|
464
553
|
var POLL_MS = 5e3;
|
|
465
554
|
var TICK_MS = 250;
|
|
466
555
|
var MAX_BACKOFF_MS = 5 * 6e4;
|
|
556
|
+
var STANDBY_POLL_MS = 3e4;
|
|
557
|
+
var UNSERVABLE_RECHECK_MS = 6e4;
|
|
558
|
+
var BLOCKED_RETRY_MS = 5 * 6e4;
|
|
467
559
|
var SHUTDOWN_GRACE_MS = 1e4;
|
|
468
560
|
var MAX_LOG_BYTES = 5 * 1024 * 1024;
|
|
469
561
|
var KEEP_LOG_BYTES = 1024 * 1024;
|
|
470
|
-
|
|
562
|
+
function sleepUnless(ms, signal) {
|
|
563
|
+
if (signal?.aborted === true) return Promise.resolve();
|
|
564
|
+
return new Promise((resolve3) => {
|
|
565
|
+
const done = () => {
|
|
566
|
+
clearTimeout(timer);
|
|
567
|
+
signal?.removeEventListener("abort", done);
|
|
568
|
+
resolve3();
|
|
569
|
+
};
|
|
570
|
+
const timer = setTimeout(done, ms);
|
|
571
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
572
|
+
});
|
|
573
|
+
}
|
|
471
574
|
function fingerprint(home, envKey) {
|
|
472
575
|
const id = resolveIdentity(home, { envKey });
|
|
473
576
|
return id === null ? null : `${id.apiKey}:${id.handle ?? ""}`;
|
|
@@ -492,6 +595,8 @@ ${keep.toString("utf-8")}`
|
|
|
492
595
|
} catch {
|
|
493
596
|
}
|
|
494
597
|
}
|
|
598
|
+
var StandbyError = class extends Error {
|
|
599
|
+
};
|
|
495
600
|
async function runIntegration(opts) {
|
|
496
601
|
const home = path2.resolve(opts.home);
|
|
497
602
|
const workdir = path2.resolve(opts.workdir);
|
|
@@ -500,8 +605,21 @@ async function runIntegration(opts) {
|
|
|
500
605
|
const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env);
|
|
501
606
|
boundDaemonLog(home);
|
|
502
607
|
if (process.env["AGENTCHAT_LOG_LEVEL"] === void 0) process.env["AGENTCHAT_LOG_LEVEL"] = "info";
|
|
503
|
-
|
|
608
|
+
let nudged = false;
|
|
609
|
+
const stopChecks = new AbortController();
|
|
610
|
+
if (opts.signal?.aborted === true) stopChecks.abort();
|
|
611
|
+
else opts.signal?.addEventListener("abort", () => stopChecks.abort(), { once: true });
|
|
612
|
+
const lock = await acquireLeaderLock(home, { ...opts.lease ?? {}, signal: stopChecks.signal });
|
|
504
613
|
if (lock === null) return 1;
|
|
614
|
+
let homeLost = null;
|
|
615
|
+
let starting = null;
|
|
616
|
+
lock.onLost((why) => {
|
|
617
|
+
homeLost = why;
|
|
618
|
+
nudged = true;
|
|
619
|
+
starting?.stop();
|
|
620
|
+
live?.stop();
|
|
621
|
+
log.error(`lost this home's daemon lock (${why}) \u2014 another daemon serves ${home} now; this one exits`);
|
|
622
|
+
});
|
|
505
623
|
const envKey = opts.credentialsFromHomeOnly !== true;
|
|
506
624
|
const identityOf = () => resolveIdentity(home, { envKey });
|
|
507
625
|
const disabledBy = integrationDisabledBy(env);
|
|
@@ -512,6 +630,37 @@ async function runIntegration(opts) {
|
|
|
512
630
|
let failures = 0;
|
|
513
631
|
let lastFailure = null;
|
|
514
632
|
let shuttingDown = false;
|
|
633
|
+
let agentLock = null;
|
|
634
|
+
let agentLost = null;
|
|
635
|
+
let standby = null;
|
|
636
|
+
let unservable = null;
|
|
637
|
+
let lastRunner = null;
|
|
638
|
+
let cachedCfg = null;
|
|
639
|
+
let agentLockFile = null;
|
|
640
|
+
let prepared = null;
|
|
641
|
+
let standbyCheck = null;
|
|
642
|
+
const runnerFor = (cfg, fp) => {
|
|
643
|
+
if (prepared === null || prepared.fp !== fp) prepared = { fp, runner: isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner };
|
|
644
|
+
return prepared.runner;
|
|
645
|
+
};
|
|
646
|
+
const preflightOf = async (runner) => {
|
|
647
|
+
const deadlineMs = opts.preflightDeadlineMs ?? PREFLIGHT_DEADLINE_MS;
|
|
648
|
+
return withDeadline(runner.preflight({ signal: stopChecks.signal }), deadlineMs, () => ({ ok: false, detail: `preflight did not answer within ${Math.round(deadlineMs / 1e3)} s` })).catch(
|
|
649
|
+
(err) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` })
|
|
650
|
+
);
|
|
651
|
+
};
|
|
652
|
+
const releaseAgent = () => {
|
|
653
|
+
agentLock?.release();
|
|
654
|
+
agentLock = null;
|
|
655
|
+
agentLost = null;
|
|
656
|
+
};
|
|
657
|
+
const stopWaiting = () => {
|
|
658
|
+
if (agentLockFile !== null) clearStandby(agentLockFile, home);
|
|
659
|
+
};
|
|
660
|
+
const leaseErrors = () => {
|
|
661
|
+
const count = lock.renewErrors + (agentLock?.renewErrors ?? 0);
|
|
662
|
+
return count === 0 ? null : { count, last: agentLock?.lastRenewError ?? lock.lastRenewError };
|
|
663
|
+
};
|
|
515
664
|
const offStatus = (handle) => writeIntegrationStatus(home, {
|
|
516
665
|
version: 2,
|
|
517
666
|
updated_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -519,6 +668,7 @@ async function runIntegration(opts) {
|
|
|
519
668
|
runtime: opts.runner.name,
|
|
520
669
|
handle,
|
|
521
670
|
profile,
|
|
671
|
+
workdir,
|
|
522
672
|
socket: disabled ? "off" : "idle",
|
|
523
673
|
wakes: 0,
|
|
524
674
|
wakes_absorbed: 0,
|
|
@@ -533,7 +683,11 @@ async function runIntegration(opts) {
|
|
|
533
683
|
retry_rung: 0,
|
|
534
684
|
retry_due_at: null,
|
|
535
685
|
last_error: lastFailure,
|
|
536
|
-
texts: null
|
|
686
|
+
texts: null,
|
|
687
|
+
standby,
|
|
688
|
+
runs_failing: unservable?.runsFailing ?? null,
|
|
689
|
+
unservable: unservable === null ? null : { reason: unservable.kind, detail: unservable.detail, since: unservable.since, retry_at: new Date(unservable.retryAt).toISOString() },
|
|
690
|
+
lease_errors: leaseErrors()
|
|
537
691
|
});
|
|
538
692
|
const disconnect = (why) => {
|
|
539
693
|
if (live === null) return;
|
|
@@ -541,18 +695,19 @@ async function runIntegration(opts) {
|
|
|
541
695
|
live.stop();
|
|
542
696
|
live = null;
|
|
543
697
|
liveFingerprint = null;
|
|
698
|
+
releaseAgent();
|
|
544
699
|
idle(home);
|
|
545
700
|
};
|
|
546
701
|
const shutdown = (sig) => {
|
|
547
702
|
if (shuttingDown) return;
|
|
548
703
|
shuttingDown = true;
|
|
704
|
+
stopChecks.abort();
|
|
549
705
|
log.info(`${sig} \u2014 shutting down`);
|
|
550
706
|
};
|
|
551
707
|
const onSigint = () => shutdown("SIGINT");
|
|
552
708
|
const onSigterm = () => shutdown("SIGTERM");
|
|
553
709
|
process.on("SIGINT", onSigint);
|
|
554
710
|
process.on("SIGTERM", onSigterm);
|
|
555
|
-
let nudged = false;
|
|
556
711
|
try {
|
|
557
712
|
fs.mkdirSync(home, { recursive: true });
|
|
558
713
|
const watcher = fs.watch(home, (_event, filename) => {
|
|
@@ -571,6 +726,9 @@ async function runIntegration(opts) {
|
|
|
571
726
|
log.info(`integration resident for ${home} (${credentialsPath(home)}) \u2014 ${opts.client.runtime} ${opts.client.version}`);
|
|
572
727
|
if (disabled) {
|
|
573
728
|
log.info(`${disabledBy}=off \u2014 holding no socket and starting no run; the hosted tools and the manual still work in every session`);
|
|
729
|
+
if (disabledBy === INTEGRATION_ENV_LEGACY) {
|
|
730
|
+
log.warn(`${INTEGRATION_ENV_LEGACY} is the old name of ${INTEGRATION_ENV} (agent contract v1 schedules its removal for ${INTEGRATION_ENV_LEGACY_REMOVAL}); set ${INTEGRATION_ENV}=off instead`);
|
|
731
|
+
}
|
|
574
732
|
}
|
|
575
733
|
idle(home);
|
|
576
734
|
offStatus(null);
|
|
@@ -578,19 +736,98 @@ async function runIntegration(opts) {
|
|
|
578
736
|
if (shuttingDown || opts.signal?.aborted) break;
|
|
579
737
|
const fp = fingerprint(home, envKey);
|
|
580
738
|
const identityChanged = fp !== observedFingerprint;
|
|
739
|
+
if (homeLost !== null) break;
|
|
581
740
|
if (identityChanged) {
|
|
582
741
|
disconnect(fp === null ? "signed out" : "identity changed");
|
|
583
742
|
observedFingerprint = fp;
|
|
584
743
|
failures = 0;
|
|
585
744
|
lastFailure = null;
|
|
745
|
+
stopWaiting();
|
|
746
|
+
standby = null;
|
|
747
|
+
unservable = null;
|
|
748
|
+
cachedCfg = null;
|
|
749
|
+
agentLockFile = null;
|
|
586
750
|
if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null);
|
|
587
751
|
}
|
|
588
752
|
if (fp === null) {
|
|
589
753
|
} else if (disabled) {
|
|
590
|
-
} else if (
|
|
754
|
+
} else if (live !== null && fp === liveFingerprint) {
|
|
755
|
+
const health = live.health();
|
|
756
|
+
if (agentLost !== null) {
|
|
757
|
+
const why = agentLost;
|
|
758
|
+
disconnect(`the agent lock is no longer this home's (${why})`);
|
|
759
|
+
lastFailure = `@${cachedCfg?.cfg.handle ?? "?"}: ${why}; another listener serves this agent now`;
|
|
760
|
+
} else if (!health.ok) {
|
|
761
|
+
const handle = cachedCfg?.cfg.handle ?? "?";
|
|
762
|
+
const kind = health.runsFailing === null ? "key_refused" : "runs_failing";
|
|
763
|
+
if (kind === "key_refused" || agentLockFile !== null && standbyWaiting(agentLockFile, home)) {
|
|
764
|
+
const retryMs = opts.unservableRecheckMs ?? (kind === "key_refused" ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS);
|
|
765
|
+
unservable = { kind, detail: health.reason, since: (/* @__PURE__ */ new Date()).toISOString(), retryAt: Date.now() + retryMs, runsFailing: health.runsFailing };
|
|
766
|
+
disconnect(`this home cannot serve @${handle} (${health.reason}): giving it up to ${kind === "key_refused" ? "any healthy listener" : "the healthy listener waiting for it"}`);
|
|
767
|
+
lastFailure = `this home cannot serve @${handle}: ${health.reason}. It holds no socket and starts no run while another listener can serve @${handle}; it looks again every ${Math.round(retryMs / 1e3)} s${kind === "runs_failing" ? " (the runtime checked first: a check that passes clears this)" : " (signing in again here clears this at once)"}, and takes @${handle} back whenever no other listener holds it.`;
|
|
768
|
+
log.warn(lastFailure);
|
|
769
|
+
offStatus(handle);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
} else if (live === null) {
|
|
591
773
|
try {
|
|
592
|
-
|
|
593
|
-
const
|
|
774
|
+
if (unservable !== null && Date.now() < unservable.retryAt) throw new StandbyError(unservable.detail);
|
|
775
|
+
const waiting = unservable;
|
|
776
|
+
if (waiting !== null && waiting.kind === "runs_failing" && lastRunner !== null) {
|
|
777
|
+
const before = waiting;
|
|
778
|
+
const checker = lastRunner;
|
|
779
|
+
const pre = await preflightOf(checker);
|
|
780
|
+
standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${checker.name}: ${pre.detail ?? "its check failed"}`, at: Date.now() };
|
|
781
|
+
if (shuttingDown || opts.signal?.aborted) throw new StandbyError("stopping");
|
|
782
|
+
if (pre.ok) unservable = null;
|
|
783
|
+
else unservable = { ...before, detail: `runs failing: ${checker.name}: ${pre.detail ?? "its check failed"}`, retryAt: Date.now() + (opts.unservableRecheckMs ?? UNSERVABLE_RECHECK_MS) };
|
|
784
|
+
}
|
|
785
|
+
if (cachedCfg === null || cachedCfg.fp !== fp) cachedCfg = { fp, cfg: await resolveDaemonConfig({ home, workdir, client: opts.client, envKey }) };
|
|
786
|
+
const cfg = cachedCfg.cfg;
|
|
787
|
+
agentLockFile = agentLockPath({ apiBase: cfg.apiBase, handle: cfg.handle });
|
|
788
|
+
const attempt = await acquireAgentLock({ apiBase: cfg.apiBase, handle: cfg.handle, home }, process.env, { ...opts.lease ?? {}, signal: stopChecks.signal });
|
|
789
|
+
if (shuttingDown || opts.signal?.aborted) {
|
|
790
|
+
if (attempt.ok) attempt.lease.release();
|
|
791
|
+
throw new StandbyError("stopping");
|
|
792
|
+
}
|
|
793
|
+
if (!attempt.ok) {
|
|
794
|
+
const current = unservable;
|
|
795
|
+
if (current !== null) {
|
|
796
|
+
unservable = { ...current, retryAt: Date.now() + (opts.unservableRecheckMs ?? (current.kind === "key_refused" ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS)) };
|
|
797
|
+
throw new StandbyError(current.detail);
|
|
798
|
+
}
|
|
799
|
+
standby = { home: attempt.holder?.home ?? null, pid: attempt.holder?.pid ?? null, since: attempt.holder?.acquired_at ?? null };
|
|
800
|
+
const recheckMs = opts.runtimeRecheckMs ?? RUNTIME_RECHECK_MS;
|
|
801
|
+
if (standbyCheck === null || standbyCheck.fp !== fp || Date.now() - standbyCheck.at >= recheckMs) {
|
|
802
|
+
const runner2 = runnerFor(cfg, fp);
|
|
803
|
+
const pre = await preflightOf(runner2);
|
|
804
|
+
if (shuttingDown || opts.signal?.aborted) throw new StandbyError("stopping");
|
|
805
|
+
standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${runner2.name}: ${pre.detail ?? "its check failed"}`, at: Date.now() };
|
|
806
|
+
}
|
|
807
|
+
if (standbyCheck.ok) markStandby(attempt.path, home);
|
|
808
|
+
else clearStandby(attempt.path, home);
|
|
809
|
+
const refusal = agentLockRefusal({ handle: cfg.handle, home }, attempt.holder, attempt.path);
|
|
810
|
+
const msg = standbyCheck.ok ? refusal : `${refusal} Its own runtime does not check out (${standbyCheck.detail ?? "its check failed"}), so it does not offer to take over from a holder whose runs fail.`;
|
|
811
|
+
if (msg !== lastFailure) log.warn(msg);
|
|
812
|
+
lastFailure = msg;
|
|
813
|
+
throw new StandbyError(msg);
|
|
814
|
+
}
|
|
815
|
+
stopWaiting();
|
|
816
|
+
if (standby !== null) log.info(`@${cfg.handle}: the other listener stopped; this one serves the agent now`);
|
|
817
|
+
if (unservable !== null) log.info(`@${cfg.handle}: no other listener holds the agent; this home serves it again (${unservable.detail})`);
|
|
818
|
+
standby = null;
|
|
819
|
+
unservable = null;
|
|
820
|
+
const lease = attempt.lease;
|
|
821
|
+
agentLock = lease;
|
|
822
|
+
lease.onLost((why) => {
|
|
823
|
+
if (agentLock !== lease) return;
|
|
824
|
+
agentLost = why;
|
|
825
|
+
nudged = true;
|
|
826
|
+
starting?.stop();
|
|
827
|
+
live?.stop();
|
|
828
|
+
});
|
|
829
|
+
const runner = runnerFor(cfg, fp);
|
|
830
|
+
lastRunner = runner;
|
|
594
831
|
const candidate = new Integration({
|
|
595
832
|
cfg,
|
|
596
833
|
runner,
|
|
@@ -599,31 +836,51 @@ async function runIntegration(opts) {
|
|
|
599
836
|
...opts.manualPath !== void 0 ? { manualPath: opts.manualPath } : {},
|
|
600
837
|
profile,
|
|
601
838
|
budgetMs,
|
|
602
|
-
...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}
|
|
839
|
+
...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {},
|
|
840
|
+
...opts.runtimeRecheckMs !== void 0 ? { runtimeRecheckMs: opts.runtimeRecheckMs } : {},
|
|
841
|
+
...opts.quietMs !== void 0 ? { quietMs: opts.quietMs } : {},
|
|
842
|
+
...opts.maxMs !== void 0 ? { maxMs: opts.maxMs } : {},
|
|
843
|
+
...opts.paceMs !== void 0 ? { paceMs: opts.paceMs } : {},
|
|
844
|
+
statusExtra: () => ({ lease_errors: leaseErrors() })
|
|
603
845
|
});
|
|
604
|
-
|
|
846
|
+
starting = candidate;
|
|
847
|
+
try {
|
|
848
|
+
await candidate.start();
|
|
849
|
+
} finally {
|
|
850
|
+
starting = null;
|
|
851
|
+
}
|
|
852
|
+
if (agentLost !== null || homeLost !== null) {
|
|
853
|
+
candidate.stop();
|
|
854
|
+
throw new StandbyError(`the agent lock is no longer this home's (${agentLost ?? homeLost})`);
|
|
855
|
+
}
|
|
605
856
|
live = candidate;
|
|
606
857
|
liveFingerprint = fp;
|
|
607
858
|
failures = 0;
|
|
608
859
|
lastFailure = null;
|
|
609
860
|
} catch (err) {
|
|
610
|
-
|
|
611
|
-
if (msg !== lastFailure) {
|
|
612
|
-
log.warn(`not connecting yet: ${msg}`);
|
|
613
|
-
lastFailure = msg;
|
|
614
|
-
offStatus(identityOf()?.handle ?? null);
|
|
615
|
-
}
|
|
616
|
-
failures += 1;
|
|
861
|
+
releaseAgent();
|
|
617
862
|
live = null;
|
|
618
863
|
liveFingerprint = null;
|
|
864
|
+
if (err instanceof StandbyError) {
|
|
865
|
+
offStatus(cachedCfg?.cfg.handle ?? identityOf()?.handle ?? null);
|
|
866
|
+
} else {
|
|
867
|
+
const msg = String(err instanceof Error ? err.message : err);
|
|
868
|
+
if (msg !== lastFailure) {
|
|
869
|
+
log.warn(`not connecting yet: ${msg}`);
|
|
870
|
+
lastFailure = msg;
|
|
871
|
+
offStatus(identityOf()?.handle ?? null);
|
|
872
|
+
}
|
|
873
|
+
failures += 1;
|
|
874
|
+
}
|
|
619
875
|
idle(home);
|
|
620
876
|
}
|
|
621
877
|
}
|
|
622
|
-
const
|
|
878
|
+
const pollMs = opts.pollMs ?? POLL_MS;
|
|
879
|
+
const waitMs = homeLost !== null || agentLost !== null ? 0 : standby !== null || unservable !== null ? opts.standbyPollMs ?? STANDBY_POLL_MS : failures === 0 ? pollMs : Math.min(pollMs * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS);
|
|
623
880
|
nudged = false;
|
|
624
881
|
const deadline = Date.now() + waitMs;
|
|
625
882
|
while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {
|
|
626
|
-
await
|
|
883
|
+
await sleepUnless(opts.tickMs ?? TICK_MS, opts.signal);
|
|
627
884
|
}
|
|
628
885
|
}
|
|
629
886
|
process.off("SIGINT", onSigint);
|
|
@@ -633,8 +890,11 @@ async function runIntegration(opts) {
|
|
|
633
890
|
if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1e3)}s of being interrupted \u2014 exiting anyway`);
|
|
634
891
|
live = null;
|
|
635
892
|
}
|
|
893
|
+
releaseAgent();
|
|
894
|
+
stopWaiting();
|
|
636
895
|
idle(home);
|
|
637
896
|
lock.release();
|
|
897
|
+
if (homeLost !== null) return 1;
|
|
638
898
|
if (shuttingDown) {
|
|
639
899
|
log.info("shutdown complete");
|
|
640
900
|
(opts.exit ?? process.exit)(0);
|