@ai-devkit/agent-manager 0.28.1 → 0.30.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/dist/__tests__/adapters/ClaudeCodeAdapter.test.js +1 -342
- package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js.map +1 -1
- package/dist/__tests__/capacity/codex.test.js +343 -0
- package/dist/__tests__/capacity/codex.test.js.map +1 -0
- package/dist/__tests__/capacity/index.test.js +50 -0
- package/dist/__tests__/capacity/index.test.js.map +1 -0
- package/dist/__tests__/database/DurableAgentsDatabase.test.js +31 -3
- package/dist/__tests__/database/DurableAgentsDatabase.test.js.map +1 -1
- package/dist/__tests__/durable/CodexCliProbe.test.js +129 -0
- package/dist/__tests__/durable/CodexCliProbe.test.js.map +1 -0
- package/dist/__tests__/durable/CodexDurableAgentRepository.test.js +84 -0
- package/dist/__tests__/durable/CodexDurableAgentRepository.test.js.map +1 -0
- package/dist/__tests__/durable/CodexPrintAgent.integration.test.js +126 -0
- package/dist/__tests__/durable/CodexPrintAgent.integration.test.js.map +1 -0
- package/dist/__tests__/durable/CodexPrintAgentService.test.js +271 -0
- package/dist/__tests__/durable/CodexPrintAgentService.test.js.map +1 -0
- package/dist/__tests__/durable/CodexPrintRunner.test.js +393 -0
- package/dist/__tests__/durable/CodexPrintRunner.test.js.map +1 -0
- package/dist/__tests__/print/ClaudeCliProbe.test.js +3 -7
- package/dist/__tests__/print/ClaudeCliProbe.test.js.map +1 -1
- package/dist/__tests__/print/ClaudePrintAgent.integration.test.js +33 -27
- package/dist/__tests__/print/ClaudePrintAgent.integration.test.js.map +1 -1
- package/dist/__tests__/print/ClaudePrintAgentService.test.js +65 -0
- package/dist/__tests__/print/ClaudePrintAgentService.test.js.map +1 -1
- package/dist/__tests__/print/ClaudePrintRunner.test.js +4 -10
- package/dist/__tests__/print/ClaudePrintRunner.test.js.map +1 -1
- package/dist/__tests__/providers/claude/ClaudeAgentMapper.test.js +79 -0
- package/dist/__tests__/providers/claude/ClaudeAgentMapper.test.js.map +1 -0
- package/dist/__tests__/providers/claude/ClaudeSessionLocator.test.js +436 -0
- package/dist/__tests__/providers/claude/ClaudeSessionLocator.test.js.map +1 -0
- package/dist/__tests__/providers/pi/durable/PiCliProbe.test.js +76 -0
- package/dist/__tests__/providers/pi/durable/PiCliProbe.test.js.map +1 -0
- package/dist/__tests__/providers/pi/durable/PiDurableAgentRepository.test.js +43 -0
- package/dist/__tests__/providers/pi/durable/PiDurableAgentRepository.test.js.map +1 -0
- package/dist/__tests__/providers/pi/durable/PiPrintAgentService.test.js +202 -0
- package/dist/__tests__/providers/pi/durable/PiPrintAgentService.test.js.map +1 -0
- package/dist/__tests__/providers/pi/durable/PiPrintProtocol.test.js +119 -0
- package/dist/__tests__/providers/pi/durable/PiPrintProtocol.test.js.map +1 -0
- package/dist/__tests__/providers/pi/durable/PiPrintRunner.test.js +386 -0
- package/dist/__tests__/providers/pi/durable/PiPrintRunner.test.js.map +1 -0
- package/dist/__tests__/providers/pi/durable/PiStreamParser.test.js +34 -0
- package/dist/__tests__/providers/pi/durable/PiStreamParser.test.js.map +1 -0
- package/dist/__tests__/utils/ClaudeSessionParser.test.js +2 -2
- package/dist/__tests__/utils/ClaudeSessionParser.test.js.map +1 -1
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/index.js.map +1 -1
- package/dist/capacity/codex.d.ts +36 -0
- package/dist/capacity/codex.d.ts.map +1 -0
- package/dist/capacity/codex.js +317 -0
- package/dist/capacity/codex.js.map +1 -0
- package/dist/capacity/index.d.ts +11 -0
- package/dist/capacity/index.d.ts.map +1 -0
- package/dist/capacity/index.js +49 -0
- package/dist/capacity/index.js.map +1 -0
- package/dist/capacity/types.d.ts +17 -0
- package/dist/capacity/types.d.ts.map +1 -0
- package/dist/capacity/types.js +3 -0
- package/dist/capacity/types.js.map +1 -0
- package/dist/database/migrations/004_codex_durable_sessions.sql +1 -0
- package/dist/durable/DurableAgent.d.ts +23 -3
- package/dist/durable/DurableAgent.d.ts.map +1 -1
- package/dist/durable/DurableAgent.js +12 -0
- package/dist/durable/DurableAgent.js.map +1 -1
- package/dist/durable/DurableAgentRepository.d.ts +6 -7
- package/dist/durable/DurableAgentRepository.d.ts.map +1 -1
- package/dist/durable/DurableAgentRepository.js +73 -42
- package/dist/durable/DurableAgentRepository.js.map +1 -1
- package/dist/durable/process.d.ts +8 -0
- package/dist/durable/process.d.ts.map +1 -0
- package/dist/durable/process.js +40 -0
- package/dist/durable/process.js.map +1 -0
- package/dist/durable/run.d.ts +32 -0
- package/dist/durable/run.d.ts.map +1 -0
- package/dist/durable/run.js +46 -0
- package/dist/durable/run.js.map +1 -0
- package/dist/durable/utils.d.ts +19 -0
- package/dist/durable/utils.d.ts.map +1 -0
- package/dist/durable/utils.js +52 -0
- package/dist/durable/utils.js.map +1 -0
- package/dist/index.d.ts +19 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -8
- package/dist/index.js.map +1 -1
- package/dist/providers/claude/ClaudeAgentMapper.d.ts +21 -0
- package/dist/providers/claude/ClaudeAgentMapper.d.ts.map +1 -0
- package/dist/providers/claude/ClaudeAgentMapper.js +42 -0
- package/dist/providers/claude/ClaudeAgentMapper.js.map +1 -0
- package/dist/providers/claude/ClaudeCodeAdapter.d.ts +29 -0
- package/dist/providers/claude/ClaudeCodeAdapter.d.ts.map +1 -0
- package/dist/providers/claude/ClaudeCodeAdapter.js +129 -0
- package/dist/providers/claude/ClaudeCodeAdapter.js.map +1 -0
- package/dist/{adapters/ClaudeCodeAdapter.d.ts → providers/claude/ClaudeSessionLocator.d.ts} +68 -52
- package/dist/providers/claude/ClaudeSessionLocator.d.ts.map +1 -0
- package/dist/{adapters/ClaudeCodeAdapter.js → providers/claude/ClaudeSessionLocator.js} +71 -189
- package/dist/providers/claude/ClaudeSessionLocator.js.map +1 -0
- package/dist/{utils → providers/claude}/ClaudeSessionParser.d.ts +2 -2
- package/dist/providers/claude/ClaudeSessionParser.d.ts.map +1 -0
- package/dist/{utils → providers/claude}/ClaudeSessionParser.js +1 -1
- package/dist/providers/claude/ClaudeSessionParser.js.map +1 -0
- package/dist/providers/claude/durable/ClaudeCliProbe.d.ts.map +1 -0
- package/dist/{durable → providers/claude/durable}/ClaudeCliProbe.js +4 -9
- package/dist/providers/claude/durable/ClaudeCliProbe.js.map +1 -0
- package/dist/{durable → providers/claude/durable}/ClaudePrintAgentService.d.ts +4 -9
- package/dist/providers/claude/durable/ClaudePrintAgentService.d.ts.map +1 -0
- package/dist/providers/claude/durable/ClaudePrintAgentService.js +45 -0
- package/dist/providers/claude/durable/ClaudePrintAgentService.js.map +1 -0
- package/dist/{durable → providers/claude/durable}/ClaudePrintRunner.d.ts +3 -3
- package/dist/providers/claude/durable/ClaudePrintRunner.d.ts.map +1 -0
- package/dist/providers/claude/durable/ClaudePrintRunner.js +75 -0
- package/dist/providers/claude/durable/ClaudePrintRunner.js.map +1 -0
- package/dist/providers/claude/durable/ClaudeStreamParser.d.ts +17 -0
- package/dist/providers/claude/durable/ClaudeStreamParser.d.ts.map +1 -0
- package/dist/providers/claude/durable/ClaudeStreamParser.js +69 -0
- package/dist/providers/claude/durable/ClaudeStreamParser.js.map +1 -0
- package/dist/providers/codex/durable/CodexCliProbe.d.ts +20 -0
- package/dist/providers/codex/durable/CodexCliProbe.d.ts.map +1 -0
- package/dist/providers/codex/durable/CodexCliProbe.js +61 -0
- package/dist/providers/codex/durable/CodexCliProbe.js.map +1 -0
- package/dist/providers/codex/durable/CodexPrintAgentService.d.ts +40 -0
- package/dist/providers/codex/durable/CodexPrintAgentService.d.ts.map +1 -0
- package/dist/providers/codex/durable/CodexPrintAgentService.js +50 -0
- package/dist/providers/codex/durable/CodexPrintAgentService.js.map +1 -0
- package/dist/providers/codex/durable/CodexPrintRunner.d.ts +34 -0
- package/dist/providers/codex/durable/CodexPrintRunner.d.ts.map +1 -0
- package/dist/providers/codex/durable/CodexPrintRunner.js +78 -0
- package/dist/providers/codex/durable/CodexPrintRunner.js.map +1 -0
- package/dist/providers/codex/durable/CodexStreamParser.d.ts +21 -0
- package/dist/providers/codex/durable/CodexStreamParser.d.ts.map +1 -0
- package/dist/providers/codex/durable/CodexStreamParser.js +86 -0
- package/dist/providers/codex/durable/CodexStreamParser.js.map +1 -0
- package/dist/providers/pi/durable/PiCliProbe.d.ts +20 -0
- package/dist/providers/pi/durable/PiCliProbe.d.ts.map +1 -0
- package/dist/providers/pi/durable/PiCliProbe.js +51 -0
- package/dist/providers/pi/durable/PiCliProbe.js.map +1 -0
- package/dist/providers/pi/durable/PiPrintAgentService.d.ts +39 -0
- package/dist/providers/pi/durable/PiPrintAgentService.d.ts.map +1 -0
- package/dist/providers/pi/durable/PiPrintAgentService.js +47 -0
- package/dist/providers/pi/durable/PiPrintAgentService.js.map +1 -0
- package/dist/providers/pi/durable/PiPrintProtocol.d.ts +4 -0
- package/dist/providers/pi/durable/PiPrintProtocol.d.ts.map +1 -0
- package/dist/providers/pi/durable/PiPrintProtocol.js +44 -0
- package/dist/providers/pi/durable/PiPrintProtocol.js.map +1 -0
- package/dist/providers/pi/durable/PiPrintRunner.d.ts +32 -0
- package/dist/providers/pi/durable/PiPrintRunner.d.ts.map +1 -0
- package/dist/providers/pi/durable/PiPrintRunner.js +61 -0
- package/dist/providers/pi/durable/PiPrintRunner.js.map +1 -0
- package/dist/providers/pi/durable/PiStreamParser.d.ts +21 -0
- package/dist/providers/pi/durable/PiStreamParser.d.ts.map +1 -0
- package/dist/providers/pi/durable/PiStreamParser.js +71 -0
- package/dist/providers/pi/durable/PiStreamParser.js.map +1 -0
- package/package.json +1 -1
- package/src/__tests__/adapters/ClaudeCodeAdapter.test.ts +1 -307
- package/src/__tests__/capacity/codex.test.ts +184 -0
- package/src/__tests__/capacity/index.test.ts +38 -0
- package/src/__tests__/database/DurableAgentsDatabase.test.ts +28 -3
- package/src/__tests__/durable/CodexCliProbe.test.ts +63 -0
- package/src/__tests__/durable/CodexDurableAgentRepository.test.ts +54 -0
- package/src/__tests__/durable/CodexPrintAgent.integration.test.ts +79 -0
- package/src/__tests__/durable/CodexPrintAgentService.test.ts +139 -0
- package/src/__tests__/durable/CodexPrintRunner.test.ts +189 -0
- package/src/__tests__/fixtures/fake-codex.cjs +45 -0
- package/src/__tests__/print/ClaudeCliProbe.test.ts +3 -7
- package/src/__tests__/print/ClaudePrintAgent.integration.test.ts +19 -22
- package/src/__tests__/print/ClaudePrintAgentService.test.ts +33 -1
- package/src/__tests__/print/ClaudePrintRunner.test.ts +4 -10
- package/src/__tests__/providers/claude/ClaudeAgentMapper.test.ts +84 -0
- package/src/__tests__/providers/claude/ClaudeSessionLocator.test.ts +411 -0
- package/src/__tests__/providers/pi/durable/PiCliProbe.test.ts +38 -0
- package/src/__tests__/providers/pi/durable/PiDurableAgentRepository.test.ts +32 -0
- package/src/__tests__/providers/pi/durable/PiPrintAgentService.test.ts +69 -0
- package/src/__tests__/providers/pi/durable/PiPrintProtocol.test.ts +33 -0
- package/src/__tests__/providers/pi/durable/PiPrintRunner.test.ts +107 -0
- package/src/__tests__/providers/pi/durable/PiStreamParser.test.ts +24 -0
- package/src/__tests__/utils/ClaudeSessionParser.test.ts +2 -2
- package/src/adapters/index.ts +1 -1
- package/src/capacity/codex.ts +320 -0
- package/src/capacity/index.ts +57 -0
- package/src/capacity/types.ts +18 -0
- package/src/database/migrations/004_codex_durable_sessions.sql +1 -0
- package/src/durable/DurableAgent.ts +51 -3
- package/src/durable/DurableAgentRepository.ts +60 -31
- package/src/durable/process.ts +28 -0
- package/src/durable/run.ts +74 -0
- package/src/durable/utils.ts +61 -0
- package/src/index.ts +37 -15
- package/src/providers/claude/ClaudeAgentMapper.ts +62 -0
- package/src/providers/claude/ClaudeCodeAdapter.ts +160 -0
- package/src/{adapters/ClaudeCodeAdapter.ts → providers/claude/ClaudeSessionLocator.ts} +97 -239
- package/src/{utils → providers/claude}/ClaudeSessionParser.ts +2 -2
- package/src/{durable → providers/claude/durable}/ClaudeCliProbe.ts +4 -10
- package/src/providers/claude/durable/ClaudePrintAgentService.ts +66 -0
- package/src/providers/claude/durable/ClaudePrintRunner.ts +92 -0
- package/src/providers/claude/durable/ClaudeStreamParser.ts +79 -0
- package/src/providers/codex/durable/CodexCliProbe.ts +60 -0
- package/src/providers/codex/durable/CodexPrintAgentService.ts +65 -0
- package/src/providers/codex/durable/CodexPrintRunner.ts +94 -0
- package/src/providers/codex/durable/CodexStreamParser.ts +104 -0
- package/src/providers/pi/durable/PiCliProbe.ts +48 -0
- package/src/providers/pi/durable/PiPrintAgentService.ts +69 -0
- package/src/providers/pi/durable/PiPrintProtocol.ts +39 -0
- package/src/providers/pi/durable/PiPrintRunner.ts +88 -0
- package/src/providers/pi/durable/PiStreamParser.ts +84 -0
- package/dist/adapters/ClaudeCodeAdapter.d.ts.map +0 -1
- package/dist/adapters/ClaudeCodeAdapter.js.map +0 -1
- package/dist/durable/ClaudeCliProbe.d.ts.map +0 -1
- package/dist/durable/ClaudeCliProbe.js.map +0 -1
- package/dist/durable/ClaudePrintAgentService.d.ts.map +0 -1
- package/dist/durable/ClaudePrintAgentService.js +0 -66
- package/dist/durable/ClaudePrintAgentService.js.map +0 -1
- package/dist/durable/ClaudePrintRunner.d.ts.map +0 -1
- package/dist/durable/ClaudePrintRunner.js +0 -128
- package/dist/durable/ClaudePrintRunner.js.map +0 -1
- package/dist/utils/ClaudeSessionParser.d.ts.map +0 -1
- package/dist/utils/ClaudeSessionParser.js.map +0 -1
- package/src/durable/ClaudePrintAgentService.ts +0 -94
- package/src/durable/ClaudePrintRunner.ts +0 -139
- /package/dist/{durable → providers/claude/durable}/ClaudeCliProbe.d.ts +0 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { spawn as nodeSpawn, type ChildProcessWithoutNullStreams, type SpawnOptionsWithoutStdio } from 'child_process';
|
|
2
|
+
import type { PiDurableAgent, ProcessIdentity } from '../../../durable/DurableAgent.js';
|
|
3
|
+
import { PiPrintError } from '../../../durable/DurableAgent.js';
|
|
4
|
+
import { LocalProcessInspector, type ProcessInspector } from '../../../durable/process.js';
|
|
5
|
+
import { waitForChildClose } from '../../../durable/utils.js';
|
|
6
|
+
import { buildPiPrintArgs } from './PiPrintProtocol.js';
|
|
7
|
+
import { PiStreamParser } from './PiStreamParser.js';
|
|
8
|
+
|
|
9
|
+
type Spawn = (
|
|
10
|
+
command: string,
|
|
11
|
+
args: readonly string[],
|
|
12
|
+
options: SpawnOptionsWithoutStdio & { stdio: ['pipe', 'pipe', 'pipe'] },
|
|
13
|
+
) => ChildProcessWithoutNullStreams;
|
|
14
|
+
|
|
15
|
+
export interface PiPrintRunRequest {
|
|
16
|
+
agent: PiDurableAgent;
|
|
17
|
+
prompt: string;
|
|
18
|
+
executable?: string;
|
|
19
|
+
onSpawn(identity: ProcessIdentity): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface PiPrintRunResult {
|
|
23
|
+
sessionId: string;
|
|
24
|
+
result: string;
|
|
25
|
+
messages: string[];
|
|
26
|
+
exitCode: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface PiPrintRunnerOptions {
|
|
30
|
+
spawn?: Spawn;
|
|
31
|
+
processInspector?: ProcessInspector;
|
|
32
|
+
maxLineBytes?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class PiPrintRunner {
|
|
36
|
+
private readonly spawn: Spawn;
|
|
37
|
+
private readonly processInspector: ProcessInspector;
|
|
38
|
+
private readonly maxLineBytes: number;
|
|
39
|
+
|
|
40
|
+
constructor(options: PiPrintRunnerOptions = {}) {
|
|
41
|
+
this.spawn = options.spawn ?? (nodeSpawn as Spawn);
|
|
42
|
+
this.processInspector = options.processInspector ?? new LocalProcessInspector();
|
|
43
|
+
this.maxLineBytes = options.maxLineBytes ?? 1024 * 1024;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async run(request: PiPrintRunRequest): Promise<PiPrintRunResult> {
|
|
47
|
+
const args = buildPiPrintArgs(request.agent.providerSessionId, request.agent.sessionHealth === 'uninitialized');
|
|
48
|
+
const child = this.spawn(request.executable ?? 'pi', args, {
|
|
49
|
+
cwd: request.agent.cwd,
|
|
50
|
+
shell: false,
|
|
51
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
52
|
+
});
|
|
53
|
+
if (!child.pid) {
|
|
54
|
+
child.kill();
|
|
55
|
+
throw new PiPrintError('Pi process did not provide a PID.', 'PI_PROCESS');
|
|
56
|
+
}
|
|
57
|
+
const identity = this.processInspector.getIdentity(child.pid);
|
|
58
|
+
if (!identity) {
|
|
59
|
+
child.kill();
|
|
60
|
+
throw new PiPrintError('Cannot verify Pi process identity.', 'PI_PROCESS');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const parser = new PiStreamParser(request.agent.providerSessionId, this.maxLineBytes);
|
|
64
|
+
child.stdout.on('data', (chunk: Buffer | string) => {
|
|
65
|
+
if (parser.hasFailed()) return;
|
|
66
|
+
try {
|
|
67
|
+
parser.accept(chunk);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
parser.fail(error);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
child.stderr.resume();
|
|
73
|
+
|
|
74
|
+
const closed = waitForChildClose(child);
|
|
75
|
+
try {
|
|
76
|
+
await request.onSpawn(identity);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
child.kill();
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
child.stdin.end(request.prompt);
|
|
83
|
+
const close = await closed.catch(() => {
|
|
84
|
+
throw new PiPrintError('Pi process failed to start or communicate.', 'PI_PROCESS');
|
|
85
|
+
});
|
|
86
|
+
return parser.result(close);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { PiPrintError } from '../../../durable/DurableAgent.js';
|
|
2
|
+
import { LineBuffer, type ChildCloseResult } from '../../../durable/utils.js';
|
|
3
|
+
import { readPiAssistantText, readPiSessionId } from './PiPrintProtocol.js';
|
|
4
|
+
|
|
5
|
+
export class PiStreamParser {
|
|
6
|
+
private readonly lines: LineBuffer;
|
|
7
|
+
private sessionId: string | null = null;
|
|
8
|
+
private ended = false;
|
|
9
|
+
private readonly messages: string[] = [];
|
|
10
|
+
private failure: PiPrintError | null = null;
|
|
11
|
+
|
|
12
|
+
constructor(
|
|
13
|
+
private readonly expectedSessionId: string,
|
|
14
|
+
maxLineBytes: number,
|
|
15
|
+
) {
|
|
16
|
+
this.lines = new LineBuffer(
|
|
17
|
+
maxLineBytes,
|
|
18
|
+
() => new PiPrintError('Pi stream line exceeded the safety limit.', 'PI_PROTOCOL'),
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
hasFailed(): boolean {
|
|
23
|
+
return this.failure !== null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
accept(chunk: Buffer | string): void {
|
|
27
|
+
for (const line of this.lines.accept(chunk)) {
|
|
28
|
+
if (line.length === 0) continue;
|
|
29
|
+
this.acceptLine(line);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
fail(error: unknown): void {
|
|
34
|
+
this.failure = error instanceof PiPrintError
|
|
35
|
+
? error
|
|
36
|
+
: new PiPrintError('Pi stream processing failed.', 'PI_PROTOCOL');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
result(close: ChildCloseResult): { sessionId: string; result: string; messages: string[]; exitCode: number } {
|
|
40
|
+
if (this.failure) throw this.failure;
|
|
41
|
+
this.lines.assertComplete(
|
|
42
|
+
() => new PiPrintError('Pi stream ended with incomplete JSON.', 'PI_PROTOCOL'),
|
|
43
|
+
);
|
|
44
|
+
if (close.code !== 0) {
|
|
45
|
+
throw new PiPrintError(`Pi print run failed${close.signal ? ` (${close.signal})` : '.'}`, 'PI_PROCESS');
|
|
46
|
+
}
|
|
47
|
+
if (this.sessionId === null) {
|
|
48
|
+
throw new PiPrintError('Pi stream ended without a session identity.', 'PI_PROTOCOL');
|
|
49
|
+
}
|
|
50
|
+
if (!this.ended) throw new PiPrintError('Pi stream ended before agent completion.', 'PI_PROTOCOL');
|
|
51
|
+
if (this.messages.length === 0) {
|
|
52
|
+
throw new PiPrintError('Pi stream ended without an assistant result.', 'PI_RESULT_MISSING');
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
sessionId: this.sessionId,
|
|
56
|
+
result: this.messages.at(-1)!,
|
|
57
|
+
messages: this.messages,
|
|
58
|
+
exitCode: close.code,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private acceptLine(line: Buffer): void {
|
|
63
|
+
let value: unknown;
|
|
64
|
+
try {
|
|
65
|
+
value = JSON.parse(line.toString('utf8'));
|
|
66
|
+
} catch {
|
|
67
|
+
throw new PiPrintError('Pi emitted malformed stream JSON.', 'PI_PROTOCOL');
|
|
68
|
+
}
|
|
69
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
70
|
+
throw new PiPrintError('Pi emitted a non-object stream message.', 'PI_PROTOCOL');
|
|
71
|
+
}
|
|
72
|
+
const event = value as Record<string, unknown>;
|
|
73
|
+
if (event.type === 'session') {
|
|
74
|
+
this.sessionId = readPiSessionId(event, this.sessionId, this.expectedSessionId);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (event.type === 'agent_end') {
|
|
78
|
+
this.ended = true;
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const text = readPiAssistantText(event);
|
|
82
|
+
if (text !== null) this.messages.push(text);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ClaudeCodeAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/ClaudeCodeAdapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACR,YAAY,EACZ,SAAS,EACT,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,mBAAmB,EACnB,qBAAqB,EACxB,MAAM,mBAAmB,CAAC;AAiD3B;;;;;;;;;GASG;AACH,qBAAa,iBAAkB,YAAW,YAAY;IAClD,QAAQ,CAAC,IAAI,EAAG,QAAQ,CAAU;IAClC,QAAQ,CAAC,YAAY,sBAAuB;IAE5C,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,MAAM,CAAsB;;IASpC,SAAS,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO;IAI5C,OAAO,CAAC,kBAAkB;IAKpB,YAAY,CAAC,OAAO,CAAC,EAAE,qBAAqB,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAqEzE;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB;IA6BxB;;;;;OAKG;IACH,OAAO,CAAC,iBAAiB;IA8CzB,OAAO,CAAC,sBAAsB;IAK9B;;;;;;;;OAQG;IACH,OAAO,CAAC,mBAAmB;IAoB3B;;;;;OAKG;IACH,OAAO,CAAC,YAAY;IAapB;;;;;;;;;OASG;IACH,OAAO,CAAC,kBAAkB;IAuC1B;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,aAAa;IAKrB,OAAO,CAAC,iBAAiB;IA4BzB,OAAO,CAAC,mBAAmB;IAa3B,eAAe,CAAC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,mBAAmB,EAAE;IAI1F,YAAY,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAkCzE;;;;;;;;;;OAUG;IACH,OAAO,CAAC,oBAAoB;CAqB/B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/ClaudeCodeAdapter.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type {\n AgentAdapter,\n AgentInfo,\n ProcessInfo,\n ConversationMessage,\n SessionSummary,\n ListSessionsOptions,\n AgentDetectionContext,\n} from './AgentAdapter.js';\nimport { AgentStatus } from './AgentAdapter.js';\nimport { captureProcessSnapshot, executableBasename, filterByProcessNames } from '../utils/process.js';\nimport { batchGetSessionFileBirthtimes, isDirectory, listJsonl, safeReaddir, safeStat } from '../utils/session.js';\nimport type { SessionFile } from '../utils/session.js';\nimport { matchProcessesToSessions, generateAgentName } from '../utils/matching.js';\nimport { ClaudeSessionParser } from '../utils/ClaudeSessionParser.js';\nimport type { ClaudeSession } from '../utils/ClaudeSessionParser.js';\n\n/**\n * Entry in ~/.claude/sessions/<pid>.json written by Claude Code.\n * Maps a running process to its session file via PID.\n */\ninterface PidFileEntry {\n pid: number;\n sessionId: string;\n cwd: string;\n /** Epoch milliseconds when the Claude Code process started */\n startedAt: number;\n kind: string;\n entrypoint: string;\n /**\n * Authoritative live status published by the Claude Code process\n * (e.g., 'running', 'waiting', 'idle'). Preferred over JSONL-derived\n * status because trailing entries like 'permission-mode' / 'ai-title'\n * can mask the real conversational state.\n */\n status?: string;\n /** Short description of what the agent is waiting on (e.g., \"approve Read\"). */\n waitingFor?: string;\n}\n\n/**\n * A process directly matched to a session via PID file (authoritative path).\n *\n * When the matching PID file also exposes live status/waitingFor metadata,\n * those values are carried here so `mapSessionToAgent` can prefer them\n * over the JSONL-derived heuristic.\n */\ninterface DirectMatch {\n process: ProcessInfo;\n sessionFile: SessionFile;\n pidStatus?: AgentStatus;\n waitingFor?: string;\n}\n\n/** Maximum allowed delta (ms) between process start time and PID file startedAt. */\nconst PID_FILE_STALENESS_MS = 60000;\n\n/**\n * Claude Code Adapter\n *\n * Detects Claude Code agents by:\n * 1. Filtering Claude processes from a shared asynchronous process snapshot\n * 2. Using snapshot CWD and start-time enrichment\n * 3. Attempting authoritative PID-file matching via ~/.claude/sessions/<pid>.json\n * 4. Falling back to CWD+birthtime heuristic (matchProcessesToSessions) for processes without a PID file\n * 5. Extracting summary from last user message in session JSONL\n */\nexport class ClaudeCodeAdapter implements AgentAdapter {\n readonly type = 'claude' as const;\n readonly processNames = ['claude'] as const;\n\n private projectsDir: string;\n private sessionsDir: string;\n private parser: ClaudeSessionParser;\n\n constructor() {\n const homeDir = process.env.HOME || process.env.USERPROFILE || '';\n this.projectsDir = path.join(homeDir, '.claude', 'projects');\n this.sessionsDir = path.join(homeDir, '.claude', 'sessions');\n this.parser = new ClaudeSessionParser();\n }\n\n canHandle(processInfo: ProcessInfo): boolean {\n return this.isClaudeExecutable(processInfo.command);\n }\n\n private isClaudeExecutable(command: string): boolean {\n const base = executableBasename(command);\n return base === 'claude' || base === 'claude.exe';\n }\n\n async detectAgents(context?: AgentDetectionContext): Promise<AgentInfo[]> {\n const snapshot = context?.processes ?? await captureProcessSnapshot(this.processNames);\n const relevant = filterByProcessNames(snapshot, this.processNames);\n const processes = relevant.filter((process) => this.canHandle(process));\n if (processes.length === 0) {\n return [];\n }\n\n // Step 1: extract `--resume <id>` from command line — authoritative for\n // resumed sessions where the JSONL predates the process and PID-file/\n // birthtime heuristics can't match it.\n const { direct: resumeDirect, fallback: noResume } = this.tryResumeMatching(processes);\n\n // Step 2: try authoritative PID-file matching for the rest\n const { direct: pidDirect, fallback } = this.tryPidFileMatching(noResume);\n\n const direct = [...resumeDirect, ...pidDirect];\n\n // Step 3: run legacy CWD+birthtime matching only for processes without a PID file\n const legacySessions = this.discoverSessions(fallback);\n const legacyMatches =\n fallback.length > 0 && legacySessions.length > 0\n ? matchProcessesToSessions(fallback, legacySessions)\n : [];\n\n const matchedPids = new Set([\n ...direct.map((d) => d.process.pid),\n ...legacyMatches.map((m) => m.process.pid),\n ]);\n\n const agents: AgentInfo[] = [];\n\n // Build agents from direct (resume + PID-file) matches\n for (const match of direct) {\n const { process: proc, sessionFile } = match;\n const sessionData = this.parser.readSession(sessionFile.filePath, sessionFile.resolvedCwd);\n if (sessionData) {\n agents.push(this.mapSessionToAgent(sessionData, proc, sessionFile, {\n pidStatus: match.pidStatus,\n waitingFor: match.waitingFor,\n }));\n } else {\n matchedPids.delete(proc.pid);\n }\n }\n\n // Build agents from legacy matches\n for (const match of legacyMatches) {\n const sessionData = this.parser.readSession(\n match.session.filePath,\n match.session.resolvedCwd,\n );\n if (sessionData) {\n agents.push(this.mapSessionToAgent(sessionData, match.process, match.session));\n } else {\n matchedPids.delete(match.process.pid);\n }\n }\n\n // Any process with no match (direct or legacy) appears as IDLE\n for (const proc of processes) {\n if (!matchedPids.has(proc.pid)) {\n agents.push(this.mapProcessOnlyAgent(proc));\n }\n }\n\n return agents;\n }\n\n /**\n * Discover session files for the given processes.\n *\n * For each unique process CWD, encodes it to derive the expected\n * ~/.claude/projects/<encoded>/ directory, then gets session file birthtimes\n * via a single batched stat call across all directories.\n */\n private discoverSessions(processes: ProcessInfo[]): SessionFile[] {\n const dirToCwd = new Map<string, string>();\n\n for (const proc of processes) {\n if (!proc.cwd) continue;\n\n const projectDir = this.getProjectDir(proc.cwd);\n if (dirToCwd.has(projectDir)) continue;\n\n try {\n if (!fs.statSync(projectDir).isDirectory()) continue;\n } catch {\n continue;\n }\n\n dirToCwd.set(projectDir, proc.cwd);\n }\n\n if (dirToCwd.size === 0) return [];\n\n const files = batchGetSessionFileBirthtimes([...dirToCwd.keys()]);\n\n for (const file of files) {\n file.resolvedCwd = dirToCwd.get(file.projectDir) || '';\n }\n\n return files;\n }\n\n /**\n * Match processes via `claude --resume <uuid>` in their command line.\n * This works for resumed sessions, where the JSONL was created earlier\n * (so its birthtime is far from the process startTime and the legacy\n * matcher can't pair them) and the PID file may also be misaligned.\n */\n private tryResumeMatching(processes: ProcessInfo[]): {\n direct: DirectMatch[];\n fallback: ProcessInfo[];\n } {\n const direct: DirectMatch[] = [];\n const fallback: ProcessInfo[] = [];\n\n for (const proc of processes) {\n const sessionId = this.extractResumeSessionId(proc.command);\n if (!sessionId || !proc.cwd) {\n fallback.push(proc);\n continue;\n }\n\n const projectDir = this.getProjectDir(proc.cwd);\n const jsonlPath = path.join(projectDir, `${sessionId}.jsonl`);\n\n const stat = safeStat(jsonlPath);\n if (!stat) {\n fallback.push(proc);\n continue;\n }\n\n // Best-effort: the PID file (if present for this proc) is the\n // authoritative source of live status. We still match the session\n // via --resume, but we read the PID file alongside to capture\n // status/waitingFor.\n const pidEntry = this.readMatchingPidFile(proc.pid, proc.startTime);\n\n direct.push({\n process: proc,\n sessionFile: {\n sessionId,\n filePath: jsonlPath,\n projectDir,\n birthtimeMs: stat.birthtimeMs,\n resolvedCwd: proc.cwd,\n },\n pidStatus: this.mapPidStatus(pidEntry?.status),\n waitingFor: pidEntry?.waitingFor,\n });\n }\n\n return { direct, fallback };\n }\n\n private extractResumeSessionId(command: string): string | null {\n const match = command.match(/--resume\\s+([0-9a-f-]{36})/i);\n return match?.[1] ?? null;\n }\n\n /**\n * Read and parse ~/.claude/sessions/<pid>.json, returning null on any\n * I/O / parse failure or when the file is stale relative to the live\n * process.\n *\n * \"Stale\" means the PID file's startedAt diverges from the process's\n * start time by more than {@link PID_FILE_STALENESS_MS} — typically\n * a previous Claude Code process recycled the same PID without cleanup.\n */\n private readMatchingPidFile(pid: number, procStartTime?: Date): PidFileEntry | null {\n const pidFilePath = path.join(this.sessionsDir, `${pid}.json`);\n try {\n const entry = JSON.parse(\n fs.readFileSync(pidFilePath, 'utf-8'),\n ) as PidFileEntry;\n\n if (procStartTime) {\n const deltaMs = Math.abs(procStartTime.getTime() - entry.startedAt);\n if (deltaMs > PID_FILE_STALENESS_MS) {\n return null;\n }\n }\n\n return entry;\n } catch {\n return null;\n }\n }\n\n /**\n * Map the PID file's live status string to {@link AgentStatus}.\n *\n * Returns undefined for missing / unrecognized values so the caller\n * can fall back to JSONL-derived heuristics.\n */\n private mapPidStatus(status: string | undefined): AgentStatus | undefined {\n switch (status) {\n case 'running':\n return AgentStatus.RUNNING;\n case 'waiting':\n return AgentStatus.WAITING;\n case 'idle':\n return AgentStatus.IDLE;\n default:\n return undefined;\n }\n }\n\n /**\n * Attempt to match each process to its session via ~/.claude/sessions/<pid>.json.\n *\n * Returns:\n * direct — processes matched authoritatively via PID file\n * fallback — processes with no valid PID file (sent to legacy matching)\n *\n * Per-process fallback triggers on: file absent, malformed JSON,\n * stale startedAt (>60s from proc.startTime), or missing JSONL.\n */\n private tryPidFileMatching(processes: ProcessInfo[]): {\n direct: DirectMatch[];\n fallback: ProcessInfo[];\n } {\n const direct: DirectMatch[] = [];\n const fallback: ProcessInfo[] = [];\n\n for (const proc of processes) {\n const entry = this.readMatchingPidFile(proc.pid, proc.startTime);\n if (!entry) {\n fallback.push(proc);\n continue;\n }\n\n const projectDir = this.getProjectDir(entry.cwd);\n const jsonlPath = path.join(projectDir, `${entry.sessionId}.jsonl`);\n\n if (!fs.existsSync(jsonlPath)) {\n fallback.push(proc);\n continue;\n }\n\n direct.push({\n process: proc,\n sessionFile: {\n sessionId: entry.sessionId,\n filePath: jsonlPath,\n projectDir,\n birthtimeMs: entry.startedAt,\n resolvedCwd: entry.cwd,\n },\n pidStatus: this.mapPidStatus(entry.status),\n waitingFor: entry.waitingFor,\n });\n }\n\n return { direct, fallback };\n }\n\n /**\n * Derive the Claude Code project directory for a given CWD.\n *\n * Claude Code encodes paths by replacing every non-alphanumeric\n * character with '-', so '/', '_', '.', spaces, etc. all collapse:\n * /Users/foo/bar → -Users-foo-bar\n * /Users/foo/my_project → -Users-foo-my-project\n * /Users/foo/.worktrees/x → -Users-foo--worktrees-x\n *\n * The encoding is lossy — multiple real paths can collide on the\n * same encoded dir. Callers that need to disambiguate must read the\n * `cwd` field inside each session JSONL.\n */\n private getProjectDir(cwd: string): string {\n const encoded = cwd.replace(/[^a-zA-Z0-9]/g, '-');\n return path.join(this.projectsDir, encoded);\n }\n\n private mapSessionToAgent(\n session: ClaudeSession,\n processInfo: ProcessInfo,\n sessionFile: SessionFile,\n liveInfo?: { pidStatus?: AgentStatus; waitingFor?: string },\n ): AgentInfo {\n // Live PID-file status is authoritative when present — JSONL-derived\n // status mis-classifies sessions whose latest entry is a UI-state\n // event like `permission-mode` or `ai-title`.\n const status = liveInfo?.pidStatus ?? this.parser.determineStatus(session);\n const baseSummary = session.lastUserMessage || 'Session started';\n const summary = status === AgentStatus.WAITING && liveInfo?.waitingFor\n ? `${baseSummary} — waiting for ${liveInfo.waitingFor}`\n : baseSummary;\n\n return {\n name: generateAgentName(processInfo.cwd, processInfo.pid),\n type: this.type,\n status,\n summary,\n pid: processInfo.pid,\n projectPath: sessionFile.resolvedCwd || processInfo.cwd || '',\n sessionId: sessionFile.sessionId,\n lastActive: session.lastActive,\n sessionFilePath: sessionFile.filePath,\n };\n }\n\n private mapProcessOnlyAgent(processInfo: ProcessInfo): AgentInfo {\n return {\n name: generateAgentName(processInfo.cwd || '', processInfo.pid),\n type: this.type,\n status: AgentStatus.IDLE,\n summary: 'Unknown',\n pid: processInfo.pid,\n projectPath: processInfo.cwd || '',\n sessionId: `pid-${processInfo.pid}`,\n lastActive: new Date(),\n };\n }\n\n getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {\n return this.parser.getConversation(sessionFilePath, options);\n }\n\n async listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]> {\n const filterCwd = opts?.cwd;\n const candidates = this.discoverSessionFiles();\n const summaries: SessionSummary[] = [];\n\n for (const { filePath, defaultCwd } of candidates) {\n const session = this.parser.readSession(filePath, defaultCwd);\n if (!session) continue;\n\n // Drop sessions whose JSONL had no parseable conversation entries.\n // readSession is permissive (returns a shell record even when every\n // line fails to parse); listSessions needs at least one real entry\n // so we don't surface garbage files.\n if (!session.lastEntryType) continue;\n\n const recordedCwd = session.lastCwd || defaultCwd;\n if (filterCwd !== undefined && recordedCwd !== filterCwd) continue;\n\n const stat = safeStat(filePath);\n\n summaries.push({\n type: 'claude',\n sessionId: session.sessionId,\n cwd: recordedCwd,\n firstUserMessage: session.firstUserMessage || '',\n lastActive: session.lastActive ?? stat?.mtime ?? new Date(),\n startedAt: session.sessionStart ?? stat?.birthtime ?? stat?.mtime ?? new Date(),\n sessionFilePath: filePath,\n });\n }\n\n return summaries;\n }\n\n /**\n * Discover candidate session files for {@link listSessions}.\n *\n * Always walks every subdirectory of `projectsDir`. We can't use the\n * encoded-dir shortcut for the cwd-scoped path because Claude Code\n * indexes session files by where the *process was launched*, not by\n * the recorded `cwd` field inside the session — these diverge in\n * worktrees and similar setups. The cwd filter is applied later\n * against `session.lastCwd` so callers see exactly the sessions whose\n * recorded cwd matches.\n */\n private discoverSessionFiles(): Array<{ filePath: string; defaultCwd: string }> {\n const out: Array<{ filePath: string; defaultCwd: string }> = [];\n\n if (!isDirectory(this.projectsDir)) return out;\n\n for (const dirName of safeReaddir(this.projectsDir)) {\n const projectDir = path.join(this.projectsDir, dirName);\n if (!isDirectory(projectDir)) continue;\n\n // Best-effort decode for the rare case session content has no\n // recorded cwd: '-Users-foo-bar' → '/Users/foo/bar'. Lossy for\n // paths containing '-'; session content's lastCwd overrides\n // this when available.\n const decoded = dirName.replace(/-/g, '/');\n for (const name of listJsonl(projectDir)) {\n out.push({ filePath: path.join(projectDir, name), defaultCwd: decoded });\n }\n }\n\n return out;\n }\n}\n"],"names":["fs","path","AgentStatus","captureProcessSnapshot","executableBasename","filterByProcessNames","batchGetSessionFileBirthtimes","isDirectory","listJsonl","safeReaddir","safeStat","matchProcessesToSessions","generateAgentName","ClaudeSessionParser","PID_FILE_STALENESS_MS","ClaudeCodeAdapter","type","processNames","projectsDir","sessionsDir","parser","homeDir","process","env","HOME","USERPROFILE","join","canHandle","processInfo","isClaudeExecutable","command","base","detectAgents","context","snapshot","processes","relevant","filter","length","direct","resumeDirect","fallback","noResume","tryResumeMatching","pidDirect","tryPidFileMatching","legacySessions","discoverSessions","legacyMatches","matchedPids","Set","map","d","pid","m","agents","match","proc","sessionFile","sessionData","readSession","filePath","resolvedCwd","push","mapSessionToAgent","pidStatus","waitingFor","delete","session","has","mapProcessOnlyAgent","dirToCwd","Map","cwd","projectDir","getProjectDir","statSync","set","size","files","keys","file","get","sessionId","extractResumeSessionId","jsonlPath","stat","pidEntry","readMatchingPidFile","startTime","birthtimeMs","mapPidStatus","status","procStartTime","pidFilePath","entry","JSON","parse","readFileSync","deltaMs","Math","abs","getTime","startedAt","RUNNING","WAITING","IDLE","undefined","existsSync","encoded","replace","liveInfo","determineStatus","baseSummary","lastUserMessage","summary","name","projectPath","lastActive","sessionFilePath","Date","getConversation","options","listSessions","opts","filterCwd","candidates","discoverSessionFiles","summaries","defaultCwd","lastEntryType","recordedCwd","lastCwd","firstUserMessage","mtime","sessionStart","birthtime","out","dirName","decoded"],"mappings":"AAAA,YAAYA,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAU7B,SAASC,WAAW,QAAQ,oBAAoB;AAChD,SAASC,sBAAsB,EAAEC,kBAAkB,EAAEC,oBAAoB,QAAQ,sBAAsB;AACvG,SAASC,6BAA6B,EAAEC,WAAW,EAAEC,SAAS,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,sBAAsB;AAEnH,SAASC,wBAAwB,EAAEC,iBAAiB,QAAQ,uBAAuB;AACnF,SAASC,mBAAmB,QAAQ,kCAAkC;AAwCtE,kFAAkF,GAClF,MAAMC,wBAAwB;AAE9B;;;;;;;;;CASC,GACD,OAAO,MAAMC;IACAC,OAAO,SAAkB;IACzBC,eAAe;QAAC;KAAS,CAAU;IAEpCC,YAAoB;IACpBC,YAAoB;IACpBC,OAA4B;IAEpC,aAAc;QACV,MAAMC,UAAUC,QAAQC,GAAG,CAACC,IAAI,IAAIF,QAAQC,GAAG,CAACE,WAAW,IAAI;QAC/D,IAAI,CAACP,WAAW,GAAGjB,KAAKyB,IAAI,CAACL,SAAS,WAAW;QACjD,IAAI,CAACF,WAAW,GAAGlB,KAAKyB,IAAI,CAACL,SAAS,WAAW;QACjD,IAAI,CAACD,MAAM,GAAG,IAAIP;IACtB;IAEAc,UAAUC,WAAwB,EAAW;QACzC,OAAO,IAAI,CAACC,kBAAkB,CAACD,YAAYE,OAAO;IACtD;IAEQD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O,GAAE,qBAA0B;IAQzC,QAAQ,IAAI,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;CAuBrE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/durable/ClaudeCliProbe.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport { ClaudePrintError } from './DurableAgent.js';\n\ntype ExecResult = { stdout: string; stderr: string };\ntype Exec = (file: string, args: string[]) => Promise<ExecResult>;\n\nconst execFileAsync = promisify(execFile);\nconst REQUIRED = ['--print', '--session-id', '--resume', '--output-format', 'stream-json'];\n\nexport interface ClaudeCliProbeOptions {\n executable?: string;\n exec?: Exec;\n}\n\nexport class ClaudeCliProbe {\n private readonly executable: string;\n private readonly exec: Exec;\n\n constructor(options: ClaudeCliProbeOptions = {}) {\n this.executable = options.executable ?? 'claude';\n this.exec = options.exec ?? (async (file, args) => {\n const result = await execFileAsync(file, args, { encoding: 'utf8', maxBuffer: 1024 * 1024 });\n return { stdout: result.stdout, stderr: result.stderr };\n });\n }\n\n async validate(): Promise<{ executable: string; version: string }> {\n try {\n const versionResult = await this.exec(this.executable, ['--version']);\n const helpResult = await this.exec(this.executable, ['--help']);\n const missing = REQUIRED.filter((capability) => !helpResult.stdout.includes(capability));\n if (missing.length > 0) {\n throw new ClaudePrintError(\n `Claude CLI does not support required print-mode capabilities: ${missing.join(', ')}.`,\n 'CLAUDE_CLI_UNSUPPORTED',\n );\n }\n return {\n executable: this.executable,\n version: sanitize(versionResult.stdout, 256) || 'unknown',\n };\n } catch (error) {\n if (error instanceof ClaudePrintError) throw error;\n throw new ClaudePrintError(\n `Claude CLI validation failed: ${sanitize((error as Error).message, 512)}`,\n 'CLAUDE_CLI_UNAVAILABLE',\n );\n }\n }\n}\n\nfunction sanitize(value: string, max: number): string {\n return Array.from(value, (character) => {\n const code = character.charCodeAt(0);\n return code <= 31 || code === 127 ? ' ' : character;\n }).join('').trim().slice(0, max);\n}\n"],"names":["execFile","promisify","ClaudePrintError","execFileAsync","REQUIRED","ClaudeCliProbe","executable","exec","options","file","args","result","encoding","maxBuffer","stdout","stderr","validate","versionResult","helpResult","missing","filter","capability","includes","length","join","version","sanitize","error","message","value","max","Array","from","character","code","charCodeAt","trim","slice"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,gBAAgB,QAAQ,oBAAoB;AAKrD,MAAMC,gBAAgBF,UAAUD;AAChC,MAAMI,WAAW;IAAC;IAAW;IAAgB;IAAY;IAAmB;CAAc;AAO1F,OAAO,MAAMC;IACQC,WAAmB;IACnBC,KAAW;IAE5B,YAAYC,UAAiC,CAAC,CAAC,CAAE;QAC7C,IAAI,CAACF,UAAU,GAAGE,QAAQF,UAAU,IAAI;QACxC,IAAI,CAACC,IAAI,GAAGC,QAAQD,IAAI,IAAK,CAAA,OAAOE,MAAMC;YACtC,MAAMC,SAAS,MAAMR,cAAcM,MAAMC,MAAM;gBAAEE,UAAU;gBAAQC,WAAW,OAAO;YAAK;YAC1F,OAAO;gBAAEC,QAAQH,OAAOG,MAAM;gBAAEC,QAAQJ,OAAOI,MAAM;YAAC;QAC1D,CAAA;IACJ;IAEA,MAAMC,WAA6D;QAC/D,IAAI;YACA,MAAMC,gBAAgB,MAAM,IAAI,CAACV,IAAI,CAAC,IAAI,CAACD,UAAU,EAAE;gBAAC;aAAY;YACpE,MAAMY,aAAa,MAAM,IAAI,CAACX,IAAI,CAAC,IAAI,CAACD,UAAU,EAAE;gBAAC;aAAS;YAC9D,MAAMa,UAAUf,SAASgB,MAAM,CAAC,CAACC,aAAe,CAACH,WAAWJ,MAAM,CAACQ,QAAQ,CAACD;YAC5E,IAAIF,QAAQI,MAAM,GAAG,GAAG;gBACpB,MAAM,IAAIrB,iBACN,CAAC,8DAA8D,EAAEiB,QAAQK,IAAI,CAAC,MAAM,CAAC,CAA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,OAAO,CAAC,qBAAqB,CAAC;CAoChF"}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import { ClaudePrintError, DurableAgentNotFoundError } from './DurableAgent.js';
|
|
2
|
-
import { ClaudeCliProbe } from './ClaudeCliProbe.js';
|
|
3
|
-
import { ClaudePrintRunner } from './ClaudePrintRunner.js';
|
|
4
|
-
import { DurableAgentRepository } from './DurableAgentRepository.js';
|
|
5
|
-
export class ClaudePrintAgentService {
|
|
6
|
-
repository;
|
|
7
|
-
probe;
|
|
8
|
-
runner;
|
|
9
|
-
executable;
|
|
10
|
-
constructor(options = {}){
|
|
11
|
-
this.repository = options.repository ?? new DurableAgentRepository();
|
|
12
|
-
this.probe = options.probe ?? new ClaudeCliProbe();
|
|
13
|
-
this.runner = options.runner ?? new ClaudePrintRunner();
|
|
14
|
-
this.executable = options.executable;
|
|
15
|
-
}
|
|
16
|
-
async create(input) {
|
|
17
|
-
await this.probe.validate();
|
|
18
|
-
return this.repository.create(input);
|
|
19
|
-
}
|
|
20
|
-
async send(reference, prompt) {
|
|
21
|
-
const resolved = await this.repository.resolve(reference);
|
|
22
|
-
if (!resolved) throw new DurableAgentNotFoundError(reference);
|
|
23
|
-
if (Array.isArray(resolved)) {
|
|
24
|
-
throw new ClaudePrintError(`Multiple durable agents match "${reference}".`, 'DURABLE_AGENT_AMBIGUOUS');
|
|
25
|
-
}
|
|
26
|
-
const acquired = await this.repository.acquireRun(resolved.id);
|
|
27
|
-
try {
|
|
28
|
-
const result = await this.runner.run({
|
|
29
|
-
agent: acquired.agent,
|
|
30
|
-
prompt,
|
|
31
|
-
executable: this.executable,
|
|
32
|
-
firstRun: acquired.agent.sessionHealth === 'uninitialized',
|
|
33
|
-
onSpawn: (identity)=>this.repository.recordProviderProcess(resolved.id, acquired.token, identity)
|
|
34
|
-
});
|
|
35
|
-
await this.repository.completeRun(resolved.id, acquired.token, {
|
|
36
|
-
status: 'succeeded',
|
|
37
|
-
exitCode: result.exitCode,
|
|
38
|
-
summary: sanitize(result.result, 4096),
|
|
39
|
-
sessionHealth: 'healthy'
|
|
40
|
-
});
|
|
41
|
-
return {
|
|
42
|
-
...result,
|
|
43
|
-
agentId: resolved.id,
|
|
44
|
-
agentName: resolved.name
|
|
45
|
-
};
|
|
46
|
-
} catch (error) {
|
|
47
|
-
const failure = error instanceof Error ? error : new Error(String(error));
|
|
48
|
-
const sessionHealth = error instanceof ClaudePrintError && error.code === 'CLAUDE_SESSION_MISMATCH' ? 'mismatch' : 'unknown';
|
|
49
|
-
await this.repository.completeRun(resolved.id, acquired.token, {
|
|
50
|
-
status: 'failed',
|
|
51
|
-
exitCode: null,
|
|
52
|
-
summary: sanitize(failure.message, 4096),
|
|
53
|
-
sessionHealth
|
|
54
|
-
});
|
|
55
|
-
throw error;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
function sanitize(value, max) {
|
|
60
|
-
return Array.from(value, (character)=>{
|
|
61
|
-
const code = character.charCodeAt(0);
|
|
62
|
-
return code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31 || code === 127 ? ' ' : character;
|
|
63
|
-
}).join('').trim().slice(0, max);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
//# sourceMappingURL=ClaudePrintAgentService.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/durable/ClaudePrintAgentService.ts"],"sourcesContent":["import type { DurableAgent, ProcessIdentity } from './DurableAgent.js';\nimport { ClaudePrintError, DurableAgentNotFoundError } from './DurableAgent.js';\nimport { ClaudeCliProbe } from './ClaudeCliProbe.js';\nimport { ClaudePrintRunner, type ClaudePrintRunResult } from './ClaudePrintRunner.js';\nimport { DurableAgentRepository, type CreateDurableAgentInput, type DurableRunCompletion } from './DurableAgentRepository.js';\n\ninterface RepositoryLike {\n create(input: CreateDurableAgentInput): Promise<DurableAgent>;\n list(): Promise<DurableAgent[]>;\n resolve(reference: string): Promise<DurableAgent | DurableAgent[] | null>;\n acquireRun(id: string): Promise<{ agent: DurableAgent; token: string }>;\n recordProviderProcess(id: string, token: string, identity: ProcessIdentity): Promise<void>;\n completeRun(id: string, token: string, result: DurableRunCompletion): Promise<DurableAgent>;\n}\n\ninterface ProbeLike { validate(): Promise<{ executable: string; version: string }> }\ninterface RunnerLike { run(request: Parameters<ClaudePrintRunner['run']>[0]): Promise<ClaudePrintRunResult> }\n\nexport interface ClaudePrintAgentServiceOptions {\n repository?: RepositoryLike;\n probe?: ProbeLike;\n runner?: RunnerLike;\n executable?: string;\n}\n\nexport interface ClaudePrintSendResult extends ClaudePrintRunResult {\n agentId: string;\n agentName: string;\n}\n\nexport class ClaudePrintAgentService {\n readonly repository: RepositoryLike;\n private readonly probe: ProbeLike;\n private readonly runner: RunnerLike;\n private readonly executable?: string;\n\n constructor(options: ClaudePrintAgentServiceOptions = {}) {\n this.repository = options.repository ?? new DurableAgentRepository();\n this.probe = options.probe ?? new ClaudeCliProbe();\n this.runner = options.runner ?? new ClaudePrintRunner();\n this.executable = options.executable;\n }\n\n async create(input: CreateDurableAgentInput): Promise<DurableAgent> {\n await this.probe.validate();\n return this.repository.create(input);\n }\n\n async send(reference: string, prompt: string): Promise<ClaudePrintSendResult> {\n const resolved = await this.repository.resolve(reference);\n if (!resolved) throw new DurableAgentNotFoundError(reference);\n if (Array.isArray(resolved)) {\n throw new ClaudePrintError(`Multiple durable agents match \"${reference}\".`, 'DURABLE_AGENT_AMBIGUOUS');\n }\n const acquired = await this.repository.acquireRun(resolved.id);\n try {\n const result = await this.runner.run({\n agent: acquired.agent,\n prompt,\n executable: this.executable,\n firstRun: acquired.agent.sessionHealth === 'uninitialized',\n onSpawn: (identity) => this.repository.recordProviderProcess(resolved.id, acquired.token, identity),\n });\n await this.repository.completeRun(resolved.id, acquired.token, {\n status: 'succeeded',\n exitCode: result.exitCode,\n summary: sanitize(result.result, 4096),\n sessionHealth: 'healthy',\n });\n return { ...result, agentId: resolved.id, agentName: resolved.name };\n } catch (error) {\n const failure = error instanceof Error ? error : new Error(String(error));\n const sessionHealth = error instanceof ClaudePrintError && error.code === 'CLAUDE_SESSION_MISMATCH'\n ? 'mismatch' as const\n : 'unknown' as const;\n await this.repository.completeRun(resolved.id, acquired.token, {\n status: 'failed',\n exitCode: null,\n summary: sanitize(failure.message, 4096),\n sessionHealth,\n });\n throw error;\n }\n }\n}\n\nfunction sanitize(value: string, max: number): string {\n return Array.from(value, (character) => {\n const code = character.charCodeAt(0);\n return (code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127)\n ? ' '\n : character;\n }).join('').trim().slice(0, max);\n}\n"],"names":["ClaudePrintError","DurableAgentNotFoundError","ClaudeCliProbe","ClaudePrintRunner","DurableAgentRepository","ClaudePrintAgentService","repository","probe","runner","executable","options","create","input","validate","send","reference","prompt","resolved","resolve","Array","isArray","acquired","acquireRun","id","result","run","agent","firstRun","sessionHealth","onSpawn","identity","recordProviderProcess","token","completeRun","status","exitCode","summary","sanitize","agentId","agentName","name","error","failure","Error","String","code","message","value","max","from","character","charCodeAt","join","trim","slice"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,yBAAyB,QAAQ,oBAAoB;AAChF,SAASC,cAAc,QAAQ,sBAAsB;AACrD,SAASC,iBAAiB,QAAmC,yBAAyB;AACtF,SAASC,sBAAsB,QAAiE,8BAA8B;AA0B9H,OAAO,MAAMC;IACAC,WAA2B;IACnBC,MAAiB;IACjBC,OAAmB;IACnBC,WAAoB;IAErC,YAAYC,UAA0C,CAAC,CAAC,CAAE;QACtD,IAAI,CAACJ,UAAU,GAAGI,QAAQJ,UAAU,IAAI,IAAIF;QAC5C,IAAI,CAACG,KAAK,GAAGG,QAAQH,KAAK,IAAI,IAAIL;QAClC,IAAI,CAACM,MAAM,GAAGE,QAAQF,MAAM,IAAI,IAAIL;QACpC,IAAI,CAACM,UAAU,GAAGC,QAAQD,UAAU;IACxC;IAEA,MAAME,OAAOC,KAA8B,EAAyB;QAChE,MAAM,IAAI,CAACL,KA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ED,MAAM,WAAW,oBAAoB;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,wBAAwB;IACrC,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IACpC,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,qBAAa,iBAAiB;IAC1B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAQ;IAC9B,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAmB;IACpD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;gBAE1B,OAAO,GAAE,wBAA6B;IAM5C,GAAG,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC;CAgG3E"}
|
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
import { spawn as nodeSpawn } from 'child_process';
|
|
2
|
-
import { ClaudePrintError } from './DurableAgent.js';
|
|
3
|
-
import { LocalProcessInspector } from './DurableAgentRepository.js';
|
|
4
|
-
export class ClaudePrintRunner {
|
|
5
|
-
spawn;
|
|
6
|
-
processInspector;
|
|
7
|
-
maxLineBytes;
|
|
8
|
-
constructor(options = {}){
|
|
9
|
-
this.spawn = options.spawn ?? nodeSpawn;
|
|
10
|
-
this.processInspector = options.processInspector ?? new LocalProcessInspector();
|
|
11
|
-
this.maxLineBytes = options.maxLineBytes ?? 1024 * 1024;
|
|
12
|
-
}
|
|
13
|
-
async run(request) {
|
|
14
|
-
const sessionArgs = request.firstRun ? [
|
|
15
|
-
'--session-id',
|
|
16
|
-
request.agent.providerSessionId
|
|
17
|
-
] : [
|
|
18
|
-
'--resume',
|
|
19
|
-
request.agent.providerSessionId
|
|
20
|
-
];
|
|
21
|
-
const args = [
|
|
22
|
-
'-p',
|
|
23
|
-
...sessionArgs,
|
|
24
|
-
'--output-format',
|
|
25
|
-
'stream-json',
|
|
26
|
-
'--verbose'
|
|
27
|
-
];
|
|
28
|
-
const child = this.spawn(request.executable ?? 'claude', args, {
|
|
29
|
-
cwd: request.agent.cwd,
|
|
30
|
-
shell: false,
|
|
31
|
-
stdio: [
|
|
32
|
-
'pipe',
|
|
33
|
-
'pipe',
|
|
34
|
-
'pipe'
|
|
35
|
-
]
|
|
36
|
-
});
|
|
37
|
-
if (!child.pid) {
|
|
38
|
-
child.kill();
|
|
39
|
-
throw new ClaudePrintError('Claude process did not provide a PID.', 'CLAUDE_PROCESS_IDENTITY');
|
|
40
|
-
}
|
|
41
|
-
const identity = this.processInspector.getIdentity(child.pid);
|
|
42
|
-
if (!identity) {
|
|
43
|
-
child.kill();
|
|
44
|
-
throw new ClaudePrintError('Cannot verify Claude process identity.', 'CLAUDE_PROCESS_IDENTITY');
|
|
45
|
-
}
|
|
46
|
-
let buffer = Buffer.alloc(0);
|
|
47
|
-
let terminal = null;
|
|
48
|
-
let protocolError = null;
|
|
49
|
-
child.stdout.on('data', (chunk)=>{
|
|
50
|
-
if (protocolError) return;
|
|
51
|
-
buffer = Buffer.concat([
|
|
52
|
-
buffer,
|
|
53
|
-
Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
54
|
-
]);
|
|
55
|
-
if (buffer.length > this.maxLineBytes && buffer.indexOf(0x0a) < 0) {
|
|
56
|
-
protocolError = new ClaudePrintError('Claude stream line exceeded the safety limit.', 'CLAUDE_STREAM_OVERSIZED');
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
let newline;
|
|
60
|
-
while((newline = buffer.indexOf(0x0a)) >= 0){
|
|
61
|
-
const line = buffer.subarray(0, newline);
|
|
62
|
-
buffer = buffer.subarray(newline + 1);
|
|
63
|
-
if (line.length === 0) continue;
|
|
64
|
-
if (line.length > this.maxLineBytes) {
|
|
65
|
-
protocolError = new ClaudePrintError('Claude stream line exceeded the safety limit.', 'CLAUDE_STREAM_OVERSIZED');
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
try {
|
|
69
|
-
const value = JSON.parse(line.toString('utf8'));
|
|
70
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
71
|
-
throw new ClaudePrintError('Claude emitted a non-object stream message.', 'CLAUDE_STREAM_INVALID');
|
|
72
|
-
}
|
|
73
|
-
const event = value;
|
|
74
|
-
if (typeof event.session_id === 'string' && event.session_id !== request.agent.providerSessionId) {
|
|
75
|
-
throw new ClaudePrintError('Claude returned a different session identity.', 'CLAUDE_SESSION_MISMATCH');
|
|
76
|
-
}
|
|
77
|
-
if (event.type === 'result') {
|
|
78
|
-
if (terminal) throw new ClaudePrintError('Claude emitted more than one terminal result.', 'CLAUDE_STREAM_INVALID');
|
|
79
|
-
if (typeof event.session_id !== 'string' || typeof event.result !== 'string') {
|
|
80
|
-
throw new ClaudePrintError('Claude emitted an invalid terminal result.', 'CLAUDE_STREAM_INVALID');
|
|
81
|
-
}
|
|
82
|
-
terminal = {
|
|
83
|
-
sessionId: event.session_id,
|
|
84
|
-
result: event.result,
|
|
85
|
-
exitCode: 0
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
} catch (error) {
|
|
89
|
-
protocolError = error instanceof ClaudePrintError ? error : new ClaudePrintError('Claude emitted malformed stream JSON.', 'CLAUDE_STREAM_INVALID');
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
});
|
|
94
|
-
// Drain provider diagnostics without reflecting potentially sensitive prompt/tool data.
|
|
95
|
-
child.stderr.resume();
|
|
96
|
-
const closed = new Promise((resolve, reject)=>{
|
|
97
|
-
child.once('error', reject);
|
|
98
|
-
child.once('close', (code, signal)=>resolve({
|
|
99
|
-
code,
|
|
100
|
-
signal
|
|
101
|
-
}));
|
|
102
|
-
});
|
|
103
|
-
try {
|
|
104
|
-
await request.onSpawn(identity);
|
|
105
|
-
} catch (error) {
|
|
106
|
-
child.kill();
|
|
107
|
-
throw error;
|
|
108
|
-
}
|
|
109
|
-
child.stdin.end(request.prompt);
|
|
110
|
-
const { code, signal } = await closed;
|
|
111
|
-
if (protocolError) throw protocolError;
|
|
112
|
-
if (buffer.length > 0) {
|
|
113
|
-
throw new ClaudePrintError('Claude stream ended with incomplete JSON.', 'CLAUDE_STREAM_INVALID');
|
|
114
|
-
}
|
|
115
|
-
if (code !== 0) {
|
|
116
|
-
throw new ClaudePrintError(`Claude print run failed${signal ? ` (${signal})` : '.'}`, 'CLAUDE_PROCESS_FAILED');
|
|
117
|
-
}
|
|
118
|
-
if (!terminal) throw new ClaudePrintError('Claude stream ended without a terminal result.', 'CLAUDE_RESULT_MISSING');
|
|
119
|
-
const finalResult = terminal;
|
|
120
|
-
return {
|
|
121
|
-
sessionId: finalResult.sessionId,
|
|
122
|
-
result: finalResult.result,
|
|
123
|
-
exitCode: code
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
//# sourceMappingURL=ClaudePrintRunner.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/durable/ClaudePrintRunner.ts"],"sourcesContent":["import { spawn as nodeSpawn, type ChildProcessWithoutNullStreams, type SpawnOptionsWithoutStdio } from 'child_process';\nimport type { DurableAgent, ProcessIdentity } from './DurableAgent.js';\nimport { ClaudePrintError } from './DurableAgent.js';\nimport { LocalProcessInspector, type ProcessInspector } from './DurableAgentRepository.js';\n\ntype Spawn = (\n command: string,\n args: readonly string[],\n options: SpawnOptionsWithoutStdio & { stdio: ['pipe', 'pipe', 'pipe'] },\n) => ChildProcessWithoutNullStreams;\n\nexport interface ClaudePrintRunRequest {\n agent: DurableAgent;\n prompt: string;\n executable?: string;\n firstRun: boolean;\n onSpawn(identity: ProcessIdentity): Promise<void>;\n}\n\nexport interface ClaudePrintRunResult {\n sessionId: string;\n result: string;\n exitCode: number;\n}\n\nexport interface ClaudePrintRunnerOptions {\n spawn?: Spawn;\n processInspector?: ProcessInspector;\n maxLineBytes?: number;\n}\n\nexport class ClaudePrintRunner {\n private readonly spawn: Spawn;\n private readonly processInspector: ProcessInspector;\n private readonly maxLineBytes: number;\n\n constructor(options: ClaudePrintRunnerOptions = {}) {\n this.spawn = options.spawn ?? (nodeSpawn as Spawn);\n this.processInspector = options.processInspector ?? new LocalProcessInspector();\n this.maxLineBytes = options.maxLineBytes ?? 1024 * 1024;\n }\n\n async run(request: ClaudePrintRunRequest): Promise<ClaudePrintRunResult> {\n const sessionArgs = request.firstRun\n ? ['--session-id', request.agent.providerSessionId]\n : ['--resume', request.agent.providerSessionId];\n const args = ['-p', ...sessionArgs, '--output-format', 'stream-json', '--verbose'];\n const child = this.spawn(request.executable ?? 'claude', args, {\n cwd: request.agent.cwd,\n shell: false,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n if (!child.pid) {\n child.kill();\n throw new ClaudePrintError('Claude process did not provide a PID.', 'CLAUDE_PROCESS_IDENTITY');\n }\n const identity = this.processInspector.getIdentity(child.pid);\n if (!identity) {\n child.kill();\n throw new ClaudePrintError('Cannot verify Claude process identity.', 'CLAUDE_PROCESS_IDENTITY');\n }\n\n let buffer = Buffer.alloc(0);\n let terminal: ClaudePrintRunResult | null = null;\n let protocolError: ClaudePrintError | null = null;\n\n child.stdout.on('data', (chunk: Buffer | string) => {\n if (protocolError) return;\n buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);\n if (buffer.length > this.maxLineBytes && buffer.indexOf(0x0a) < 0) {\n protocolError = new ClaudePrintError('Claude stream line exceeded the safety limit.', 'CLAUDE_STREAM_OVERSIZED');\n return;\n }\n let newline: number;\n while ((newline = buffer.indexOf(0x0a)) >= 0) {\n const line = buffer.subarray(0, newline);\n buffer = buffer.subarray(newline + 1);\n if (line.length === 0) continue;\n if (line.length > this.maxLineBytes) {\n protocolError = new ClaudePrintError('Claude stream line exceeded the safety limit.', 'CLAUDE_STREAM_OVERSIZED');\n return;\n }\n try {\n const value = JSON.parse(line.toString('utf8')) as unknown;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ClaudePrintError('Claude emitted a non-object stream message.', 'CLAUDE_STREAM_INVALID');\n }\n const event = value as Record<string, unknown>;\n if (typeof event.session_id === 'string' && event.session_id !== request.agent.providerSessionId) {\n throw new ClaudePrintError('Claude returned a different session identity.', 'CLAUDE_SESSION_MISMATCH');\n }\n if (event.type === 'result') {\n if (terminal) throw new ClaudePrintError('Claude emitted more than one terminal result.', 'CLAUDE_STREAM_INVALID');\n if (typeof event.session_id !== 'string' || typeof event.result !== 'string') {\n throw new ClaudePrintError('Claude emitted an invalid terminal result.', 'CLAUDE_STREAM_INVALID');\n }\n terminal = { sessionId: event.session_id, result: event.result, exitCode: 0 };\n }\n } catch (error) {\n protocolError = error instanceof ClaudePrintError\n ? error\n : new ClaudePrintError('Claude emitted malformed stream JSON.', 'CLAUDE_STREAM_INVALID');\n return;\n }\n }\n });\n // Drain provider diagnostics without reflecting potentially sensitive prompt/tool data.\n child.stderr.resume();\n\n const closed = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve, reject) => {\n child.once('error', reject);\n child.once('close', (code, signal) => resolve({ code, signal }));\n });\n\n try {\n await request.onSpawn(identity);\n } catch (error) {\n child.kill();\n throw error;\n }\n\n child.stdin.end(request.prompt);\n const { code, signal } = await closed;\n\n if (protocolError) throw protocolError;\n if (buffer.length > 0) {\n throw new ClaudePrintError('Claude stream ended with incomplete JSON.', 'CLAUDE_STREAM_INVALID');\n }\n if (code !== 0) {\n throw new ClaudePrintError(\n `Claude print run failed${signal ? ` (${signal})` : '.'}`,\n 'CLAUDE_PROCESS_FAILED',\n );\n }\n if (!terminal) throw new ClaudePrintError('Claude stream ended without a terminal result.', 'CLAUDE_RESULT_MISSING');\n const finalResult = terminal as ClaudePrintRunResult;\n return { sessionId: finalResult.sessionId, result: finalResult.result, exitCode: code };\n }\n}\n"],"names":["spawn","nodeSpawn","ClaudePrintError","LocalProcessInspector","ClaudePrintRunner","processInspector","maxLineBytes","options","run","request","sessionArgs","firstRun","agent","providerSessionId","args","child","executable","cwd","shell","stdio","pid","kill","identity","getIdentity","buffer","Buffer","alloc","terminal","protocolError","stdout","on","chunk","concat","isBuffer","from","length","indexOf","newline","line","subarray","value","JSON","parse","toString","Array","isArray","event","session_id","type","result","sessionId","exitCode","error","stderr","resume","closed","Promise","resolve","reject","once","code","signal","onSpawn","stdin","end","prompt","finalResult"],"mappings":"AAAA,SAASA,SAASC,SAAS,QAA4E,gBAAgB;AAEvH,SAASC,gBAAgB,QAAQ,oBAAoB;AACrD,SAASC,qBAAqB,QAA+B,8BAA8B;AA4B3F,OAAO,MAAMC;IACQJ,MAAa;IACbK,iBAAmC;IACnCC,aAAqB;IAEtC,YAAYC,UAAoC,CAAC,CAAC,CAAE;QAChD,IAAI,CAACP,KAAK,GAAGO,QAAQP,KAAK,IAAKC;QAC/B,IAAI,CAACI,gBAAgB,GAAGE,QAAQF,gBAAgB,IAAI,IAAIF;QACxD,IAAI,CAACG,YAAY,GAAGC,QAAQD,YAAY,IAAI,OAAO;IACvD;IAEA,MAAME,IAAIC,OAA8B,EAAiC;QACrE,MAAMC,cAAcD,QAAQE,QAAQ,GAC9B;YAAC;YAAgBF,QAAQG,KAAK,CAACC,iBAAiB;SAAC,GACjD;YAAC;YAAYJ,QAAQG,KAAK,CAACC,iBAAiB;SAAC;QACnD,MAAMC,OAAO;YAAC;eAASJ;YAAa;YAAmB;YAAe;SAAY;QAClF,MAAMK,QAAQ,IAAI,CAACf,KAAK,CAACS,QAAQO,UAAU,IAAI,UAAUF,MAAM;YAC3DG,KAAKR,QAAQG,KAAK,CAACK,GAAG;YACtBC,OAAO;YACPC,OAAO;gBAAC;gBAAQ;gBAAQ;aAAO;QACnC;QACA,IAAI,CAACJ,MAAMK,GAAG,EAAE;YACZL,MAAMM,IAAI;YACV,MAAM,IAAInB,iBAAiB,yCAAyC;QACxE;QACA,MAAMoB,WAAW,IAAI,CAACjB,gBAAgB,CAACkB,WAAW,CAACR,MAAMK,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oBD;;;;;;GAMG;AACH,qBAAa,mBAAmB;IAC5B;;;;;;;;OAQG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,aAAa,GAAG,IAAI;IAmFxE;;;;;;;;;OASG;IACH,eAAe,CAAC,OAAO,EAAE,aAAa,GAAG,WAAW;IA6BpD;;;;;OAKG;IACH,eAAe,CAAC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,mBAAmB,EAAE;IA6ChG;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAiBzB;;;;;;;;;OASG;IACH,OAAO,CAAC,sBAAsB;IAwC9B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAW3B;;OAEG;IACH,OAAO,CAAC,0BAA0B;CAmCrC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/ClaudeSessionParser.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { ConversationMessage } from '../adapters/AgentAdapter.js';\nimport { AgentStatus } from '../adapters/AgentAdapter.js';\n\n/**\n * Content block within a Claude Code JSONL message entry.\n * Handles text, tool_use, and tool_result block types.\n */\nexport interface ContentBlock {\n type?: string;\n text?: string;\n content?: string;\n name?: string;\n input?: Record<string, unknown>;\n tool_use_id?: string;\n is_error?: boolean;\n}\n\n/**\n * A single line entry in a Claude Code session JSONL file.\n *\n * Each line is an independent JSON object with a type discriminator:\n * - \"user\" / \"assistant\" / \"system\" — conversation turns\n * - \"progress\" / \"thinking\" — intermediate agent state\n * - \"last-prompt\" / \"file-history-snapshot\" — metadata (not conversation state)\n */\nexport interface SessionEntry {\n type?: string;\n timestamp?: string;\n cwd?: string;\n message?: {\n content?: string | ContentBlock[];\n };\n}\n\n/**\n * Parsed session state extracted from a JSONL file.\n * Aggregates data from all entries into a single summary.\n */\nexport interface ClaudeSession {\n sessionId: string;\n projectPath: string;\n lastCwd?: string;\n sessionStart: Date;\n lastActive: Date;\n lastEntryType?: string;\n isInterrupted: boolean;\n lastUserMessage?: string;\n /** First meaningful user prompt in the session (post noise filter) */\n firstUserMessage?: string;\n}\n\n/**\n * Top-level JSONL entry types that represent conversation/agent state.\n *\n * Only these types update `lastEntryType` for status determination. All\n * other types Claude Code emits (`attachment`, `permission-mode`,\n * `ai-title`, `queued_command`, `tools_changed`, `model_changed`,\n * `hook_progress`, …) are UI-state events that must not overwrite the\n * last conversation turn — otherwise polling between writes lands on a\n * UI-state entry and `determineStatus` falls through to UNKNOWN.\n */\nconst CONVERSATION_ENTRY_TYPES = new Set([\n 'user',\n 'assistant',\n 'system',\n 'progress',\n 'thinking',\n]);\n\n/**\n * Parses Claude Code session JSONL files into structured data.\n *\n * Session files live at ~/.claude/projects/<encoded-cwd>/<session-id>.jsonl\n * and contain one JSON object per line, each representing a conversation\n * event (user turn, assistant response, tool call, etc.).\n */\nexport class ClaudeSessionParser {\n /**\n * Parse a session JSONL file into a ClaudeSession summary.\n *\n * Iterates all lines to extract: session start time (from first entry),\n * last activity timestamp, last entry type (for status), whether the\n * session was interrupted, and the last meaningful user message.\n *\n * Returns null if the file is unreadable or empty.\n */\n readSession(filePath: string, projectPath: string): ClaudeSession | null {\n const sessionId = path.basename(filePath, '.jsonl');\n\n let content: string;\n try {\n content = fs.readFileSync(filePath, 'utf-8');\n } catch {\n return null;\n }\n\n const allLines = content.trim().split('\\n');\n if (allLines.length === 0) {\n return null;\n }\n\n const sessionStart = this.parseSessionStart(allLines[0]);\n\n let lastEntryType: string | undefined;\n let lastActive: Date | undefined;\n let lastCwd: string | undefined;\n let isInterrupted = false;\n let lastUserMessage: string | undefined;\n let firstUserMessage: string | undefined;\n\n for (const line of allLines) {\n try {\n const entry: SessionEntry = JSON.parse(line);\n\n if (entry.timestamp) {\n const ts = new Date(entry.timestamp);\n if (!Number.isNaN(ts.getTime())) {\n lastActive = ts;\n }\n }\n\n if (typeof entry.cwd === 'string' && entry.cwd.trim().length > 0) {\n lastCwd = entry.cwd;\n }\n\n if (entry.type && CONVERSATION_ENTRY_TYPES.has(entry.type)) {\n lastEntryType = entry.type;\n\n if (entry.type === 'user') {\n const msgContent = entry.message?.content;\n isInterrupted =\n Array.isArray(msgContent) &&\n msgContent.some(\n (c) =>\n (c.type === 'text' &&\n c.text?.includes('[Request interrupted')) ||\n (c.type === 'tool_result' &&\n c.content?.includes('[Request interrupted')),\n );\n\n const text = this.extractUserMessageText(msgContent);\n if (text) {\n lastUserMessage = text;\n if (!firstUserMessage) {\n firstUserMessage = text;\n }\n }\n } else {\n isInterrupted = false;\n }\n }\n } catch {\n continue;\n }\n }\n\n return {\n sessionId,\n projectPath: projectPath || lastCwd || '',\n lastCwd,\n sessionStart: sessionStart || lastActive || new Date(),\n lastActive: lastActive || new Date(),\n lastEntryType,\n isInterrupted,\n lastUserMessage,\n firstUserMessage,\n };\n }\n\n /**\n * Determine agent status from parsed session state.\n *\n * Status mapping:\n * - \"user\" + interrupted → WAITING (agent finished, awaiting new input)\n * - \"user\" + not interrupted → RUNNING (agent is processing)\n * - \"progress\" / \"thinking\" → RUNNING\n * - \"assistant\" → WAITING (agent responded, awaiting user)\n * - \"system\" → IDLE\n */\n determineStatus(session: ClaudeSession): AgentStatus {\n if (!session.lastEntryType) {\n return AgentStatus.UNKNOWN;\n }\n\n if (session.lastEntryType === 'user') {\n return session.isInterrupted\n ? AgentStatus.WAITING\n : AgentStatus.RUNNING;\n }\n\n if (\n session.lastEntryType === 'progress' ||\n session.lastEntryType === 'thinking'\n ) {\n return AgentStatus.RUNNING;\n }\n\n if (session.lastEntryType === 'assistant') {\n return AgentStatus.WAITING;\n }\n\n if (session.lastEntryType === 'system') {\n return AgentStatus.IDLE;\n }\n\n return AgentStatus.UNKNOWN;\n }\n\n /**\n * Read the full conversation from a session JSONL file.\n *\n * Default mode returns only text content from user/assistant/system messages.\n * Verbose mode also includes tool_use and tool_result blocks.\n */\n getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {\n const verbose = options?.verbose ?? false;\n\n let content: string;\n try {\n content = fs.readFileSync(sessionFilePath, 'utf-8');\n } catch {\n return [];\n }\n\n const lines = content.trim().split('\\n');\n const messages: ConversationMessage[] = [];\n\n for (const line of lines) {\n let entry: SessionEntry;\n try {\n entry = JSON.parse(line);\n } catch {\n continue;\n }\n\n let role: ConversationMessage['role'];\n if (entry.type === 'user') {\n role = 'user';\n } else if (entry.type === 'assistant') {\n role = 'assistant';\n } else if (entry.type === 'system') {\n role = 'system';\n } else {\n continue;\n }\n\n const text = this.extractConversationContent(entry.message?.content, role, verbose);\n if (!text) continue;\n\n messages.push({\n role,\n content: text,\n timestamp: entry.timestamp,\n });\n }\n\n return messages;\n }\n\n /**\n * Parse session start time from the first JSONL line.\n *\n * Claude Code may emit a \"file-history-snapshot\" as the first entry,\n * which stores its timestamp inside \"snapshot.timestamp\" rather than\n * at the root level.\n */\n private parseSessionStart(firstLine: string): Date | null {\n try {\n const firstEntry = JSON.parse(firstLine);\n const rawTs: string | undefined =\n firstEntry.timestamp || firstEntry.snapshot?.timestamp;\n if (rawTs) {\n const ts = new Date(rawTs);\n if (!Number.isNaN(ts.getTime())) {\n return ts;\n }\n }\n } catch {\n /* malformed first line */\n }\n return null;\n }\n\n /**\n * Extract meaningful text from a user message content field.\n *\n * Handles multiple formats:\n * - Plain string content\n * - Array of content blocks (extracts first text block)\n * - Skill slash-commands (<command-message> tags)\n * - Expanded skill content (extracts ARGUMENTS line)\n * - Filters noise messages (interruptions, tool loaded, session continued)\n */\n private extractUserMessageText(\n content: string | Array<{ type?: string; text?: string }> | undefined,\n ): string | undefined {\n if (!content) {\n return undefined;\n }\n\n let raw: string | undefined;\n\n if (typeof content === 'string') {\n raw = content.trim();\n } else if (Array.isArray(content)) {\n for (const block of content) {\n if (block.type === 'text' && block.text?.trim()) {\n raw = block.text.trim();\n break;\n }\n }\n }\n\n if (!raw) {\n return undefined;\n }\n\n if (raw.startsWith('<command-message>')) {\n return this.parseCommandMessage(raw);\n }\n\n if (raw.startsWith('Base directory for this skill:')) {\n const argsMatch = raw.match(/\\nARGUMENTS:\\s*(.+)/);\n return argsMatch?.[1]?.trim() || undefined;\n }\n\n if (isNoiseMessage(raw)) {\n return undefined;\n }\n\n return raw;\n }\n\n /**\n * Parse a <command-message> string into \"/command args\" format.\n */\n private parseCommandMessage(raw: string): string | undefined {\n const nameMatch = raw.match(/<command-name>([^<]+)<\\/command-name>/);\n const argsMatch = raw.match(/<command-args>([^<]+)<\\/command-args>/);\n const name = nameMatch?.[1]?.trim();\n if (!name) {\n return undefined;\n }\n const args = argsMatch?.[1]?.trim();\n return args ? `${name} ${args}` : name;\n }\n\n /**\n * Extract displayable content from a message content field for conversation output.\n */\n private extractConversationContent(\n content: string | ContentBlock[] | undefined,\n role: ConversationMessage['role'],\n verbose: boolean,\n ): string | undefined {\n if (!content) return undefined;\n\n if (typeof content === 'string') {\n const cleaned = stripHarnessTags(content);\n if (role === 'user' && isNoiseMessage(cleaned)) return undefined;\n return cleaned || undefined;\n }\n\n if (!Array.isArray(content)) return undefined;\n\n const parts: string[] = [];\n\n for (const block of content) {\n if (block.type === 'text' && block.text?.trim()) {\n const cleaned = stripHarnessTags(block.text);\n if (!cleaned) continue;\n if (role === 'user' && isNoiseMessage(cleaned)) continue;\n parts.push(cleaned);\n } else if (block.type === 'tool_use' && verbose) {\n const inputSummary = block.input?.file_path || block.input?.pattern || block.input?.command || '';\n parts.push(`[Tool: ${block.name}]${inputSummary ? ' ' + inputSummary : ''}`);\n } else if (block.type === 'tool_result' && verbose) {\n const truncated = truncateToolResult(block.content || '');\n const prefix = block.is_error ? '[Tool Error]' : '[Tool Result]';\n parts.push(`${prefix} ${truncated}`);\n }\n }\n\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n}\n\n/**\n * Tags whose entire block (including content) should be dropped — they are\n * harness-injected prompt context (system reminders, hook output, command\n * stdout), not meaningful conversation content.\n */\nconst HARNESS_DROP_TAGS = [\n 'system-reminder',\n 'local-command-stdout',\n 'local-command-stderr',\n 'user-prompt-submit-hook',\n 'command-stdout',\n 'command-stderr',\n 'bash-input',\n 'bash-stdout',\n 'bash-stderr',\n 'command-message',\n] as const;\n\nconst HARNESS_DROP_RE = new RegExp(\n `<(${HARNESS_DROP_TAGS.join('|')})>[\\\\s\\\\S]*?</\\\\1>`,\n 'g',\n);\n\nconst COMMAND_INVOCATION_RE =\n /<command-name>([^<]+)<\\/command-name>(?:\\s*<command-args>([\\s\\S]*?)<\\/command-args>)?/g;\n\n/**\n * Remove harness-injected XML blocks from message text and collapse\n * <command-name>/<command-args> pairs into a \"/name args\" shorthand.\n *\n * Returns the cleaned, trimmed text. Returns an empty string if nothing\n * survives stripping.\n */\nfunction stripHarnessTags(text: string): string {\n let out = text.replace(HARNESS_DROP_RE, '');\n\n out = out.replace(COMMAND_INVOCATION_RE, (_match, rawName: string, rawArgs?: string) => {\n const name = rawName.trim();\n const args = rawArgs?.trim();\n return args ? `${name} ${args}` : name;\n });\n\n return out.replace(/\\n{3,}/g, '\\n\\n').trim();\n}\n\n/** Check if a message is noise (not a meaningful user intent). */\nfunction isNoiseMessage(text: string): boolean {\n return (\n text.startsWith('[Request interrupted') ||\n text === 'Tool loaded.' ||\n text.startsWith('This session is being continued')\n );\n}\n\nfunction truncateToolResult(content: string, maxLength = 200): string {\n const firstLine = content.split('\\n')[0] || '';\n if (firstLine.length <= maxLength) return firstLine;\n return firstLine.slice(0, maxLength - 3) + '...';\n}\n"],"names":["fs","path","AgentStatus","CONVERSATION_ENTRY_TYPES","Set","ClaudeSessionParser","readSession","filePath","projectPath","sessionId","basename","content","readFileSync","allLines","trim","split","length","sessionStart","parseSessionStart","lastEntryType","lastActive","lastCwd","isInterrupted","lastUserMessage","firstUserMessage","line","entry","JSON","parse","timestamp","ts","Date","Number","isNaN","getTime","cwd","type","has","msgContent","message","Array","isArray","some","c","text","includes","extractUserMessageText","determineStatus","session","UNKNOWN","WAITING","RUNNING","IDLE","getConversation","sessionFilePath","options","verbose","lines","messages","role","extractConversationContent","push","firstLine","firstEntry","rawTs","snapshot","undefined","raw","block","startsWith","parseCommandMessage","argsMatch","match","isNoiseMessage","nameMatch","name","args","cleaned","stripHarnessTags","parts","inputSummary","input","file_path","pattern","command","truncated","truncateToolResult","prefix","is_error","join","HARNESS_DROP_TAGS","HARNESS_DROP_RE","RegExp","COMMAND_INVOCATION_RE","out","replace","_match","rawName","rawArgs","maxLength","slice"],"mappings":"AAAA,YAAYA,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAE7B,SAASC,WAAW,QAAQ,8BAA8B;AAkD1D;;;;;;;;;CASC,GACD,MAAMC,2BAA2B,IAAIC,IAAI;IACrC;IACA;IACA;IACA;IACA;CACH;AAED;;;;;;CAMC,GACD,OAAO,MAAMC;IACT;;;;;;;;KAQC,GACDC,YAAYC,QAAgB,EAAEC,WAAmB,EAAwB;QACrE,MAAMC,YAAYR,KAAKS,QAAQ,CAACH,UAAU;QAE1C,IAAII;QACJ,IAAI;YACAA,UAAUX,GAAGY,YAAY,CAACL,UAAU;QACxC,EAAE,OAAM;YACJ,OAAO;QACX;QAEA,MAAMM,WAAWF,QAAQG,IAAI,GAAGC,KAAK,CAAC;QACtC,IAAIF,SAASG,MAAM,KAAK,GAAG;YACvB,OAAO;QACX;QAEA,MAAMC,eAAe,IAAI,CAACC,iBAAiB,CAACL,QAAQ,CAAC,EAAE;QAEvD,IAAIM;QACJ,IAAIC;QACJ,IAAIC;QACJ,IAAIC,gBAAgB;QACpB,IAAIC;QACJ,IAAIC;QAEJ,KAAK,MAAMC,QAAQZ,SAAU;YACzB,IAAI;gBACA,MAAMa,QAAsBC,KAAKC,KAAK,CAACH;gBAEvC,IAAIC,MAAMG,SAAS,EAAE;oBACjB,MAAMC,KAAK,IAAIC,KAAKL,MAAMG,SAAS;oBACnC,IAAI,CAACG,OAAOC,KAAK,CAACH,GAAGI,OAAO,KAAK;wBAC7Bd,aA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