@ai-devkit/agent-manager 0.29.0 → 0.31.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__/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 +25 -28
- 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/database/connection.d.ts.map +1 -1
- package/dist/database/connection.js +5 -1
- package/dist/database/connection.js.map +1 -1
- 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 +17 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -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__/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 +11 -21
- 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/database/connection.ts +3 -1
- 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 +31 -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
|
@@ -1,24 +1,72 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ProcessInfo } from '../../adapters/AgentAdapter.js';
|
|
2
|
+
import { AgentStatus } from '../../adapters/AgentAdapter.js';
|
|
3
|
+
import { type MatchResult } from '../../utils/matching.js';
|
|
4
|
+
import { type SessionFile } from '../../utils/session.js';
|
|
2
5
|
/**
|
|
3
|
-
*
|
|
6
|
+
* A process directly matched to a session via PID file (authoritative path).
|
|
4
7
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* 3. Attempting authoritative PID-file matching via ~/.claude/sessions/<pid>.json
|
|
9
|
-
* 4. Falling back to CWD+birthtime heuristic (matchProcessesToSessions) for processes without a PID file
|
|
10
|
-
* 5. Extracting summary from last user message in session JSONL
|
|
8
|
+
* When the matching PID file also exposes live status/waitingFor metadata,
|
|
9
|
+
* those values are carried here so the agent mapper can prefer them over
|
|
10
|
+
* the JSONL-derived heuristic.
|
|
11
11
|
*/
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
12
|
+
export interface ClaudeDirectMatch {
|
|
13
|
+
process: ProcessInfo;
|
|
14
|
+
sessionFile: SessionFile;
|
|
15
|
+
pidStatus?: AgentStatus;
|
|
16
|
+
waitingFor?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface ClaudeProcessSessionMatches {
|
|
19
|
+
direct: ClaudeDirectMatch[];
|
|
20
|
+
legacyMatches: MatchResult[];
|
|
21
|
+
}
|
|
22
|
+
export interface ClaudeSessionLocatorOptions {
|
|
23
|
+
projectsDir?: string;
|
|
24
|
+
sessionsDir?: string;
|
|
25
|
+
}
|
|
26
|
+
export declare class ClaudeSessionLocator {
|
|
27
|
+
private readonly projectsDir;
|
|
28
|
+
private readonly sessionsDir;
|
|
29
|
+
constructor(options?: ClaudeSessionLocatorOptions);
|
|
30
|
+
/**
|
|
31
|
+
* Pair live Claude processes with their session files.
|
|
32
|
+
*
|
|
33
|
+
* Runs three staged strategies, each handing its unmatched processes
|
|
34
|
+
* to the next:
|
|
35
|
+
* 1. `--resume <id>` on the command line — authoritative for resumed
|
|
36
|
+
* sessions whose JSONL predates the process.
|
|
37
|
+
* 2. PID-file matching via ~/.claude/sessions/<pid>.json.
|
|
38
|
+
* 3. Legacy CWD+birthtime heuristic, for processes with no PID file.
|
|
39
|
+
*/
|
|
40
|
+
matchRunningProcesses(processes: ProcessInfo[]): ClaudeProcessSessionMatches;
|
|
41
|
+
/**
|
|
42
|
+
* Discover candidate session files for listing historical sessions.
|
|
43
|
+
*
|
|
44
|
+
* Always walks every subdirectory of `projectsDir`. We can't use the
|
|
45
|
+
* encoded-dir shortcut for the cwd-scoped path because Claude Code
|
|
46
|
+
* indexes session files by where the *process was launched*, not by
|
|
47
|
+
* the recorded `cwd` field inside the session — these diverge in
|
|
48
|
+
* worktrees and similar setups. The cwd filter is applied later
|
|
49
|
+
* against `session.lastCwd` so callers see exactly the sessions whose
|
|
50
|
+
* recorded cwd matches.
|
|
51
|
+
*/
|
|
52
|
+
discoverHistoricalSessionFiles(): Array<{
|
|
53
|
+
filePath: string;
|
|
54
|
+
defaultCwd: string;
|
|
55
|
+
}>;
|
|
56
|
+
/**
|
|
57
|
+
* Derive the Claude Code project directory for a given CWD.
|
|
58
|
+
*
|
|
59
|
+
* Claude Code encodes paths by replacing every non-alphanumeric
|
|
60
|
+
* character with '-', so '/', '_', '.', spaces, etc. all collapse:
|
|
61
|
+
* /Users/foo/bar → -Users-foo-bar
|
|
62
|
+
* /Users/foo/my_project → -Users-foo-my-project
|
|
63
|
+
* /Users/foo/.worktrees/x → -Users-foo--worktrees-x
|
|
64
|
+
*
|
|
65
|
+
* The encoding is lossy — multiple real paths can collide on the
|
|
66
|
+
* same encoded dir. Callers that need to disambiguate must read the
|
|
67
|
+
* `cwd` field inside each session JSONL.
|
|
68
|
+
*/
|
|
69
|
+
private getProjectDir;
|
|
22
70
|
/**
|
|
23
71
|
* Discover session files for the given processes.
|
|
24
72
|
*
|
|
@@ -26,7 +74,7 @@ export declare class ClaudeCodeAdapter implements AgentAdapter {
|
|
|
26
74
|
* ~/.claude/projects/<encoded>/ directory, then gets session file birthtimes
|
|
27
75
|
* via a single batched stat call across all directories.
|
|
28
76
|
*/
|
|
29
|
-
|
|
77
|
+
discoverLiveSessions(processes: ProcessInfo[]): SessionFile[];
|
|
30
78
|
/**
|
|
31
79
|
* Match processes via `claude --resume <uuid>` in their command line.
|
|
32
80
|
* This works for resumed sessions, where the JSONL was created earlier
|
|
@@ -63,37 +111,5 @@ export declare class ClaudeCodeAdapter implements AgentAdapter {
|
|
|
63
111
|
* stale startedAt (>60s from proc.startTime), or missing JSONL.
|
|
64
112
|
*/
|
|
65
113
|
private tryPidFileMatching;
|
|
66
|
-
/**
|
|
67
|
-
* Derive the Claude Code project directory for a given CWD.
|
|
68
|
-
*
|
|
69
|
-
* Claude Code encodes paths by replacing every non-alphanumeric
|
|
70
|
-
* character with '-', so '/', '_', '.', spaces, etc. all collapse:
|
|
71
|
-
* /Users/foo/bar → -Users-foo-bar
|
|
72
|
-
* /Users/foo/my_project → -Users-foo-my-project
|
|
73
|
-
* /Users/foo/.worktrees/x → -Users-foo--worktrees-x
|
|
74
|
-
*
|
|
75
|
-
* The encoding is lossy — multiple real paths can collide on the
|
|
76
|
-
* same encoded dir. Callers that need to disambiguate must read the
|
|
77
|
-
* `cwd` field inside each session JSONL.
|
|
78
|
-
*/
|
|
79
|
-
private getProjectDir;
|
|
80
|
-
private mapSessionToAgent;
|
|
81
|
-
private mapProcessOnlyAgent;
|
|
82
|
-
getConversation(sessionFilePath: string, options?: {
|
|
83
|
-
verbose?: boolean;
|
|
84
|
-
}): ConversationMessage[];
|
|
85
|
-
listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;
|
|
86
|
-
/**
|
|
87
|
-
* Discover candidate session files for {@link listSessions}.
|
|
88
|
-
*
|
|
89
|
-
* Always walks every subdirectory of `projectsDir`. We can't use the
|
|
90
|
-
* encoded-dir shortcut for the cwd-scoped path because Claude Code
|
|
91
|
-
* indexes session files by where the *process was launched*, not by
|
|
92
|
-
* the recorded `cwd` field inside the session — these diverge in
|
|
93
|
-
* worktrees and similar setups. The cwd filter is applied later
|
|
94
|
-
* against `session.lastCwd` so callers see exactly the sessions whose
|
|
95
|
-
* recorded cwd matches.
|
|
96
|
-
*/
|
|
97
|
-
private discoverSessionFiles;
|
|
98
114
|
}
|
|
99
|
-
//# sourceMappingURL=
|
|
115
|
+
//# sourceMappingURL=ClaudeSessionLocator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ClaudeSessionLocator.d.ts","sourceRoot":"","sources":["../../../src/providers/claude/ClaudeSessionLocator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,gC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95 +1,84 @@
|
|
|
1
1
|
import * as fs from 'fs';
|
|
2
2
|
import * as path from 'path';
|
|
3
|
-
import { AgentStatus } from '
|
|
4
|
-
import {
|
|
5
|
-
import { batchGetSessionFileBirthtimes, isDirectory, listJsonl, safeReaddir, safeStat } from '
|
|
6
|
-
import { matchProcessesToSessions, generateAgentName } from '../utils/matching.js';
|
|
7
|
-
import { ClaudeSessionParser } from '../utils/ClaudeSessionParser.js';
|
|
3
|
+
import { AgentStatus } from '../../adapters/AgentAdapter.js';
|
|
4
|
+
import { matchProcessesToSessions } from '../../utils/matching.js';
|
|
5
|
+
import { batchGetSessionFileBirthtimes, isDirectory, listJsonl, safeReaddir, safeStat } from '../../utils/session.js';
|
|
8
6
|
/** Maximum allowed delta (ms) between process start time and PID file startedAt. */ const PID_FILE_STALENESS_MS = 60000;
|
|
9
|
-
|
|
10
|
-
* Claude Code Adapter
|
|
11
|
-
*
|
|
12
|
-
* Detects Claude Code agents by:
|
|
13
|
-
* 1. Filtering Claude processes from a shared asynchronous process snapshot
|
|
14
|
-
* 2. Using snapshot CWD and start-time enrichment
|
|
15
|
-
* 3. Attempting authoritative PID-file matching via ~/.claude/sessions/<pid>.json
|
|
16
|
-
* 4. Falling back to CWD+birthtime heuristic (matchProcessesToSessions) for processes without a PID file
|
|
17
|
-
* 5. Extracting summary from last user message in session JSONL
|
|
18
|
-
*/ export class ClaudeCodeAdapter {
|
|
19
|
-
type = 'claude';
|
|
20
|
-
processNames = [
|
|
21
|
-
'claude'
|
|
22
|
-
];
|
|
7
|
+
export class ClaudeSessionLocator {
|
|
23
8
|
projectsDir;
|
|
24
9
|
sessionsDir;
|
|
25
|
-
|
|
26
|
-
constructor(){
|
|
10
|
+
constructor(options = {}){
|
|
27
11
|
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
|
28
|
-
this.projectsDir = path.join(homeDir, '.claude', 'projects');
|
|
29
|
-
this.sessionsDir = path.join(homeDir, '.claude', 'sessions');
|
|
30
|
-
this.parser = new ClaudeSessionParser();
|
|
12
|
+
this.projectsDir = options.projectsDir ?? path.join(homeDir, '.claude', 'projects');
|
|
13
|
+
this.sessionsDir = options.sessionsDir ?? path.join(homeDir, '.claude', 'sessions');
|
|
31
14
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
const processes = relevant.filter((process1)=>this.canHandle(process1));
|
|
43
|
-
if (processes.length === 0) {
|
|
44
|
-
return [];
|
|
45
|
-
}
|
|
46
|
-
// Step 1: extract `--resume <id>` from command line — authoritative for
|
|
47
|
-
// resumed sessions where the JSONL predates the process and PID-file/
|
|
48
|
-
// birthtime heuristics can't match it.
|
|
15
|
+
/**
|
|
16
|
+
* Pair live Claude processes with their session files.
|
|
17
|
+
*
|
|
18
|
+
* Runs three staged strategies, each handing its unmatched processes
|
|
19
|
+
* to the next:
|
|
20
|
+
* 1. `--resume <id>` on the command line — authoritative for resumed
|
|
21
|
+
* sessions whose JSONL predates the process.
|
|
22
|
+
* 2. PID-file matching via ~/.claude/sessions/<pid>.json.
|
|
23
|
+
* 3. Legacy CWD+birthtime heuristic, for processes with no PID file.
|
|
24
|
+
*/ matchRunningProcesses(processes) {
|
|
49
25
|
const { direct: resumeDirect, fallback: noResume } = this.tryResumeMatching(processes);
|
|
50
|
-
// Step 2: try authoritative PID-file matching for the rest
|
|
51
26
|
const { direct: pidDirect, fallback } = this.tryPidFileMatching(noResume);
|
|
52
|
-
const
|
|
53
|
-
...resumeDirect,
|
|
54
|
-
...pidDirect
|
|
55
|
-
];
|
|
56
|
-
// Step 3: run legacy CWD+birthtime matching only for processes without a PID file
|
|
57
|
-
const legacySessions = this.discoverSessions(fallback);
|
|
27
|
+
const legacySessions = this.discoverLiveSessions(fallback);
|
|
58
28
|
const legacyMatches = fallback.length > 0 && legacySessions.length > 0 ? matchProcessesToSessions(fallback, legacySessions) : [];
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
29
|
+
return {
|
|
30
|
+
direct: [
|
|
31
|
+
...resumeDirect,
|
|
32
|
+
...pidDirect
|
|
33
|
+
],
|
|
34
|
+
legacyMatches
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Discover candidate session files for listing historical sessions.
|
|
39
|
+
*
|
|
40
|
+
* Always walks every subdirectory of `projectsDir`. We can't use the
|
|
41
|
+
* encoded-dir shortcut for the cwd-scoped path because Claude Code
|
|
42
|
+
* indexes session files by where the *process was launched*, not by
|
|
43
|
+
* the recorded `cwd` field inside the session — these diverge in
|
|
44
|
+
* worktrees and similar setups. The cwd filter is applied later
|
|
45
|
+
* against `session.lastCwd` so callers see exactly the sessions whose
|
|
46
|
+
* recorded cwd matches.
|
|
47
|
+
*/ discoverHistoricalSessionFiles() {
|
|
48
|
+
const out = [];
|
|
49
|
+
if (!isDirectory(this.projectsDir)) return out;
|
|
50
|
+
for (const dirName of safeReaddir(this.projectsDir)){
|
|
51
|
+
const projectDir = path.join(this.projectsDir, dirName);
|
|
52
|
+
if (!isDirectory(projectDir)) continue;
|
|
53
|
+
// Best-effort decode for the rare case session content has no
|
|
54
|
+
// recorded cwd: '-Users-foo-bar' → '/Users/foo/bar'. Lossy for
|
|
55
|
+
// paths containing '-'; session content's lastCwd overrides
|
|
56
|
+
// this when available.
|
|
57
|
+
const decoded = dirName.replace(/-/g, '/');
|
|
58
|
+
for (const name of listJsonl(projectDir)){
|
|
59
|
+
out.push({
|
|
60
|
+
filePath: path.join(projectDir, name),
|
|
61
|
+
defaultCwd: decoded
|
|
62
|
+
});
|
|
90
63
|
}
|
|
91
64
|
}
|
|
92
|
-
return
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Derive the Claude Code project directory for a given CWD.
|
|
69
|
+
*
|
|
70
|
+
* Claude Code encodes paths by replacing every non-alphanumeric
|
|
71
|
+
* character with '-', so '/', '_', '.', spaces, etc. all collapse:
|
|
72
|
+
* /Users/foo/bar → -Users-foo-bar
|
|
73
|
+
* /Users/foo/my_project → -Users-foo-my-project
|
|
74
|
+
* /Users/foo/.worktrees/x → -Users-foo--worktrees-x
|
|
75
|
+
*
|
|
76
|
+
* The encoding is lossy — multiple real paths can collide on the
|
|
77
|
+
* same encoded dir. Callers that need to disambiguate must read the
|
|
78
|
+
* `cwd` field inside each session JSONL.
|
|
79
|
+
*/ getProjectDir(cwd) {
|
|
80
|
+
const encoded = cwd.replace(/[^a-zA-Z0-9]/g, '-');
|
|
81
|
+
return path.join(this.projectsDir, encoded);
|
|
93
82
|
}
|
|
94
83
|
/**
|
|
95
84
|
* Discover session files for the given processes.
|
|
@@ -97,7 +86,7 @@ import { ClaudeSessionParser } from '../utils/ClaudeSessionParser.js';
|
|
|
97
86
|
* For each unique process CWD, encodes it to derive the expected
|
|
98
87
|
* ~/.claude/projects/<encoded>/ directory, then gets session file birthtimes
|
|
99
88
|
* via a single batched stat call across all directories.
|
|
100
|
-
*/
|
|
89
|
+
*/ discoverLiveSessions(processes) {
|
|
101
90
|
const dirToCwd = new Map();
|
|
102
91
|
for (const proc of processes){
|
|
103
92
|
if (!proc.cwd) continue;
|
|
@@ -249,113 +238,6 @@ import { ClaudeSessionParser } from '../utils/ClaudeSessionParser.js';
|
|
|
249
238
|
fallback
|
|
250
239
|
};
|
|
251
240
|
}
|
|
252
|
-
/**
|
|
253
|
-
* Derive the Claude Code project directory for a given CWD.
|
|
254
|
-
*
|
|
255
|
-
* Claude Code encodes paths by replacing every non-alphanumeric
|
|
256
|
-
* character with '-', so '/', '_', '.', spaces, etc. all collapse:
|
|
257
|
-
* /Users/foo/bar → -Users-foo-bar
|
|
258
|
-
* /Users/foo/my_project → -Users-foo-my-project
|
|
259
|
-
* /Users/foo/.worktrees/x → -Users-foo--worktrees-x
|
|
260
|
-
*
|
|
261
|
-
* The encoding is lossy — multiple real paths can collide on the
|
|
262
|
-
* same encoded dir. Callers that need to disambiguate must read the
|
|
263
|
-
* `cwd` field inside each session JSONL.
|
|
264
|
-
*/ getProjectDir(cwd) {
|
|
265
|
-
const encoded = cwd.replace(/[^a-zA-Z0-9]/g, '-');
|
|
266
|
-
return path.join(this.projectsDir, encoded);
|
|
267
|
-
}
|
|
268
|
-
mapSessionToAgent(session, processInfo, sessionFile, liveInfo) {
|
|
269
|
-
// Live PID-file status is authoritative when present — JSONL-derived
|
|
270
|
-
// status mis-classifies sessions whose latest entry is a UI-state
|
|
271
|
-
// event like `permission-mode` or `ai-title`.
|
|
272
|
-
const status = liveInfo?.pidStatus ?? this.parser.determineStatus(session);
|
|
273
|
-
const baseSummary = session.lastUserMessage || 'Session started';
|
|
274
|
-
const summary = status === AgentStatus.WAITING && liveInfo?.waitingFor ? `${baseSummary} — waiting for ${liveInfo.waitingFor}` : baseSummary;
|
|
275
|
-
return {
|
|
276
|
-
name: generateAgentName(processInfo.cwd, processInfo.pid),
|
|
277
|
-
type: this.type,
|
|
278
|
-
status,
|
|
279
|
-
summary,
|
|
280
|
-
pid: processInfo.pid,
|
|
281
|
-
projectPath: sessionFile.resolvedCwd || processInfo.cwd || '',
|
|
282
|
-
sessionId: sessionFile.sessionId,
|
|
283
|
-
lastActive: session.lastActive,
|
|
284
|
-
sessionFilePath: sessionFile.filePath
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
mapProcessOnlyAgent(processInfo) {
|
|
288
|
-
return {
|
|
289
|
-
name: generateAgentName(processInfo.cwd || '', processInfo.pid),
|
|
290
|
-
type: this.type,
|
|
291
|
-
status: AgentStatus.IDLE,
|
|
292
|
-
summary: 'Unknown',
|
|
293
|
-
pid: processInfo.pid,
|
|
294
|
-
projectPath: processInfo.cwd || '',
|
|
295
|
-
sessionId: `pid-${processInfo.pid}`,
|
|
296
|
-
lastActive: new Date()
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
getConversation(sessionFilePath, options) {
|
|
300
|
-
return this.parser.getConversation(sessionFilePath, options);
|
|
301
|
-
}
|
|
302
|
-
async listSessions(opts) {
|
|
303
|
-
const filterCwd = opts?.cwd;
|
|
304
|
-
const candidates = this.discoverSessionFiles();
|
|
305
|
-
const summaries = [];
|
|
306
|
-
for (const { filePath, defaultCwd } of candidates){
|
|
307
|
-
const session = this.parser.readSession(filePath, defaultCwd);
|
|
308
|
-
if (!session) continue;
|
|
309
|
-
// Drop sessions whose JSONL had no parseable conversation entries.
|
|
310
|
-
// readSession is permissive (returns a shell record even when every
|
|
311
|
-
// line fails to parse); listSessions needs at least one real entry
|
|
312
|
-
// so we don't surface garbage files.
|
|
313
|
-
if (!session.lastEntryType) continue;
|
|
314
|
-
const recordedCwd = session.lastCwd || defaultCwd;
|
|
315
|
-
if (filterCwd !== undefined && recordedCwd !== filterCwd) continue;
|
|
316
|
-
const stat = safeStat(filePath);
|
|
317
|
-
summaries.push({
|
|
318
|
-
type: 'claude',
|
|
319
|
-
sessionId: session.sessionId,
|
|
320
|
-
cwd: recordedCwd,
|
|
321
|
-
firstUserMessage: session.firstUserMessage || '',
|
|
322
|
-
lastActive: session.lastActive ?? stat?.mtime ?? new Date(),
|
|
323
|
-
startedAt: session.sessionStart ?? stat?.birthtime ?? stat?.mtime ?? new Date(),
|
|
324
|
-
sessionFilePath: filePath
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
return summaries;
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Discover candidate session files for {@link listSessions}.
|
|
331
|
-
*
|
|
332
|
-
* Always walks every subdirectory of `projectsDir`. We can't use the
|
|
333
|
-
* encoded-dir shortcut for the cwd-scoped path because Claude Code
|
|
334
|
-
* indexes session files by where the *process was launched*, not by
|
|
335
|
-
* the recorded `cwd` field inside the session — these diverge in
|
|
336
|
-
* worktrees and similar setups. The cwd filter is applied later
|
|
337
|
-
* against `session.lastCwd` so callers see exactly the sessions whose
|
|
338
|
-
* recorded cwd matches.
|
|
339
|
-
*/ discoverSessionFiles() {
|
|
340
|
-
const out = [];
|
|
341
|
-
if (!isDirectory(this.projectsDir)) return out;
|
|
342
|
-
for (const dirName of safeReaddir(this.projectsDir)){
|
|
343
|
-
const projectDir = path.join(this.projectsDir, dirName);
|
|
344
|
-
if (!isDirectory(projectDir)) continue;
|
|
345
|
-
// Best-effort decode for the rare case session content has no
|
|
346
|
-
// recorded cwd: '-Users-foo-bar' → '/Users/foo/bar'. Lossy for
|
|
347
|
-
// paths containing '-'; session content's lastCwd overrides
|
|
348
|
-
// this when available.
|
|
349
|
-
const decoded = dirName.replace(/-/g, '/');
|
|
350
|
-
for (const name of listJsonl(projectDir)){
|
|
351
|
-
out.push({
|
|
352
|
-
filePath: path.join(projectDir, name),
|
|
353
|
-
defaultCwd: decoded
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
return out;
|
|
358
|
-
}
|
|
359
241
|
}
|
|
360
242
|
|
|
361
|
-
//# sourceMappingURL=
|
|
243
|
+
//# sourceMappingURL=ClaudeSessionLocator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/providers/claude/ClaudeSessionLocator.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { ProcessInfo } from '../../adapters/AgentAdapter.js';\nimport { AgentStatus } from '../../adapters/AgentAdapter.js';\nimport { matchProcessesToSessions, type MatchResult } from '../../utils/matching.js';\nimport {\n batchGetSessionFileBirthtimes,\n isDirectory,\n listJsonl,\n safeReaddir,\n safeStat,\n type SessionFile,\n} from '../../utils/session.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 the agent mapper can prefer them over\n * the JSONL-derived heuristic.\n */\nexport interface ClaudeDirectMatch {\n process: ProcessInfo;\n sessionFile: SessionFile;\n pidStatus?: AgentStatus;\n waitingFor?: string;\n}\n\nexport interface ClaudeProcessSessionMatches {\n direct: ClaudeDirectMatch[];\n legacyMatches: MatchResult[];\n}\n\nexport interface ClaudeSessionLocatorOptions {\n projectsDir?: string;\n sessionsDir?: string;\n}\n\n/** Maximum allowed delta (ms) between process start time and PID file startedAt. */\nconst PID_FILE_STALENESS_MS = 60000;\n\nexport class ClaudeSessionLocator {\n private readonly projectsDir: string;\n private readonly sessionsDir: string;\n\n constructor(options: ClaudeSessionLocatorOptions = {}) {\n const homeDir = process.env.HOME || process.env.USERPROFILE || '';\n this.projectsDir = options.projectsDir ?? path.join(homeDir, '.claude', 'projects');\n this.sessionsDir = options.sessionsDir ?? path.join(homeDir, '.claude', 'sessions');\n }\n\n /**\n * Pair live Claude processes with their session files.\n *\n * Runs three staged strategies, each handing its unmatched processes\n * to the next:\n * 1. `--resume <id>` on the command line — authoritative for resumed\n * sessions whose JSONL predates the process.\n * 2. PID-file matching via ~/.claude/sessions/<pid>.json.\n * 3. Legacy CWD+birthtime heuristic, for processes with no PID file.\n */\n matchRunningProcesses(processes: ProcessInfo[]): ClaudeProcessSessionMatches {\n const { direct: resumeDirect, fallback: noResume } = this.tryResumeMatching(processes);\n const { direct: pidDirect, fallback } = this.tryPidFileMatching(noResume);\n const legacySessions = this.discoverLiveSessions(fallback);\n const legacyMatches =\n fallback.length > 0 && legacySessions.length > 0\n ? matchProcessesToSessions(fallback, legacySessions)\n : [];\n\n return {\n direct: [...resumeDirect, ...pidDirect],\n legacyMatches,\n };\n }\n\n /**\n * Discover candidate session files for listing historical sessions.\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 discoverHistoricalSessionFiles(): 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 /**\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 /**\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 discoverLiveSessions(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: ClaudeDirectMatch[];\n fallback: ProcessInfo[];\n } {\n const direct: ClaudeDirectMatch[] = [];\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: ClaudeDirectMatch[];\n fallback: ProcessInfo[];\n } {\n const direct: ClaudeDirectMatch[] = [];\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"],"names":["fs","path","AgentStatus","matchProcessesToSessions","batchGetSessionFileBirthtimes","isDirectory","listJsonl","safeReaddir","safeStat","PID_FILE_STALENESS_MS","ClaudeSessionLocator","projectsDir","sessionsDir","options","homeDir","process","env","HOME","USERPROFILE","join","matchRunningProcesses","processes","direct","resumeDirect","fallback","noResume","tryResumeMatching","pidDirect","tryPidFileMatching","legacySessions","discoverLiveSessions","legacyMatches","length","discoverHistoricalSessionFiles","out","dirName","projectDir","decoded","replace","name","push","filePath","defaultCwd","getProjectDir","cwd","encoded","dirToCwd","Map","proc","has","statSync","set","size","files","keys","file","resolvedCwd","get","sessionId","extractResumeSessionId","command","jsonlPath","stat","pidEntry","readMatchingPidFile","pid","startTime","sessionFile","birthtimeMs","pidStatus","mapPidStatus","status","waitingFor","match","procStartTime","pidFilePath","entry","JSON","parse","readFileSync","deltaMs","Math","abs","getTime","startedAt","RUNNING","WAITING","IDLE","undefined","existsSync"],"mappings":"AAAA,YAAYA,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAE7B,SAASC,WAAW,QAAQ,iCAAiC;AAC7D,SAASC,wBAAwB,QAA0B,0BAA0B;AACrF,SACIC,6BAA6B,EAC7BC,WAAW,EACXC,SA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ConversationMessage } from '
|
|
2
|
-
import { AgentStatus } from '
|
|
1
|
+
import type { ConversationMessage } from '../../adapters/AgentAdapter.js';
|
|
2
|
+
import { AgentStatus } from '../../adapters/AgentAdapter.js';
|
|
3
3
|
/**
|
|
4
4
|
* Content block within a Claude Code JSONL message entry.
|
|
5
5
|
* Handles text, tool_use, and tool_result block types.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ClaudeSessionParser.d.ts","sourceRoot":"","sources":["../../../src/providers/claude/ClaudeSessionParser.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAE7D;;;GAGG;AACH,MAAM,WAAW,YAAY;IACzB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IACzB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE;QACN,OAAO,CAAC,EAAE,MAAM,GAAG,YAAY,EAAE,CAAC;KACrC,CAAC;CACL;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,IAAI,CAAC;IACnB,UAAU,EAAE,IAAI,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,OAAO,CAAC;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,sEAAsE;IACtE,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAoBD;;;;;;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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/providers/claude/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,iCAAiC;AAkD7D;;;;;;;;;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,C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B,QAAQ,GAAG,iBAAiB;gBACjDT,MAAMlB,IAAI,CAAC,GAAG0B,OAAO,CAAC,EAAEF,WAAW;YACvC;QACJ;QAEA,OAAON,MAAM/D,MAAM,GAAG,IAAI+D,MAAMU,IAAI,CAAC,QAAQvB;IACjD;AACJ;AAEA;;;;CAIC,GACD,MAAMwB,oBAAoB;IACtB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACH;AAED,MAAMC,kBAAkB,IAAIC,OACxB,CAAC,EAAE,EAAEF,kBAAkBD,IAAI,CAAC,KAAK,kBAAkB,CAAC,EACpD;AAGJ,MAAMI,wBACF;AAEJ;;;;;;CAMC,GACD,SAASf,iBAAiBlC,IAAY;IAClC,IAAIkD,MAAMlD,KAAKmD,OAAO,CAACJ,iBAAiB;IAExCG,MAAMA,IAAIC,OAAO,CAACF,uBAAuB,CAACG,QAAQC,SAAiBC;QAC/D,MAAMvB,OAAOsB,QAAQnF,IAAI;QACzB,MAAM8D,OAAOsB,SAASpF;QACtB,OAAO8D,OAAO,GAAGD,KAAK,CAAC,EAAEC,MAAM,GAAGD;IACtC;IAEA,OAAOmB,IAAIC,OAAO,CAAC,WAAW,QAAQjF,IAAI;AAC9C;AAEA,gEAAgE,GAChE,SAAS2D,eAAe7B,IAAY;IAChC,OACIA,KAAKyB,UAAU,CAAC,2BAChBzB,SAAS,kBACTA,KAAKyB,UAAU,CAAC;AAExB;AAEA,SAASiB,mBAAmB3E,OAAe,EAAEwF,YAAY,GAAG;IACxD,MAAMrC,YAAYnD,QAAQI,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI;IAC5C,IAAI+C,UAAU9C,MAAM,IAAImF,WAAW,OAAOrC;IAC1C,OAAOA,UAAUsC,KAAK,CAAC,GAAGD,YAAY,KAAK;AAC/C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ClaudeCliProbe.d.ts","sourceRoot":"","sources":["../../../../src/providers/claude/durable/ClaudeCliProbe.ts"],"names":[],"mappings":"AAKA,KAAK,UAAU,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AACrD,KAAK,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;AAKlE,MAAM,WAAW,qBAAqB;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,IAAI,CAAC;CACf;AAED,qBAAa,cAAc;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAO;gBAEhB,OAAO,GAAE,qBAA0B;IAQzC,QAAQ,IAAI,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;CAuBrE"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execFile } from 'child_process';
|
|
2
2
|
import { promisify } from 'util';
|
|
3
|
-
import { ClaudePrintError } from '
|
|
3
|
+
import { ClaudePrintError } from '../../../durable/DurableAgent.js';
|
|
4
|
+
import { sanitizeText } from '../../../durable/utils.js';
|
|
4
5
|
const execFileAsync = promisify(execFile);
|
|
5
6
|
const REQUIRED = [
|
|
6
7
|
'--print',
|
|
@@ -39,19 +40,13 @@ export class ClaudeCliProbe {
|
|
|
39
40
|
}
|
|
40
41
|
return {
|
|
41
42
|
executable: this.executable,
|
|
42
|
-
version:
|
|
43
|
+
version: sanitizeText(versionResult.stdout, 256) || 'unknown'
|
|
43
44
|
};
|
|
44
45
|
} catch (error) {
|
|
45
46
|
if (error instanceof ClaudePrintError) throw error;
|
|
46
|
-
throw new ClaudePrintError(`Claude CLI validation failed: ${
|
|
47
|
+
throw new ClaudePrintError(`Claude CLI validation failed: ${sanitizeText(error.message, 512)}`, 'CLAUDE_CLI_UNAVAILABLE');
|
|
47
48
|
}
|
|
48
49
|
}
|
|
49
50
|
}
|
|
50
|
-
function sanitize(value, max) {
|
|
51
|
-
return Array.from(value, (character)=>{
|
|
52
|
-
const code = character.charCodeAt(0);
|
|
53
|
-
return code <= 31 || code === 127 ? ' ' : character;
|
|
54
|
-
}).join('').trim().slice(0, max);
|
|
55
|
-
}
|
|
56
51
|
|
|
57
52
|
//# sourceMappingURL=ClaudeCliProbe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/providers/claude/durable/ClaudeCliProbe.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport { ClaudePrintError } from '../../../durable/DurableAgent.js';\nimport { sanitizeText } from '../../../durable/utils.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: sanitizeText(versionResult.stdout, 256) || 'unknown',\n };\n } catch (error) {\n if (error instanceof ClaudePrintError) throw error;\n throw new ClaudePrintError(\n `Claude CLI validation failed: ${sanitizeText((error as Error).message, 512)}`,\n 'CLAUDE_CLI_UNAVAILABLE',\n );\n }\n }\n}\n"],"names":["execFile","promisify","ClaudePrintError","sanitizeText","execFileAsync","REQUIRED","ClaudeCliProbe","executable","exec","options","file","args","result","encoding","maxBuffer","stdout","stderr","validate","versionResult","helpResult","missing","filter","capability","includes","length","join","version","error","message"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,gBAAgB,QAAQ,mCAAmC;AACpE,SAASC,YAAY,QAAQ,4BAA4B;AAKzD,MAAMC,gBAAgBH,UAAUD;AAChC,MAAMK,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,IAAItB,iBACN,CAAC,8DAA8D,EAAEkB,QAAQK,IAAI,CAAC,MAAM,CAAC,CAAC,EACtF;YAER;YACA,OAAO;gBACHlB,YAAY,IAAI,CAACA,UAAU;gBAC3BmB,SAASvB,aAAae,cAAcH,MAAM,EAAE,QAAQ;YACxD;QACJ,EAAE,OAAOY,OAAO;YACZ,IAAIA,iBAAiBzB,kBAAkB,MAAMyB;YAC7C,MAAM,IAAIzB,iBACN,CAAC,8BAA8B,EAAEC,aAAa,AAACwB,MAAgBC,OAAO,EAAE,MAAM,EAC9E;QAER;IACJ;AACJ"}
|
|
@@ -1,16 +1,11 @@
|
|
|
1
|
-
import type { DurableAgent, ProcessIdentity } from '
|
|
1
|
+
import type { DurableAgent, ProcessIdentity } from '../../../durable/DurableAgent.js';
|
|
2
2
|
import { ClaudePrintRunner, type ClaudePrintRunResult } from './ClaudePrintRunner.js';
|
|
3
|
-
import { type CreateDurableAgentInput
|
|
4
|
-
|
|
3
|
+
import { type CreateDurableAgentInput } from '../../../durable/DurableAgentRepository.js';
|
|
4
|
+
import { type DurableRunRepository } from '../../../durable/run.js';
|
|
5
|
+
interface RepositoryLike extends DurableRunRepository {
|
|
5
6
|
create(input: CreateDurableAgentInput): Promise<DurableAgent>;
|
|
6
7
|
list(): Promise<DurableAgent[]>;
|
|
7
|
-
resolve(reference: string): Promise<DurableAgent | DurableAgent[] | null>;
|
|
8
|
-
acquireRun(id: string): Promise<{
|
|
9
|
-
agent: DurableAgent;
|
|
10
|
-
token: string;
|
|
11
|
-
}>;
|
|
12
8
|
recordProviderProcess(id: string, token: string, identity: ProcessIdentity): Promise<void>;
|
|
13
|
-
completeRun(id: string, token: string, result: DurableRunCompletion): Promise<DurableAgent>;
|
|
14
9
|
}
|
|
15
10
|
interface ProbeLike {
|
|
16
11
|
validate(): Promise<{
|