@senpi/runtime 3.0.221 → 3.0.223
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/actions/action-runtime-module.d.ts.map +1 -1
- package/dist/actions/action-runtime-module.js +1 -0
- package/dist/actions/action-runtime-module.js.map +1 -1
- package/dist/cli/senpi-commands.js +1 -1
- package/dist/cli/senpi-commands.js.map +1 -1
- package/dist/health/index.d.ts.map +1 -1
- package/dist/health/index.js +2 -1
- package/dist/health/index.js.map +1 -1
- package/dist/health/types.d.ts +1 -1
- package/dist/health/types.d.ts.map +1 -1
- package/dist/health/types.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -1
- package/dist/runtime/boot-skip.d.ts +3 -0
- package/dist/runtime/boot-skip.d.ts.map +1 -1
- package/dist/runtime/boot-skip.js +7 -2
- package/dist/runtime/boot-skip.js.map +1 -1
- package/dist/runtime/lifecycle-reaper.d.ts +16 -2
- package/dist/runtime/lifecycle-reaper.d.ts.map +1 -1
- package/dist/runtime/lifecycle-reaper.js +71 -11
- package/dist/runtime/lifecycle-reaper.js.map +1 -1
- package/dist/runtime-api/intake/scanner-launcher.d.ts +17 -0
- package/dist/runtime-api/intake/scanner-launcher.d.ts.map +1 -1
- package/dist/runtime-api/intake/scanner-launcher.js +339 -246
- package/dist/runtime-api/intake/scanner-launcher.js.map +1 -1
- package/dist/scanners/runtime-module.d.ts.map +1 -1
- package/dist/scanners/runtime-module.js +9 -2
- package/dist/scanners/runtime-module.js.map +1 -1
- package/dist/scanners/supervision.d.ts +3 -2
- package/dist/scanners/supervision.d.ts.map +1 -1
- package/dist/senpi/__tests__/helpers/fake-paper-mcp.d.ts +2 -0
- package/dist/senpi/__tests__/helpers/fake-paper-mcp.d.ts.map +1 -1
- package/dist/senpi/__tests__/helpers/fake-paper-mcp.js +1 -0
- package/dist/senpi/__tests__/helpers/fake-paper-mcp.js.map +1 -1
- package/dist/senpi/client.d.ts.map +1 -1
- package/dist/senpi/client.js +1 -0
- package/dist/senpi/client.js.map +1 -1
- package/dist/senpi/types.d.ts +2 -0
- package/dist/senpi/types.d.ts.map +1 -1
- package/dist/utils/event-catalog.d.ts +1 -1
- package/dist/utils/event-catalog.d.ts.map +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
|
@@ -19,6 +19,7 @@ import { emitEvent } from "../../actions/event-derivation.js";
|
|
|
19
19
|
import { buildScannerLifecycleEvent, buildScannerLaunchFailedEvent, recordScannerLifecycleMetrics, stoppedForSizeReason, } from "./supervisor-events.js";
|
|
20
20
|
import { walletMode } from "../../senpi/paper.js";
|
|
21
21
|
import { clearSizeStop, holds, readSizeStop, scannerCodeDigest, sizeStopRecord, writeSizeStop, } from "./size-stop.js";
|
|
22
|
+
const OUT_OF_CREDITS = "out_of_credits";
|
|
22
23
|
// ── ScannerLauncher ────────────────────────────────────────────────────────────
|
|
23
24
|
export class ScannerLauncher {
|
|
24
25
|
deps;
|
|
@@ -29,6 +30,10 @@ export class ScannerLauncher {
|
|
|
29
30
|
* called after eager wiring.
|
|
30
31
|
*/
|
|
31
32
|
_initialized = false;
|
|
33
|
+
started = false;
|
|
34
|
+
stopped = false;
|
|
35
|
+
pausing = Promise.resolve();
|
|
36
|
+
simulationPauseReason = null;
|
|
32
37
|
constructor(rawDeps) {
|
|
33
38
|
this.deps = rawDeps;
|
|
34
39
|
}
|
|
@@ -46,253 +51,15 @@ export class ScannerLauncher {
|
|
|
46
51
|
_buildAndRegister() {
|
|
47
52
|
if (this._initialized)
|
|
48
53
|
return;
|
|
49
|
-
const {
|
|
50
|
-
// Resolve MCP creds: explicit deps win, else fall back to process.env.
|
|
51
|
-
// Empty/absent values are dropped so we never inject a misleading "".
|
|
52
|
-
const senpiApiKey = this.deps.senpiApiKey ||
|
|
53
|
-
process.env.SENPI_AUTH_TOKEN ||
|
|
54
|
-
process.env.SENPI_API_KEY ||
|
|
55
|
-
undefined;
|
|
56
|
-
const senpiMcpUrl = this.deps.senpiMcpUrl || process.env.SENPI_MCP_URL || undefined;
|
|
57
|
-
const mintScannerId = this.deps.mintScannerId ?? (() => makeId("scanner"));
|
|
58
|
-
const createSupervisor = this.deps.createSupervisor ??
|
|
59
|
-
((spec, lg) => new LongRunningSupervisor(spec, lg));
|
|
60
|
-
const onSupervisorEvent = this.deps.onSupervisorEvent;
|
|
61
|
-
const simulation = walletMode(wallet) === "paper";
|
|
54
|
+
const { scanners, registry, logger, wallet } = this.deps;
|
|
62
55
|
// Track ids registered in this call so we can roll back on partial failure.
|
|
63
56
|
const registeredInThisCall = [];
|
|
64
57
|
// The scanner being wired when a failure throws — names it on the launch-failed event.
|
|
65
58
|
let failingScanner;
|
|
66
59
|
try {
|
|
67
60
|
for (let i = 0; i < scanners.length; i++) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (!scanner.path) {
|
|
71
|
-
throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "path"`);
|
|
72
|
-
}
|
|
73
|
-
if (!scanner.entrypoint) {
|
|
74
|
-
throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "entrypoint"`);
|
|
75
|
-
}
|
|
76
|
-
const safeName = scanner.name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
77
|
-
// Include the scanner's array index so two scanners that share a name (or
|
|
78
|
-
// whose names sanitize to the same string) never share a state directory
|
|
79
|
-
// or delivery journal. The index is stable across relaunch (same config
|
|
80
|
-
// position), so state and the journal survive a restart.
|
|
81
|
-
const stateDir = path.join(launchConfigDir, "scanner-state", `${safeName}-${i}`);
|
|
82
|
-
fs.mkdirSync(stateDir, { recursive: true });
|
|
83
|
-
const classes = this.deps.scannerClassesMb;
|
|
84
|
-
const classMb = simulation && classes !== undefined && Object.hasOwn(classes, scanner.name)
|
|
85
|
-
? classes[scanner.name]
|
|
86
|
-
: undefined;
|
|
87
|
-
const identity = {
|
|
88
|
-
scannerName: scanner.name,
|
|
89
|
-
classMb,
|
|
90
|
-
codeDigest: classMb !== undefined ? scannerCodeDigest(scanner) : "",
|
|
91
|
-
};
|
|
92
|
-
const sizeStop = readSizeStop(stateDir);
|
|
93
|
-
if (sizeStop !== undefined && holds(sizeStop, identity)) {
|
|
94
|
-
logger.info("simulation scanner stays stopped for size until its class or code changes", {
|
|
95
|
-
runtimeId,
|
|
96
|
-
scannerName: scanner.name,
|
|
97
|
-
classMb,
|
|
98
|
-
nextClassMb: sizeStop.nextClassMb,
|
|
99
|
-
});
|
|
100
|
-
this.active.push({
|
|
101
|
-
kind: "stopped-for-size",
|
|
102
|
-
scannerName: scanner.name,
|
|
103
|
-
intervalSeconds: scanner.intervalSeconds,
|
|
104
|
-
record: sizeStop,
|
|
105
|
-
});
|
|
106
|
-
continue;
|
|
107
|
-
}
|
|
108
|
-
if (sizeStop !== undefined) {
|
|
109
|
-
clearSizeStop(stateDir);
|
|
110
|
-
logger.info("simulation scanner's stop for size cleared: its class or code changed", {
|
|
111
|
-
runtimeId,
|
|
112
|
-
scannerName: scanner.name,
|
|
113
|
-
stoppedClassMb: sizeStop.classMb,
|
|
114
|
-
classMb,
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
// 1. Mint.
|
|
118
|
-
const scannerId = mintScannerId();
|
|
119
|
-
// 2. Register.
|
|
120
|
-
registry.register({
|
|
121
|
-
scannerId,
|
|
122
|
-
runtimeId,
|
|
123
|
-
scannerName: scanner.name,
|
|
124
|
-
wallet,
|
|
125
|
-
fields: scanner.fields,
|
|
126
|
-
});
|
|
127
|
-
registeredInThisCall.push(scannerId);
|
|
128
|
-
// 3. Write launch config. The filename is keyed on the unique scanner_id
|
|
129
|
-
// so two scanners that share a name never overwrite each other on disk.
|
|
130
|
-
// The state directory is keyed on the scanner NAME so it is stable
|
|
131
|
-
// across relaunch — the restarted child resumes its state and replays
|
|
132
|
-
// its delivery journal (the scaffold derives the journal from state_path).
|
|
133
|
-
const cfgPath = path.join(launchConfigDir, `${scannerId}.launch.json`);
|
|
134
|
-
// Launch-config JSON — the FROZEN launcher↔scaffold key contract (design §4a).
|
|
135
|
-
// Hard cut: `interval` → `interval_seconds`, `params` → `inputs`.
|
|
136
|
-
const launchCfg = {
|
|
137
|
-
path: scanner.path,
|
|
138
|
-
entrypoint: scanner.entrypoint,
|
|
139
|
-
interval_seconds: scanner.intervalSeconds,
|
|
140
|
-
state_path: path.join(stateDir, "state.json"),
|
|
141
|
-
default_signal_validity_seconds: scanner.defaultSignalValiditySeconds,
|
|
142
|
-
// Per-signal data{} schema (recipe `signal_data_schema`, held here as
|
|
143
|
-
// `scanner.fields`). The scaffold reads it and validates each signal's
|
|
144
|
-
// `data` scaffold-side, POSTing a violation to /errors for early, loud
|
|
145
|
-
// feedback. Additive — intake keeps its authoritative server-side check.
|
|
146
|
-
signal_data_schema: scanner.fields,
|
|
147
|
-
wallet,
|
|
148
|
-
scanner_name: scanner.name,
|
|
149
|
-
};
|
|
150
|
-
if (scanner.timeoutSeconds !== undefined) {
|
|
151
|
-
launchCfg.timeout_seconds = scanner.timeoutSeconds;
|
|
152
|
-
}
|
|
153
|
-
if (scanner.inputs !== undefined) {
|
|
154
|
-
launchCfg.inputs = scanner.inputs;
|
|
155
|
-
}
|
|
156
|
-
if (scanner.stateHistoryMaxCount !== undefined) {
|
|
157
|
-
launchCfg.state_history_max_count = scanner.stateHistoryMaxCount;
|
|
158
|
-
}
|
|
159
|
-
if (classMb !== undefined) {
|
|
160
|
-
launchCfg.class_mb = classMb;
|
|
161
|
-
}
|
|
162
|
-
else if (simulation) {
|
|
163
|
-
logger.warn("simulation scanner has no memory class in the registry; running it unlimited", {
|
|
164
|
-
runtimeId,
|
|
165
|
-
scannerName: scanner.name,
|
|
166
|
-
wallet,
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
fs.writeFileSync(cfgPath, JSON.stringify(launchCfg, null, 2), "utf8");
|
|
170
|
-
// Mutable id holder so the lastAliveAt closure always reads the current id.
|
|
171
|
-
const idHolder = { value: scannerId };
|
|
172
|
-
// 4. Build spawn spec.
|
|
173
|
-
const pythonBin = process.env.PYTHON ?? "python3";
|
|
174
|
-
const existingPythonPath = process.env.PYTHONPATH ?? "";
|
|
175
|
-
const pythonPath = existingPythonPath
|
|
176
|
-
? `${scaffoldPackageDir}:${existingPythonPath}`
|
|
177
|
-
: scaffoldPackageDir;
|
|
178
|
-
const maxSilenceMs = Math.max(scanner.intervalSeconds * 2, 30) * 1000;
|
|
179
|
-
const spec = {
|
|
180
|
-
command: pythonBin,
|
|
181
|
-
args: ["-m", "scaffold", cfgPath],
|
|
182
|
-
env: {
|
|
183
|
-
EXTERNAL_SCANNER_ID: scannerId,
|
|
184
|
-
SIGNAL_INGESTION_URL: intakeUrl,
|
|
185
|
-
PYTHONPATH: pythonPath,
|
|
186
|
-
// Inject MCP creds only when present — omit (never "") when absent so
|
|
187
|
-
// the Python ctx.senpi_mcp client stays loud at first use.
|
|
188
|
-
...(senpiApiKey ? { SENPI_AUTH_TOKEN: senpiApiKey } : {}),
|
|
189
|
-
...(senpiMcpUrl ? { SENPI_MCP_URL: senpiMcpUrl } : {}),
|
|
190
|
-
},
|
|
191
|
-
marker: runtimeId,
|
|
192
|
-
initialDelayMs: i * 250,
|
|
193
|
-
lastAliveAt: () => liveness.lastAliveAt(idHolder.value),
|
|
194
|
-
maxSilenceMs,
|
|
195
|
-
...(classMb !== undefined ? { memoryClassMb: classMb } : {}),
|
|
196
|
-
...supervisorOptions,
|
|
197
|
-
};
|
|
198
|
-
// 5. Construct supervisor (NOT started yet — start() calls supervisor.start()).
|
|
199
|
-
const supervisor = createSupervisor(spec, logger);
|
|
200
|
-
// Per-scanner supervision accumulator, read by describeSupervision(). Kept
|
|
201
|
-
// alongside the supervisor (whose getStatus() is the status source of truth).
|
|
202
|
-
const supervision = {
|
|
203
|
-
restartCount: 0,
|
|
204
|
-
};
|
|
205
|
-
// Wire the supervisor event hook (used by E2E to capture pid).
|
|
206
|
-
if (onSupervisorEvent) {
|
|
207
|
-
supervisor.on("event", (e) => {
|
|
208
|
-
onSupervisorEvent(e);
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
// Telemetry bridge: translate each lifecycle event into its `scanner.*` catalog event and its
|
|
212
|
-
// health metric. Read the scanner id fresh from the holder so it reflects the run being
|
|
213
|
-
// reported — this is wired BEFORE the remint listener below, so a `restarting` event still
|
|
214
|
-
// carries the exiting run's id.
|
|
215
|
-
supervisor.on("event", (e) => {
|
|
216
|
-
const evt = e;
|
|
217
|
-
const lifecycleCtx = {
|
|
218
|
-
scannerName: scanner.name,
|
|
219
|
-
scannerId: idHolder.value,
|
|
220
|
-
supervisorId: supervisor.supervisorId,
|
|
221
|
-
wallet,
|
|
222
|
-
};
|
|
223
|
-
emitEvent(logger, () => buildScannerLifecycleEvent(evt, lifecycleCtx));
|
|
224
|
-
recordScannerLifecycleMetrics(evt, lifecycleCtx);
|
|
225
|
-
// Accumulate supervision facts for describeSupervision(). restartCount is
|
|
226
|
-
// the cumulative child-restart tally; degradedReason mirrors the supervisor's
|
|
227
|
-
// degraded/recovered transitions so it never lingers after recovery.
|
|
228
|
-
if (evt.type === "restarting") {
|
|
229
|
-
supervision.restartCount++;
|
|
230
|
-
}
|
|
231
|
-
else if (evt.type === "degraded") {
|
|
232
|
-
supervision.degradedReason = evt.reason;
|
|
233
|
-
}
|
|
234
|
-
else if (evt.type === "recovered") {
|
|
235
|
-
supervision.degradedReason = undefined;
|
|
236
|
-
}
|
|
237
|
-
else if (evt.type === "stopped-for-size") {
|
|
238
|
-
supervision.degradedReason = stoppedForSizeReason(evt.classMb, evt.memoryMb);
|
|
239
|
-
try {
|
|
240
|
-
writeSizeStop(stateDir, sizeStopRecord({ ...identity, classMb: evt.classMb }, evt.memoryMb, new Date()));
|
|
241
|
-
}
|
|
242
|
-
catch (err) {
|
|
243
|
-
logger.warn("could not record the stop for size; the scanner starts again at the next boot", {
|
|
244
|
-
runtimeId,
|
|
245
|
-
scannerName: scanner.name,
|
|
246
|
-
error: err instanceof Error ? err.message : String(err),
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
});
|
|
251
|
-
// 6. Subscribe to restarting for remint.
|
|
252
|
-
supervisor.on("event", (e) => {
|
|
253
|
-
const evt = e;
|
|
254
|
-
if (evt.type === "restarting") {
|
|
255
|
-
const oldId = idHolder.value;
|
|
256
|
-
try {
|
|
257
|
-
registry.unregister(oldId);
|
|
258
|
-
const newId = mintScannerId();
|
|
259
|
-
idHolder.value = newId;
|
|
260
|
-
registry.register({
|
|
261
|
-
scannerId: newId,
|
|
262
|
-
runtimeId,
|
|
263
|
-
scannerName: scanner.name,
|
|
264
|
-
wallet,
|
|
265
|
-
fields: scanner.fields,
|
|
266
|
-
});
|
|
267
|
-
// Rewrite env so the next spawn carries the new id.
|
|
268
|
-
supervisor.spec.env = {
|
|
269
|
-
...supervisor.spec.env,
|
|
270
|
-
EXTERNAL_SCANNER_ID: newId,
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
catch (err) {
|
|
274
|
-
// A failed re-mint breaks the zombie fence — the scanner can be left with no registry
|
|
275
|
-
// entry, so its signals are refused (UNKNOWN_SCANNER). Surface it rather than let the
|
|
276
|
-
// supervisor's safeEmit swallow it as a generic listener throw.
|
|
277
|
-
emitEvent(logger, () => buildScannerLaunchFailedEvent({
|
|
278
|
-
scannerName: scanner.name,
|
|
279
|
-
phase: "remint",
|
|
280
|
-
wallet,
|
|
281
|
-
scannerId: oldId,
|
|
282
|
-
supervisorId: supervisor.supervisorId,
|
|
283
|
-
error: err,
|
|
284
|
-
}));
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
this.active.push({
|
|
289
|
-
kind: "supervised",
|
|
290
|
-
scannerName: scanner.name,
|
|
291
|
-
intervalSeconds: scanner.intervalSeconds,
|
|
292
|
-
currentId: idHolder,
|
|
293
|
-
supervisor,
|
|
294
|
-
supervision,
|
|
295
|
-
});
|
|
61
|
+
failingScanner = scanners[i].name;
|
|
62
|
+
this.active.push(this.buildScanner(i, registeredInThisCall));
|
|
296
63
|
}
|
|
297
64
|
// Mark as initialized only after the full loop succeeds (so a partial
|
|
298
65
|
// failure does not prevent a clean retry on start()).
|
|
@@ -318,8 +85,251 @@ export class ScannerLauncher {
|
|
|
318
85
|
throw err;
|
|
319
86
|
}
|
|
320
87
|
}
|
|
88
|
+
buildScanner(i, registered) {
|
|
89
|
+
const { runtimeId, wallet, scanners, registry, liveness, intakeUrl, scaffoldPackageDir, launchConfigDir, logger, supervisorOptions = {}, } = this.deps;
|
|
90
|
+
// Resolve MCP creds: explicit deps win, else fall back to process.env.
|
|
91
|
+
// Empty/absent values are dropped so we never inject a misleading "".
|
|
92
|
+
const senpiApiKey = this.deps.senpiApiKey ||
|
|
93
|
+
process.env.SENPI_AUTH_TOKEN ||
|
|
94
|
+
process.env.SENPI_API_KEY ||
|
|
95
|
+
undefined;
|
|
96
|
+
const senpiMcpUrl = this.deps.senpiMcpUrl || process.env.SENPI_MCP_URL || undefined;
|
|
97
|
+
const mintScannerId = this.deps.mintScannerId ?? (() => makeId("scanner"));
|
|
98
|
+
const createSupervisor = this.deps.createSupervisor ??
|
|
99
|
+
((spec, lg) => new LongRunningSupervisor(spec, lg));
|
|
100
|
+
const onSupervisorEvent = this.deps.onSupervisorEvent;
|
|
101
|
+
const simulation = walletMode(wallet) === "paper";
|
|
102
|
+
const scanner = scanners[i];
|
|
103
|
+
if (!scanner.path) {
|
|
104
|
+
throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "path"`);
|
|
105
|
+
}
|
|
106
|
+
if (!scanner.entrypoint) {
|
|
107
|
+
throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "entrypoint"`);
|
|
108
|
+
}
|
|
109
|
+
const safeName = scanner.name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
110
|
+
// Include the scanner's array index so two scanners that share a name (or
|
|
111
|
+
// whose names sanitize to the same string) never share a state directory
|
|
112
|
+
// or delivery journal. The index is stable across relaunch (same config
|
|
113
|
+
// position), so state and the journal survive a restart.
|
|
114
|
+
const stateDir = path.join(launchConfigDir, "scanner-state", `${safeName}-${i}`);
|
|
115
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
116
|
+
const classes = this.deps.scannerClassesMb;
|
|
117
|
+
const classMb = simulation && classes !== undefined && Object.hasOwn(classes, scanner.name)
|
|
118
|
+
? classes[scanner.name]
|
|
119
|
+
: undefined;
|
|
120
|
+
const identity = {
|
|
121
|
+
scannerName: scanner.name,
|
|
122
|
+
classMb,
|
|
123
|
+
codeDigest: classMb !== undefined ? scannerCodeDigest(scanner) : "",
|
|
124
|
+
};
|
|
125
|
+
const sizeStop = readSizeStop(stateDir);
|
|
126
|
+
if (sizeStop !== undefined && holds(sizeStop, identity)) {
|
|
127
|
+
logger.info("simulation scanner stays stopped for size until its class or code changes", {
|
|
128
|
+
runtimeId,
|
|
129
|
+
scannerName: scanner.name,
|
|
130
|
+
classMb,
|
|
131
|
+
nextClassMb: sizeStop.nextClassMb,
|
|
132
|
+
});
|
|
133
|
+
return {
|
|
134
|
+
kind: "stopped-for-size",
|
|
135
|
+
scannerName: scanner.name,
|
|
136
|
+
intervalSeconds: scanner.intervalSeconds,
|
|
137
|
+
record: sizeStop,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
if (sizeStop !== undefined) {
|
|
141
|
+
clearSizeStop(stateDir);
|
|
142
|
+
logger.info("simulation scanner's stop for size cleared: its class or code changed", {
|
|
143
|
+
runtimeId,
|
|
144
|
+
scannerName: scanner.name,
|
|
145
|
+
stoppedClassMb: sizeStop.classMb,
|
|
146
|
+
classMb,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
// 1. Mint.
|
|
150
|
+
const scannerId = mintScannerId();
|
|
151
|
+
// 2. Register.
|
|
152
|
+
registry.register({
|
|
153
|
+
scannerId,
|
|
154
|
+
runtimeId,
|
|
155
|
+
scannerName: scanner.name,
|
|
156
|
+
wallet,
|
|
157
|
+
fields: scanner.fields,
|
|
158
|
+
});
|
|
159
|
+
registered.push(scannerId);
|
|
160
|
+
// 3. Write launch config. The filename is keyed on the unique scanner_id
|
|
161
|
+
// so two scanners that share a name never overwrite each other on disk.
|
|
162
|
+
// The state directory is keyed on the scanner NAME so it is stable
|
|
163
|
+
// across relaunch — the restarted child resumes its state and replays
|
|
164
|
+
// its delivery journal (the scaffold derives the journal from state_path).
|
|
165
|
+
const cfgPath = path.join(launchConfigDir, `${scannerId}.launch.json`);
|
|
166
|
+
// Launch-config JSON — the FROZEN launcher↔scaffold key contract (design §4a).
|
|
167
|
+
// Hard cut: `interval` → `interval_seconds`, `params` → `inputs`.
|
|
168
|
+
const launchCfg = {
|
|
169
|
+
path: scanner.path,
|
|
170
|
+
entrypoint: scanner.entrypoint,
|
|
171
|
+
interval_seconds: scanner.intervalSeconds,
|
|
172
|
+
state_path: path.join(stateDir, "state.json"),
|
|
173
|
+
default_signal_validity_seconds: scanner.defaultSignalValiditySeconds,
|
|
174
|
+
// Per-signal data{} schema (recipe `signal_data_schema`, held here as
|
|
175
|
+
// `scanner.fields`). The scaffold reads it and validates each signal's
|
|
176
|
+
// `data` scaffold-side, POSTing a violation to /errors for early, loud
|
|
177
|
+
// feedback. Additive — intake keeps its authoritative server-side check.
|
|
178
|
+
signal_data_schema: scanner.fields,
|
|
179
|
+
wallet,
|
|
180
|
+
scanner_name: scanner.name,
|
|
181
|
+
};
|
|
182
|
+
if (scanner.timeoutSeconds !== undefined) {
|
|
183
|
+
launchCfg.timeout_seconds = scanner.timeoutSeconds;
|
|
184
|
+
}
|
|
185
|
+
if (scanner.inputs !== undefined) {
|
|
186
|
+
launchCfg.inputs = scanner.inputs;
|
|
187
|
+
}
|
|
188
|
+
if (scanner.stateHistoryMaxCount !== undefined) {
|
|
189
|
+
launchCfg.state_history_max_count = scanner.stateHistoryMaxCount;
|
|
190
|
+
}
|
|
191
|
+
if (classMb !== undefined) {
|
|
192
|
+
launchCfg.class_mb = classMb;
|
|
193
|
+
}
|
|
194
|
+
else if (simulation) {
|
|
195
|
+
logger.warn("simulation scanner has no memory class in the registry; running it unlimited", {
|
|
196
|
+
runtimeId,
|
|
197
|
+
scannerName: scanner.name,
|
|
198
|
+
wallet,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
fs.writeFileSync(cfgPath, JSON.stringify(launchCfg, null, 2), "utf8");
|
|
202
|
+
// Mutable id holder so the lastAliveAt closure always reads the current id.
|
|
203
|
+
const idHolder = { value: scannerId };
|
|
204
|
+
// 4. Build spawn spec.
|
|
205
|
+
const pythonBin = process.env.PYTHON ?? "python3";
|
|
206
|
+
const existingPythonPath = process.env.PYTHONPATH ?? "";
|
|
207
|
+
const pythonPath = existingPythonPath
|
|
208
|
+
? `${scaffoldPackageDir}:${existingPythonPath}`
|
|
209
|
+
: scaffoldPackageDir;
|
|
210
|
+
const maxSilenceMs = Math.max(scanner.intervalSeconds * 2, 30) * 1000;
|
|
211
|
+
const spec = {
|
|
212
|
+
command: pythonBin,
|
|
213
|
+
args: ["-m", "scaffold", cfgPath],
|
|
214
|
+
env: {
|
|
215
|
+
EXTERNAL_SCANNER_ID: scannerId,
|
|
216
|
+
SIGNAL_INGESTION_URL: intakeUrl,
|
|
217
|
+
PYTHONPATH: pythonPath,
|
|
218
|
+
// Inject MCP creds only when present — omit (never "") when absent so
|
|
219
|
+
// the Python ctx.senpi_mcp client stays loud at first use.
|
|
220
|
+
...(senpiApiKey ? { SENPI_AUTH_TOKEN: senpiApiKey } : {}),
|
|
221
|
+
...(senpiMcpUrl ? { SENPI_MCP_URL: senpiMcpUrl } : {}),
|
|
222
|
+
},
|
|
223
|
+
marker: runtimeId,
|
|
224
|
+
initialDelayMs: i * 250,
|
|
225
|
+
lastAliveAt: () => liveness.lastAliveAt(idHolder.value),
|
|
226
|
+
maxSilenceMs,
|
|
227
|
+
...(classMb !== undefined ? { memoryClassMb: classMb } : {}),
|
|
228
|
+
...supervisorOptions,
|
|
229
|
+
};
|
|
230
|
+
// 5. Construct supervisor (NOT started yet — start() calls supervisor.start()).
|
|
231
|
+
const supervisor = createSupervisor(spec, logger);
|
|
232
|
+
// Per-scanner supervision accumulator, read by describeSupervision(). Kept
|
|
233
|
+
// alongside the supervisor (whose getStatus() is the status source of truth).
|
|
234
|
+
const supervision = {
|
|
235
|
+
restartCount: 0,
|
|
236
|
+
};
|
|
237
|
+
// Wire the supervisor event hook (used by E2E to capture pid).
|
|
238
|
+
if (onSupervisorEvent) {
|
|
239
|
+
supervisor.on("event", (e) => {
|
|
240
|
+
onSupervisorEvent(e);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
// Telemetry bridge: translate each lifecycle event into its `scanner.*` catalog event and its
|
|
244
|
+
// health metric. Read the scanner id fresh from the holder so it reflects the run being
|
|
245
|
+
// reported — this is wired BEFORE the remint listener below, so a `restarting` event still
|
|
246
|
+
// carries the exiting run's id.
|
|
247
|
+
supervisor.on("event", (e) => {
|
|
248
|
+
const evt = e;
|
|
249
|
+
const lifecycleCtx = {
|
|
250
|
+
scannerName: scanner.name,
|
|
251
|
+
scannerId: idHolder.value,
|
|
252
|
+
supervisorId: supervisor.supervisorId,
|
|
253
|
+
wallet,
|
|
254
|
+
};
|
|
255
|
+
emitEvent(logger, () => buildScannerLifecycleEvent(evt, lifecycleCtx));
|
|
256
|
+
recordScannerLifecycleMetrics(evt, lifecycleCtx);
|
|
257
|
+
// Accumulate supervision facts for describeSupervision(). restartCount is
|
|
258
|
+
// the cumulative child-restart tally; degradedReason mirrors the supervisor's
|
|
259
|
+
// degraded/recovered transitions so it never lingers after recovery.
|
|
260
|
+
if (evt.type === "restarting") {
|
|
261
|
+
supervision.restartCount++;
|
|
262
|
+
}
|
|
263
|
+
else if (evt.type === "degraded") {
|
|
264
|
+
supervision.degradedReason = evt.reason;
|
|
265
|
+
}
|
|
266
|
+
else if (evt.type === "recovered") {
|
|
267
|
+
supervision.degradedReason = undefined;
|
|
268
|
+
}
|
|
269
|
+
else if (evt.type === "stopped-for-size") {
|
|
270
|
+
supervision.degradedReason = stoppedForSizeReason(evt.classMb, evt.memoryMb);
|
|
271
|
+
try {
|
|
272
|
+
writeSizeStop(stateDir, sizeStopRecord({ ...identity, classMb: evt.classMb }, evt.memoryMb, new Date()));
|
|
273
|
+
}
|
|
274
|
+
catch (err) {
|
|
275
|
+
logger.warn("could not record the stop for size; the scanner starts again at the next boot", {
|
|
276
|
+
runtimeId,
|
|
277
|
+
scannerName: scanner.name,
|
|
278
|
+
error: err instanceof Error ? err.message : String(err),
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
// 6. Subscribe to restarting for remint.
|
|
284
|
+
supervisor.on("event", (e) => {
|
|
285
|
+
const evt = e;
|
|
286
|
+
if (evt.type === "restarting") {
|
|
287
|
+
const oldId = idHolder.value;
|
|
288
|
+
try {
|
|
289
|
+
registry.unregister(oldId);
|
|
290
|
+
const newId = mintScannerId();
|
|
291
|
+
idHolder.value = newId;
|
|
292
|
+
registry.register({
|
|
293
|
+
scannerId: newId,
|
|
294
|
+
runtimeId,
|
|
295
|
+
scannerName: scanner.name,
|
|
296
|
+
wallet,
|
|
297
|
+
fields: scanner.fields,
|
|
298
|
+
});
|
|
299
|
+
// Rewrite env so the next spawn carries the new id.
|
|
300
|
+
supervisor.spec.env = {
|
|
301
|
+
...supervisor.spec.env,
|
|
302
|
+
EXTERNAL_SCANNER_ID: newId,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
// A failed re-mint breaks the zombie fence — the scanner can be left with no registry
|
|
307
|
+
// entry, so its signals are refused (UNKNOWN_SCANNER). Surface it rather than let the
|
|
308
|
+
// supervisor's safeEmit swallow it as a generic listener throw.
|
|
309
|
+
emitEvent(logger, () => buildScannerLaunchFailedEvent({
|
|
310
|
+
scannerName: scanner.name,
|
|
311
|
+
phase: "remint",
|
|
312
|
+
wallet,
|
|
313
|
+
scannerId: oldId,
|
|
314
|
+
supervisorId: supervisor.supervisorId,
|
|
315
|
+
error: err,
|
|
316
|
+
}));
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
return {
|
|
321
|
+
kind: "supervised",
|
|
322
|
+
index: i,
|
|
323
|
+
scannerName: scanner.name,
|
|
324
|
+
intervalSeconds: scanner.intervalSeconds,
|
|
325
|
+
currentId: idHolder,
|
|
326
|
+
supervisor,
|
|
327
|
+
supervision,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
321
330
|
async start() {
|
|
322
331
|
this._buildAndRegister();
|
|
332
|
+
this.started = true;
|
|
323
333
|
for (const scanner of this.active) {
|
|
324
334
|
if (scanner.kind === "supervised")
|
|
325
335
|
scanner.supervisor.start();
|
|
@@ -346,6 +356,16 @@ export class ScannerLauncher {
|
|
|
346
356
|
degradedReason: scanner.record.reason,
|
|
347
357
|
};
|
|
348
358
|
}
|
|
359
|
+
if (scanner.kind === "paused") {
|
|
360
|
+
return {
|
|
361
|
+
scannerName: scanner.scannerName,
|
|
362
|
+
supervisorStatus: "paused",
|
|
363
|
+
restartCount: 0,
|
|
364
|
+
intervalSeconds: scanner.intervalSeconds,
|
|
365
|
+
lastAliveAt: null,
|
|
366
|
+
...(this.simulationPauseReason === OUT_OF_CREDITS ? { degradedReason: "out of credits" } : {}),
|
|
367
|
+
};
|
|
368
|
+
}
|
|
349
369
|
const { scannerName, intervalSeconds, currentId, supervisor, supervision } = scanner;
|
|
350
370
|
const supervisorStatus = supervisor.getStatus();
|
|
351
371
|
const row = {
|
|
@@ -364,13 +384,86 @@ export class ScannerLauncher {
|
|
|
364
384
|
return row;
|
|
365
385
|
});
|
|
366
386
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
387
|
+
/**
|
|
388
|
+
* Stop every running scanner because its simulation is paused, and show it `paused`. A scanner
|
|
389
|
+
* held stopped for size stays held. A no-op when nothing runs, so every status read may call it.
|
|
390
|
+
* `reason` is paper-service's pause code; `out_of_credits` shows as `paused (out of credits)`.
|
|
391
|
+
*/
|
|
392
|
+
async pause(reason) {
|
|
393
|
+
this.simulationPauseReason = reason ?? null;
|
|
394
|
+
const stopping = [];
|
|
395
|
+
const paused = [];
|
|
396
|
+
this.active.forEach((scanner, k) => {
|
|
397
|
+
if (scanner.kind !== "supervised" || scanner.supervisor.getStatus() === "stopped-for-size")
|
|
370
398
|
return;
|
|
371
399
|
this.deps.registry.unregister(scanner.currentId.value);
|
|
372
|
-
|
|
373
|
-
|
|
400
|
+
stopping.push(scanner.supervisor.stop());
|
|
401
|
+
paused.push(scanner.scannerName);
|
|
402
|
+
this.active[k] = {
|
|
403
|
+
kind: "paused",
|
|
404
|
+
index: scanner.index,
|
|
405
|
+
scannerName: scanner.scannerName,
|
|
406
|
+
intervalSeconds: scanner.intervalSeconds,
|
|
407
|
+
};
|
|
408
|
+
});
|
|
409
|
+
if (paused.length === 0)
|
|
410
|
+
return;
|
|
411
|
+
this.deps.logger.info("simulation paused: its scanners are stopped until it is active again", {
|
|
412
|
+
runtimeId: this.deps.runtimeId,
|
|
413
|
+
scanners: paused,
|
|
414
|
+
});
|
|
415
|
+
this.pausing = Promise.allSettled([this.pausing, ...stopping]);
|
|
416
|
+
await Promise.all(stopping);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Start every paused scanner again, rebuilt as at boot: one whose stop-for-size record still holds
|
|
420
|
+
* stays stopped. A no-op when nothing is paused or after `stop()`. A scanner that fails to rebuild
|
|
421
|
+
* stays paused, so the next status read retries it.
|
|
422
|
+
*/
|
|
423
|
+
resume() {
|
|
424
|
+
if (this.stopped)
|
|
425
|
+
return;
|
|
426
|
+
this.simulationPauseReason = null;
|
|
427
|
+
const resumed = [];
|
|
428
|
+
this.active.forEach((scanner, k) => {
|
|
429
|
+
if (scanner.kind !== "paused")
|
|
430
|
+
return;
|
|
431
|
+
const registered = [];
|
|
432
|
+
try {
|
|
433
|
+
const next = this.buildScanner(scanner.index, registered);
|
|
434
|
+
if (this.started && next.kind === "supervised")
|
|
435
|
+
next.supervisor.start();
|
|
436
|
+
this.active[k] = next;
|
|
437
|
+
resumed.push(scanner.scannerName);
|
|
438
|
+
}
|
|
439
|
+
catch (err) {
|
|
440
|
+
for (const id of registered)
|
|
441
|
+
this.deps.registry.unregister(id);
|
|
442
|
+
this.deps.logger.warn("simulation scanner not started again; the next status read retries", {
|
|
443
|
+
runtimeId: this.deps.runtimeId,
|
|
444
|
+
scannerName: scanner.scannerName,
|
|
445
|
+
error: err instanceof Error ? err.message : String(err),
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
if (resumed.length === 0)
|
|
450
|
+
return;
|
|
451
|
+
this.deps.logger.info("simulation active again: its scanners are started", {
|
|
452
|
+
runtimeId: this.deps.runtimeId,
|
|
453
|
+
scanners: resumed,
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
async stop() {
|
|
457
|
+
this.stopped = true;
|
|
458
|
+
await Promise.all([
|
|
459
|
+
this.pausing,
|
|
460
|
+
...this.active.map(async (scanner) => {
|
|
461
|
+
if (scanner.kind !== "supervised")
|
|
462
|
+
return;
|
|
463
|
+
this.deps.registry.unregister(scanner.currentId.value);
|
|
464
|
+
await scanner.supervisor.stop();
|
|
465
|
+
}),
|
|
466
|
+
]);
|
|
374
467
|
this.active.length = 0;
|
|
375
468
|
}
|
|
376
469
|
}
|