blun-king-cli 9.1.589 → 9.1.595

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +12 -0
  3. package/agent-spine-plugin/CHANGELOG.md +1 -0
  4. package/agent-spine-plugin/docs/host-integration.md +15 -1
  5. package/agent-spine-plugin/docs/preflight-recall.md +1 -1
  6. package/agent-spine-plugin/scripts/check-install-hook.js +6 -5
  7. package/agent-spine-plugin/scripts/check-install-king.js +37 -0
  8. package/agent-spine-plugin/scripts/check-install.js +6 -1
  9. package/agent-spine-plugin/scripts/release-check.js +3 -2
  10. package/agent-spine-plugin/src/cli-agent.js +20 -1
  11. package/agent-spine-plugin/src/cli.js +1 -0
  12. package/agent-spine-plugin/src/index.js +1 -1
  13. package/agent-spine-plugin/src/lib/delivery-command-actions.js +16 -7
  14. package/agent-spine-plugin/src/lib/gateway-control.js +69 -1
  15. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +92 -0
  16. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +9 -1
  17. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +28 -0
  18. package/agent-spine-plugin/src/lib/gateway-runs.js +46 -10
  19. package/agent-spine-plugin/src/lib/gateway-runtime.js +1 -1
  20. package/agent-spine-plugin/src/lib/gateway-state.js +3 -1
  21. package/agent-spine-plugin/src/lib/hook-context.js +8 -3
  22. package/agent-spine-plugin/src/lib/hook-output.js +2 -3
  23. package/agent-spine-plugin/src/lib/hook-process-advisory.js +1 -2
  24. package/agent-spine-plugin/src/lib/host-instruction-budget.js +17 -0
  25. package/agent-spine-plugin/src/lib/preflight.js +5 -19
  26. package/agent-spine-plugin/src/lib/source-roots.js +3 -2
  27. package/agent-spine-plugin/src/worker.js +30 -12
  28. package/bin/agentspine-king-goal-inbox.mjs +127 -0
  29. package/bin/agentspine-king-goal-intake.mjs +106 -0
  30. package/bin/agentspine-king-host-runner.mjs +109 -0
  31. package/bin/agentspine-king-snapshot-policy.cjs +80 -0
  32. package/bin/agentspine-king-status-policy.mjs +226 -0
  33. package/bin/agentspine-king-worker-host.mjs +160 -0
  34. package/bin/core-bootstrap.js +20 -3
  35. package/bin/launcher-mode.js +38 -1
  36. package/bin/launcher-restart-policy.cjs +131 -0
  37. package/bin/launcher-runtime.js +48 -9
  38. package/bin/runtime-exit-ledger.cjs +144 -0
  39. package/bin/runtime-exit-ledger.d.cts +23 -0
  40. package/bin/windows-node-crash-dump.cjs +289 -0
  41. package/blun.mjs +83241 -74234
  42. package/bundled-agent-sources.json +109 -34
  43. package/codebase-index/codebase_index.py +470 -0
  44. package/package.json +6 -1
  45. package/telegram-plugin/dist/bridge.mjs +390 -4
  46. package/worker-host.mjs +348023 -0
@@ -0,0 +1,289 @@
1
+ 'use strict';
2
+
3
+ const { spawnSync } = require('node:child_process');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { ensurePrivateDirectory } = require('./private-paths');
7
+ const { recordRuntimeExit } = require('./runtime-exit-ledger.cjs');
8
+
9
+ const WER_DUMP_COUNT = 3;
10
+ const WER_DUMP_TYPE = 1;
11
+ const WER_REGISTRY_KEY = 'HKLM\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\\node.exe';
12
+ const MAX_NODE_REPORTS = 3;
13
+ const LEGACY_REPORT_PATTERN = /^blun-node\.[1-9]\d*\.[a-f0-9]{32}\.report\.json$/u;
14
+ const REG_OPTIONS = Object.freeze({ encoding: 'utf8', shell: false, windowsHide: true, timeout: 3000, maxBuffer: 65536 });
15
+
16
+ function windowsRegistryCommand(options) {
17
+ const env = options.env || process.env;
18
+ const systemRoot = env.SystemRoot || env.SYSTEMROOT || env.WINDIR || env.windir;
19
+ if (typeof systemRoot !== 'string' || !/^[a-z]:\\/iu.test(systemRoot)
20
+ || path.win32.normalize(systemRoot) !== systemRoot || systemRoot.slice(2).includes(':')
21
+ || /[\u0000-\u001F<>"|?*/]/u.test(systemRoot)
22
+ || systemRoot.slice(3).split('\\').some(part => !part || /[. ]$/u.test(part))) {
23
+ throw new Error('invalid-system-directory');
24
+ }
25
+ const directory = path.win32.join(systemRoot, 'System32');
26
+ return { executable: path.win32.join(directory, 'reg.exe'),
27
+ options: { ...REG_OPTIONS, cwd: directory, env: { SystemRoot: systemRoot, WINDIR: systemRoot } } };
28
+ }
29
+
30
+ function windowsWerCrashDumpPlan(options = {}) {
31
+ const pathImpl = (options.platform || process.platform) === 'win32' ? path.win32 : path;
32
+ if (typeof options.homeDir !== 'string' || !pathImpl.isAbsolute(options.homeDir)
33
+ || /[\r\n\0]/u.test(options.homeDir)) throw new Error('invalid-home-directory');
34
+ const dumpFolder = pathImpl.join(options.homeDir, 'diagnostics', 'crash-dumps');
35
+ return { dumpFolder, registryKey: WER_REGISTRY_KEY,
36
+ values: { DumpFolder: dumpFolder, DumpCount: WER_DUMP_COUNT, DumpType: WER_DUMP_TYPE } };
37
+ }
38
+
39
+ function configureWindowsWerCrashDumps(options = {}) {
40
+ if ((options.platform || process.platform) !== 'win32') return { configured: false, reason: 'not-windows' };
41
+ if (options.confirmSystemWide !== true) return { configured: false, reason: 'explicit-system-wide-consent-required' };
42
+ let command;
43
+ try { command = windowsRegistryCommand(options); }
44
+ catch { return { configured: false, reason: 'system-directory-unavailable' }; }
45
+ let plan;
46
+ try {
47
+ plan = windowsWerCrashDumpPlan({ homeDir: options.homeDir, platform: 'win32' });
48
+ (options.prepareDirectory || ensurePrivateDirectory)(plan.dumpFolder);
49
+ } catch { return { configured: false, reason: 'report-directory-unavailable' }; }
50
+ const execute = options.spawnSync || spawnSync;
51
+ const appliedValues = [];
52
+ for (const [name, type, value] of [
53
+ ['DumpFolder', 'REG_EXPAND_SZ', plan.dumpFolder],
54
+ ['DumpCount', 'REG_DWORD', String(WER_DUMP_COUNT)],
55
+ ['DumpType', 'REG_DWORD', String(WER_DUMP_TYPE)],
56
+ ]) {
57
+ let result;
58
+ try { result = execute(command.executable, ['ADD', plan.registryKey, '/v', name, '/t', type, '/d', value, '/f'], command.options); }
59
+ catch { result = { status: 1 }; }
60
+ if (result.error || result.status !== 0) {
61
+ return { configured: false, reason: 'registry-write-failed', appliedValues, failedValue: name, plan };
62
+ }
63
+ appliedValues.push(name);
64
+ }
65
+ return { configured: true, appliedValues, plan };
66
+ }
67
+
68
+ function queryWindowsWerCrashDumps(options = {}) {
69
+ if ((options.platform || process.platform) !== 'win32') return { configured: false, reason: 'not-windows' };
70
+ let plan;
71
+ let result;
72
+ try {
73
+ const command = windowsRegistryCommand(options);
74
+ plan = windowsWerCrashDumpPlan({ homeDir: options.homeDir, platform: 'win32' });
75
+ result = (options.spawnSync || spawnSync)(command.executable, ['QUERY', plan.registryKey], command.options);
76
+ } catch { return { configured: false, reason: 'registry-query-failed' }; }
77
+ if (result.error || result.status !== 0) return { configured: false, reason: 'registry-query-failed', plan };
78
+ const values = new Map();
79
+ for (const line of String(result.stdout || '').split(/\r?\n/u)) {
80
+ const match = /^\s+(DumpFolder|DumpCount|DumpType)\s+(REG_EXPAND_SZ|REG_DWORD)\s+(.+?)\s*$/iu.exec(line);
81
+ if (match) {
82
+ const key = match[1].toLowerCase();
83
+ if (values.has(key)) return { configured: false, reason: 'registry-values-mismatch', plan };
84
+ values.set(key, [match[2].toUpperCase(), match[3]]);
85
+ }
86
+ }
87
+ const [folderType, folder] = values.get('dumpfolder') || [];
88
+ const [countType, count] = values.get('dumpcount') || [];
89
+ const [dumpType, type] = values.get('dumptype') || [];
90
+ const configured = folderType === 'REG_EXPAND_SZ'
91
+ && path.win32.normalize(folder).toLowerCase() === path.win32.normalize(plan.dumpFolder).toLowerCase()
92
+ && countType === 'REG_DWORD' && /^0x0*3$/iu.test(count)
93
+ && dumpType === 'REG_DWORD' && /^0x0*1$/iu.test(type);
94
+ return { configured, reason: configured ? undefined : 'registry-values-mismatch', plan };
95
+ }
96
+
97
+ function reportFailure(code) {
98
+ return Object.assign(new Error(code), { reportFailure: code });
99
+ }
100
+
101
+ function sameEntry(left, right) {
102
+ return left.dev === right.dev && left.ino === right.ino;
103
+ }
104
+
105
+ function reportIdentity(file) {
106
+ try {
107
+ const stat = fs.lstatSync(file, { bigint: true });
108
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n) throw reportFailure('unsafe-report-file');
109
+ return stat;
110
+ } catch (error) {
111
+ if (error.code === 'ENOENT') return undefined;
112
+ throw error;
113
+ }
114
+ }
115
+
116
+ function reserveReportSlot(directory, pid) {
117
+ const identity = fs.lstatSync(directory, { bigint: true });
118
+ const verifyDirectory = () => {
119
+ const current = fs.lstatSync(directory, { bigint: true });
120
+ if (!current.isDirectory() || current.isSymbolicLink() || !sameEntry(current, identity)) {
121
+ throw reportFailure('unsafe-report-directory');
122
+ }
123
+ };
124
+ verifyDirectory();
125
+ const entries = fs.opendirSync(directory);
126
+ try {
127
+ let count = 0;
128
+ for (let entry = entries.readSync(); entry; entry = entries.readSync()) {
129
+ if (++count > 1024) throw reportFailure('report-directory-too-large');
130
+ if (LEGACY_REPORT_PATTERN.test(entry.name)) throw reportFailure('legacy-reports-require-cleanup');
131
+ }
132
+ } finally { entries.closeSync(); }
133
+
134
+ const slots = Array.from({ length: MAX_NODE_REPORTS }, (_, index) => {
135
+ const filename = `blun-node.slot-${index + 1}.report.json`;
136
+ return { filename, lock: path.join(directory, `blun-node.slot-${index + 1}.lock`),
137
+ previous: reportIdentity(path.join(directory, filename)) };
138
+ }).toSorted((left, right) => {
139
+ const a = left.previous?.mtimeNs ?? -1n;
140
+ const b = right.previous?.mtimeNs ?? -1n;
141
+ return a < b ? -1 : a > b ? 1 : 0;
142
+ });
143
+ for (const slot of slots) {
144
+ verifyDirectory();
145
+ let descriptor;
146
+ try { descriptor = fs.openSync(slot.lock, 'wx', 0o600); }
147
+ catch (error) { if (error.code === 'EEXIST') continue; throw error; }
148
+ let lockIdentity;
149
+ let closed = false;
150
+ const release = () => {
151
+ if (closed) return;
152
+ closed = true;
153
+ try {
154
+ verifyDirectory();
155
+ const current = reportIdentity(slot.lock);
156
+ if (lockIdentity && current && sameEntry(current, lockIdentity)
157
+ && sameEntry(fs.fstatSync(descriptor, { bigint: true }), lockIdentity)) fs.unlinkSync(slot.lock);
158
+ } catch {} finally { try { fs.closeSync(descriptor); } catch {} }
159
+ };
160
+ try {
161
+ lockIdentity = fs.fstatSync(descriptor, { bigint: true });
162
+ if (!lockIdentity.isFile() || lockIdentity.nlink !== 1n) throw reportFailure('unsafe-report-reservation');
163
+ fs.writeFileSync(descriptor, `${JSON.stringify({ schemaVersion: 1, pid })}\n`);
164
+ verifyDirectory();
165
+ const reportPath = path.join(directory, slot.filename);
166
+ const previous = reportIdentity(reportPath);
167
+ return { filename: slot.filename, release,
168
+ verify() {
169
+ verifyDirectory();
170
+ const owner = reportIdentity(slot.lock);
171
+ const current = reportIdentity(reportPath);
172
+ if (!owner || !sameEntry(owner, lockIdentity)
173
+ || (previous ? !current || !sameEntry(previous, current)
174
+ || previous.size !== current.size || previous.mtimeNs !== current.mtimeNs : current !== undefined)) {
175
+ throw reportFailure('report-file-changed');
176
+ }
177
+ } };
178
+ } catch (error) { release(); throw error; }
179
+ }
180
+ // Abrupt native exits may leave reservations behind. Never guess that an
181
+ // owner is dead: capacity exhaustion disables detail reports, not startup.
182
+ throw reportFailure('report-capacity-unavailable');
183
+ }
184
+
185
+ function installWindowsNodeCrashDump(options = {}) {
186
+ if ((options.platform || process.platform) !== 'win32') {
187
+ return { enabled: false, detailedReportsEnabled: false, reason: 'not-windows', dispose() {} };
188
+ }
189
+ const processObject = options.processObject || process;
190
+ const report = options.report || processObject.report;
191
+ const homeDir = options.homeDir || processObject.env.BLUN_HOME;
192
+ const env = options.env || processObject.env;
193
+ const recordExit = options.recordExit || recordRuntimeExit;
194
+ const requested = env.BLUN_NODE_CRASH_REPORTS === '1';
195
+ let detailedReportsEnabled = false;
196
+ let dumpFolder;
197
+ let reason;
198
+ let previous;
199
+ let assigned;
200
+ let filename;
201
+ let reservation;
202
+ const restore = () => {
203
+ if (!previous) return;
204
+ for (const key of Object.keys(previous)) {
205
+ try { if (report[key] === assigned[key]) report[key] = previous[key]; } catch {}
206
+ }
207
+ };
208
+ const releaseReservation = () => {
209
+ try {
210
+ if (!assigned || report.directory !== dumpFolder || report.filename !== filename
211
+ || !(report.reportOnFatalError || report.reportOnUncaughtException || report.reportOnSignal)) reservation?.release();
212
+ } catch {}
213
+ };
214
+ if (requested) {
215
+ if (!report || typeof report.writeReport !== 'function' || !('excludeEnv' in report)
216
+ || !('excludeNetwork' in report)) reason = 'report-unavailable';
217
+ else {
218
+ try {
219
+ if (typeof homeDir !== 'string' || !path.isAbsolute(homeDir)) throw new Error('invalid-home-directory');
220
+ dumpFolder = path.join(homeDir, 'diagnostics', 'crash-dumps');
221
+ (options.prepareDirectory || ensurePrivateDirectory)(dumpFolder);
222
+ reservation = reserveReportSlot(dumpFolder, processObject.pid);
223
+ filename = reservation.filename;
224
+ assigned = { directory: dumpFolder, filename, excludeEnv: true, excludeNetwork: true,
225
+ reportOnSignal: false, reportOnUncaughtException: false, reportOnFatalError: true };
226
+ previous = Object.fromEntries(Object.keys(assigned).map(key => [key, report[key]]));
227
+ for (const [key, value] of Object.entries(assigned)) {
228
+ report[key] = value;
229
+ if (report[key] !== value) throw new Error('report-setting-rejected');
230
+ }
231
+ detailedReportsEnabled = true;
232
+ } catch (error) {
233
+ restore();
234
+ releaseReservation();
235
+ reason = error.reportFailure || 'report-directory-unavailable';
236
+ }
237
+ }
238
+ }
239
+ let attempted = false;
240
+ let disposed = false;
241
+ const write = (error, origin) => {
242
+ if (disposed || attempted) return null;
243
+ attempted = true;
244
+ const kind = origin === 'bootstrap-failure' ? origin
245
+ : origin === 'unhandledRejection' ? 'unhandled-rejection' : 'uncaught-exception';
246
+ try { recordExit({ homeDir, source: 'bootstrap', kind, error, pid: processObject.pid,
247
+ ppid: processObject.ppid, phase: kind === 'bootstrap-failure' ? 'startup' : 'runtime' }); } catch {}
248
+ if (!detailedReportsEnabled) return null;
249
+ try {
250
+ if (report.directory !== dumpFolder || report.filename !== filename
251
+ || report.excludeEnv !== true || report.excludeNetwork !== true) return null;
252
+ reservation.verify();
253
+ report.writeReport(filename, error instanceof Error ? error : new Error(String(error)));
254
+ return path.join(dumpFolder, filename);
255
+ } catch { return null; }
256
+ };
257
+ const dispose = () => {
258
+ if (disposed) return;
259
+ disposed = true;
260
+ try { processObject.removeListener('uncaughtExceptionMonitor', write); } catch {}
261
+ try { processObject.removeListener('exit', dispose); } catch {}
262
+ restore();
263
+ releaseReservation();
264
+ };
265
+ try {
266
+ processObject.on('uncaughtExceptionMonitor', write);
267
+ processObject.once('exit', dispose);
268
+ } catch {
269
+ dispose();
270
+ return { enabled: false, detailedReportsEnabled: false, reason: 'observer-unavailable', write, dispose };
271
+ }
272
+ return { enabled: true, detailedReportsEnabled, dumpFolder, reason, write, dispose };
273
+ }
274
+
275
+ if (require.main === module) {
276
+ const args = process.argv.slice(2);
277
+ let result;
278
+ if (args.length === 1 && args[0] === '--query-wer') result = queryWindowsWerCrashDumps({ homeDir: process.env.BLUN_HOME });
279
+ else if (args.length === 2 && args[0] === '--configure-wer' && args[1] === '--confirm-system-wide') {
280
+ result = configureWindowsWerCrashDumps({ homeDir: process.env.BLUN_HOME, confirmSystemWide: true });
281
+ } else {
282
+ result = { configured: false, reason: 'explicit-command-required' };
283
+ }
284
+ process.stdout.write(`${JSON.stringify(result)}\n`);
285
+ process.exitCode = result.configured ? 0 : 1;
286
+ }
287
+
288
+ module.exports = { WER_DUMP_COUNT, WER_DUMP_TYPE, MAX_NODE_REPORTS, configureWindowsWerCrashDumps,
289
+ installWindowsNodeCrashDump, queryWindowsWerCrashDumps, windowsWerCrashDumpPlan };