@eyeauras/insight-cli 0.6.6 → 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.
Files changed (122) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/activity-audit.d.ts +130 -0
  4. package/dist/src/activity-audit.js +320 -0
  5. package/dist/src/analysis-storage.d.ts +5 -1
  6. package/dist/src/analysis-storage.js +9 -2
  7. package/dist/src/audit-commands.d.ts +10 -0
  8. package/dist/src/audit-commands.js +85 -0
  9. package/dist/src/audit-retention.d.ts +44 -0
  10. package/dist/src/audit-retention.js +167 -0
  11. package/dist/src/cli.js +28 -6
  12. package/dist/src/context-diagnostics.d.ts +1 -1
  13. package/dist/src/context-diagnostics.js +10 -2
  14. package/dist/src/contexts.d.ts +118 -10
  15. package/dist/src/contexts.js +851 -199
  16. package/dist/src/debugger.js +2 -1
  17. package/dist/src/diagnostic-error.d.ts +12 -0
  18. package/dist/src/diagnostic-error.js +82 -0
  19. package/dist/src/inline-script.js +3 -4
  20. package/dist/src/internal-timing.d.ts +8 -2
  21. package/dist/src/internal-timing.js +50 -7
  22. package/dist/src/lifecycle.d.ts +12 -1
  23. package/dist/src/lifecycle.js +34 -6
  24. package/dist/src/native-inputs.d.ts +6 -0
  25. package/dist/src/native-inputs.js +30 -6
  26. package/dist/src/native-queries.js +1 -6
  27. package/dist/src/native-service.d.ts +40 -0
  28. package/dist/src/native-service.js +406 -0
  29. package/dist/src/research.d.ts +30 -2
  30. package/dist/src/research.js +106 -27
  31. package/dist/src/server.d.ts +38 -1
  32. package/dist/src/server.js +160 -12
  33. package/dist/src/storage-gc.js +374 -341
  34. package/dist/src/sync-policy.js +2 -1
  35. package/dist/src/timed-backend.js +8 -0
  36. package/dist/src/timing-report.d.ts +32 -0
  37. package/dist/src/timing-report.js +74 -0
  38. package/dist/src/tool-runtime/identity.js +86 -1
  39. package/dist/src/tool-runtime/supervisor.js +6 -5
  40. package/dist/src/transport.d.ts +35 -0
  41. package/dist/src/transport.js +95 -16
  42. package/dist/src/unresolved-guidance.d.ts +46 -0
  43. package/dist/src/unresolved-guidance.js +55 -0
  44. package/dist/src/windbg.d.ts +1 -1
  45. package/dist/src/worker-lease.d.ts +17 -0
  46. package/dist/src/worker-lease.js +50 -0
  47. package/dist/src/workspace.d.ts +5 -9
  48. package/dist/src/workspace.js +34 -41
  49. package/package.json +1 -1
  50. package/references/native/InsightHeadlessMain.java +9 -2
  51. package/references/native/InsightNativeCheckout.java +113 -43
  52. package/references/native/InsightNativeFingerprint.java +28 -1
  53. package/references/native/InsightNativeRead.java +32 -9
  54. package/references/native/InsightNativeService.java +43 -0
  55. package/references/native/InsightNativeView.java +17 -6
  56. package/references/native/InsightOwnedScripts.java +170 -0
  57. package/references/native/InsightWorkerLease.java +132 -0
  58. package/references/recovery.md +68 -3
  59. package/references/research.md +71 -6
  60. package/references/setup.md +5 -1
  61. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  62. package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
  63. package/skill-bundle/insight-binary/SKILL.md +1 -1
  64. package/skill-bundle/insight-capture/SKILL.md +1 -1
  65. package/skill-bundle/insight-cli/SKILL.md +1 -1
  66. package/skill-bundle/insight-cli/references/recovery.md +68 -3
  67. package/skill-bundle/insight-cli/references/setup.md +5 -1
  68. package/skill-bundle/insight-die/SKILL.md +1 -1
  69. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  70. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  71. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  72. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  73. package/skill-bundle/insight-frida/SKILL.md +1 -1
  74. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  75. package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
  76. package/skill-bundle/insight-ghidra/references/research.md +71 -6
  77. package/skill-bundle/insight-ghidra/references/setup.md +5 -1
  78. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  79. package/skill-bundle/insight-interop/SKILL.md +1 -1
  80. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  81. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  82. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  83. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  84. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  85. package/skill-bundle/insight-overview/SKILL.md +1 -1
  86. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  87. package/skill-bundle/insight-re/SKILL.md +7 -1
  88. package/skill-bundle/insight-re/references/recovery.md +68 -3
  89. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  90. package/skill-bundle/insight-strace/SKILL.md +1 -1
  91. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  92. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  93. package/skill-bundle/manifest.json +1 -1
  94. package/skills/insight-artifacts/SKILL.md +1 -1
  95. package/skills/insight-artifacts/references/recovery.md +68 -3
  96. package/skills/insight-binary/SKILL.md +1 -1
  97. package/skills/insight-capture/SKILL.md +1 -1
  98. package/skills/insight-die/SKILL.md +1 -1
  99. package/skills/insight-dnspy/SKILL.md +1 -1
  100. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  101. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  102. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  103. package/skills/insight-frida/SKILL.md +1 -1
  104. package/skills/insight-ghidra/SKILL.md +1 -1
  105. package/skills/insight-ghidra/references/recovery.md +68 -3
  106. package/skills/insight-ghidra/references/research.md +71 -6
  107. package/skills/insight-ghidra/references/setup.md +5 -1
  108. package/skills/insight-ilspy/SKILL.md +1 -1
  109. package/skills/insight-interop/SKILL.md +1 -1
  110. package/skills/insight-lldb/SKILL.md +1 -1
  111. package/skills/insight-llvm/SKILL.md +1 -1
  112. package/skills/insight-managed-heap/SKILL.md +1 -1
  113. package/skills/insight-managed-metadata/SKILL.md +1 -1
  114. package/skills/insight-mitmproxy/SKILL.md +1 -1
  115. package/skills/insight-overview/SKILL.md +1 -1
  116. package/skills/insight-procmon/SKILL.md +1 -1
  117. package/skills/insight-re/SKILL.md +7 -1
  118. package/skills/insight-re/references/recovery.md +68 -3
  119. package/skills/insight-sevenzip/SKILL.md +1 -1
  120. package/skills/insight-strace/SKILL.md +1 -1
  121. package/skills/insight-tshark/SKILL.md +1 -1
  122. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1,6 +1,7 @@
1
1
  import { command, Permission } from '@eyeauras/cli-factory';
2
2
  import { scope } from './research.js';
3
3
  import { fail, id, object, text } from './model.js';
4
+ import { failUnresolved } from './unresolved-guidance.js';
4
5
  import { selectedOptions } from './arguments.js';
5
6
  export const manualPolicy = { publish: 'manual', refresh: 'manual' };
6
7
  export function syncPolicy(value) {
@@ -28,7 +29,7 @@ export class Synchronization {
28
29
  if (request.state !== 'accepted')
29
30
  fail('unknown', 'Policy change has a retained outcome.');
30
31
  if (this.workspace.unresolved(selected).length)
31
- fail('blocked', 'Reconcile the context outcome before changing its synchronization policy.');
32
+ failUnresolved(this.workspace, selected, 'The context outcome is unresolved; its synchronization policy cannot change yet.');
32
33
  const current = this.workspace.context(selected), result = { ...selected, state: 'configured', ...policy };
33
34
  this.workspace.startRequest(request.id);
34
35
  this.workspace.completeSavedRequest(selected, request.id, current.generation, { syncPolicy: policy }, result);
@@ -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
- return withToolLock(directory, spec.tool, async () => {
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
- for (let i = 0; i < 100; i++) {
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
  }
@@ -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;
@@ -1,7 +1,15 @@
1
1
  import { fail, object } from './model.js';
2
2
  import { parseDomainJson } from './json.js';
3
- import { timed } from './internal-timing.js';
3
+ import { timed, currentTraceId } from './internal-timing.js';
4
+ import { auditEvent } from './activity-audit.js';
4
5
  import { CliError } from '@eyeauras/cli-factory';
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');
5
13
  /** The pinned GhidraMCP HTTP side of a dedicated bridge. No discovery by project name. */
6
14
  export class HttpBridge {
7
15
  endpoint;
@@ -11,6 +19,11 @@ export class HttpBridge {
11
19
  timeoutMilliseconds;
12
20
  saveTimeoutMilliseconds;
13
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;
14
27
  constructor(endpoint, fetch = globalThis.fetch, signal, token, timeoutMilliseconds, saveTimeoutMilliseconds = 120000) {
15
28
  this.endpoint = endpoint;
16
29
  this.fetch = fetch;
@@ -26,22 +39,30 @@ export class HttpBridge {
26
39
  if (timeoutMilliseconds !== undefined && (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds < 1 || timeoutMilliseconds > 1800000))
27
40
  fail('invalid', 'Bridge timeout is outside the supported bound.');
28
41
  }
29
- async request(path, method, query, body) {
30
- return timed('native.http', path, () => this.requestBody(path, method, query, body));
42
+ async request(path, method, query, body, ownedPort) {
43
+ return timed('native.http', path, async () => { try {
44
+ return await this.requestBody(path, method, query, body, ownedPort);
45
+ }
46
+ catch (error) {
47
+ auditEvent('transport.failed', { error, outcome: 'failure', traceId: currentTraceId() });
48
+ throw error;
49
+ } });
31
50
  }
32
- async requestBody(path, method, query, body) {
33
- 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);
34
53
  // Import includes synchronous auto-analysis. Keep discovery/ordinary requests short,
35
54
  // while allowing a real executable to finish its first analysis without losing the reply.
36
- const saving = path === '/save_program' || path === '/export_program';
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';
37
57
  const timeoutMilliseconds = this.timeoutMilliseconds ?? (saving ? this.saveTimeoutMilliseconds : path === '/import_file' ? 600000 : 30000);
38
58
  const signal = this.signal ? AbortSignal.any([this.signal, AbortSignal.timeout(timeoutMilliseconds)]) : AbortSignal.timeout(timeoutMilliseconds);
39
- const transportFailure = () => {
59
+ const transportFailure = (error, phase) => {
60
+ const detail = { operation: path, transport: transportDiagnostic(error, phase, method, Number(url.port)) };
40
61
  if (this.signal?.aborted)
41
- fail('cancelled', `Ghidra request ${path} was cancelled; its outcome may require reconciliation.`, { operation: path });
62
+ fail('cancelled', `Ghidra request ${path} was cancelled; its outcome may require reconciliation.`, detail);
42
63
  if (signal.aborted)
43
- fail('timeout', `Ghidra request ${path} exceeded ${timeoutMilliseconds / 1000} seconds; its outcome may require reconciliation.${saving ? ' Configure profile saveSeconds before future work; inspect sessions status and never replay an uncertain script.' : ''}`, { operation: path, timeoutMilliseconds, ...(saving ? { phase: 'save', budgetSetting: 'saveSeconds', outcome: 'unknown' } : {}) });
44
- fail('transport', `Ghidra request ${path} did not complete; its outcome may require reconciliation.`, { operation: path });
64
+ fail('timeout', `Ghidra request ${path} exceeded ${timeoutMilliseconds / 1000} seconds; its outcome may require reconciliation.${saving ? ' Configure profile saveSeconds before future work; inspect sessions status and never replay an uncertain script.' : ''}`, { ...detail, timeoutMilliseconds, ...(saving ? { phase: 'save', budgetSetting: 'saveSeconds', outcome: 'unknown' } : {}) });
65
+ fail('transport', `Ghidra request ${path} did not complete; its outcome may require reconciliation.`, detail);
45
66
  };
46
67
  for (const [name, value] of Object.entries(query))
47
68
  url.searchParams.set(name, String(value));
@@ -49,11 +70,19 @@ export class HttpBridge {
49
70
  try {
50
71
  response = await this.fetch(url, { method, redirect: 'error', signal, headers: { ...(this.token ? { Authorization: 'Bearer ' + this.token } : {}), ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}) }, ...(method === 'POST' ? { body: JSON.stringify(body) } : {}) });
51
72
  }
52
- catch {
53
- return transportFailure();
73
+ catch (error) {
74
+ return transportFailure(error, 'fetch');
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 });
54
83
  }
55
84
  if (!response.ok)
56
- fail('remote', 'Ghidra bridge rejected the operation.');
85
+ fail('remote', 'Ghidra bridge rejected the operation.', { operation: path, transport: transportDiagnostic(undefined, 'status', method, Number(url.port), response.status) });
57
86
  // Bound even a chunked/malformed service response; never persist raw payloads as logs.
58
87
  const reader = response.body?.getReader();
59
88
  if (!reader)
@@ -66,15 +95,22 @@ export class HttpBridge {
66
95
  if (next.done)
67
96
  break;
68
97
  length += next.value.byteLength;
69
- if (length > 1024 * 1024)
70
- fail('limit', 'Ghidra response exceeded one MiB.');
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
+ }
71
107
  chunks.push(next.value);
72
108
  }
73
109
  }
74
110
  catch (error) {
75
111
  if (error instanceof CliError)
76
112
  throw error;
77
- return transportFailure();
113
+ return transportFailure(error, 'body');
78
114
  }
79
115
  finally {
80
116
  await reader.cancel().catch(() => { });
@@ -109,6 +145,33 @@ export class HttpBridge {
109
145
  fail('schema', 'Required Ghidra operation is missing from the observed schema.');
110
146
  return tool;
111
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
+ }
112
175
  async call(path, params = {}) {
113
176
  const tool = await this.descriptor(path);
114
177
  const query = {}, body = {};
@@ -121,6 +184,22 @@ export class HttpBridge {
121
184
  return this.request(path, tool.method, query, body);
122
185
  }
123
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
+ }
124
203
  export function decodeMcp(result) {
125
204
  const r = object(result);
126
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
+ }
@@ -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" | "registers" | "memory" | "threads" | "overview" | "stack" | "disassembly";
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): {