@parall/daemon 1.60.0 → 1.62.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/dist/config.d.ts CHANGED
@@ -28,8 +28,6 @@ export type ClaudeDaemonConfig = {
28
28
  swimlaneName?: string;
29
29
  /** @deprecated Superseded by WS event-driven model; kept for backward compat. */
30
30
  pollIntervalMs: number;
31
- /** @deprecated Superseded by WS event-driven model; kept for backward compat. */
32
- heartbeatIntervalMs: number;
33
31
  /** Backoff base after a subprocess crash, in ms. */
34
32
  restartBackoffMs: number;
35
33
  /** Hard cap on parallel restart attempts per agent before giving up for a cycle. */
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAe,MAAM,mBAAmB,CAAC;AAEnF,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,CAAC;AAE7C;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,qCAAqC;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,2GAA2G;IAC3G,QAAQ,EAAE,MAAM,CAAC;IACjB,yFAAyF;IACzF,YAAY,EAAE,MAAM,CAAC;IACrB,kGAAkG;IAClG,cAAc,EAAE,MAAM,CAAC;IACvB,wEAAwE;IACxE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oDAAoD;IACpD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iFAAiF;IACjF,cAAc,EAAE,MAAM,CAAC;IACvB,iFAAiF;IACjF,mBAAmB,EAAE,MAAM,CAAC;IAC5B,oDAAoD;IACpD,gBAAgB,EAAE,MAAM,CAAC;IACzB,oFAAoF;IACpF,mBAAmB,EAAE,MAAM,CAAC;IAC5B;;;;;OAKG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAC3B,qBAAqB,EAAE,MAAM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E;AA+BD,wBAAgB,yBAAyB,CACvC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,kBAAkB,CA8DpB;AASD,wDAAwD;AACxD,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE9E;AAED;;mEAEmE;AACnE,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAElF;AAED,+EAA+E;AAC/E,wBAAgB,8BAA8B,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED,uEAAuE;AACvE,wBAAgB,6BAA6B,CAAC,eAAe,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED,iEAAiE;AACjE,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAElF;AAED,8EAA8E;AAC9E,wBAAgB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAEzF;AAED,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,aAAa,CAAC,EAAE,MAAM,EACtB,YAAY,CAAC,EAAE,MAAM,GACpB,MAAM,CAMR"}
package/dist/config.js CHANGED
@@ -80,7 +80,6 @@ export function resolveClaudeDaemonConfig(env = process.env) {
80
80
  wsUrl: env.PRLL_WS_URL?.trim() || undefined,
81
81
  swimlaneName: env.PRLL_SWIMLANE_NAME?.trim() || undefined,
82
82
  pollIntervalMs: parseMs(env.PRLL_DAEMON_POLL_INTERVAL_MS, 30_000),
83
- heartbeatIntervalMs: parseMs(env.PRLL_DAEMON_HEARTBEAT_INTERVAL_MS, 30_000),
84
83
  restartBackoffMs: parseMs(env.PRLL_DAEMON_RESTART_BACKOFF_MS, 5_000),
85
84
  restartBackoffMaxMs: parseMs(env.PRLL_DAEMON_RESTART_BACKOFF_MAX_MS, 5 * 60_000),
86
85
  bootstrapBackoffMs: parseMsAllowZero(env.PRLL_DAEMON_BOOTSTRAP_BACKOFF_MS, 2_000),
@@ -1 +1 @@
1
- {"version":3,"file":"daemon-main.d.ts","sourceRoot":"","sources":["../src/daemon-main.ts"],"names":[],"mappings":";AA2BA,MAAM,MAAM,oBAAoB,GAAG;IACjC,sBAAsB,EAAE,OAAO,CAAC;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,OAAO,CAAC;CAC1B,CAAC;AAqLF,wBAAsB,cAAc,CAClC,SAAS,EAAE,oBAAoB,EAC/B,IAAI,WAAwB,GAC3B,OAAO,CAAC,IAAI,CAAC,CASf"}
1
+ {"version":3,"file":"daemon-main.d.ts","sourceRoot":"","sources":["../src/daemon-main.ts"],"names":[],"mappings":";AA+BA,MAAM,MAAM,oBAAoB,GAAG;IACjC,sBAAsB,EAAE,OAAO,CAAC;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,OAAO,CAAC;CAC1B,CAAC;AAiNF,wBAAsB,cAAc,CAClC,SAAS,EAAE,oBAAoB,EAC/B,IAAI,WAAwB,GAC3B,OAAO,CAAC,IAAI,CAAC,CASf"}
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { configureHttpKeepAlive, createLogger, createOtelLogger, initAgentTelemetry, resolveServiceVersion, } from '@parall/agent-core';
2
+ import { configureHttpKeepAlive, createLogger, createOtelLogger, initAgentTelemetry, resolveServiceVersion, traceContextHeaders, } from '@parall/agent-core';
3
3
  import { ParallClient } from '@parall/sdk';
4
4
  import { runCLI } from './cli.js';
5
- import { resolveBundleDir, resolveClaudeDaemonConfig, resolveWsUrl, } from './config.js';
5
+ import * as path from 'node:path';
6
+ import { daemonConfigDir, resolveBundleDir, resolveClaudeDaemonConfig, resolveWsUrl, } from './config.js';
7
+ import { DaemonTelemetry, proxyEnvNames } from './daemon-telemetry.js';
6
8
  import { isSelfUpdateManaged } from './daemon-update-mode.js';
7
9
  import { DaemonSupervisor, sleepCancellable } from './supervisor.js';
8
10
  import { DaemonUpdater } from './updater.js';
@@ -34,7 +36,7 @@ function formatError(reason) {
34
36
  * any supervisor.run() rejection and rely entirely on the shell wrapper +
35
37
  * K8s for restart.
36
38
  */
37
- async function runForever(config, client, log, signal, updater, gate) {
39
+ async function runForever(config, client, log, signal, updater, gate, daemonTelemetry) {
38
40
  let attempt = 0;
39
41
  while (!signal.aborted) {
40
42
  const supervisor = new DaemonSupervisor(config, client, log);
@@ -42,6 +44,8 @@ async function runForever(config, client, log, signal, updater, gate) {
42
44
  supervisor.setUpdater(updater);
43
45
  if (gate)
44
46
  supervisor.setHealthGate(gate);
47
+ if (daemonTelemetry)
48
+ supervisor.setDaemonTelemetry(daemonTelemetry);
45
49
  try {
46
50
  await supervisor.run(signal);
47
51
  // Clean exit (signal aborted) — done.
@@ -85,10 +89,21 @@ async function main(bootstrap) {
85
89
  apiUrl: config.apiUrl,
86
90
  apiKey: config.apiKey,
87
91
  serviceVersion: resolveServiceVersion(import.meta.url),
92
+ // Batches that fail to export while the machine is offline wait here
93
+ // and replay later; the bridges get their own directory via env.
94
+ spoolDir: path.join(daemonConfigDir(process.env), 'otel-spool', 'daemon'),
88
95
  });
89
96
  log = createOtelLogger('daemon', 'daemon');
90
- log.info(`boot: api=${config.apiUrl} pollMs=${config.pollIntervalMs} heartbeatMs=${config.heartbeatIntervalMs} agentBin=${config.agentBin}`);
97
+ // Process-level (survives supervisor in-process restarts); constructed only
98
+ // now because the metrics API resolves its provider at getMeter time.
99
+ const daemonTelemetry = new DaemonTelemetry({ log });
100
+ daemonTelemetry.start();
101
+ log.info(`boot: api=${config.apiUrl} pollMs=${config.pollIntervalMs} agentBin=${config.agentBin}`);
91
102
  log.info(`keepalive: bootstrapBackoffMs=${config.bootstrapBackoffMs} supervisorRestartBackoffMs=${config.supervisorRestartBackoffMs}`);
103
+ // Names only — a proxy URL carries credentials. The daemon's own egress
104
+ // does not honor these; knowing they exist explains a machine that can
105
+ // reach the API only through a corporate proxy.
106
+ log.info(`proxy env: ${proxyEnvNames(process.env).join(',') || 'none'}`);
92
107
  // --- Self-update: rollback check (before any network calls) ---
93
108
  // Only run when a service manager supervises us (see isSelfUpdateManaged):
94
109
  // a bare `npx` foreground run can't load the overlay and won't be restarted
@@ -100,6 +115,7 @@ async function main(bootstrap) {
100
115
  if (selfUpdateEnabled) {
101
116
  const signingEnabled = true;
102
117
  updater = new DaemonUpdater(bundleDir, config.updateCdnUrl, log, signingEnabled);
118
+ updater.setOutcomeReporter((outcome, reason) => daemonTelemetry.recordUpdateOutcome(outcome, reason));
103
119
  // Process-level canary gate: machine.hello arms a stability window; the
104
120
  // version is confirmed only if the process stays up through it. Owned here
105
121
  // (not in the supervisor) so it survives supervisor in-process restarts.
@@ -109,6 +125,7 @@ async function main(bootstrap) {
109
125
  // daemon app startup path while still letting updater.ts stay mechanism-only.
110
126
  if (updater.checkRollback(bootstrap.uncleanPrevExit)) {
111
127
  log.info('rollback applied — exiting for service manager restart');
128
+ daemonTelemetry.stop();
112
129
  await telemetry.shutdown();
113
130
  process.exit(UPDATE_EXIT_CODE);
114
131
  }
@@ -124,6 +141,7 @@ async function main(bootstrap) {
124
141
  baseUrl: config.apiUrl,
125
142
  token: config.apiKey,
126
143
  swimlaneName: config.swimlaneName,
144
+ getRequestHeaders: traceContextHeaders,
127
145
  });
128
146
  const abortController = new AbortController();
129
147
  const onSignal = (sig) => {
@@ -152,12 +170,14 @@ async function main(bootstrap) {
152
170
  });
153
171
  if (applied) {
154
172
  log.info('boot update applied — exiting for restart');
173
+ daemonTelemetry.stop();
155
174
  await telemetry.shutdown();
156
175
  process.exit(UPDATE_EXIT_CODE);
157
176
  }
158
177
  updater.startPeriodicCheck(config.updateIntervalMs);
159
178
  }
160
- await runForever(config, client, log, abortController.signal, updater, healthGate);
179
+ await runForever(config, client, log, abortController.signal, updater, healthGate, daemonTelemetry);
180
+ daemonTelemetry.stop();
161
181
  await telemetry.shutdown();
162
182
  }
163
183
  export async function runDaemonEntry(bootstrap, args = process.argv.slice(2)) {
@@ -0,0 +1,83 @@
1
+ import { type Meter } from '@opentelemetry/api';
2
+ import type { GatewayLogger } from '@parall/agent-core';
3
+ /**
4
+ * The daemon's own runtime facts as OpenTelemetry metrics (SigNoz is the
5
+ * consumer; nothing here is sent to the api-server or persisted). Every
6
+ * attribute value is drawn from a closed set defined in this file.
7
+ */
8
+ export type ChildExitKind = 'clean' | 'crash' | 'signal' | 'spawn_error';
9
+ export type UpdateOutcome = 'applied' | 'failed' | 'skipped' | 'rolled_back' | 'confirmed';
10
+ export type UpdateReason = 'pending_activation' | 'previously_rolled_back' | 'node_version' | 'node_version_invalid' | 'manifest_fetch' | 'manifest_parse' | 'signing_key_missing' | 'signature' | 'download' | 'sha256_mismatch' | 'size_mismatch' | 'exception' | 'boot_threshold';
11
+ export type ClockGapKind = 'sleep' | 'stall';
12
+ /** Which proxy variables are set — names only; the values are never logged. */
13
+ export declare function proxyEnvNames(env: NodeJS.ProcessEnv): string[];
14
+ /** `server_time` from machine.hello minus the local clock at receipt; null when unparseable. */
15
+ export declare function computeClockSkewMs(serverTime: string, nowMs: number): number | null;
16
+ export declare function classifyChildExit(code: number | null, signal: NodeJS.Signals | null, err?: Error): ChildExitKind;
17
+ export interface ClockSample {
18
+ wall: number;
19
+ mono: number;
20
+ }
21
+ /**
22
+ * Compare two consecutive ticks of a wall clock and a monotonic clock. The
23
+ * monotonic clock pauses while the machine sleeps, so wall advancing far
24
+ * beyond it is a sleep (or an NTP step — advisory, not proof); both
25
+ * advancing far beyond the interval is an event-loop stall.
26
+ */
27
+ export declare function classifyTick(prev: ClockSample, cur: ClockSample, intervalMs: number): {
28
+ kind: ClockGapKind;
29
+ gapMs: number;
30
+ } | null;
31
+ type TimerHandle = {
32
+ unref?: () => void;
33
+ };
34
+ export interface TimerApi {
35
+ setInterval(callback: () => void, ms: number): TimerHandle;
36
+ clearInterval(handle: TimerHandle): void;
37
+ }
38
+ export interface DaemonTelemetryDeps {
39
+ log: GatewayLogger;
40
+ /**
41
+ * Defaults to the global `parall.daemon` meter. The metrics API has no
42
+ * lazy proxy: construct this after `initAgentTelemetry`, or every
43
+ * instrument stays a no-op for the life of the process.
44
+ */
45
+ meter?: Meter;
46
+ now?: () => number;
47
+ mono?: () => number;
48
+ uptimeSeconds?: () => number;
49
+ timers?: TimerApi;
50
+ tickMs?: number;
51
+ }
52
+ export declare class DaemonTelemetry {
53
+ private readonly log;
54
+ private readonly now;
55
+ private readonly mono;
56
+ private readonly timers;
57
+ private readonly tickMs;
58
+ private readonly childExit;
59
+ private readonly update;
60
+ private readonly wsReconnect;
61
+ private readonly wakeGap;
62
+ private lastSkewMs;
63
+ private lastTick;
64
+ private timer;
65
+ constructor(deps: DaemonTelemetryDeps);
66
+ /** Start the sleep/stall detector. */
67
+ start(): void;
68
+ stop(): void;
69
+ recordChildExit(a: {
70
+ runtimeType: string;
71
+ exitKind: ChildExitKind;
72
+ restart: boolean;
73
+ }): void;
74
+ recordUpdateOutcome(outcome: UpdateOutcome, reason?: UpdateReason): void;
75
+ recordWsReconnect(a: {
76
+ cause?: string;
77
+ closeCode?: number;
78
+ }): void;
79
+ recordClockSkew(ms: number): void;
80
+ private tick;
81
+ }
82
+ export {};
83
+ //# sourceMappingURL=daemon-telemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daemon-telemetry.d.ts","sourceRoot":"","sources":["../src/daemon-telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,KAAK,EAAW,MAAM,oBAAoB,CAAC;AACvF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD;;;;GAIG;AAEH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ,GAAG,aAAa,CAAC;AACzE,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,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AAG,IAAI;IAOlE,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAIjC,OAAO,CAAC,IAAI;CAeb"}
@@ -0,0 +1,143 @@
1
+ import { metrics } from '@opentelemetry/api';
2
+ const PROXY_ENV_NAMES = ['HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY'];
3
+ const DEFAULT_TICK_MS = 30_000;
4
+ /** Which proxy variables are set — names only; the values are never logged. */
5
+ export function proxyEnvNames(env) {
6
+ const names = [];
7
+ for (const upper of PROXY_ENV_NAMES) {
8
+ for (const name of [upper, upper.toLowerCase()]) {
9
+ if (env[name]?.trim())
10
+ names.push(name);
11
+ }
12
+ }
13
+ return names;
14
+ }
15
+ /** `server_time` from machine.hello minus the local clock at receipt; null when unparseable. */
16
+ export function computeClockSkewMs(serverTime, nowMs) {
17
+ const parsed = Date.parse(serverTime);
18
+ return Number.isFinite(parsed) ? parsed - nowMs : null;
19
+ }
20
+ export function classifyChildExit(code, signal, err) {
21
+ if (err)
22
+ return 'spawn_error';
23
+ if (signal)
24
+ return 'signal';
25
+ return code === 0 ? 'clean' : 'crash';
26
+ }
27
+ /**
28
+ * Compare two consecutive ticks of a wall clock and a monotonic clock. The
29
+ * monotonic clock pauses while the machine sleeps, so wall advancing far
30
+ * beyond it is a sleep (or an NTP step — advisory, not proof); both
31
+ * advancing far beyond the interval is an event-loop stall.
32
+ */
33
+ export function classifyTick(prev, cur, intervalMs) {
34
+ const wallDelta = cur.wall - prev.wall;
35
+ const monoDelta = cur.mono - prev.mono;
36
+ if (wallDelta - monoDelta > intervalMs)
37
+ return { kind: 'sleep', gapMs: wallDelta - monoDelta };
38
+ if (monoDelta > 2 * intervalMs)
39
+ return { kind: 'stall', gapMs: monoDelta - intervalMs };
40
+ return null;
41
+ }
42
+ const realTimers = {
43
+ setInterval: (callback, ms) => setInterval(callback, ms),
44
+ clearInterval: (handle) => clearInterval(handle),
45
+ };
46
+ export class DaemonTelemetry {
47
+ log;
48
+ now;
49
+ mono;
50
+ timers;
51
+ tickMs;
52
+ childExit;
53
+ update;
54
+ wsReconnect;
55
+ wakeGap;
56
+ lastSkewMs = null;
57
+ lastTick = null;
58
+ timer = null;
59
+ constructor(deps) {
60
+ this.log = deps.log;
61
+ this.now = deps.now ?? Date.now;
62
+ this.mono = deps.mono ?? (() => performance.now());
63
+ this.timers = deps.timers ?? realTimers;
64
+ this.tickMs = deps.tickMs ?? DEFAULT_TICK_MS;
65
+ const meter = deps.meter ?? metrics.getMeter('parall.daemon');
66
+ const uptimeSeconds = deps.uptimeSeconds ?? (() => process.uptime());
67
+ this.childExit = meter.createCounter('parall.daemon.child_exit', {
68
+ description: 'Bridge child process exits, by kind and whether the daemon restarts it',
69
+ });
70
+ this.update = meter.createCounter('parall.daemon.update', {
71
+ description: 'Self-update outcomes, by outcome and reason',
72
+ });
73
+ this.wsReconnect = meter.createCounter('parall.daemon.ws_reconnect', {
74
+ description: 'Machine WebSocket reconnect attempts, by disconnect cause',
75
+ });
76
+ this.wakeGap = meter.createHistogram('parall.daemon.wake_gap', {
77
+ description: 'Gaps between daemon ticks: machine sleep or event-loop stall',
78
+ unit: 's',
79
+ });
80
+ meter
81
+ .createObservableGauge('parall.daemon.uptime', {
82
+ description: 'Seconds since the daemon process started',
83
+ unit: 's',
84
+ })
85
+ .addCallback((result) => result.observe(uptimeSeconds()));
86
+ meter
87
+ .createObservableGauge('parall.daemon.clock_skew_ms', {
88
+ description: 'Server time minus local time at the last machine.hello',
89
+ unit: 'ms',
90
+ })
91
+ .addCallback((result) => {
92
+ if (this.lastSkewMs !== null)
93
+ result.observe(this.lastSkewMs);
94
+ });
95
+ }
96
+ /** Start the sleep/stall detector. */
97
+ start() {
98
+ if (this.timer)
99
+ return;
100
+ this.lastTick = { wall: this.now(), mono: this.mono() };
101
+ this.timer = this.timers.setInterval(() => this.tick(), this.tickMs);
102
+ this.timer.unref?.();
103
+ }
104
+ stop() {
105
+ if (this.timer)
106
+ this.timers.clearInterval(this.timer);
107
+ this.timer = null;
108
+ }
109
+ recordChildExit(a) {
110
+ this.childExit.add(1, {
111
+ runtime_type: a.runtimeType,
112
+ exit_kind: a.exitKind,
113
+ restart: a.restart,
114
+ });
115
+ }
116
+ recordUpdateOutcome(outcome, reason) {
117
+ this.update.add(1, { outcome, ...(reason ? { reason } : {}) });
118
+ }
119
+ recordWsReconnect(a) {
120
+ this.wsReconnect.add(1, {
121
+ cause: a.cause ?? 'unknown',
122
+ ...(a.closeCode !== undefined ? { close_code: String(a.closeCode) } : {}),
123
+ });
124
+ }
125
+ recordClockSkew(ms) {
126
+ this.lastSkewMs = ms;
127
+ }
128
+ tick() {
129
+ const cur = { wall: this.now(), mono: this.mono() };
130
+ const prev = this.lastTick;
131
+ this.lastTick = cur;
132
+ if (!prev)
133
+ return;
134
+ const gap = classifyTick(prev, cur, this.tickMs);
135
+ if (!gap)
136
+ return;
137
+ const seconds = Math.round(gap.gapMs / 1000);
138
+ this.wakeGap.record(gap.gapMs / 1000, { kind: gap.kind });
139
+ this.log.warn(gap.kind === 'sleep'
140
+ ? `clock gap: ~${seconds}s while the process was not running (machine asleep, or the clock stepped)`
141
+ : `clock gap: ~${seconds}s event-loop stall`);
142
+ }
143
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * How each launch failure shape is reported to the platform
3
+ * (agent-health-alerting-design.md §4.6).
4
+ *
5
+ * The daemon is the only place that can see WHY an agent process failed to
6
+ * come up, and the server's readiness derivation only treats a report as a
7
+ * failed launch when it is `failed`, or `backoff` deep enough to have
8
+ * crossed `model.LaunchFailedAttempts`. Getting that distinction wrong makes
9
+ * a real failure look like a plain "not connected", so the decision lives
10
+ * here as named cases rather than inline at each call site in the
11
+ * supervisor.
12
+ */
13
+ import type { LaunchStateInput } from './launch-state.js';
14
+ /** Spawn is starting: clears any previous failure once it succeeds. */
15
+ export declare function launchingReport(attempts: number): LaunchStateInput;
16
+ /** The child has been alive long enough to count as up. */
17
+ export declare function runningReport(): LaunchStateInput;
18
+ /**
19
+ * The credential request failed on the INITIAL spawn. Nothing retries this
20
+ * path — the agent stays down until the next reconcile or attach event — so
21
+ * it is a failed launch, not a backoff (a backoff at attempt 0 would never
22
+ * become visible).
23
+ */
24
+ export declare function mintFailedReport(err: unknown): LaunchStateInput;
25
+ /**
26
+ * The credential request failed while RESTARTING. This path does retry on
27
+ * the backoff curve, so it reports the same shape the crash loop does: a
28
+ * growing attempt count that becomes visible once it is deep enough, and an
29
+ * outright failure when no retry was scheduled.
30
+ */
31
+ export declare function restartMintFailedReport(err: unknown, attempts: number, retrying: boolean): LaunchStateInput;
32
+ /** Workspace preparation threw before the process existed. */
33
+ export declare function workspaceFailedReport(err: unknown): LaunchStateInput;
34
+ /** Restart reached startChild without a credential — a bug, but a visible one. */
35
+ export declare function missingCredentialReport(attempts: number): LaunchStateInput;
36
+ /**
37
+ * The child exited. `err` set means the spawn itself failed (ENOENT and
38
+ * friends); otherwise the exit code and signal describe it. A backoff this
39
+ * deep counts as failed.
40
+ */
41
+ export declare function childExitReport(opts: {
42
+ err?: Error;
43
+ attempts: number;
44
+ failedAttempts: number;
45
+ code: number | null;
46
+ signal: NodeJS.Signals | null;
47
+ outputTail?: string;
48
+ }): LaunchStateInput;
49
+ //# sourceMappingURL=launch-lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch-lifecycle.d.ts","sourceRoot":"","sources":["../src/launch-lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAE1D,uEAAuE;AACvE,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,CAElE;AAED,2DAA2D;AAC3D,wBAAgB,aAAa,IAAI,gBAAgB,CAEhD;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,gBAAgB,CAM/D;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,OAAO,EACZ,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,OAAO,GAChB,gBAAgB,CAMlB;AAED,8DAA8D;AAC9D,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,gBAAgB,CAEpE;AAED,kFAAkF;AAClF,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,CAM1E;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE;IACpC,GAAG,CAAC,EAAE,KAAK,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,gBAAgB,CAYnB"}
@@ -0,0 +1,64 @@
1
+ /** Spawn is starting: clears any previous failure once it succeeds. */
2
+ export function launchingReport(attempts) {
3
+ return { status: 'launching', attempts };
4
+ }
5
+ /** The child has been alive long enough to count as up. */
6
+ export function runningReport() {
7
+ return { status: 'running', attempts: 0 };
8
+ }
9
+ /**
10
+ * The credential request failed on the INITIAL spawn. Nothing retries this
11
+ * path — the agent stays down until the next reconcile or attach event — so
12
+ * it is a failed launch, not a backoff (a backoff at attempt 0 would never
13
+ * become visible).
14
+ */
15
+ export function mintFailedReport(err) {
16
+ return {
17
+ status: 'failed',
18
+ attempts: 0,
19
+ lastError: `launch credential request failed: ${String(err)}`,
20
+ };
21
+ }
22
+ /**
23
+ * The credential request failed while RESTARTING. This path does retry on
24
+ * the backoff curve, so it reports the same shape the crash loop does: a
25
+ * growing attempt count that becomes visible once it is deep enough, and an
26
+ * outright failure when no retry was scheduled.
27
+ */
28
+ export function restartMintFailedReport(err, attempts, retrying) {
29
+ return {
30
+ status: retrying ? 'backoff' : 'failed',
31
+ attempts,
32
+ lastError: `launch credential request failed: ${String(err)}`,
33
+ };
34
+ }
35
+ /** Workspace preparation threw before the process existed. */
36
+ export function workspaceFailedReport(err) {
37
+ return { status: 'failed', attempts: 0, lastError: `workspace setup failed: ${String(err)}` };
38
+ }
39
+ /** Restart reached startChild without a credential — a bug, but a visible one. */
40
+ export function missingCredentialReport(attempts) {
41
+ return {
42
+ status: 'failed',
43
+ attempts,
44
+ lastError: 'no launch credential available for the agent process',
45
+ };
46
+ }
47
+ /**
48
+ * The child exited. `err` set means the spawn itself failed (ENOENT and
49
+ * friends); otherwise the exit code and signal describe it. A backoff this
50
+ * deep counts as failed.
51
+ */
52
+ export function childExitReport(opts) {
53
+ const failed = opts.err !== undefined || opts.attempts >= opts.failedAttempts;
54
+ return {
55
+ status: failed ? 'failed' : 'backoff',
56
+ attempts: opts.attempts,
57
+ lastExitCode: opts.code,
58
+ lastSignal: opts.signal,
59
+ lastError: opts.err
60
+ ? String(opts.err.message ?? opts.err)
61
+ : `exited with code ${opts.code ?? 'null'} signal ${opts.signal ?? 'null'}`,
62
+ ...(opts.outputTail ? { outputTail: opts.outputTail } : {}),
63
+ };
64
+ }
@@ -0,0 +1,72 @@
1
+ import type { AgentLaunchReportStatus, AgentLaunchStateReport } from '@parall/sdk';
2
+ export declare const LAUNCH_REPLAY_INTERVAL_MS: number;
3
+ /** How much stderr tail travels with a backoff / failed report. */
4
+ export declare const LAUNCH_OUTPUT_TAIL_BYTES = 4096;
5
+ /**
6
+ * Backoff depth at which a still-restarting launch is reported as failed.
7
+ * Deliberately higher than the server's `model.LaunchFailedAttempts` (3),
8
+ * which already treats a backoff that deep as failed for readiness and
9
+ * alerting: the user is warned while the daemon is still retrying. Changing
10
+ * one without the other widens or collapses that early-warning window.
11
+ */
12
+ export declare const LAUNCH_FAILED_ATTEMPTS = 5;
13
+ /**
14
+ * A ULID (26 chars, Crockford base32): 48-bit millisecond timestamp + 80
15
+ * random bits. The server compares two daemon instances by the timestamp
16
+ * component, so the time prefix is the contract — not just uniqueness.
17
+ */
18
+ export declare function newDaemonInstanceId(now?: number, random?: () => number): string;
19
+ /** Decode the millisecond timestamp of a ULID minted by newDaemonInstanceId. */
20
+ export declare function daemonInstanceTimestamp(id: string): number;
21
+ /** Fixed-size tail buffer for a child's stderr — never blocks the child. */
22
+ export declare class OutputTail {
23
+ private readonly limit;
24
+ private chunks;
25
+ private size;
26
+ constructor(limit?: number);
27
+ push(chunk: Buffer | string): void;
28
+ text(): string;
29
+ reset(): void;
30
+ }
31
+ export interface LaunchStateInput {
32
+ status: AgentLaunchReportStatus;
33
+ attempts: number;
34
+ lastExitCode?: number | null;
35
+ lastSignal?: string | null;
36
+ lastError?: string | null;
37
+ outputTail?: string | null;
38
+ }
39
+ export interface LaunchStateClient {
40
+ reportAgentLaunchState(agentId: string, report: AgentLaunchStateReport): Promise<void>;
41
+ }
42
+ export interface LaunchStateLogger {
43
+ warn(msg: string): void;
44
+ }
45
+ /**
46
+ * Tracks the last reported state per agent, sends on change, replays on
47
+ * demand. Reports are best-effort: a failed send is logged and the next
48
+ * change (or replay) carries the current truth.
49
+ */
50
+ export declare class LaunchStateReporter {
51
+ private readonly client;
52
+ private readonly log;
53
+ readonly instanceId: string;
54
+ private seq;
55
+ private readonly current;
56
+ private readonly redactValues;
57
+ constructor(client: LaunchStateClient, log: LaunchStateLogger, opts?: {
58
+ instanceId?: string;
59
+ redactValues?: string[];
60
+ });
61
+ /** Report a state; a no-op when nothing changed since the last report. */
62
+ update(agentId: string, next: LaunchStateInput): Promise<void>;
63
+ /** Forget an agent (detached / shut down) so replays stop mentioning it. */
64
+ forget(agentId: string): void;
65
+ /** Re-send every current state (boot, reconnect, periodic). */
66
+ replayAll(): Promise<void>;
67
+ /** Current in-memory view (tests, diagnostics). */
68
+ snapshot(agentId: string): LaunchStateInput | undefined;
69
+ private send;
70
+ private clean;
71
+ }
72
+ //# sourceMappingURL=launch-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch-state.d.ts","sourceRoot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