@ai-devkit/agent-manager 0.29.0 → 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.
Files changed (198) hide show
  1. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js +1 -342
  2. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js.map +1 -1
  3. package/dist/__tests__/database/DurableAgentsDatabase.test.js +31 -3
  4. package/dist/__tests__/database/DurableAgentsDatabase.test.js.map +1 -1
  5. package/dist/__tests__/durable/CodexCliProbe.test.js +129 -0
  6. package/dist/__tests__/durable/CodexCliProbe.test.js.map +1 -0
  7. package/dist/__tests__/durable/CodexDurableAgentRepository.test.js +84 -0
  8. package/dist/__tests__/durable/CodexDurableAgentRepository.test.js.map +1 -0
  9. package/dist/__tests__/durable/CodexPrintAgent.integration.test.js +126 -0
  10. package/dist/__tests__/durable/CodexPrintAgent.integration.test.js.map +1 -0
  11. package/dist/__tests__/durable/CodexPrintAgentService.test.js +271 -0
  12. package/dist/__tests__/durable/CodexPrintAgentService.test.js.map +1 -0
  13. package/dist/__tests__/durable/CodexPrintRunner.test.js +393 -0
  14. package/dist/__tests__/durable/CodexPrintRunner.test.js.map +1 -0
  15. package/dist/__tests__/print/ClaudeCliProbe.test.js +3 -7
  16. package/dist/__tests__/print/ClaudeCliProbe.test.js.map +1 -1
  17. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js +25 -28
  18. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js.map +1 -1
  19. package/dist/__tests__/print/ClaudePrintAgentService.test.js +65 -0
  20. package/dist/__tests__/print/ClaudePrintAgentService.test.js.map +1 -1
  21. package/dist/__tests__/print/ClaudePrintRunner.test.js +4 -10
  22. package/dist/__tests__/print/ClaudePrintRunner.test.js.map +1 -1
  23. package/dist/__tests__/providers/claude/ClaudeAgentMapper.test.js +79 -0
  24. package/dist/__tests__/providers/claude/ClaudeAgentMapper.test.js.map +1 -0
  25. package/dist/__tests__/providers/claude/ClaudeSessionLocator.test.js +436 -0
  26. package/dist/__tests__/providers/claude/ClaudeSessionLocator.test.js.map +1 -0
  27. package/dist/__tests__/providers/pi/durable/PiCliProbe.test.js +76 -0
  28. package/dist/__tests__/providers/pi/durable/PiCliProbe.test.js.map +1 -0
  29. package/dist/__tests__/providers/pi/durable/PiDurableAgentRepository.test.js +43 -0
  30. package/dist/__tests__/providers/pi/durable/PiDurableAgentRepository.test.js.map +1 -0
  31. package/dist/__tests__/providers/pi/durable/PiPrintAgentService.test.js +202 -0
  32. package/dist/__tests__/providers/pi/durable/PiPrintAgentService.test.js.map +1 -0
  33. package/dist/__tests__/providers/pi/durable/PiPrintProtocol.test.js +119 -0
  34. package/dist/__tests__/providers/pi/durable/PiPrintProtocol.test.js.map +1 -0
  35. package/dist/__tests__/providers/pi/durable/PiPrintRunner.test.js +386 -0
  36. package/dist/__tests__/providers/pi/durable/PiPrintRunner.test.js.map +1 -0
  37. package/dist/__tests__/providers/pi/durable/PiStreamParser.test.js +34 -0
  38. package/dist/__tests__/providers/pi/durable/PiStreamParser.test.js.map +1 -0
  39. package/dist/__tests__/utils/ClaudeSessionParser.test.js +2 -2
  40. package/dist/__tests__/utils/ClaudeSessionParser.test.js.map +1 -1
  41. package/dist/adapters/index.d.ts +1 -1
  42. package/dist/adapters/index.d.ts.map +1 -1
  43. package/dist/adapters/index.js +1 -1
  44. package/dist/adapters/index.js.map +1 -1
  45. package/dist/database/migrations/004_codex_durable_sessions.sql +1 -0
  46. package/dist/durable/DurableAgent.d.ts +23 -3
  47. package/dist/durable/DurableAgent.d.ts.map +1 -1
  48. package/dist/durable/DurableAgent.js +12 -0
  49. package/dist/durable/DurableAgent.js.map +1 -1
  50. package/dist/durable/DurableAgentRepository.d.ts +6 -7
  51. package/dist/durable/DurableAgentRepository.d.ts.map +1 -1
  52. package/dist/durable/DurableAgentRepository.js +73 -42
  53. package/dist/durable/DurableAgentRepository.js.map +1 -1
  54. package/dist/durable/process.d.ts +8 -0
  55. package/dist/durable/process.d.ts.map +1 -0
  56. package/dist/durable/process.js +40 -0
  57. package/dist/durable/process.js.map +1 -0
  58. package/dist/durable/run.d.ts +32 -0
  59. package/dist/durable/run.d.ts.map +1 -0
  60. package/dist/durable/run.js +46 -0
  61. package/dist/durable/run.js.map +1 -0
  62. package/dist/durable/utils.d.ts +19 -0
  63. package/dist/durable/utils.d.ts.map +1 -0
  64. package/dist/durable/utils.js +52 -0
  65. package/dist/durable/utils.js.map +1 -0
  66. package/dist/index.d.ts +17 -13
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +9 -8
  69. package/dist/index.js.map +1 -1
  70. package/dist/providers/claude/ClaudeAgentMapper.d.ts +21 -0
  71. package/dist/providers/claude/ClaudeAgentMapper.d.ts.map +1 -0
  72. package/dist/providers/claude/ClaudeAgentMapper.js +42 -0
  73. package/dist/providers/claude/ClaudeAgentMapper.js.map +1 -0
  74. package/dist/providers/claude/ClaudeCodeAdapter.d.ts +29 -0
  75. package/dist/providers/claude/ClaudeCodeAdapter.d.ts.map +1 -0
  76. package/dist/providers/claude/ClaudeCodeAdapter.js +129 -0
  77. package/dist/providers/claude/ClaudeCodeAdapter.js.map +1 -0
  78. package/dist/{adapters/ClaudeCodeAdapter.d.ts → providers/claude/ClaudeSessionLocator.d.ts} +68 -52
  79. package/dist/providers/claude/ClaudeSessionLocator.d.ts.map +1 -0
  80. package/dist/{adapters/ClaudeCodeAdapter.js → providers/claude/ClaudeSessionLocator.js} +71 -189
  81. package/dist/providers/claude/ClaudeSessionLocator.js.map +1 -0
  82. package/dist/{utils → providers/claude}/ClaudeSessionParser.d.ts +2 -2
  83. package/dist/providers/claude/ClaudeSessionParser.d.ts.map +1 -0
  84. package/dist/{utils → providers/claude}/ClaudeSessionParser.js +1 -1
  85. package/dist/providers/claude/ClaudeSessionParser.js.map +1 -0
  86. package/dist/providers/claude/durable/ClaudeCliProbe.d.ts.map +1 -0
  87. package/dist/{durable → providers/claude/durable}/ClaudeCliProbe.js +4 -9
  88. package/dist/providers/claude/durable/ClaudeCliProbe.js.map +1 -0
  89. package/dist/{durable → providers/claude/durable}/ClaudePrintAgentService.d.ts +4 -9
  90. package/dist/providers/claude/durable/ClaudePrintAgentService.d.ts.map +1 -0
  91. package/dist/providers/claude/durable/ClaudePrintAgentService.js +45 -0
  92. package/dist/providers/claude/durable/ClaudePrintAgentService.js.map +1 -0
  93. package/dist/{durable → providers/claude/durable}/ClaudePrintRunner.d.ts +3 -3
  94. package/dist/providers/claude/durable/ClaudePrintRunner.d.ts.map +1 -0
  95. package/dist/providers/claude/durable/ClaudePrintRunner.js +75 -0
  96. package/dist/providers/claude/durable/ClaudePrintRunner.js.map +1 -0
  97. package/dist/providers/claude/durable/ClaudeStreamParser.d.ts +17 -0
  98. package/dist/providers/claude/durable/ClaudeStreamParser.d.ts.map +1 -0
  99. package/dist/providers/claude/durable/ClaudeStreamParser.js +69 -0
  100. package/dist/providers/claude/durable/ClaudeStreamParser.js.map +1 -0
  101. package/dist/providers/codex/durable/CodexCliProbe.d.ts +20 -0
  102. package/dist/providers/codex/durable/CodexCliProbe.d.ts.map +1 -0
  103. package/dist/providers/codex/durable/CodexCliProbe.js +61 -0
  104. package/dist/providers/codex/durable/CodexCliProbe.js.map +1 -0
  105. package/dist/providers/codex/durable/CodexPrintAgentService.d.ts +40 -0
  106. package/dist/providers/codex/durable/CodexPrintAgentService.d.ts.map +1 -0
  107. package/dist/providers/codex/durable/CodexPrintAgentService.js +50 -0
  108. package/dist/providers/codex/durable/CodexPrintAgentService.js.map +1 -0
  109. package/dist/providers/codex/durable/CodexPrintRunner.d.ts +34 -0
  110. package/dist/providers/codex/durable/CodexPrintRunner.d.ts.map +1 -0
  111. package/dist/providers/codex/durable/CodexPrintRunner.js +78 -0
  112. package/dist/providers/codex/durable/CodexPrintRunner.js.map +1 -0
  113. package/dist/providers/codex/durable/CodexStreamParser.d.ts +21 -0
  114. package/dist/providers/codex/durable/CodexStreamParser.d.ts.map +1 -0
  115. package/dist/providers/codex/durable/CodexStreamParser.js +86 -0
  116. package/dist/providers/codex/durable/CodexStreamParser.js.map +1 -0
  117. package/dist/providers/pi/durable/PiCliProbe.d.ts +20 -0
  118. package/dist/providers/pi/durable/PiCliProbe.d.ts.map +1 -0
  119. package/dist/providers/pi/durable/PiCliProbe.js +51 -0
  120. package/dist/providers/pi/durable/PiCliProbe.js.map +1 -0
  121. package/dist/providers/pi/durable/PiPrintAgentService.d.ts +39 -0
  122. package/dist/providers/pi/durable/PiPrintAgentService.d.ts.map +1 -0
  123. package/dist/providers/pi/durable/PiPrintAgentService.js +47 -0
  124. package/dist/providers/pi/durable/PiPrintAgentService.js.map +1 -0
  125. package/dist/providers/pi/durable/PiPrintProtocol.d.ts +4 -0
  126. package/dist/providers/pi/durable/PiPrintProtocol.d.ts.map +1 -0
  127. package/dist/providers/pi/durable/PiPrintProtocol.js +44 -0
  128. package/dist/providers/pi/durable/PiPrintProtocol.js.map +1 -0
  129. package/dist/providers/pi/durable/PiPrintRunner.d.ts +32 -0
  130. package/dist/providers/pi/durable/PiPrintRunner.d.ts.map +1 -0
  131. package/dist/providers/pi/durable/PiPrintRunner.js +61 -0
  132. package/dist/providers/pi/durable/PiPrintRunner.js.map +1 -0
  133. package/dist/providers/pi/durable/PiStreamParser.d.ts +21 -0
  134. package/dist/providers/pi/durable/PiStreamParser.d.ts.map +1 -0
  135. package/dist/providers/pi/durable/PiStreamParser.js +71 -0
  136. package/dist/providers/pi/durable/PiStreamParser.js.map +1 -0
  137. package/package.json +1 -1
  138. package/src/__tests__/adapters/ClaudeCodeAdapter.test.ts +1 -307
  139. package/src/__tests__/database/DurableAgentsDatabase.test.ts +28 -3
  140. package/src/__tests__/durable/CodexCliProbe.test.ts +63 -0
  141. package/src/__tests__/durable/CodexDurableAgentRepository.test.ts +54 -0
  142. package/src/__tests__/durable/CodexPrintAgent.integration.test.ts +79 -0
  143. package/src/__tests__/durable/CodexPrintAgentService.test.ts +139 -0
  144. package/src/__tests__/durable/CodexPrintRunner.test.ts +189 -0
  145. package/src/__tests__/fixtures/fake-codex.cjs +45 -0
  146. package/src/__tests__/print/ClaudeCliProbe.test.ts +3 -7
  147. package/src/__tests__/print/ClaudePrintAgent.integration.test.ts +11 -21
  148. package/src/__tests__/print/ClaudePrintAgentService.test.ts +33 -1
  149. package/src/__tests__/print/ClaudePrintRunner.test.ts +4 -10
  150. package/src/__tests__/providers/claude/ClaudeAgentMapper.test.ts +84 -0
  151. package/src/__tests__/providers/claude/ClaudeSessionLocator.test.ts +411 -0
  152. package/src/__tests__/providers/pi/durable/PiCliProbe.test.ts +38 -0
  153. package/src/__tests__/providers/pi/durable/PiDurableAgentRepository.test.ts +32 -0
  154. package/src/__tests__/providers/pi/durable/PiPrintAgentService.test.ts +69 -0
  155. package/src/__tests__/providers/pi/durable/PiPrintProtocol.test.ts +33 -0
  156. package/src/__tests__/providers/pi/durable/PiPrintRunner.test.ts +107 -0
  157. package/src/__tests__/providers/pi/durable/PiStreamParser.test.ts +24 -0
  158. package/src/__tests__/utils/ClaudeSessionParser.test.ts +2 -2
  159. package/src/adapters/index.ts +1 -1
  160. package/src/database/migrations/004_codex_durable_sessions.sql +1 -0
  161. package/src/durable/DurableAgent.ts +51 -3
  162. package/src/durable/DurableAgentRepository.ts +60 -31
  163. package/src/durable/process.ts +28 -0
  164. package/src/durable/run.ts +74 -0
  165. package/src/durable/utils.ts +61 -0
  166. package/src/index.ts +31 -15
  167. package/src/providers/claude/ClaudeAgentMapper.ts +62 -0
  168. package/src/providers/claude/ClaudeCodeAdapter.ts +160 -0
  169. package/src/{adapters/ClaudeCodeAdapter.ts → providers/claude/ClaudeSessionLocator.ts} +97 -239
  170. package/src/{utils → providers/claude}/ClaudeSessionParser.ts +2 -2
  171. package/src/{durable → providers/claude/durable}/ClaudeCliProbe.ts +4 -10
  172. package/src/providers/claude/durable/ClaudePrintAgentService.ts +66 -0
  173. package/src/providers/claude/durable/ClaudePrintRunner.ts +92 -0
  174. package/src/providers/claude/durable/ClaudeStreamParser.ts +79 -0
  175. package/src/providers/codex/durable/CodexCliProbe.ts +60 -0
  176. package/src/providers/codex/durable/CodexPrintAgentService.ts +65 -0
  177. package/src/providers/codex/durable/CodexPrintRunner.ts +94 -0
  178. package/src/providers/codex/durable/CodexStreamParser.ts +104 -0
  179. package/src/providers/pi/durable/PiCliProbe.ts +48 -0
  180. package/src/providers/pi/durable/PiPrintAgentService.ts +69 -0
  181. package/src/providers/pi/durable/PiPrintProtocol.ts +39 -0
  182. package/src/providers/pi/durable/PiPrintRunner.ts +88 -0
  183. package/src/providers/pi/durable/PiStreamParser.ts +84 -0
  184. package/dist/adapters/ClaudeCodeAdapter.d.ts.map +0 -1
  185. package/dist/adapters/ClaudeCodeAdapter.js.map +0 -1
  186. package/dist/durable/ClaudeCliProbe.d.ts.map +0 -1
  187. package/dist/durable/ClaudeCliProbe.js.map +0 -1
  188. package/dist/durable/ClaudePrintAgentService.d.ts.map +0 -1
  189. package/dist/durable/ClaudePrintAgentService.js +0 -66
  190. package/dist/durable/ClaudePrintAgentService.js.map +0 -1
  191. package/dist/durable/ClaudePrintRunner.d.ts.map +0 -1
  192. package/dist/durable/ClaudePrintRunner.js +0 -128
  193. package/dist/durable/ClaudePrintRunner.js.map +0 -1
  194. package/dist/utils/ClaudeSessionParser.d.ts.map +0 -1
  195. package/dist/utils/ClaudeSessionParser.js.map +0 -1
  196. package/src/durable/ClaudePrintAgentService.ts +0 -94
  197. package/src/durable/ClaudePrintRunner.ts +0 -139
  198. /package/dist/{durable → providers/claude/durable}/ClaudeCliProbe.d.ts +0 -0
@@ -1,95 +1,84 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { AgentStatus } from './AgentAdapter.js';
4
- import { captureProcessSnapshot, executableBasename, filterByProcessNames } from '../utils/process.js';
5
- import { batchGetSessionFileBirthtimes, isDirectory, listJsonl, safeReaddir, safeStat } from '../utils/session.js';
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
- parser;
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
- canHandle(processInfo) {
33
- return this.isClaudeExecutable(processInfo.command);
34
- }
35
- isClaudeExecutable(command) {
36
- const base = executableBasename(command);
37
- return base === 'claude' || base === 'claude.exe';
38
- }
39
- async detectAgents(context) {
40
- const snapshot = context?.processes ?? await captureProcessSnapshot(this.processNames);
41
- const relevant = filterByProcessNames(snapshot, this.processNames);
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 direct = [
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
- const matchedPids = new Set([
60
- ...direct.map((d)=>d.process.pid),
61
- ...legacyMatches.map((m)=>m.process.pid)
62
- ]);
63
- const agents = [];
64
- // Build agents from direct (resume + PID-file) matches
65
- for (const match of direct){
66
- const { process: proc, sessionFile } = match;
67
- const sessionData = this.parser.readSession(sessionFile.filePath, sessionFile.resolvedCwd);
68
- if (sessionData) {
69
- agents.push(this.mapSessionToAgent(sessionData, proc, sessionFile, {
70
- pidStatus: match.pidStatus,
71
- waitingFor: match.waitingFor
72
- }));
73
- } else {
74
- matchedPids.delete(proc.pid);
75
- }
76
- }
77
- // Build agents from legacy matches
78
- for (const match of legacyMatches){
79
- const sessionData = this.parser.readSession(match.session.filePath, match.session.resolvedCwd);
80
- if (sessionData) {
81
- agents.push(this.mapSessionToAgent(sessionData, match.process, match.session));
82
- } else {
83
- matchedPids.delete(match.process.pid);
84
- }
85
- }
86
- // Any process with no match (direct or legacy) appears as IDLE
87
- for (const proc of processes){
88
- if (!matchedPids.has(proc.pid)) {
89
- agents.push(this.mapProcessOnlyAgent(proc));
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 agents;
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
- */ discoverSessions(processes) {
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=ClaudeCodeAdapter.js.map
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,SAAS,EACTC,WAAW,EACXC,QAAQ,QAEL,yBAAyB;AAiDhC,kFAAkF,GAClF,MAAMC,wBAAwB;AAE9B,OAAO,MAAMC;IACQC,YAAoB;IACpBC,YAAoB;IAErC,YAAYC,UAAuC,CAAC,CAAC,CAAE;QACnD,MAAMC,UAAUC,QAAQC,GAAG,CAACC,IAAI,IAAIF,QAAQC,GAAG,CAACE,WAAW,IAAI;QAC/D,IAAI,CAACP,WAAW,GAAGE,QAAQF,WAAW,IAAIV,KAAKkB,IAAI,CAACL,SAAS,WAAW;QACxE,IAAI,CAACF,WAAW,GAAGC,QAAQD,WAAW,IAAIX,KAAKkB,IAAI,CAACL,SAAS,WAAW;IAC5E;IAEA;;;;;;;;;KASC,GACDM,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W;YAC1B,MAAMuD,QAAQ,IAAI,CAACZ,mBAAmB,CAAChB,KAAKiB,GAAG,EAAEjB,KAAKkB,SAAS;YAC/D,IAAI,CAACU,OAAO;gBACRpD,SAASgB,IAAI,CAACQ;gBACd;YACJ;YAEA,MAAMZ,aAAa,IAAI,CAACO,aAAa,CAACiC,MAAMhC,GAAG;YAC/C,MAAMiB,YAAY5D,KAAKkB,IAAI,CAACiB,YAAY,GAAGwC,MAAMlB,SAAS,CAAC,MAAM,CAAC;YAElE,IAAI,CAAC1D,GAAGyF,UAAU,CAAC5B,YAAY;gBAC3BrC,SAASgB,IAAI,CAACQ;gBACd;YACJ;YAEA1B,OAAOkB,IAAI,CAAC;gBACRzB,SAASiC;gBACTmB,aAAa;oBACTT,WAAWkB,MAAMlB,SAAS;oBAC1BjB,UAAUoB;oBACVzB;oBACAgC,aAAaQ,MAAMQ,SAAS;oBAC5B5B,aAAaoB,MAAMhC,GAAG;gBAC1B;gBACAyB,WAAW,IAAI,CAACC,YAAY,CAACM,MAAML,MAAM;gBACzCC,YAAYI,MAAMJ,UAAU;YAChC;QACJ;QAEA,OAAO;YAAElD;YAAQE;QAAS;IAC9B;AACJ"}
@@ -1,5 +1,5 @@
1
- import type { ConversationMessage } from '../adapters/AgentAdapter.js';
2
- import { AgentStatus } from '../adapters/AgentAdapter.js';
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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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,6 +1,6 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { AgentStatus } from '../adapters/AgentAdapter.js';
3
+ import { AgentStatus } from '../../adapters/AgentAdapter.js';
4
4
  /**
5
5
  * Top-level JSONL entry types that represent conversation/agent state.
6
6
  *
@@ -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,CAACH;gBAEvC,IAAIC,MAAMG,SAAS,EAAE;oBACjB,MAAMC,KAAK,IAAIC,KAAKL,MAAMG,SAAS;oBACnC,IAAI,CAACG,OAAOC,KAAK,CAACH,GAAGI,OAAO,KAAK;wBAC7Bd,aAAaU;oBACjB;gBACJ;gBAEA,IAAI,OAAOJ,MAAMS,GAAG,KAAK,YAAYT,MAAMS,GAAG,CAACrB,IAAI,GAAGE,MAAM,GAAG,GAAG;oBAC9DK,UAAUK,MAAMS,GAAG;gBACvB;gBAE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a,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 './DurableAgent.js';
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: sanitize(versionResult.stdout, 256) || 'unknown'
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: ${sanitize(error.message, 512)}`, 'CLAUDE_CLI_UNAVAILABLE');
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 './DurableAgent.js';
1
+ import type { DurableAgent, ProcessIdentity } from '../../../durable/DurableAgent.js';
2
2
  import { ClaudePrintRunner, type ClaudePrintRunResult } from './ClaudePrintRunner.js';
3
- import { type CreateDurableAgentInput, type DurableRunCompletion } from './DurableAgentRepository.js';
4
- interface RepositoryLike {
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<{
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ClaudePrintAgentService.d.ts","sourceRoot":"","sources":["../../../../src/providers/claude/durable/ClaudePrintAgentService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAGtF,OAAO,EAAE,iBAAiB,EAAE,KAAK,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACtF,OAAO,EAA0B,KAAK,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AAClH,OAAO,EAAmB,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAErF,UAAU,cAAe,SAAQ,oBAAoB;IACjD,MAAM,CAAC,KAAK,EAAE,uBAAuB,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IAC9D,IAAI,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC;IAChC,qBAAqB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9F;AAED,UAAU,SAAS;IAAG,QAAQ,IAAI,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE;AACpF,UAAU,UAAU;IAAG,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAA;CAAE;AAE7G,MAAM,WAAW,8BAA8B;IAC3C,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,qBAAsB,SAAQ,oBAAoB;IAC/D,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,qBAAa,uBAAuB;IAChC,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC;IACpC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAa;IACpC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAS;gBAEzB,OAAO,GAAE,8BAAmC;IAOlD,MAAM,CAAC,KAAK,EAAE,uBAAuB,GAAG,OAAO,CAAC,YAAY,CAAC;IAK7D,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,CAAC;CAmBhF"}
@@ -0,0 +1,45 @@
1
+ import { ClaudePrintError } from '../../../durable/DurableAgent.js';
2
+ import { ClaudeCliProbe } from './ClaudeCliProbe.js';
3
+ import { ClaudePrintRunner } from './ClaudePrintRunner.js';
4
+ import { DurableAgentRepository } from '../../../durable/DurableAgentRepository.js';
5
+ import { runDurableAgent } from '../../../durable/run.js';
6
+ export class ClaudePrintAgentService {
7
+ repository;
8
+ probe;
9
+ runner;
10
+ executable;
11
+ constructor(options = {}){
12
+ this.repository = options.repository ?? new DurableAgentRepository();
13
+ this.probe = options.probe ?? new ClaudeCliProbe();
14
+ this.runner = options.runner ?? new ClaudePrintRunner();
15
+ this.executable = options.executable;
16
+ }
17
+ async create(input) {
18
+ await this.probe.validate();
19
+ return this.repository.create(input);
20
+ }
21
+ async send(reference, prompt) {
22
+ const completed = await runDurableAgent({
23
+ reference,
24
+ provider: 'claude',
25
+ repository: this.repository,
26
+ ambiguousError: ()=>new ClaudePrintError(`Multiple durable agents match "${reference}".`, 'DURABLE_AGENT_AMBIGUOUS'),
27
+ providerError: ()=>new ClaudePrintError('Durable agent provider is not Claude.', 'CLAUDE_PRINT_UNSUPPORTED'),
28
+ execute: (agent, token)=>this.runner.run({
29
+ agent,
30
+ prompt,
31
+ executable: this.executable,
32
+ firstRun: agent.sessionHealth === 'uninitialized',
33
+ onSpawn: (identity)=>this.repository.recordProviderProcess(agent.id, token, identity)
34
+ }),
35
+ isSessionMismatch: (error)=>error instanceof ClaudePrintError && error.code === 'CLAUDE_SESSION_MISMATCH'
36
+ });
37
+ return {
38
+ ...completed.result,
39
+ agentId: completed.agent.id,
40
+ agentName: completed.agent.name
41
+ };
42
+ }
43
+ }
44
+
45
+ //# sourceMappingURL=ClaudePrintAgentService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/providers/claude/durable/ClaudePrintAgentService.ts"],"sourcesContent":["import type { DurableAgent, ProcessIdentity } from '../../../durable/DurableAgent.js';\nimport { ClaudePrintError } from '../../../durable/DurableAgent.js';\nimport { ClaudeCliProbe } from './ClaudeCliProbe.js';\nimport { ClaudePrintRunner, type ClaudePrintRunResult } from './ClaudePrintRunner.js';\nimport { DurableAgentRepository, type CreateDurableAgentInput } from '../../../durable/DurableAgentRepository.js';\nimport { runDurableAgent, type DurableRunRepository } from '../../../durable/run.js';\n\ninterface RepositoryLike extends DurableRunRepository {\n create(input: CreateDurableAgentInput): Promise<DurableAgent>;\n list(): Promise<DurableAgent[]>;\n recordProviderProcess(id: string, token: string, identity: ProcessIdentity): Promise<void>;\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 completed = await runDurableAgent({\n reference, provider: 'claude', repository: this.repository,\n ambiguousError: () => new ClaudePrintError(\n `Multiple durable agents match \"${reference}\".`, 'DURABLE_AGENT_AMBIGUOUS'),\n providerError: () => new ClaudePrintError(\n 'Durable agent provider is not Claude.', 'CLAUDE_PRINT_UNSUPPORTED'),\n execute: (agent, token) => this.runner.run({\n agent,\n prompt,\n executable: this.executable,\n firstRun: agent.sessionHealth === 'uninitialized',\n onSpawn: (identity) => this.repository.recordProviderProcess(agent.id, token, identity),\n }),\n isSessionMismatch: (error) => error instanceof ClaudePrintError\n && error.code === 'CLAUDE_SESSION_MISMATCH',\n });\n return { ...completed.result, agentId: completed.agent.id, agentName: completed.agent.name };\n }\n}\n"],"names":["ClaudePrintError","ClaudeCliProbe","ClaudePrintRunner","DurableAgentRepository","runDurableAgent","ClaudePrintAgentService","repository","probe","runner","executable","options","create","input","validate","send","reference","prompt","completed","provider","ambiguousError","providerError","execute","agent","token","run","firstRun","sessionHealth","onSpawn","identity","recordProviderProcess","id","isSessionMismatch","error","code","result","agentId","agentName","name"],"mappings":"AACA,SAASA,gBAAgB,QAAQ,mCAAmC;AACpE,SAASC,cAAc,QAAQ,sBAAsB;AACrD,SAASC,iBAAiB,QAAmC,yBAAyB;AACtF,SAASC,sBAAsB,QAAsC,6CAA6C;AAClH,SAASC,eAAe,QAAmC,0BAA0B;AAuBrF,OAAO,MAAMC;IACAC,WAA2B;IACnBC,MAAiB;IACjBC,OAAmB;IACnBC,WAAoB;IAErC,YAAYC,UAA0C,CAAC,CAAC,CAAE;QACtD,IAAI,CAACJ,UAAU,GAAGI,QAAQJ,UAAU,IAAI,IAAIH;QAC5C,IAAI,CAACI,KAAK,GAAGG,QAAQH,KAAK,IAAI,IAAIN;QAClC,IAAI,CAACO,MAAM,GAAGE,QAAQF,MAAM,IAAI,IAAIN;QACpC,IAAI,CAACO,UAAU,GAAGC,QAAQD,UAAU;IACxC;IAEA,MAAME,OAAOC,KAA8B,EAAyB;QAChE,MAAM,IAAI,CAACL,KAAK,CAACM,QAAQ;QACzB,OAAO,IAAI,CAACP,UAAU,CAACK,MAAM,CAACC;IAClC;IAEA,MAAME,KAAKC,SAAiB,EAAEC,MAAc,EAAkC;QAC1E,MAAMC,YAAY,MAAMb,gBAAgB;YACpCW;YAAWG,UAAU;YAAUZ,YAAY,IAAI,CAACA,UAAU;YAC1Da,gBAAgB,IAAM,IAAInB,iBACtB,CAAC,+BAA+B,EAAEe,UAAU,EAAE,CAAC,EAAE;YACrDK,eAAe,IAAM,IAAIpB,iBACrB,yCAAyC;YAC7CqB,SAAS,CAACC,OAAOC,QAAU,IAAI,CAACf,MAAM,CAACgB,GAAG,CAAC;oBACvCF;oBACAN;oBACAP,YAAY,IAAI,CAACA,UAAU;oBAC3BgB,UAAUH,MAAMI,aAAa,KAAK;oBAClCC,SAAS,CAACC,WAAa,IAAI,CAACtB,UAAU,CAACuB,qBAAqB,CAACP,MAAMQ,EAAE,EAAEP,OAAOK;gBAClF;YACAG,mBAAmB,CAACC,QAAUA,iBAAiBhC,oBACxCgC,MAAMC,IAAI,KAAK;QAC1B;QACA,OAAO;YAAE,GAAGhB,UAAUiB,MAAM;YAAEC,SAASlB,UAAUK,KAAK,CAACQ,EAAE;YAAEM,WAAWnB,UAAUK,KAAK,CAACe,IAAI;QAAC;IAC/F;AACJ"}
@@ -1,11 +1,11 @@
1
1
  import { type ChildProcessWithoutNullStreams, type SpawnOptionsWithoutStdio } from 'child_process';
2
- import type { DurableAgent, ProcessIdentity } from './DurableAgent.js';
3
- import { type ProcessInspector } from './DurableAgentRepository.js';
2
+ import type { ClaudeDurableAgent, ProcessIdentity } from '../../../durable/DurableAgent.js';
3
+ import { type ProcessInspector } from '../../../durable/process.js';
4
4
  type Spawn = (command: string, args: readonly string[], options: SpawnOptionsWithoutStdio & {
5
5
  stdio: ['pipe', 'pipe', 'pipe'];
6
6
  }) => ChildProcessWithoutNullStreams;
7
7
  export interface ClaudePrintRunRequest {
8
- agent: DurableAgent;
8
+ agent: ClaudeDurableAgent;
9
9
  prompt: string;
10
10
  executable?: string;
11
11
  firstRun: boolean;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ClaudePrintRunner.d.ts","sourceRoot":"","sources":["../../../../src/providers/claude/durable/ClaudePrintRunner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,8BAA8B,EAAE,KAAK,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACvH,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAE5F,OAAO,EAAyB,KAAK,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAI3F,KAAK,KAAK,GAAG,CACT,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,EAAE,wBAAwB,GAAG;IAAE,KAAK,EAAE,CAAC,M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