@eyeauras/insight-cli 0.5.4 → 0.5.6
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/analysis-storage.d.ts +2 -1
- package/dist/src/analysis-storage.js +71 -7
- package/dist/src/context-diagnostics.d.ts +1 -1
- package/dist/src/context-diagnostics.js +1 -1
- package/dist/src/contexts.d.ts +1 -0
- package/dist/src/contexts.js +63 -5
- package/dist/src/ghidra-processes.js +6 -1
- package/dist/src/initial-model.d.ts +3 -2
- package/dist/src/initial-model.js +23 -15
- package/dist/src/server.d.ts +1 -0
- package/dist/src/server.js +5 -2
- package/dist/src/tool-runtime/java-arguments.js +2 -2
- package/dist/src/tool-runtime/native-process-proof.d.ts +2 -0
- package/dist/src/tool-runtime/native-process-proof.js +26 -0
- package/dist/src/tool-runtime/run.js +3 -3
- package/dist/src/tool-runtime/store.d.ts +2 -0
- package/dist/src/tool-runtime/store.js +26 -8
- package/dist/src/tool-runtime/supervisor.js +4 -4
- package/package.json +1 -1
- package/references/native/InsightInitialImport.java +2 -2
- package/references/native/InsightInitialJournal.java +9 -0
- package/references/native/InsightInitialPublication.java +1 -1
- package/references/native/InsightInitialRecovery.java +131 -0
- package/references/recovery.md +25 -0
- package/references/storage.md +11 -0
- package/runtime/native/process-identity-darwin-arm64 +0 -0
- package/runtime/native/process-identity-darwin.c +47 -0
- package/runtime/native/process-identity.provenance.json +18 -0
- package/skill-bundle/insight-artifacts/SKILL.md +1 -1
- package/skill-bundle/insight-artifacts/references/recovery.md +25 -0
- package/skill-bundle/insight-artifacts/references/storage.md +11 -0
- 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 +25 -0
- package/skill-bundle/insight-cli/references/storage.md +11 -0
- 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 +4 -1
- package/skill-bundle/insight-ghidra/references/recovery.md +25 -0
- package/skill-bundle/insight-ghidra/references/storage.md +11 -0
- 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 +25 -0
- package/skill-bundle/insight-re/references/storage.md +11 -0
- 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 +25 -0
- package/skills/insight-artifacts/references/storage.md +11 -0
- 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 +4 -1
- package/skills/insight-ghidra/references/recovery.md +25 -0
- package/skills/insight-ghidra/references/storage.md +11 -0
- 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 +25 -0
- package/skills/insight-re/references/storage.md +11 -0
- 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
package/.cli-package-build.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"artifact":"
|
|
1
|
+
{"version":1,"artifact":"019e53d8315780cfa97539254385fde8d16f9944ede8d2a6636b319d4fda6c17"}
|
package/SKILL.md
CHANGED
|
@@ -3,7 +3,7 @@ name: insight-cli
|
|
|
3
3
|
description: Choose and prepare reverse-engineering capabilities from the insight-cli toolbox for binary, managed-code and runtime investigations. Use to discover the appropriate tool or its packaged skill before installing native runtimes.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
# insight-cli 0.5.
|
|
6
|
+
# insight-cli 0.5.6
|
|
7
7
|
|
|
8
8
|
If local help/status reports AppData or IPC access denied, retry that **read-only probe**
|
|
9
9
|
with the agent host's normal permission escalation, then use that route for later authorized
|
|
@@ -115,7 +115,8 @@ export declare class AnalysisStorage {
|
|
|
115
115
|
}>;
|
|
116
116
|
private checkCopy;
|
|
117
117
|
private continue;
|
|
118
|
-
|
|
118
|
+
private repairBinding;
|
|
119
|
+
resume(c: CommandContext, repairProfile?: boolean): Promise<{
|
|
119
120
|
state: "rolled_back";
|
|
120
121
|
id: string;
|
|
121
122
|
directory: string;
|
|
@@ -251,8 +251,14 @@ export class AnalysisStorage {
|
|
|
251
251
|
fail('busy', 'Finish active commands before storage migration.');
|
|
252
252
|
this.changing.add(key);
|
|
253
253
|
try {
|
|
254
|
-
|
|
255
|
-
|
|
254
|
+
let processes, native;
|
|
255
|
+
try {
|
|
256
|
+
processes = (await listProcesses(key)).filter(p => !['exited', 'failed'].includes(p.state));
|
|
257
|
+
native = await runtimeProcesses(key);
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
throw new CliError('Cannot verify storage process inventory. Inspect storage show and preserve legacy compatibility paths before retrying.', { code: 'storage.inventory', cause: error, next: [['storage', 'show']] });
|
|
261
|
+
}
|
|
256
262
|
if (processes.length || native.length)
|
|
257
263
|
throw new CliError('Close the profile contexts and stop its owned server/processes before migration. Unverified lifetimes also block copying.', { code: 'storage.busy', result: { processes, native }, next: [['tools', 'processes']] });
|
|
258
264
|
await this.release(c);
|
|
@@ -354,8 +360,14 @@ export class AnalysisStorage {
|
|
|
354
360
|
return this.restore(c, j);
|
|
355
361
|
if (j.state === 'cleaning')
|
|
356
362
|
return this.finishCleanup(c, j);
|
|
357
|
-
if (terminal(j.state) && !(j.automatic && j.state === 'committed'))
|
|
358
|
-
|
|
363
|
+
if (terminal(j.state) && !(j.automatic && j.state === 'committed')) {
|
|
364
|
+
const selected = { ...c, profile: await this.store(c).get(c.profile.name) };
|
|
365
|
+
await this.validate(selected);
|
|
366
|
+
const status = await this.show(selected);
|
|
367
|
+
if (status.availability !== 'available')
|
|
368
|
+
throw new CliError('Completed migration storage is unavailable. Inspect storage show before retrying.', { code: 'storage.unavailable', next: [['storage', 'show']] });
|
|
369
|
+
return status;
|
|
370
|
+
}
|
|
359
371
|
if (j.makeDefault && !j.defaultApplied) {
|
|
360
372
|
const base = dirname(dirname(j.destination));
|
|
361
373
|
if (await canonicalFuture(base) !== base)
|
|
@@ -535,8 +547,60 @@ export class AnalysisStorage {
|
|
|
535
547
|
}
|
|
536
548
|
return { state: j.state, id: j.id, directory: j.destination, manifest: j.manifest, sourceRetained: true, defaultBaseDirectory: storageDefault(c)?.base ?? null, installationDefault: j.makeDefault ? (j.defaultSuperseded ? 'superseded' : 'configured') : 'unchanged', rollback: 'storage rollback', cleanup: 'storage cleanup' };
|
|
537
549
|
}
|
|
538
|
-
async
|
|
539
|
-
|
|
550
|
+
async repairBinding(c, j) {
|
|
551
|
+
if (!['committed', 'cleaned'].includes(j.state))
|
|
552
|
+
fail('repair', 'Profile repair requires a completed migration. Resume the pending transaction without --repair-profile.');
|
|
553
|
+
if (await directoryIdentity(j.source) !== j.sourceIdentity || await canonicalFuture(j.destination) !== j.destination || !j.targetIdentity || await directoryIdentity(j.destination) !== j.targetIdentity)
|
|
554
|
+
fail('binding', 'Migration source or destination identity changed. Preserve both copies; profile repair was refused.');
|
|
555
|
+
if (await directoryIdentity(j.destinationAnchor) !== j.destinationIdentity)
|
|
556
|
+
fail('volume', 'Migration destination volume changed. Profile repair was refused.');
|
|
557
|
+
if (j.defaultBinding)
|
|
558
|
+
validateStorageDefault(c, j.defaultBinding);
|
|
559
|
+
if (j.defaultBaseIdentity && await directoryIdentity(dirname(dirname(j.destination))) !== j.defaultBaseIdentity)
|
|
560
|
+
fail('volume', 'Storage base changed. Profile repair was refused.');
|
|
561
|
+
const marker = await readJson(join(j.destination, '.insight-analysis.json'));
|
|
562
|
+
if (marker?.schema !== 1 || marker.id !== j.id || marker.binding !== j.binding || marker.profile !== j.profile)
|
|
563
|
+
fail('binding', 'Destination ownership does not match the retained migration. Profile repair was refused.');
|
|
564
|
+
for (const tree of analysisTrees) {
|
|
565
|
+
const target = join(j.destination, tree), alias = join(j.source, tree);
|
|
566
|
+
try {
|
|
567
|
+
if (await canonicalFuture(target) !== target || !(await lstat(target)).isDirectory() || !(await lstat(alias)).isSymbolicLink() || await realpath(alias) !== target)
|
|
568
|
+
fail('aliases', 'A migration compatibility path changed. Preserve the conflicting path and restore its recorded destination before profile repair.');
|
|
569
|
+
}
|
|
570
|
+
catch (error) {
|
|
571
|
+
if (error instanceof CliError)
|
|
572
|
+
throw error;
|
|
573
|
+
throw new CliError('Cannot verify a migration compatibility path. Preserve both copies before profile repair.', { code: 'storage.aliases', cause: error });
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const setting = c.profile.values.analysisDirectory;
|
|
577
|
+
if (setting !== undefined && setting !== null && setting !== j.previous && setting !== j.source && setting !== j.destination)
|
|
578
|
+
fail('configuration', 'The profile selects a different storage location. Preserve it; automatic profile repair was refused.');
|
|
579
|
+
}
|
|
580
|
+
async resume(c, repairProfile = false) {
|
|
581
|
+
const j = await this.journal(c, true);
|
|
582
|
+
if (!j)
|
|
583
|
+
fail('missing', 'No migration journal exists.');
|
|
584
|
+
// Diagnose a terminal profile mismatch before scanning legacy native paths.
|
|
585
|
+
if (['committed', 'cleaned'].includes(j.state)) {
|
|
586
|
+
if (repairProfile)
|
|
587
|
+
await this.repairBinding(c, j);
|
|
588
|
+
else if (analysisDirectory(c) !== j.destination)
|
|
589
|
+
throw new CliError('Factory profile and completed migration differ. Verify and restore the profile with storage resume --repair-profile.', { code: 'storage.configuration', next: [['storage', 'resume', '--repair-profile']] });
|
|
590
|
+
}
|
|
591
|
+
else if (repairProfile)
|
|
592
|
+
fail('repair', 'Profile repair requires a completed migration. Resume without --repair-profile.');
|
|
593
|
+
return this.exclusive(c, async () => {
|
|
594
|
+
if (repairProfile) {
|
|
595
|
+
c = { ...c, profile: await this.store(c).get(c.profile.name) };
|
|
596
|
+
await this.repairBinding(c, j);
|
|
597
|
+
await this.store(c).set(c.profile.name, { analysisDirectory: j.destination });
|
|
598
|
+
await sync(join(c.appArguments.RoamingAppDataDirectory, 'profiles.json'));
|
|
599
|
+
c = { ...c, profile: await this.store(c).get(c.profile.name) };
|
|
600
|
+
}
|
|
601
|
+
return this.continue(c, j);
|
|
602
|
+
});
|
|
603
|
+
}
|
|
540
604
|
async rollback(c) {
|
|
541
605
|
return this.exclusive(c, async () => {
|
|
542
606
|
const j = await this.journal(c, true);
|
|
@@ -650,7 +714,7 @@ export class AnalysisStorage {
|
|
|
650
714
|
command('default', 'Set the installation storage base for new profiles; preserve existing data locations', ({ options: o }, c) => this.setDefault(c, o.directory), { permission: Permission.Update, options: [directory] }),
|
|
651
715
|
command('configure', 'Choose storage for an empty profile and subsequent new profiles', ({ options: o }, c) => this.migrate(c, o.directory, false, true, Boolean(o.profileOnly)), { permission: Permission.Update, options: [directory, profileOnly] }),
|
|
652
716
|
command('migrate', 'Copy and verify all analysis data, retain source, then switch storage', ({ options: o }, c) => this.migrate(c, o.directory, Boolean(o.dryRun), false, Boolean(o.profileOnly)), { permission: Permission.Update, options: [directory, profileOnly, { flags: '--dry-run', description: 'Read-only path, capacity and quiescence preflight; create no migration' }] }),
|
|
653
|
-
command('resume', 'Resume
|
|
717
|
+
command('resume', 'Resume migration, or explicitly repair its completed profile binding', ({ options: o }, c) => this.resume(c, Boolean(o.repairProfile)), { permission: Permission.Update, options: [{ flags: '--repair-profile', description: 'Restore a completed migration setting after verifying destination ownership and compatibility paths' }] }),
|
|
654
718
|
command('rollback', 'Restore retained source; refuse after any destination content changes', (_i, c) => this.rollback(c), { permission: Permission.Update }),
|
|
655
719
|
command('cleanup', 'Delete verified retained source copies; retain compatibility paths permanently', (_i, c) => this.cleanup(c), { permission: 'Destructive' }),
|
|
656
720
|
]);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type CommandContext, type CommandDefinition } from '@eyeauras/cli-factory';
|
|
2
2
|
import { type Research } from './research.js';
|
|
3
3
|
import type { Workspace, Scope } from './workspace.js';
|
|
4
|
-
export type StopReason = 'explicit_close' | 'view_replaced' | 'mode_changed' | 'owner_dispose' | 'startup_failed' | 'temporary_complete' | 'legacy_cleanup' | 'unknown';
|
|
4
|
+
export type StopReason = 'explicit_close' | 'view_replaced' | 'mode_changed' | 'owner_dispose' | 'startup_failed' | 'temporary_complete' | 'legacy_cleanup' | 'backend_unresponsive' | 'unknown';
|
|
5
5
|
type Event = {
|
|
6
6
|
at: string;
|
|
7
7
|
event: 'start' | 'restore' | 'stop';
|
|
@@ -7,7 +7,7 @@ import { object, fail, stable } from './model.js';
|
|
|
7
7
|
import { selectedOptions } from './arguments.js';
|
|
8
8
|
const writes = new Map();
|
|
9
9
|
const journal = (workspace, context) => join(workspace.directory, 'diagnostics', 'lifecycle', context + '.json');
|
|
10
|
-
const reasons = new Set(['explicit_close', 'view_replaced', 'mode_changed', 'owner_dispose', 'startup_failed', 'temporary_complete', 'legacy_cleanup', 'unknown', 'native_launch', 'saved_snapshot']);
|
|
10
|
+
const reasons = new Set(['explicit_close', 'view_replaced', 'mode_changed', 'owner_dispose', 'startup_failed', 'temporary_complete', 'legacy_cleanup', 'unknown', 'native_launch', 'saved_snapshot', 'backend_unresponsive']);
|
|
11
11
|
async function events(path) {
|
|
12
12
|
try {
|
|
13
13
|
const rows = JSON.parse(await readFile(path, 'utf8'));
|
package/dist/src/contexts.d.ts
CHANGED
package/dist/src/contexts.js
CHANGED
|
@@ -28,7 +28,8 @@ import { nativeQuery } from './native-queries.js';
|
|
|
28
28
|
import { runInline } from './inline-script.js';
|
|
29
29
|
import { researchView } from './research-view.js';
|
|
30
30
|
import { sdkWrites } from './sdk-contracts.js';
|
|
31
|
-
import { initialIntent, initializeModel } from './initial-model.js';
|
|
31
|
+
import { initialRoot, initialIntent, initializeModel, validateInitialIntent } from './initial-model.js';
|
|
32
|
+
import { initialProgress } from './initial-progress.js';
|
|
32
33
|
import { managedGhidraDebugger, prepareGhidraDebugger } from './ghidra-debugger-runtime.js';
|
|
33
34
|
const alive = (pid) => {
|
|
34
35
|
try {
|
|
@@ -364,7 +365,38 @@ export class GhidraContexts {
|
|
|
364
365
|
if (model.state === 'ready')
|
|
365
366
|
return;
|
|
366
367
|
const server = this.server(), binding = await server.ensure();
|
|
367
|
-
if (
|
|
368
|
+
if (this.workspace.activePublication(target.id))
|
|
369
|
+
fail('blocked', 'Shared publication requires reconciliation before initial-model recovery.');
|
|
370
|
+
const intent = await initialIntent(this.workspace, target.id);
|
|
371
|
+
if (intent) {
|
|
372
|
+
await validateInitialIntent(this.workspace, target, binding, this.inputs.fingerprint, undefined, true);
|
|
373
|
+
if (intent.runtimeFingerprint !== this.inputs.fingerprint) {
|
|
374
|
+
const root = initialRoot(this.workspace, target.id);
|
|
375
|
+
const result = await server.initialRecovery(binding, root, this.inputs.fingerprint);
|
|
376
|
+
if (result.state === 'busy')
|
|
377
|
+
fail('busy', 'The retained initial-model worker is still active.');
|
|
378
|
+
if (result.state === 'candidate') {
|
|
379
|
+
const receipt = text(result.receipt);
|
|
380
|
+
if (!/^canonical-[a-f0-9-]{36}\.json$/.test(receipt))
|
|
381
|
+
fail('binding', 'Invalid canonical recovery receipt.');
|
|
382
|
+
const proof = await server.initialRecovery(binding, root, this.inputs.fingerprint, receipt);
|
|
383
|
+
if (proof.state !== 'verified' || proof.version !== result.version || proof.snapshotBuffersVerified !== true || proof.snapshot !== result.snapshot ||
|
|
384
|
+
typeof proof.snapshot !== 'string' || !/^canonical-[a-f0-9-]{36}\.gzf$/.test(proof.snapshot))
|
|
385
|
+
fail('unknown', 'Canonical model changed or independent recovery readback remains unproved.');
|
|
386
|
+
const snapshot = await this.workspace.captureSnapshot(join(root, proof.snapshot));
|
|
387
|
+
if (snapshot.sha256 !== proof.snapshotSha256)
|
|
388
|
+
fail('binding', 'Recovered canonical snapshot changed.');
|
|
389
|
+
this.workspace.establishModel(target.id, version(proof.version), snapshot);
|
|
390
|
+
await initialProgress(root, target.id, 'complete', 'complete');
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (result.state !== 'absent' || result.root !== 'runtime-' + this.inputs.fingerprint)
|
|
394
|
+
fail('unknown', 'Retained initial-model outcome requires reconciliation.');
|
|
395
|
+
await initializeModel(this.workspace, target, binding, server, this.inputs.fingerprint, join(root, String(result.root)));
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (!intent) {
|
|
368
400
|
// Old builds imported into an unversioned local shared-project stage. First stop
|
|
369
401
|
// its authenticated worker; a failed probe is never treated as authoritative absence.
|
|
370
402
|
if (model.state === 'unknown')
|
|
@@ -429,7 +461,7 @@ export class GhidraContexts {
|
|
|
429
461
|
}
|
|
430
462
|
async open(scope, request) {
|
|
431
463
|
const context = this.workspace.context(scope), target = this.workspace.target(scope.target);
|
|
432
|
-
if (this.workspace.unresolved(scope).some(intent => intent.id !== request))
|
|
464
|
+
if (this.workspace.unresolved(scope).some(intent => intent.id !== request && intent.operation !== 'ghidra.open'))
|
|
433
465
|
fail('blocked', 'This context retains an unresolved operation; reconcile its recorded outcome before continuing.');
|
|
434
466
|
let binding;
|
|
435
467
|
try {
|
|
@@ -458,8 +490,15 @@ export class GhidraContexts {
|
|
|
458
490
|
if (binding && !stopped && alive(binding.pid)) {
|
|
459
491
|
if (binding.context !== context.id)
|
|
460
492
|
fail('binding', 'Native process belongs to a different working context.');
|
|
461
|
-
|
|
462
|
-
|
|
493
|
+
try {
|
|
494
|
+
await this.verified(binding, target);
|
|
495
|
+
return context;
|
|
496
|
+
}
|
|
497
|
+
catch (error) {
|
|
498
|
+
if (!await this.retireUnresponsive(scope, binding, error))
|
|
499
|
+
throw error;
|
|
500
|
+
stopped = true;
|
|
501
|
+
}
|
|
463
502
|
}
|
|
464
503
|
if (binding?.mode === 'gui')
|
|
465
504
|
await this.debuggerReleased(binding);
|
|
@@ -486,6 +525,25 @@ export class GhidraContexts {
|
|
|
486
525
|
return this.workspace.saveContext(scope, context.generation, { state: 'ready', baseRevision: model.sharedRevision,
|
|
487
526
|
baseSnapshot: snapshot, workingSnapshot: snapshot });
|
|
488
527
|
}
|
|
528
|
+
async retireUnresponsive(scope, binding, error) {
|
|
529
|
+
const failure = error;
|
|
530
|
+
if (!['coordinator.timeout', 'coordinator.transport'].includes(failure.code ?? '') || failure.result?.operation !== '/mcp/instance_info' ||
|
|
531
|
+
binding.mode !== 'headless' || !binding.toolProcessId)
|
|
532
|
+
return false;
|
|
533
|
+
const context = this.workspace.context(scope);
|
|
534
|
+
if (!context.workingSnapshot || context.debugger?.connected || this.workspace.activePublication(scope.target) ||
|
|
535
|
+
this.workspace.unresolved(scope).some(intent => intent.operation !== 'ghidra.open'))
|
|
536
|
+
return false;
|
|
537
|
+
// Verify acknowledged bytes before retiring anything. Unknown mutations stay blocked.
|
|
538
|
+
await this.workspace.artifacts.verify(context.workingSnapshot);
|
|
539
|
+
const row = await processStatus(this.c.appArguments.AppDataDirectory, binding.toolProcessId, r => verifyGhidraProcess(r, this.c));
|
|
540
|
+
if (row.state !== 'running' || row.pid !== binding.pid || row.tool !== 'ghidra' || row.role !== 'context' || row.session !== scope.session ||
|
|
541
|
+
row.target !== scope.target || row.installation !== binding.runtimeFingerprint || row.metadata?.contextRoot !== binding.root)
|
|
542
|
+
return false;
|
|
543
|
+
await terminateProcess(this.c.appArguments.AppDataDirectory, binding.toolProcessId, true, r => verifyGhidraProcess(r, this.c));
|
|
544
|
+
await this.stopRecord({ binding, http: new HttpBridge(binding.endpoint) }, false, true, 'backend_unresponsive');
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
489
547
|
async selected(scope) {
|
|
490
548
|
const context = this.workspace.context(scope);
|
|
491
549
|
const binding = JSON.parse(await readFile(join(this.directory(), 'context', context.id, 'current.json'), 'utf8'));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nativeProcessProof } from './tool-runtime/native-process-proof.js';
|
|
1
2
|
import { sameDirectory, ownedDirectory, projectPathWithin } from './directory-identity.js';
|
|
2
3
|
import { runtimeSelection } from './runtime-selection.js';
|
|
3
4
|
import { join, resolve, relative, sep, dirname } from 'node:path';
|
|
@@ -52,7 +53,11 @@ export async function verifyGhidraProcess(r, c) {
|
|
|
52
53
|
const root = await ownedPath(c, r.metadata.contextRoot), binding = JSON.parse(await readFile(join(root, 'process.json'), 'utf8'));
|
|
53
54
|
if (!sameDirectory(binding.root, root) || binding.pid !== r.pid || binding.runtimeFingerprint !== r.installation || binding.target !== r.target)
|
|
54
55
|
return false;
|
|
55
|
-
const token = await c.secrets.require(binding.tokenSecret)
|
|
56
|
+
const token = await c.secrets.require(binding.tokenSecret);
|
|
57
|
+
// A headless JVM may be unable to serve HTTP while the kernel still proves its token, executable and private context root.
|
|
58
|
+
if (binding.mode === 'headless' && await nativeProcessProof(r.pid, r.executable, root, token))
|
|
59
|
+
return true;
|
|
60
|
+
const info = await new HttpBridge(binding.endpoint, c.fetch, undefined, token, 1500).instance();
|
|
56
61
|
return info.pid === r.pid && info.tcp_port === Number(new URL(binding.endpoint).port) && projectPathWithin(info.project_path, binding.root);
|
|
57
62
|
}
|
|
58
63
|
return undefined;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Workspace, ResearchTarget } from './workspace.js';
|
|
2
2
|
import type { GhidraServer, ServerBinding } from './server.js';
|
|
3
3
|
export declare const initialRoot: (workspace: Workspace, target: string) => string;
|
|
4
|
-
export declare function initialIntent(workspace: Workspace, target: string): Promise<Record<string, unknown> | undefined>;
|
|
4
|
+
export declare function initialIntent(workspace: Workspace, target: string, root?: string): Promise<Record<string, unknown> | undefined>;
|
|
5
|
+
export declare function validateInitialIntent(workspace: Workspace, target: ResearchTarget, binding: ServerBinding, fingerprint: string, root?: string, allowRuntimeChange?: boolean): Promise<Record<string, unknown>>;
|
|
5
6
|
/** Immutable input/authority binding; private attempts and conditional first creation share it. */
|
|
6
|
-
export declare function initializeModel(workspace: Workspace, target: ResearchTarget, binding: ServerBinding, server: Pick<GhidraServer, 'initialImport' | 'initialPublication'>, fingerprint: string): Promise<void>;
|
|
7
|
+
export declare function initializeModel(workspace: Workspace, target: ResearchTarget, binding: ServerBinding, server: Pick<GhidraServer, 'initialImport' | 'initialPublication'>, fingerprint: string, root?: string): Promise<void>;
|
|
@@ -4,9 +4,9 @@ import { randomUUID } from 'node:crypto';
|
|
|
4
4
|
import { stable, object, fail } from './model.js';
|
|
5
5
|
import { initialProgress, progressPhase, readInitialProgress } from './initial-progress.js';
|
|
6
6
|
export const initialRoot = (workspace, target) => join(workspace.directory, 'ghidra-native', 'initial', target);
|
|
7
|
-
export async function initialIntent(workspace, target) {
|
|
7
|
+
export async function initialIntent(workspace, target, root = initialRoot(workspace, target)) {
|
|
8
8
|
try {
|
|
9
|
-
return object(JSON.parse(await readFile(join(
|
|
9
|
+
return object(JSON.parse(await readFile(join(root, 'intent.json'), 'utf8')));
|
|
10
10
|
}
|
|
11
11
|
catch (error) {
|
|
12
12
|
if (error.code === 'ENOENT')
|
|
@@ -14,10 +14,21 @@ export async function initialIntent(workspace, target) {
|
|
|
14
14
|
throw error;
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
+
export async function validateInitialIntent(workspace, target, binding, fingerprint, root = initialRoot(workspace, target.id), allowRuntimeChange = false) {
|
|
18
|
+
const expected = { schema: 1, target: target.id, sha256: target.binarySha256, input: await workspace.artifacts.verify(target.input),
|
|
19
|
+
origin: binding.origin, repository: binding.repository, readerUser: binding.readerUser, publisherUser: binding.publisherUser,
|
|
20
|
+
settings: workspace.model(target.id).settings, runtimeFingerprint: fingerprint };
|
|
21
|
+
const intent = await initialIntent(workspace, target.id, root);
|
|
22
|
+
if (!intent || typeof intent.id !== 'string' || !/^[a-f0-9-]{36}$/.test(intent.id) ||
|
|
23
|
+
Object.entries(expected).filter(([key]) => key !== 'input' && !(allowRuntimeChange && key === 'runtimeFingerprint')).some(([key, value]) => stable(intent[key]) !== stable(value)) ||
|
|
24
|
+
typeof intent.runtimeFingerprint !== 'string' || typeof intent.input !== 'string' || await realpath(intent.input) !== expected.input)
|
|
25
|
+
fail('binding', 'Retained initial model differs from its input, load settings, runtime or repository authority.');
|
|
26
|
+
return intent;
|
|
27
|
+
}
|
|
17
28
|
/** Immutable input/authority binding; private attempts and conditional first creation share it. */
|
|
18
|
-
export async function initializeModel(workspace, target, binding, server, fingerprint) {
|
|
29
|
+
export async function initializeModel(workspace, target, binding, server, fingerprint, root = initialRoot(workspace, target.id)) {
|
|
19
30
|
try {
|
|
20
|
-
return await initialize(workspace, target, binding, server, fingerprint);
|
|
31
|
+
return await initialize(workspace, target, binding, server, fingerprint, root);
|
|
21
32
|
}
|
|
22
33
|
catch (error) {
|
|
23
34
|
try {
|
|
@@ -33,15 +44,14 @@ export async function initializeModel(workspace, target, binding, server, finger
|
|
|
33
44
|
throw error;
|
|
34
45
|
}
|
|
35
46
|
}
|
|
36
|
-
async function initialize(workspace, target, binding, server, fingerprint) {
|
|
37
|
-
const root = initialRoot(workspace, target.id);
|
|
47
|
+
async function initialize(workspace, target, binding, server, fingerprint, root) {
|
|
38
48
|
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
39
49
|
if (await realpath(root) !== resolve(root))
|
|
40
50
|
fail('binding', 'Initial model storage moved outside its owned root.');
|
|
41
51
|
const expected = { schema: 1, target: target.id, sha256: target.binarySha256, input: await workspace.artifacts.verify(target.input),
|
|
42
52
|
origin: binding.origin, repository: binding.repository, readerUser: binding.readerUser, publisherUser: binding.publisherUser,
|
|
43
53
|
settings: workspace.model(target.id).settings, runtimeFingerprint: fingerprint };
|
|
44
|
-
let intent = await initialIntent(workspace, target.id);
|
|
54
|
+
let intent = await initialIntent(workspace, target.id, root);
|
|
45
55
|
if (!intent) {
|
|
46
56
|
const temporary = join(root, 'intent.new-' + randomUUID()), handle = await open(temporary, 'wx', 0o600);
|
|
47
57
|
try {
|
|
@@ -70,12 +80,9 @@ async function initialize(workspace, target, binding, server, fingerprint) {
|
|
|
70
80
|
await directory.close();
|
|
71
81
|
}
|
|
72
82
|
}
|
|
73
|
-
intent = await initialIntent(workspace, target.id);
|
|
83
|
+
intent = await initialIntent(workspace, target.id, root);
|
|
74
84
|
}
|
|
75
|
-
|
|
76
|
-
Object.entries(expected).filter(([key]) => key !== 'input').some(([key, value]) => stable(intent[key]) !== stable(value)) ||
|
|
77
|
-
typeof intent.input !== 'string' || await realpath(intent.input) !== expected.input)
|
|
78
|
-
fail('binding', 'Retained initial model differs from its input, load settings, runtime or repository authority.');
|
|
85
|
+
await validateInitialIntent(workspace, target, binding, fingerprint, root);
|
|
79
86
|
if (workspace.model(target.id).state === 'opening')
|
|
80
87
|
workspace.beginModelInitialization(target.id);
|
|
81
88
|
const prepared = await server.initialImport(root);
|
|
@@ -86,10 +93,11 @@ async function initialize(workspace, target, binding, server, fingerprint) {
|
|
|
86
93
|
const receipt = object(JSON.parse(await readFile(join(root, 'import.json'), 'utf8'))), name = receipt.snapshot;
|
|
87
94
|
if (typeof name !== 'string' || !/^attempt-[a-f0-9-]{36}\.gzf$/.test(name))
|
|
88
95
|
fail('binding', 'Initial model snapshot receipt is malformed.');
|
|
89
|
-
const
|
|
96
|
+
const observation = initialRoot(workspace, target.id);
|
|
97
|
+
const snapshot = await progressPhase(observation, target.id, 'snapshot-verification', () => workspace.captureSnapshot(join(root, name)));
|
|
90
98
|
if (snapshot.sha256 !== receipt.snapshotSha256)
|
|
91
99
|
fail('binding', 'Initial saved snapshot changed before publication.');
|
|
92
|
-
const publication = (operation) => progressPhase(
|
|
100
|
+
const publication = (operation) => progressPhase(observation, target.id, 'publication-' + operation, () => server.initialPublication(binding, root, operation));
|
|
93
101
|
let result = await publication('stage');
|
|
94
102
|
if (result.state === 'staged') {
|
|
95
103
|
const proof = await publication('verify-stage');
|
|
@@ -103,5 +111,5 @@ async function initialize(workspace, target, binding, server, fingerprint) {
|
|
|
103
111
|
if (verified.state !== 'verified' || verified.version !== 1 || verified.snapshotBuffersVerified !== true)
|
|
104
112
|
fail('unknown', 'Independent initial-model readback did not establish the complete saved buffers.');
|
|
105
113
|
workspace.establishModel(target.id, 1, snapshot);
|
|
106
|
-
await initialProgress(
|
|
114
|
+
await initialProgress(observation, target.id, 'complete', 'complete');
|
|
107
115
|
}
|
package/dist/src/server.d.ts
CHANGED
|
@@ -43,6 +43,7 @@ export declare class GhidraServer {
|
|
|
43
43
|
projectOutcome(requestId: string, expected: Record<string, unknown>): Promise<Record<string, unknown> | undefined>;
|
|
44
44
|
administration(operation: string, parameters: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
45
45
|
programStatus(binding: ServerBinding, path: string): Promise<Record<string, unknown>>;
|
|
46
|
+
initialRecovery(binding: ServerBinding, root: string, fingerprint: string, receipt?: string): Promise<Record<string, unknown>>;
|
|
46
47
|
initialImport(root: string): Promise<Record<string, unknown>>;
|
|
47
48
|
initialPublication(binding: ServerBinding, root: string, operation?: 'stage' | 'verify-stage' | 'promote' | 'verify'): Promise<Record<string, unknown>>;
|
|
48
49
|
publish(binding: ServerBinding, path: string, snapshot: string, expected: number, request: string, journal: string, sourceSha: string): Promise<Record<string, unknown>>;
|
package/dist/src/server.js
CHANGED
|
@@ -4,7 +4,7 @@ import { launchProcess, terminateProcess } from './tool-runtime/supervisor.js';
|
|
|
4
4
|
import { runTool } from './tool-runtime/run.js';
|
|
5
5
|
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
|
6
6
|
import { readFile, mkdir, open, rename, readdir, stat, chmod, realpath } from 'node:fs/promises';
|
|
7
|
-
import { delimiter, dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { basename, delimiter, dirname, join, resolve } from 'node:path';
|
|
8
8
|
import { createServer } from 'node:net';
|
|
9
9
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
10
|
import { fail, object, stable, text, digest } from './model.js';
|
|
@@ -201,11 +201,14 @@ export class GhidraServer {
|
|
|
201
201
|
async programStatus(binding, path) {
|
|
202
202
|
return this.run('program-status', 'InsightRepositoryProbe', [binding.repository, path, 'reader'], await this.credentials(binding, 'reader'));
|
|
203
203
|
}
|
|
204
|
+
async initialRecovery(binding, root, fingerprint, receipt = '') {
|
|
205
|
+
return this.run('initial-recovery', 'db.InsightInitialRecovery', [root, fingerprint, receipt], await this.credentials(binding, 'reader'));
|
|
206
|
+
}
|
|
204
207
|
async initialImport(root) {
|
|
205
208
|
const timeoutMilliseconds = ghidraBudget(this.c.profile.values, 'import');
|
|
206
209
|
const report = async () => {
|
|
207
210
|
try {
|
|
208
|
-
const p = object(JSON.parse(await readFile(join(root, 'progress.json'), 'utf8')));
|
|
211
|
+
const p = object(JSON.parse(await readFile(join(/^runtime-[a-f0-9]{64}$/.test(basename(root)) ? dirname(root) : root, 'progress.json'), 'utf8')));
|
|
209
212
|
const elapsed = Math.round((Date.now() - Date.parse(String(p.startedAt))) / 1000);
|
|
210
213
|
this.c.progress(`Ghidra ${String(p.phase)}: ${elapsed}s${typeof p.total === 'number' ? `; task ${String(p.completed)}/${p.total}` : ''}${p.message ? `; ${String(p.message).replace(/[\r\n\x00-\x1f]/g, ' ')}` : ''}`);
|
|
211
214
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { writeFile } from 'node:fs/promises';
|
|
1
|
+
import { writeFile, realpath } from 'node:fs/promises';
|
|
2
2
|
import { join, win32 } from 'node:path';
|
|
3
3
|
import { execFile } from 'node:child_process';
|
|
4
4
|
import { promisify } from 'node:util';
|
|
@@ -36,7 +36,7 @@ export async function javaClasspathArguments(root, tool, executable, args, platf
|
|
|
36
36
|
const index = args.findIndex(arg => arg === '-cp' || arg === '-classpath' || arg === '--class-path');
|
|
37
37
|
if (index < 0 || args[index + 1] === undefined)
|
|
38
38
|
return args;
|
|
39
|
-
const path = join(root, 'java-classpath.args');
|
|
39
|
+
const path = join(await realpath(root), 'java-classpath.args');
|
|
40
40
|
const content = '-classpath\n' + quoteJavaArgument(args[index + 1]) + '\n';
|
|
41
41
|
const bytes = /^java\.exe$/i.test(win32.basename(executable)) && process.platform === 'win32' ? await encodeJavaLauncherFile(content) : Buffer.from(content, 'utf8');
|
|
42
42
|
await writeFile(path, bytes, { flag: 'wx', mode: 0o600 });
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
const exec = promisify(execFile);
|
|
7
|
+
/** Independent kernel observation; no request enters the possibly wedged JVM. */
|
|
8
|
+
export async function nativeProcessProof(pid, executable, cwd, token) {
|
|
9
|
+
if (process.platform !== 'darwin' || !Number.isSafeInteger(pid) || pid < 1)
|
|
10
|
+
return false;
|
|
11
|
+
try {
|
|
12
|
+
const base = new URL('../../../runtime/native/', import.meta.url), path = fileURLToPath(new URL('process-identity-darwin-' + process.arch, base));
|
|
13
|
+
const provenance = JSON.parse(await readFile(new URL('process-identity.provenance.json', base), 'utf8'));
|
|
14
|
+
if (provenance.platform !== 'darwin' || provenance.architecture !== process.arch || createHash('sha256').update(await readFile(path)).digest('hex') !== provenance.sha256)
|
|
15
|
+
return false;
|
|
16
|
+
const result = await exec(path, [String(pid)], { timeout: 3000, maxBuffer: 16384, env: { PATH: '/usr/bin:/bin' } }), row = JSON.parse(result.stdout);
|
|
17
|
+
if (row.pid !== pid || row.uid !== process.geteuid?.() || !Number.isSafeInteger(row.birthSeconds) || row.birthSeconds <= 0 || !Number.isSafeInteger(row.birthMicroseconds) || row.birthMicroseconds < 0 || row.birthMicroseconds >= 1000000 || typeof row.tokenSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(row.tokenSha256))
|
|
18
|
+
return false;
|
|
19
|
+
if (await realpath(row.executable) !== await realpath(executable) || await realpath(row.root) !== await realpath(cwd))
|
|
20
|
+
return false;
|
|
21
|
+
return timingSafeEqual(Buffer.from(row.tokenSha256, 'hex'), createHash('sha256').update(token).digest());
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { writeFile } from 'node:fs/promises';
|
|
2
2
|
import { join, isAbsolute, resolve } from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { performance } from 'node:perf_hooks';
|
|
5
5
|
import { CliError } from '@eyeauras/cli-factory';
|
|
6
|
-
import { atomicWrite, withToolUse, toolRoot, readJson } from './store.js';
|
|
6
|
+
import { atomicWrite, withToolUse, toolRoot, readJson, prepareRunRoot } from './store.js';
|
|
7
7
|
import { launchProcess } from './supervisor.js';
|
|
8
8
|
import { digest } from '../model.js';
|
|
9
9
|
import { deadlineLaunch } from './deadline.js';
|
|
@@ -23,7 +23,7 @@ export async function runTool(c, spec) {
|
|
|
23
23
|
const started = performance.now(), limit = spec.maxOutputBytes ?? 4 * 1024 ** 2;
|
|
24
24
|
let child, outcome, truncated = false, bytes = 0;
|
|
25
25
|
const stdout = [], stderr = [], record = { schema: 1, id, tool: spec.tool, role: spec.role, installation: spec.installation ?? 'probe', state: 'starting', executable: spec.executable, createdAt: new Date().toISOString(), root, ownerPid: process.pid, profileBinding: digest(resolve(directory)), gated: process.platform !== 'win32' && typeof process.execve === 'function', phase: 'reserved', ...(spec.session ? { session: spec.session } : {}), ...(spec.target ? { target: spec.target } : {}) };
|
|
26
|
-
const lease = await withToolUse(directory, spec.tool, async () => { await
|
|
26
|
+
const lease = await withToolUse(directory, spec.tool, async () => { await prepareRunRoot(directory, id); }, c.signal);
|
|
27
27
|
const environment = { PATH: c.environment.PATH ?? process.env.PATH, HOME: root, TMPDIR: root, ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, WINDIR: process.env.WINDIR, ComSpec: process.env.ComSpec, TEMP: root, TMP: root, USERPROFILE: root, LOCALAPPDATA: root, APPDATA: root } : {}), ...spec.environment };
|
|
28
28
|
const secrets = Object.entries(environment).filter(([key, value]) => /TOKEN|PASSWORD|SECRET|KEY/i.test(key) && value && value.length >= 4).map(([, v]) => v);
|
|
29
29
|
const redact = (value) => secrets.reduce((text, secret) => text.split(secret).join('[redacted]'), value);
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export declare function atomicWrite(path: string, value: unknown): Promise<void>;
|
|
2
|
+
/** Create new run folders through the physical runtime, retaining logical receipt identity. */
|
|
3
|
+
export declare function prepareRunRoot(directory: string, id: string): Promise<void>;
|
|
2
4
|
export declare function readJson<T>(path: string): Promise<T | undefined>;
|
|
3
5
|
export declare function toolRoot(directory: string, tool: string): string;
|
|
4
6
|
/** CLI clients already share Factory's elected owner. Do not create another IPC/lease protocol. */
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { mkdir, open, rename, rm, readFile, readdir, lstat, realpath } from 'node:fs/promises';
|
|
2
|
-
import { createReadStream } from 'node:fs';
|
|
3
|
-
import { dirname, join, resolve, relative, sep } from 'node:path';
|
|
2
|
+
import { createReadStream, existsSync } from 'node:fs';
|
|
3
|
+
import { dirname, basename, join, resolve, relative, sep } from 'node:path';
|
|
4
4
|
import { randomUUID, createHash } from 'node:crypto';
|
|
5
5
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
6
6
|
import { CliError } from '@eyeauras/cli-factory';
|
|
7
7
|
import { fail } from '../model.js';
|
|
8
8
|
export async function atomicWrite(path, value) {
|
|
9
|
-
await
|
|
10
|
-
|
|
9
|
+
const parent = await physicalDirectory(dirname(path)), target = join(parent, basename(path));
|
|
10
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
11
|
+
const temporary = target + '.new-' + randomUUID(), file = await open(temporary, 'wx', 0o600);
|
|
11
12
|
try {
|
|
12
13
|
await file.writeFile(JSON.stringify(value, null, 2) + '\n');
|
|
13
14
|
await file.sync();
|
|
@@ -15,17 +16,34 @@ export async function atomicWrite(path, value) {
|
|
|
15
16
|
finally {
|
|
16
17
|
await file.close();
|
|
17
18
|
}
|
|
18
|
-
await rename(temporary,
|
|
19
|
+
await rename(temporary, target);
|
|
19
20
|
if (process.platform !== 'win32') {
|
|
20
|
-
const
|
|
21
|
+
const handle = await open(parent, 'r');
|
|
21
22
|
try {
|
|
22
|
-
await
|
|
23
|
+
await handle.sync();
|
|
23
24
|
}
|
|
24
25
|
finally {
|
|
25
|
-
await
|
|
26
|
+
await handle.close();
|
|
26
27
|
}
|
|
27
28
|
}
|
|
28
29
|
}
|
|
30
|
+
async function physicalDirectory(path) {
|
|
31
|
+
try {
|
|
32
|
+
return await realpath(path);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error.code !== 'ENOENT' || dirname(path) === path)
|
|
36
|
+
throw error;
|
|
37
|
+
return join(await physicalDirectory(dirname(path)), basename(path));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Create new run folders through the physical runtime, retaining logical receipt identity. */
|
|
41
|
+
export async function prepareRunRoot(directory, id) {
|
|
42
|
+
const runtime = join(directory, 'runtime');
|
|
43
|
+
if (!existsSync(runtime))
|
|
44
|
+
await mkdir(runtime, { recursive: true, mode: 0o700 });
|
|
45
|
+
await mkdir(join(await realpath(runtime), 'runs', id), { recursive: true, mode: 0o700 });
|
|
46
|
+
}
|
|
29
47
|
export async function readJson(path) { try {
|
|
30
48
|
return JSON.parse(await readFile(path, 'utf8'));
|
|
31
49
|
}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { sameDirectory } from '../directory-identity.js';
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { access,
|
|
3
|
+
import { access, readdir } from 'node:fs/promises';
|
|
4
4
|
import { constants } from 'node:fs';
|
|
5
5
|
import { join, isAbsolute, resolve } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { randomUUID } from 'node:crypto';
|
|
8
8
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
9
|
import { CliError } from '@eyeauras/cli-factory';
|
|
10
|
-
import { atomicWrite, readJson, toolRoot, withToolLock } from './store.js';
|
|
10
|
+
import { atomicWrite, readJson, toolRoot, withToolLock, prepareRunRoot } from './store.js';
|
|
11
11
|
import { processIdentity } from './identity.js';
|
|
12
12
|
import { javaClasspathArguments } from './java-arguments.js';
|
|
13
13
|
import { digest } from '../model.js';
|
|
@@ -53,7 +53,7 @@ export async function launchProcess(directory, spec, executable, args, options =
|
|
|
53
53
|
if (!/^[a-f0-9-]{36}$/.test(id))
|
|
54
54
|
throw Error('Invalid process identity');
|
|
55
55
|
const root = join(directory, 'runtime/runs', id), path = join(directory, 'runtime/processes', id + '.json');
|
|
56
|
-
await
|
|
56
|
+
await prepareRunRoot(directory, id);
|
|
57
57
|
const gated = process.platform !== 'win32' && typeof process.execve === 'function';
|
|
58
58
|
const record = { schema: 1, id, ...spec, state: 'starting', executable, root, ownerPid: process.pid, profileBinding: digest(resolve(directory)), gated, phase: 'reserved', createdAt: new Date().toISOString() };
|
|
59
59
|
await atomicWrite(path, record);
|
|
@@ -273,7 +273,7 @@ export async function registerExistingProcess(directory, spec, executable, pid,
|
|
|
273
273
|
const previous = await readJson(path);
|
|
274
274
|
if (previous)
|
|
275
275
|
return id;
|
|
276
|
-
await
|
|
276
|
+
await prepareRunRoot(directory, id);
|
|
277
277
|
await atomicWrite(path, record);
|
|
278
278
|
return id;
|
|
279
279
|
}
|