@eyeauras/insight-cli 0.7.0 → 0.8.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/.cli-package-build.json +1 -1
- package/SKILL.md +1 -1
- package/dist/src/activity-audit.d.ts +7 -0
- package/dist/src/activity-audit.js +14 -4
- package/dist/src/analysis-storage.d.ts +5 -1
- package/dist/src/analysis-storage.js +9 -2
- package/dist/src/audit-retention.d.ts +8 -2
- package/dist/src/audit-retention.js +68 -7
- package/dist/src/cli.js +19 -5
- package/dist/src/context-diagnostics.d.ts +1 -1
- package/dist/src/context-diagnostics.js +10 -2
- package/dist/src/contexts.d.ts +118 -10
- package/dist/src/contexts.js +851 -199
- package/dist/src/debugger.js +2 -1
- package/dist/src/diagnostic-error.js +1 -1
- package/dist/src/inline-script.js +3 -4
- package/dist/src/lifecycle.d.ts +11 -0
- package/dist/src/lifecycle.js +34 -6
- package/dist/src/native-inputs.d.ts +6 -0
- package/dist/src/native-inputs.js +30 -6
- package/dist/src/native-queries.js +1 -6
- package/dist/src/native-service.d.ts +40 -0
- package/dist/src/native-service.js +406 -0
- package/dist/src/research.d.ts +29 -1
- package/dist/src/research.js +106 -27
- package/dist/src/server.d.ts +38 -1
- package/dist/src/server.js +160 -12
- package/dist/src/storage-gc.js +1 -1
- package/dist/src/sync-policy.js +2 -1
- package/dist/src/timed-backend.js +8 -0
- package/dist/src/timing-report.d.ts +32 -0
- package/dist/src/timing-report.js +74 -0
- package/dist/src/tool-runtime/identity.js +86 -1
- package/dist/src/tool-runtime/supervisor.js +6 -5
- package/dist/src/transport.d.ts +35 -0
- package/dist/src/transport.js +77 -7
- package/dist/src/unresolved-guidance.d.ts +46 -0
- package/dist/src/unresolved-guidance.js +55 -0
- package/dist/src/windbg.d.ts +1 -1
- package/dist/src/worker-lease.d.ts +17 -0
- package/dist/src/worker-lease.js +50 -0
- package/dist/src/workspace.d.ts +3 -9
- package/dist/src/workspace.js +9 -41
- package/package.json +1 -1
- package/references/native/InsightHeadlessMain.java +9 -2
- package/references/native/InsightNativeCheckout.java +113 -43
- package/references/native/InsightNativeFingerprint.java +28 -1
- package/references/native/InsightNativeRead.java +32 -9
- package/references/native/InsightNativeService.java +43 -0
- package/references/native/InsightNativeView.java +17 -6
- package/references/native/InsightOwnedScripts.java +170 -0
- package/references/native/InsightWorkerLease.java +132 -0
- package/references/recovery.md +68 -3
- package/references/research.md +38 -4
- package/references/setup.md +5 -1
- package/skill-bundle/insight-artifacts/SKILL.md +1 -1
- package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
- package/skill-bundle/insight-binary/SKILL.md +1 -1
- package/skill-bundle/insight-capture/SKILL.md +1 -1
- package/skill-bundle/insight-cli/SKILL.md +1 -1
- package/skill-bundle/insight-cli/references/recovery.md +68 -3
- package/skill-bundle/insight-cli/references/setup.md +5 -1
- package/skill-bundle/insight-die/SKILL.md +1 -1
- package/skill-bundle/insight-dnspy/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
- package/skill-bundle/insight-frida/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
- package/skill-bundle/insight-ghidra/references/research.md +38 -4
- package/skill-bundle/insight-ghidra/references/setup.md +5 -1
- package/skill-bundle/insight-ilspy/SKILL.md +1 -1
- package/skill-bundle/insight-interop/SKILL.md +1 -1
- package/skill-bundle/insight-lldb/SKILL.md +1 -1
- package/skill-bundle/insight-llvm/SKILL.md +1 -1
- package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
- package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
- package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
- package/skill-bundle/insight-overview/SKILL.md +1 -1
- package/skill-bundle/insight-procmon/SKILL.md +1 -1
- package/skill-bundle/insight-re/SKILL.md +1 -1
- package/skill-bundle/insight-re/references/recovery.md +68 -3
- package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
- package/skill-bundle/insight-strace/SKILL.md +1 -1
- package/skill-bundle/insight-tshark/SKILL.md +1 -1
- package/skill-bundle/insight-windbg/SKILL.md +1 -1
- package/skill-bundle/manifest.json +1 -1
- package/skills/insight-artifacts/SKILL.md +1 -1
- package/skills/insight-artifacts/references/recovery.md +68 -3
- package/skills/insight-binary/SKILL.md +1 -1
- package/skills/insight-capture/SKILL.md +1 -1
- package/skills/insight-die/SKILL.md +1 -1
- package/skills/insight-dnspy/SKILL.md +1 -1
- package/skills/insight-dotnet-dump/SKILL.md +1 -1
- package/skills/insight-dotnet-stack/SKILL.md +1 -1
- package/skills/insight-dotnet-trace/SKILL.md +1 -1
- package/skills/insight-frida/SKILL.md +1 -1
- package/skills/insight-ghidra/SKILL.md +1 -1
- package/skills/insight-ghidra/references/recovery.md +68 -3
- package/skills/insight-ghidra/references/research.md +38 -4
- package/skills/insight-ghidra/references/setup.md +5 -1
- package/skills/insight-ilspy/SKILL.md +1 -1
- package/skills/insight-interop/SKILL.md +1 -1
- package/skills/insight-lldb/SKILL.md +1 -1
- package/skills/insight-llvm/SKILL.md +1 -1
- package/skills/insight-managed-heap/SKILL.md +1 -1
- package/skills/insight-managed-metadata/SKILL.md +1 -1
- package/skills/insight-mitmproxy/SKILL.md +1 -1
- package/skills/insight-overview/SKILL.md +1 -1
- package/skills/insight-procmon/SKILL.md +1 -1
- package/skills/insight-re/SKILL.md +1 -1
- package/skills/insight-re/references/recovery.md +68 -3
- package/skills/insight-sevenzip/SKILL.md +1 -1
- package/skills/insight-strace/SKILL.md +1 -1
- package/skills/insight-tshark/SKILL.md +1 -1
- package/skills/insight-windbg/SKILL.md +1 -1
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { timed } from './internal-timing.js';
|
|
2
|
+
/** Lifecycle boundaries whose duration is attributed in timings and lifecycle `--json` results. */
|
|
3
|
+
const lifecycle = {
|
|
4
|
+
close: 'context.close', capture: 'context.capture', releaseUnchanged: 'context.release', updateNative: 'native.update', publishNative: 'native.publish',
|
|
5
|
+
dropNative: 'native.drop', finishEmptyNative: 'native.finish-empty', recoverUpdate: 'native.recover-update', recoverEmptyNative: 'native.recover-empty',
|
|
6
|
+
discardNative: 'native.discard', settleUnsaved: 'native.unsaved', recover: 'native.recover-publication', collect: 'storage.collect',
|
|
7
|
+
};
|
|
2
8
|
/** Observe existing boundaries; retain original method receivers and domain behavior. */
|
|
3
9
|
export function timedBackend(backend) {
|
|
4
10
|
return new Proxy(backend, { get(target, key) {
|
|
@@ -11,6 +17,8 @@ export function timedBackend(backend) {
|
|
|
11
17
|
return (...args) => timed('context.save', 'saved', async () => Reflect.apply(member, target, args));
|
|
12
18
|
if (key === 'call')
|
|
13
19
|
return (...args) => timed('backend.operation', String(args[1]), async () => Reflect.apply(member, target, args));
|
|
20
|
+
if (typeof key === 'string' && Object.hasOwn(lifecycle, key))
|
|
21
|
+
return (...args) => timed(lifecycle[key], key, async () => Reflect.apply(member, target, args));
|
|
14
22
|
return member.bind(target);
|
|
15
23
|
} });
|
|
16
24
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Scope } from './workspace.js';
|
|
2
|
+
/**
|
|
3
|
+
* Summarizes retained timing spans per command attempt. Phases are aggregated by phase/operation; nested
|
|
4
|
+
* spans are reported separately and must not be added to their parents. `unattributedMs` is the root time
|
|
5
|
+
* not covered by any direct child span (sequential children assumed).
|
|
6
|
+
*/
|
|
7
|
+
export declare function timingDiagnostic(workspaceDirectory: string, selected: Scope, options: {
|
|
8
|
+
command?: string;
|
|
9
|
+
limit: number;
|
|
10
|
+
}): Promise<{
|
|
11
|
+
traces: {
|
|
12
|
+
traceId: string;
|
|
13
|
+
command: string;
|
|
14
|
+
startedAt: string;
|
|
15
|
+
outcome: string;
|
|
16
|
+
totalMs: number;
|
|
17
|
+
unattributedMs: number;
|
|
18
|
+
droppedSpans: number;
|
|
19
|
+
phases: {
|
|
20
|
+
totalMs: number;
|
|
21
|
+
maximumMs: number;
|
|
22
|
+
phase: string;
|
|
23
|
+
operation: string;
|
|
24
|
+
count: number;
|
|
25
|
+
failures: number;
|
|
26
|
+
}[];
|
|
27
|
+
}[];
|
|
28
|
+
limit: number;
|
|
29
|
+
coverage: string;
|
|
30
|
+
session: string;
|
|
31
|
+
target: string;
|
|
32
|
+
}>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
const maximumBytes = 16 * 1024 ** 2;
|
|
4
|
+
async function rows(path) {
|
|
5
|
+
let text;
|
|
6
|
+
try {
|
|
7
|
+
const handle = await open(path, 'r');
|
|
8
|
+
try {
|
|
9
|
+
const size = (await handle.stat()).size, length = Math.min(size, maximumBytes), buffer = Buffer.alloc(length);
|
|
10
|
+
await handle.read(buffer, 0, length, size - length);
|
|
11
|
+
text = buffer.toString('utf8');
|
|
12
|
+
}
|
|
13
|
+
finally {
|
|
14
|
+
await handle.close();
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (error.code === 'ENOENT')
|
|
19
|
+
return [];
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
const out = [];
|
|
23
|
+
for (const line of text.split('\n')) {
|
|
24
|
+
if (!line.startsWith('{'))
|
|
25
|
+
continue;
|
|
26
|
+
try {
|
|
27
|
+
const row = JSON.parse(line);
|
|
28
|
+
if (typeof row.trace === 'string' && typeof row.span === 'string' && typeof row.phase === 'string' && Number.isFinite(row.durationMs))
|
|
29
|
+
out.push(row);
|
|
30
|
+
}
|
|
31
|
+
catch { /* A partially written or rotated line is not evidence. */ }
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
const ms = (value) => Math.round(value);
|
|
36
|
+
/**
|
|
37
|
+
* Summarizes retained timing spans per command attempt. Phases are aggregated by phase/operation; nested
|
|
38
|
+
* spans are reported separately and must not be added to their parents. `unattributedMs` is the root time
|
|
39
|
+
* not covered by any direct child span (sequential children assumed).
|
|
40
|
+
*/
|
|
41
|
+
export async function timingDiagnostic(workspaceDirectory, selected, options) {
|
|
42
|
+
const directory = join(workspaceDirectory, 'diagnostics');
|
|
43
|
+
const all = [...await rows(join(directory, 'timings.jsonl.previous')), ...await rows(join(directory, 'timings.jsonl'))];
|
|
44
|
+
const traces = new Map();
|
|
45
|
+
for (const row of all) {
|
|
46
|
+
if (row.session !== selected.session || row.target !== selected.target)
|
|
47
|
+
continue;
|
|
48
|
+
if (options.command && row.command !== options.command)
|
|
49
|
+
continue;
|
|
50
|
+
const list = traces.get(row.trace);
|
|
51
|
+
if (list)
|
|
52
|
+
list.push(row);
|
|
53
|
+
else
|
|
54
|
+
traces.set(row.trace, [row]);
|
|
55
|
+
}
|
|
56
|
+
const items = [...traces.values()].filter(list => list.some(row => row.parent === null)).sort((a, b) => String(a[0].at).localeCompare(String(b[0].at))).slice(-options.limit).reverse().map(list => {
|
|
57
|
+
const root = list.find(row => row.parent === null), phases = new Map();
|
|
58
|
+
for (const row of list) {
|
|
59
|
+
if (row === root)
|
|
60
|
+
continue;
|
|
61
|
+
const key = row.phase + '\0' + row.operation, entry = phases.get(key) ?? { phase: row.phase, operation: row.operation, count: 0, totalMs: 0, maximumMs: 0, failures: 0 };
|
|
62
|
+
entry.count++;
|
|
63
|
+
entry.totalMs += row.durationMs;
|
|
64
|
+
entry.maximumMs = Math.max(entry.maximumMs, row.durationMs);
|
|
65
|
+
if (row.outcome !== 'success')
|
|
66
|
+
entry.failures++;
|
|
67
|
+
phases.set(key, entry);
|
|
68
|
+
}
|
|
69
|
+
const direct = list.filter(row => row.parent === root.span).reduce((n, row) => n + row.durationMs, 0);
|
|
70
|
+
return { traceId: root.trace, command: root.command, startedAt: root.at, outcome: root.outcome, totalMs: ms(root.durationMs), unattributedMs: ms(Math.max(0, root.durationMs - direct)),
|
|
71
|
+
droppedSpans: root.droppedSpans ?? 0, phases: [...phases.values()].sort((a, b) => b.totalMs - a.totalMs).map(p => ({ ...p, totalMs: ms(p.totalMs), maximumMs: ms(p.maximumMs) })) };
|
|
72
|
+
});
|
|
73
|
+
return { ...selected, traces: items, limit: options.limit, coverage: 'Retained internal timing spans of the current and previous segment; nested phases overlap their parents. Reading does not start or probe Ghidra.' };
|
|
74
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
|
-
import { execFile } from 'node:child_process';
|
|
2
|
+
import { execFile, spawn } from 'node:child_process';
|
|
3
3
|
import { promisify } from 'node:util';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { timed } from '../internal-timing.js';
|
|
4
6
|
const exec = promisify(execFile);
|
|
5
7
|
function unavailable(pid) { try {
|
|
6
8
|
process.kill(pid, 0);
|
|
@@ -10,6 +12,9 @@ catch (e) {
|
|
|
10
12
|
return;
|
|
11
13
|
} return { birth: 'unavailable', strong: false }; }
|
|
12
14
|
export async function processIdentity(pid) {
|
|
15
|
+
return timed('tool.identity', process.platform, () => probeIdentity(pid));
|
|
16
|
+
}
|
|
17
|
+
async function probeIdentity(pid) {
|
|
13
18
|
if (!Number.isSafeInteger(pid) || pid < 1)
|
|
14
19
|
return;
|
|
15
20
|
try {
|
|
@@ -30,6 +35,10 @@ export async function processIdentity(pid) {
|
|
|
30
35
|
return { birth: match[3], strong: false, group: Number(match[2]) };
|
|
31
36
|
}
|
|
32
37
|
if (process.platform === 'win32') {
|
|
38
|
+
// A warm probe answers in milliseconds; the original one-shot probe remains the fallback.
|
|
39
|
+
const warm = await windowsBirth(pid);
|
|
40
|
+
if (warm !== undefined)
|
|
41
|
+
return warm === 'error' ? unavailable(pid) : warm ? { birth: warm, strong: true } : unavailable(pid);
|
|
33
42
|
const script = 'try{$p=[Diagnostics.Process]::GetProcessById(' + pid + ');try{$p.StartTime.ToUniversalTime().Ticks.ToString()}finally{$p.Dispose()}}catch [ArgumentException]{}';
|
|
34
43
|
const r = await exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, timeout: 15000, maxBuffer: 4096 });
|
|
35
44
|
return r.stdout.trim() ? { birth: r.stdout.trim(), strong: true } : unavailable(pid);
|
|
@@ -48,3 +57,79 @@ export async function processIdentity(pid) {
|
|
|
48
57
|
throw error;
|
|
49
58
|
}
|
|
50
59
|
}
|
|
60
|
+
let host;
|
|
61
|
+
const loop = '$ErrorActionPreference="Stop";while($null -ne ($line=[Console]::In.ReadLine())){$out="";try{$p=[Diagnostics.Process]::GetProcessById([int]$line);try{$out=$p.StartTime.ToUniversalTime().Ticks.ToString()}finally{$p.Dispose()}}catch [ArgumentException]{$out=""}catch{$out="error"};[Console]::Out.WriteLine("r:"+$out);[Console]::Out.Flush()}';
|
|
62
|
+
function retire() {
|
|
63
|
+
const current = host;
|
|
64
|
+
host = undefined;
|
|
65
|
+
if (!current)
|
|
66
|
+
return;
|
|
67
|
+
for (const p of current.pending.splice(0)) {
|
|
68
|
+
clearTimeout(p.timer);
|
|
69
|
+
p.resolve(undefined);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
current.child.kill();
|
|
73
|
+
}
|
|
74
|
+
catch { /* Already exited. */ }
|
|
75
|
+
}
|
|
76
|
+
function windowsHost() {
|
|
77
|
+
if (host && host.child.exitCode === null && host.child.signalCode === null)
|
|
78
|
+
return host;
|
|
79
|
+
// A long-lived host must not hold the caller's working directory (it would block its removal).
|
|
80
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', loop], { cwd: process.env.SystemRoot ?? tmpdir(), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
81
|
+
const created = { child, pending: [], buffer: '' };
|
|
82
|
+
host = created;
|
|
83
|
+
child.on('error', () => { if (host === created)
|
|
84
|
+
retire(); });
|
|
85
|
+
child.on('exit', () => { if (host === created)
|
|
86
|
+
retire(); });
|
|
87
|
+
child.stdin.on('error', () => { if (host === created)
|
|
88
|
+
retire(); });
|
|
89
|
+
child.stderr.resume();
|
|
90
|
+
child.stdout.setEncoding('utf8');
|
|
91
|
+
child.stdout.on('data', (chunk) => {
|
|
92
|
+
created.buffer += chunk;
|
|
93
|
+
let index;
|
|
94
|
+
while ((index = created.buffer.indexOf('\n')) >= 0) {
|
|
95
|
+
const line = created.buffer.slice(0, index).trim();
|
|
96
|
+
created.buffer = created.buffer.slice(index + 1);
|
|
97
|
+
if (!line.startsWith('r:'))
|
|
98
|
+
continue;
|
|
99
|
+
const next = created.pending.shift();
|
|
100
|
+
if (!next)
|
|
101
|
+
continue;
|
|
102
|
+
clearTimeout(next.timer);
|
|
103
|
+
next.resolve(line.slice(2));
|
|
104
|
+
}
|
|
105
|
+
if (created.buffer.length > 65536 && host === created)
|
|
106
|
+
retire();
|
|
107
|
+
});
|
|
108
|
+
// The host never keeps the owner alive.
|
|
109
|
+
child.unref();
|
|
110
|
+
for (const stream of [child.stdin, child.stdout, child.stderr])
|
|
111
|
+
stream.unref?.();
|
|
112
|
+
return created;
|
|
113
|
+
}
|
|
114
|
+
async function windowsBirth(pid) {
|
|
115
|
+
let current;
|
|
116
|
+
try {
|
|
117
|
+
current = windowsHost();
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
return new Promise(resolve => {
|
|
123
|
+
// The referenced deadline keeps the process alive only while an answer is pending.
|
|
124
|
+
const timer = setTimeout(() => { if (host === current)
|
|
125
|
+
retire(); resolve(undefined); }, 15000);
|
|
126
|
+
current.pending.push({ resolve, timer });
|
|
127
|
+
try {
|
|
128
|
+
current.child.stdin.write(String(pid) + '\n');
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
if (host === current)
|
|
132
|
+
retire();
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
}
|
|
@@ -11,6 +11,7 @@ import { atomicWrite, readJson, toolRoot, withToolLock, prepareRunRoot } from '.
|
|
|
11
11
|
import { processIdentity } from './identity.js';
|
|
12
12
|
import { javaClasspathArguments } from './java-arguments.js';
|
|
13
13
|
import { digest } from '../model.js';
|
|
14
|
+
import { timed } from '../internal-timing.js';
|
|
14
15
|
const owned = new Map();
|
|
15
16
|
const ownedKey = (directory, id) => resolve(directory) + '\0' + id;
|
|
16
17
|
/** Receipts report pending lifetime only; they never authorize a signal to another PID. */
|
|
@@ -44,7 +45,8 @@ async function nativeChildren(record) {
|
|
|
44
45
|
}));
|
|
45
46
|
}
|
|
46
47
|
export async function launchProcess(directory, spec, executable, args, options = {}, control = {}) {
|
|
47
|
-
|
|
48
|
+
// tool.launch minus tool.locked is the wait for the profile-wide tool lock.
|
|
49
|
+
return timed('tool.launch', spec.role, () => withToolLock(directory, spec.tool, () => timed('tool.locked', spec.role, async () => {
|
|
48
50
|
control.signal?.throwIfAborted();
|
|
49
51
|
toolRoot(directory, spec.tool);
|
|
50
52
|
if (!isAbsolute(executable))
|
|
@@ -183,7 +185,7 @@ export async function launchProcess(directory, spec, executable, args, options =
|
|
|
183
185
|
finally {
|
|
184
186
|
finishLaunch();
|
|
185
187
|
}
|
|
186
|
-
}, control.signal);
|
|
188
|
+
}), control.signal));
|
|
187
189
|
}
|
|
188
190
|
export async function processStatus(directory, id, verify) {
|
|
189
191
|
if (!/^[a-f0-9-]{36}$/.test(id))
|
|
@@ -286,11 +288,10 @@ export async function terminateProcess(directory, id, force, verify, graceful) {
|
|
|
286
288
|
if (error.code !== 'ESRCH')
|
|
287
289
|
throw error;
|
|
288
290
|
}
|
|
289
|
-
|
|
291
|
+
// Time-bounded: termination latency, not probe latency, decides how long a signalled process may take to exit.
|
|
292
|
+
for (const deadline = Date.now() + 30000; Date.now() < deadline; await delay(50))
|
|
290
293
|
if (!await processIdentity(record.pid))
|
|
291
294
|
break;
|
|
292
|
-
await delay(50);
|
|
293
|
-
}
|
|
294
295
|
if (await processIdentity(record.pid))
|
|
295
296
|
throw new CliError('Owned process did not stop; its record is retained.', { code: 'tool.process.busy' });
|
|
296
297
|
}
|
package/dist/src/transport.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { CliError } from '@eyeauras/cli-factory';
|
|
2
|
+
/** Replies that were too large to read: the request ran, unlike a capacity refusal with the same code. */
|
|
3
|
+
export declare const oversizedReplies: WeakSet<object>;
|
|
1
4
|
export interface Descriptor {
|
|
2
5
|
path: string;
|
|
3
6
|
method: string;
|
|
@@ -15,11 +18,43 @@ export declare class HttpBridge {
|
|
|
15
18
|
private timeoutMilliseconds?;
|
|
16
19
|
private saveTimeoutMilliseconds;
|
|
17
20
|
private schema?;
|
|
21
|
+
/**
|
|
22
|
+
* In-process helper listener of a leased headless worker: its loopback port and the compiled helper sources
|
|
23
|
+
* the worker must have been started with. Absent for GUI and unleased workers.
|
|
24
|
+
*/
|
|
25
|
+
owned?: {
|
|
26
|
+
port: number;
|
|
27
|
+
helpers: string;
|
|
28
|
+
};
|
|
18
29
|
constructor(endpoint: string, fetch?: typeof globalThis.fetch, signal?: AbortSignal | undefined, token?: string | undefined, timeoutMilliseconds?: number | undefined, saveTimeoutMilliseconds?: number);
|
|
19
30
|
private request;
|
|
20
31
|
private requestBody;
|
|
21
32
|
instance(): Promise<Record<string, unknown>>;
|
|
22
33
|
descriptor(path: string): Promise<Descriptor>;
|
|
34
|
+
/**
|
|
35
|
+
* Run a fixed helper script of this package for an open program. A leased worker runs its precompiled class
|
|
36
|
+
* in-process. When it cannot serve the script and says so before running anything (an older worker, other
|
|
37
|
+
* helper sources), and for GUI or unleased workers, the pinned inline provider compiles the same source as
|
|
38
|
+
* before. A retiring or saturated worker gets nothing more: the command fails as busy with nothing run.
|
|
39
|
+
* A lost reply is never retried: the script may have run.
|
|
40
|
+
*/
|
|
41
|
+
script(program: string, base: string, args?: string): Promise<unknown>;
|
|
42
|
+
/** One request to the worker's own listener; undefined when it said, before doing anything, that it cannot serve it. */
|
|
43
|
+
ownedRequest(path: string, body: Record<string, unknown>): Promise<unknown>;
|
|
23
44
|
call(path: string, params?: Record<string, unknown>): Promise<unknown>;
|
|
24
45
|
}
|
|
46
|
+
/** The refusal of every command that would open a checkout holding Ghidra recovery data; `scope` adds the two ways out. */
|
|
47
|
+
export declare function unsavedChanges(scope?: {
|
|
48
|
+
session: string;
|
|
49
|
+
target: string;
|
|
50
|
+
}): CliError;
|
|
51
|
+
/**
|
|
52
|
+
* Open the working program of a worker's project. A leased worker opens it and writes nothing; the bridge's own open
|
|
53
|
+
* also clears the analysis prompt and saves, so that Ghidra would report an untouched checkout as modified. A worker
|
|
54
|
+
* without that listener (GUI, unleased or of an earlier build) uses the bridge's open as before.
|
|
55
|
+
*/
|
|
56
|
+
export declare function openWorkerProgram(http: Pick<HttpBridge, 'call'> & Partial<Pick<HttpBridge, 'owned' | 'ownedRequest'>>, path: string, scope?: {
|
|
57
|
+
session: string;
|
|
58
|
+
target: string;
|
|
59
|
+
}): Promise<unknown>;
|
|
25
60
|
export declare function decodeMcp(result: unknown): unknown;
|
package/dist/src/transport.js
CHANGED
|
@@ -4,6 +4,12 @@ import { timed, currentTraceId } from './internal-timing.js';
|
|
|
4
4
|
import { auditEvent } from './activity-audit.js';
|
|
5
5
|
import { CliError } from '@eyeauras/cli-factory';
|
|
6
6
|
import { transportDiagnostic } from './diagnostic-error.js';
|
|
7
|
+
import { readFile } from 'node:fs/promises';
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
/** Replies that were too large to read: the request ran, unlike a capacity refusal with the same code. */
|
|
10
|
+
export const oversizedReplies = new WeakSet();
|
|
11
|
+
/** The worker refused an owned helper script before running anything. */
|
|
12
|
+
const notExecuted = Symbol('not executed');
|
|
7
13
|
/** The pinned GhidraMCP HTTP side of a dedicated bridge. No discovery by project name. */
|
|
8
14
|
export class HttpBridge {
|
|
9
15
|
endpoint;
|
|
@@ -13,6 +19,11 @@ export class HttpBridge {
|
|
|
13
19
|
timeoutMilliseconds;
|
|
14
20
|
saveTimeoutMilliseconds;
|
|
15
21
|
schema;
|
|
22
|
+
/**
|
|
23
|
+
* In-process helper listener of a leased headless worker: its loopback port and the compiled helper sources
|
|
24
|
+
* the worker must have been started with. Absent for GUI and unleased workers.
|
|
25
|
+
*/
|
|
26
|
+
owned;
|
|
16
27
|
constructor(endpoint, fetch = globalThis.fetch, signal, token, timeoutMilliseconds, saveTimeoutMilliseconds = 120000) {
|
|
17
28
|
this.endpoint = endpoint;
|
|
18
29
|
this.fetch = fetch;
|
|
@@ -28,20 +39,21 @@ export class HttpBridge {
|
|
|
28
39
|
if (timeoutMilliseconds !== undefined && (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds < 1 || timeoutMilliseconds > 1800000))
|
|
29
40
|
fail('invalid', 'Bridge timeout is outside the supported bound.');
|
|
30
41
|
}
|
|
31
|
-
async request(path, method, query, body) {
|
|
42
|
+
async request(path, method, query, body, ownedPort) {
|
|
32
43
|
return timed('native.http', path, async () => { try {
|
|
33
|
-
return await this.requestBody(path, method, query, body);
|
|
44
|
+
return await this.requestBody(path, method, query, body, ownedPort);
|
|
34
45
|
}
|
|
35
46
|
catch (error) {
|
|
36
47
|
auditEvent('transport.failed', { error, outcome: 'failure', traceId: currentTraceId() });
|
|
37
48
|
throw error;
|
|
38
49
|
} });
|
|
39
50
|
}
|
|
40
|
-
async requestBody(path, method, query, body) {
|
|
41
|
-
const url = new URL(path, this.endpoint);
|
|
51
|
+
async requestBody(path, method, query, body, ownedPort) {
|
|
52
|
+
const url = new URL(path, ownedPort === undefined ? this.endpoint : 'http://127.0.0.1:' + ownedPort);
|
|
42
53
|
// Import includes synchronous auto-analysis. Keep discovery/ordinary requests short,
|
|
43
54
|
// while allowing a real executable to finish its first analysis without losing the reply.
|
|
44
|
-
|
|
55
|
+
// The headless bridge saves inside open_program (Ghidra's open-time rewrite), so it shares the save budget.
|
|
56
|
+
const saving = path === '/save_program' || path === '/export_program' || path === '/open_program' || path === '/insight/open';
|
|
45
57
|
const timeoutMilliseconds = this.timeoutMilliseconds ?? (saving ? this.saveTimeoutMilliseconds : path === '/import_file' ? 600000 : 30000);
|
|
46
58
|
const signal = this.signal ? AbortSignal.any([this.signal, AbortSignal.timeout(timeoutMilliseconds)]) : AbortSignal.timeout(timeoutMilliseconds);
|
|
47
59
|
const transportFailure = (error, phase) => {
|
|
@@ -61,6 +73,14 @@ export class HttpBridge {
|
|
|
61
73
|
catch (error) {
|
|
62
74
|
return transportFailure(error, 'fetch');
|
|
63
75
|
}
|
|
76
|
+
// The owned listener answers 409 (or, in an older worker, 404) only before it runs anything. The inline provider
|
|
77
|
+
// serves a request this listener cannot; a retiring or saturated worker must not receive it by another door.
|
|
78
|
+
if (ownedPort !== undefined && (response.status === 404 || response.status === 409)) {
|
|
79
|
+
const reason = response.status === 404 ? 'absent' : await response.json().then(value => String(object(value).reason), () => '');
|
|
80
|
+
if (['absent', 'helpers', 'script', 'provider', 'program', 'unavailable'].includes(reason))
|
|
81
|
+
return notExecuted;
|
|
82
|
+
fail('busy', reason === 'retiring' ? 'The context worker is retiring and accepted nothing; run the command again.' : 'The context worker refused the helper script before running it; run the command again.', { operation: path });
|
|
83
|
+
}
|
|
64
84
|
if (!response.ok)
|
|
65
85
|
fail('remote', 'Ghidra bridge rejected the operation.', { operation: path, transport: transportDiagnostic(undefined, 'status', method, Number(url.port), response.status) });
|
|
66
86
|
// Bound even a chunked/malformed service response; never persist raw payloads as logs.
|
|
@@ -75,8 +95,15 @@ export class HttpBridge {
|
|
|
75
95
|
if (next.done)
|
|
76
96
|
break;
|
|
77
97
|
length += next.value.byteLength;
|
|
78
|
-
if (length > 1024 * 1024)
|
|
79
|
-
|
|
98
|
+
if (length > 1024 * 1024) {
|
|
99
|
+
try {
|
|
100
|
+
fail('limit', 'Ghidra response exceeded one MiB.');
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
oversizedReplies.add(error);
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
80
107
|
chunks.push(next.value);
|
|
81
108
|
}
|
|
82
109
|
}
|
|
@@ -118,6 +145,33 @@ export class HttpBridge {
|
|
|
118
145
|
fail('schema', 'Required Ghidra operation is missing from the observed schema.');
|
|
119
146
|
return tool;
|
|
120
147
|
}
|
|
148
|
+
/**
|
|
149
|
+
* Run a fixed helper script of this package for an open program. A leased worker runs its precompiled class
|
|
150
|
+
* in-process. When it cannot serve the script and says so before running anything (an older worker, other
|
|
151
|
+
* helper sources), and for GUI or unleased workers, the pinned inline provider compiles the same source as
|
|
152
|
+
* before. A retiring or saturated worker gets nothing more: the command fails as busy with nothing run.
|
|
153
|
+
* A lost reply is never retried: the script may have run.
|
|
154
|
+
*/
|
|
155
|
+
async script(program, base, args) {
|
|
156
|
+
if (!/^Insight[A-Za-z]+$/.test(base))
|
|
157
|
+
fail('invalid', 'Unsupported helper script.');
|
|
158
|
+
if (this.owned) {
|
|
159
|
+
const result = await this.request('/insight/script', 'POST', {}, { helpers: this.owned.helpers, script: base, program, ...(args === undefined ? {} : { args }) }, this.owned.port);
|
|
160
|
+
if (result !== notExecuted)
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
const source = await readFile(new URL('../../references/native/' + base + '.java', import.meta.url), 'utf8'), declaration = 'class ' + base + ' ';
|
|
164
|
+
if (!source.includes(declaration))
|
|
165
|
+
fail('configuration', 'Installed package omitted a native helper source.');
|
|
166
|
+
return this.call('/run_script_inline', { program, code: source.replace(declaration, 'class ' + base + '_' + randomUUID().replaceAll('-', '') + ' '), ...(args === undefined ? {} : { args }) });
|
|
167
|
+
}
|
|
168
|
+
/** One request to the worker's own listener; undefined when it said, before doing anything, that it cannot serve it. */
|
|
169
|
+
async ownedRequest(path, body) {
|
|
170
|
+
if (!this.owned)
|
|
171
|
+
return undefined;
|
|
172
|
+
const result = await this.request(path, 'POST', {}, body, this.owned.port);
|
|
173
|
+
return result === notExecuted ? undefined : result;
|
|
174
|
+
}
|
|
121
175
|
async call(path, params = {}) {
|
|
122
176
|
const tool = await this.descriptor(path);
|
|
123
177
|
const query = {}, body = {};
|
|
@@ -130,6 +184,22 @@ export class HttpBridge {
|
|
|
130
184
|
return this.request(path, tool.method, query, body);
|
|
131
185
|
}
|
|
132
186
|
}
|
|
187
|
+
/** The refusal of every command that would open a checkout holding Ghidra recovery data; `scope` adds the two ways out. */
|
|
188
|
+
export function unsavedChanges(scope) {
|
|
189
|
+
return new CliError('This checkout holds unsaved changes of an interrupted Ghidra session; they are kept and the program is not opened. Keep them with `ghidra changes recover-unsaved` or drop them with `ghidra changes discard-unsaved`, then run the command again.', { code: 'coordinator.blocked',
|
|
190
|
+
...(scope ? { next: ['recover-unsaved', 'discard-unsaved'].map(name => ['ghidra', 'changes', name, '--session', scope.session, '--target', scope.target]) } : {}) });
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Open the working program of a worker's project. A leased worker opens it and writes nothing; the bridge's own open
|
|
194
|
+
* also clears the analysis prompt and saves, so that Ghidra would report an untouched checkout as modified. A worker
|
|
195
|
+
* without that listener (GUI, unleased or of an earlier build) uses the bridge's open as before.
|
|
196
|
+
*/
|
|
197
|
+
export async function openWorkerProgram(http, path, scope) {
|
|
198
|
+
const opened = http.owned && http.ownedRequest ? await http.ownedRequest('/insight/open', { path }) : undefined;
|
|
199
|
+
if (opened && typeof opened === 'object' && opened.recoverable === true)
|
|
200
|
+
throw unsavedChanges(scope);
|
|
201
|
+
return opened === undefined ? http.call('/open_program', { path }) : opened;
|
|
202
|
+
}
|
|
133
203
|
export function decodeMcp(result) {
|
|
134
204
|
const r = object(result);
|
|
135
205
|
if (r.isError === true || !Array.isArray(r.content))
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Workspace, Scope } from './workspace.js';
|
|
2
|
+
/**
|
|
3
|
+
* What an unresolved outcome blocks and what to do. Opening the owning context reconciles every outcome its proofs
|
|
4
|
+
* establish. An outcome they cannot establish keeps the saved project and its journals. A context-local outcome
|
|
5
|
+
* leaves the target free, so research continues in a new session; an unresolved publication or shared model holds
|
|
6
|
+
* the whole target, so a new session of it waits too (other targets are unaffected).
|
|
7
|
+
*/
|
|
8
|
+
export declare function unresolvedGuidance(workspace: Workspace, scope: Scope): {
|
|
9
|
+
next: {
|
|
10
|
+
continueElsewhere?: string | undefined;
|
|
11
|
+
reconcile: string;
|
|
12
|
+
inspect: string;
|
|
13
|
+
};
|
|
14
|
+
owner: {
|
|
15
|
+
session: string;
|
|
16
|
+
target: string;
|
|
17
|
+
};
|
|
18
|
+
publication?: {
|
|
19
|
+
id: string;
|
|
20
|
+
session: string;
|
|
21
|
+
state: "unknown" | "verified" | "preparing" | "commit_intent" | "conflict";
|
|
22
|
+
} | undefined;
|
|
23
|
+
session: string;
|
|
24
|
+
target: string;
|
|
25
|
+
unresolvedRequests: {
|
|
26
|
+
operation: string;
|
|
27
|
+
state: import("./workspace.js").RequestState;
|
|
28
|
+
requestId?: string | undefined;
|
|
29
|
+
id: string;
|
|
30
|
+
}[];
|
|
31
|
+
targetHeld: boolean;
|
|
32
|
+
};
|
|
33
|
+
/** Follow-up argv (without the executable and profile) for the context that owns the unresolved outcome. */
|
|
34
|
+
export declare function ownerNext(detail: {
|
|
35
|
+
owner: Scope;
|
|
36
|
+
}): string[][];
|
|
37
|
+
type Guidance = ReturnType<typeof unresolvedGuidance>;
|
|
38
|
+
/** The profile is named: a fresh invocation without it can select another profile's workspace. */
|
|
39
|
+
export declare function cliPrefix(workspace: Workspace): string;
|
|
40
|
+
/** The advice sentence: reconcile (or, after a reconciliation that could not prove it, when to try again) and how to go on. */
|
|
41
|
+
export declare function unresolvedAdvice(detail: Guidance, reconciled?: boolean): string;
|
|
42
|
+
/** Refuse with the unresolved outcome, the reconciling command and how to keep working meanwhile. */
|
|
43
|
+
export declare function failUnresolved(workspace: Workspace, scope: Scope, message: string, reconciled?: boolean): never;
|
|
44
|
+
/** An operation whose outcome was just recorded as unknown keeps its error code; it gains the same guidance. */
|
|
45
|
+
export declare function unknownOutcome(workspace: Workspace, scope: Scope, error: unknown): unknown;
|
|
46
|
+
export {};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { CliError } from '@eyeauras/cli-factory';
|
|
2
|
+
import { fail, object } from './model.js';
|
|
3
|
+
/**
|
|
4
|
+
* What an unresolved outcome blocks and what to do. Opening the owning context reconciles every outcome its proofs
|
|
5
|
+
* establish. An outcome they cannot establish keeps the saved project and its journals. A context-local outcome
|
|
6
|
+
* leaves the target free, so research continues in a new session; an unresolved publication or shared model holds
|
|
7
|
+
* the whole target, so a new session of it waits too (other targets are unaffected).
|
|
8
|
+
*/
|
|
9
|
+
export function unresolvedGuidance(workspace, scope) {
|
|
10
|
+
// Only the public identity of the owning context: a context record carries private checkout and snapshot fields.
|
|
11
|
+
const publication = workspace.activePublication(scope.target), owner = publication ? { session: publication.session, target: publication.target } : { session: scope.session, target: scope.target };
|
|
12
|
+
// The outcomes of the owning context: a publication of another session is unresolved there, not here.
|
|
13
|
+
const requests = workspace.unresolved(owner).map(request => ({ id: request.id, ...(request.callerId ? { requestId: request.callerId } : {}), operation: request.operation, state: request.state }));
|
|
14
|
+
let modelUnresolved = false;
|
|
15
|
+
try {
|
|
16
|
+
modelUnresolved = workspace.model(scope.target).state !== 'ready';
|
|
17
|
+
}
|
|
18
|
+
catch { /* No shared model yet. */ }
|
|
19
|
+
const targetHeld = Boolean(publication) || modelUnresolved;
|
|
20
|
+
const cli = cliPrefix(workspace);
|
|
21
|
+
return { session: scope.session, target: scope.target, unresolvedRequests: requests, targetHeld,
|
|
22
|
+
...(publication ? { publication: { id: publication.id, session: publication.session, state: publication.state } } : {}),
|
|
23
|
+
// The profile is named: a fresh invocation without it can select another profile's workspace.
|
|
24
|
+
next: { reconcile: `${cli} ghidra open --target ${owner.target} --session ${owner.session}`, inspect: `${cli} sessions status ${owner.session} --target ${owner.target}`,
|
|
25
|
+
...(targetHeld ? {} : { continueElsewhere: `${cli} ghidra open --target ${scope.target} --session new` }) },
|
|
26
|
+
owner };
|
|
27
|
+
}
|
|
28
|
+
/** Follow-up argv (without the executable and profile) for the context that owns the unresolved outcome. */
|
|
29
|
+
export function ownerNext(detail) {
|
|
30
|
+
return [['sessions', 'status', detail.owner.session, '--target', detail.owner.target], ['ghidra', 'open', '--target', detail.owner.target, '--session', detail.owner.session]];
|
|
31
|
+
}
|
|
32
|
+
/** The profile is named: a fresh invocation without it can select another profile's workspace. */
|
|
33
|
+
export function cliPrefix(workspace) { return `insight-cli --profile ${workspace.profile}`; }
|
|
34
|
+
/** The advice sentence: reconcile (or, after a reconciliation that could not prove it, when to try again) and how to go on. */
|
|
35
|
+
export function unresolvedAdvice(detail, reconciled = false) {
|
|
36
|
+
const first = reconciled
|
|
37
|
+
? `Reconciliation could not prove its outcome yet; inspect \`${detail.next.inspect}\` and run \`${detail.next.reconcile}\` again once the cause (for example low memory or a busy server) is gone.`
|
|
38
|
+
: `Run \`${detail.next.reconcile}\` to reconcile it; it settles every outcome it can prove.`;
|
|
39
|
+
const meanwhile = detail.next.continueElsewhere ? `Continue meanwhile with \`${detail.next.continueElsewhere}\`.`
|
|
40
|
+
: detail.publication ? `The unresolved publication of session ${detail.publication.session} holds this target, so a new session of it waits as well; other targets are unaffected.`
|
|
41
|
+
: 'The shared model of this target is unresolved, so a new session of it waits as well; other targets are unaffected.';
|
|
42
|
+
return `${first} The saved project and its journals are retained. ${meanwhile}`;
|
|
43
|
+
}
|
|
44
|
+
/** Refuse with the unresolved outcome, the reconciling command and how to keep working meanwhile. */
|
|
45
|
+
export function failUnresolved(workspace, scope, message, reconciled = false) {
|
|
46
|
+
const detail = unresolvedGuidance(workspace, scope);
|
|
47
|
+
fail('blocked', `${message} ${unresolvedAdvice(detail, reconciled)}`, detail);
|
|
48
|
+
}
|
|
49
|
+
/** An operation whose outcome was just recorded as unknown keeps its error code; it gains the same guidance. */
|
|
50
|
+
export function unknownOutcome(workspace, scope, error) {
|
|
51
|
+
if (!(error instanceof CliError))
|
|
52
|
+
return error;
|
|
53
|
+
const detail = unresolvedGuidance(workspace, scope);
|
|
54
|
+
return new CliError(`${error.message} Its outcome is recorded as unknown and is never repeated blindly. ${unresolvedAdvice(detail)}`, { code: error.code, cause: error, result: { ...object(error.result ?? {}), ...detail } });
|
|
55
|
+
}
|
package/dist/src/windbg.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ToolInstaller } from './tool-runtime/installer.js';
|
|
|
3
3
|
import type { Workspace } from './workspace.js';
|
|
4
4
|
export declare function windbgInstaller(c: CommandContext): ToolInstaller;
|
|
5
5
|
export declare function windbgPlan(o: Record<string, unknown>, nonce: string): {
|
|
6
|
-
view: "modules" | "
|
|
6
|
+
view: "modules" | "memory" | "registers" | "threads" | "overview" | "stack" | "disassembly";
|
|
7
7
|
commands: string;
|
|
8
8
|
};
|
|
9
9
|
export declare function windbgSnapshot(stdout: string, nonce: string): {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Must stay well below the worker's hold expiry (three minutes). */
|
|
2
|
+
export declare const leaseHeartbeatMs = 60000;
|
|
3
|
+
export declare function withWorkerLeases<T>(action: () => Promise<T>): Promise<T>;
|
|
4
|
+
export declare function inWorkerLeaseScope(): boolean;
|
|
5
|
+
export declare function workerLeaseHeld(key: string): boolean;
|
|
6
|
+
/** The worker-side identity of this command's hold, when it has one. */
|
|
7
|
+
export declare function workerLeaseHolder(key: string): string | undefined;
|
|
8
|
+
/** Keep a worker held for the rest of the current command. Outside a command nothing is retained. */
|
|
9
|
+
export declare function holdWorkerLease(key: string, lease: {
|
|
10
|
+
renew: () => Promise<unknown>;
|
|
11
|
+
release: () => Promise<unknown>;
|
|
12
|
+
holder?: string;
|
|
13
|
+
}): void;
|
|
14
|
+
/** Release this command's hold now (for example before asking the worker to stop). */
|
|
15
|
+
export declare function releaseWorkerLease(key: string): Promise<void>;
|
|
16
|
+
/** A stopped worker needs no further renewal or release in this command. */
|
|
17
|
+
export declare function dropWorkerLease(key: string): void;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
const scope = new AsyncLocalStorage();
|
|
3
|
+
/** Must stay well below the worker's hold expiry (three minutes). */
|
|
4
|
+
export const leaseHeartbeatMs = 60000;
|
|
5
|
+
export async function withWorkerLeases(action) {
|
|
6
|
+
const held = new Map();
|
|
7
|
+
try {
|
|
8
|
+
return await scope.run(held, action);
|
|
9
|
+
}
|
|
10
|
+
finally {
|
|
11
|
+
for (const lease of held.values())
|
|
12
|
+
clearInterval(lease.timer);
|
|
13
|
+
await Promise.all([...held.values()].map(lease => lease.release().catch(() => { })));
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function inWorkerLeaseScope() { return scope.getStore() !== undefined; }
|
|
17
|
+
export function workerLeaseHeld(key) { return scope.getStore()?.has(key) === true; }
|
|
18
|
+
/** The worker-side identity of this command's hold, when it has one. */
|
|
19
|
+
export function workerLeaseHolder(key) { return scope.getStore()?.get(key)?.holder; }
|
|
20
|
+
/** Keep a worker held for the rest of the current command. Outside a command nothing is retained. */
|
|
21
|
+
export function holdWorkerLease(key, lease) {
|
|
22
|
+
const held = scope.getStore();
|
|
23
|
+
if (!held)
|
|
24
|
+
return;
|
|
25
|
+
const previous = held.get(key);
|
|
26
|
+
if (previous) {
|
|
27
|
+
clearInterval(previous.timer);
|
|
28
|
+
void previous.release().catch(() => { });
|
|
29
|
+
}
|
|
30
|
+
const timer = setInterval(() => { void lease.renew().catch(() => { }); }, leaseHeartbeatMs);
|
|
31
|
+
timer.unref();
|
|
32
|
+
held.set(key, { ...lease, timer });
|
|
33
|
+
}
|
|
34
|
+
/** Release this command's hold now (for example before asking the worker to stop). */
|
|
35
|
+
export async function releaseWorkerLease(key) {
|
|
36
|
+
const held = scope.getStore(), lease = held?.get(key);
|
|
37
|
+
if (!lease)
|
|
38
|
+
return;
|
|
39
|
+
clearInterval(lease.timer);
|
|
40
|
+
held.delete(key);
|
|
41
|
+
await lease.release().catch(() => { });
|
|
42
|
+
}
|
|
43
|
+
/** A stopped worker needs no further renewal or release in this command. */
|
|
44
|
+
export function dropWorkerLease(key) {
|
|
45
|
+
const held = scope.getStore(), lease = held?.get(key);
|
|
46
|
+
if (!lease)
|
|
47
|
+
return;
|
|
48
|
+
clearInterval(lease.timer);
|
|
49
|
+
held.delete(key);
|
|
50
|
+
}
|