@ai-devkit/agent-manager 0.24.0 → 0.26.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 (84) hide show
  1. package/README.md +14 -0
  2. package/dist/__tests__/adapters/GrokCliAdapter.test.js +403 -0
  3. package/dist/__tests__/adapters/GrokCliAdapter.test.js.map +1 -0
  4. package/dist/__tests__/print/ClaudeCliProbe.test.js +53 -0
  5. package/dist/__tests__/print/ClaudeCliProbe.test.js.map +1 -0
  6. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js +69 -0
  7. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js.map +1 -0
  8. package/dist/__tests__/print/ClaudePrintAgentService.test.js +108 -0
  9. package/dist/__tests__/print/ClaudePrintAgentService.test.js.map +1 -0
  10. package/dist/__tests__/print/ClaudePrintRunner.test.js +187 -0
  11. package/dist/__tests__/print/ClaudePrintRunner.test.js.map +1 -0
  12. package/dist/__tests__/print/PrintAgent.test.js +17 -0
  13. package/dist/__tests__/print/PrintAgent.test.js.map +1 -0
  14. package/dist/__tests__/print/PrintAgentStore.test.js +307 -0
  15. package/dist/__tests__/print/PrintAgentStore.test.js.map +1 -0
  16. package/dist/__tests__/terminal/TmuxManager.test.js +9 -0
  17. package/dist/__tests__/terminal/TmuxManager.test.js.map +1 -1
  18. package/dist/__tests__/utils/agents.test.js +6 -0
  19. package/dist/__tests__/utils/agents.test.js.map +1 -1
  20. package/dist/adapters/AgentAdapter.d.ts +1 -1
  21. package/dist/adapters/AgentAdapter.d.ts.map +1 -1
  22. package/dist/adapters/AgentAdapter.js.map +1 -1
  23. package/dist/adapters/GrokCliAdapter.d.ts +79 -0
  24. package/dist/adapters/GrokCliAdapter.d.ts.map +1 -0
  25. package/dist/adapters/GrokCliAdapter.js +306 -0
  26. package/dist/adapters/GrokCliAdapter.js.map +1 -0
  27. package/dist/adapters/index.d.ts +1 -0
  28. package/dist/adapters/index.d.ts.map +1 -1
  29. package/dist/adapters/index.js +1 -0
  30. package/dist/adapters/index.js.map +1 -1
  31. package/dist/index.d.ts +12 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +7 -0
  34. package/dist/index.js.map +1 -1
  35. package/dist/print/ClaudeCliProbe.d.ts +20 -0
  36. package/dist/print/ClaudeCliProbe.d.ts.map +1 -0
  37. package/dist/print/ClaudeCliProbe.js +57 -0
  38. package/dist/print/ClaudeCliProbe.js.map +1 -0
  39. package/dist/print/ClaudePrintAgentService.d.ts +44 -0
  40. package/dist/print/ClaudePrintAgentService.d.ts.map +1 -0
  41. package/dist/print/ClaudePrintAgentService.js +66 -0
  42. package/dist/print/ClaudePrintAgentService.js.map +1 -0
  43. package/dist/print/ClaudePrintRunner.d.ts +32 -0
  44. package/dist/print/ClaudePrintRunner.d.ts.map +1 -0
  45. package/dist/print/ClaudePrintRunner.js +128 -0
  46. package/dist/print/ClaudePrintRunner.js.map +1 -0
  47. package/dist/print/PrintAgent.d.ts +57 -0
  48. package/dist/print/PrintAgent.d.ts.map +1 -0
  49. package/dist/print/PrintAgent.js +42 -0
  50. package/dist/print/PrintAgent.js.map +1 -0
  51. package/dist/print/PrintAgentStore.d.ts +69 -0
  52. package/dist/print/PrintAgentStore.d.ts.map +1 -0
  53. package/dist/print/PrintAgentStore.js +484 -0
  54. package/dist/print/PrintAgentStore.js.map +1 -0
  55. package/dist/terminal/TmuxManager.d.ts +2 -2
  56. package/dist/terminal/TmuxManager.d.ts.map +1 -1
  57. package/dist/terminal/TmuxManager.js +5 -7
  58. package/dist/terminal/TmuxManager.js.map +1 -1
  59. package/dist/utils/agents.d.ts +1 -1
  60. package/dist/utils/agents.d.ts.map +1 -1
  61. package/dist/utils/agents.js +4 -0
  62. package/dist/utils/agents.js.map +1 -1
  63. package/package.json +2 -2
  64. package/src/__tests__/adapters/GrokCliAdapter.test.ts +307 -0
  65. package/src/__tests__/fixtures/fake-claude.cjs +24 -0
  66. package/src/__tests__/print/ClaudeCliProbe.test.ts +32 -0
  67. package/src/__tests__/print/ClaudePrintAgent.integration.test.ts +56 -0
  68. package/src/__tests__/print/ClaudePrintAgentService.test.ts +46 -0
  69. package/src/__tests__/print/ClaudePrintRunner.test.ts +105 -0
  70. package/src/__tests__/print/PrintAgent.test.ts +21 -0
  71. package/src/__tests__/print/PrintAgentStore.test.ts +192 -0
  72. package/src/__tests__/terminal/TmuxManager.test.ts +10 -0
  73. package/src/__tests__/utils/agents.test.ts +7 -0
  74. package/src/adapters/AgentAdapter.ts +1 -1
  75. package/src/adapters/GrokCliAdapter.ts +394 -0
  76. package/src/adapters/index.ts +1 -0
  77. package/src/index.ts +40 -0
  78. package/src/print/ClaudeCliProbe.ts +58 -0
  79. package/src/print/ClaudePrintAgentService.ts +94 -0
  80. package/src/print/ClaudePrintRunner.ts +139 -0
  81. package/src/print/PrintAgent.ts +86 -0
  82. package/src/print/PrintAgentStore.ts +503 -0
  83. package/src/terminal/TmuxManager.ts +5 -7
  84. package/src/utils/agents.ts +2 -1
@@ -0,0 +1,394 @@
1
+ import * as path from 'path';
2
+ import type {
3
+ AgentAdapter,
4
+ AgentInfo,
5
+ ProcessInfo,
6
+ ConversationMessage,
7
+ SessionSummary,
8
+ ListSessionsOptions,
9
+ } from './AgentAdapter.js';
10
+ import { AgentStatus } from './AgentAdapter.js';
11
+ import { listAgentProcesses, enrichProcesses } from '../utils/process.js';
12
+ import { isDirectory, safeReadFile, safeReaddir, safeStat } from '../utils/session.js';
13
+ import { generateAgentName } from '../utils/matching.js';
14
+
15
+ /**
16
+ * Grok Build CLI Adapter
17
+ *
18
+ * Detects running Grok Build CLI agents by:
19
+ * 1. Finding running `grok` processes via shared listAgentProcesses() — Grok is
20
+ * a native binary at ~/.grok/bin/grok, so argv[0] basename is `grok`.
21
+ * 2. Resolving each live process to its working directory via
22
+ * ~/.grok/active_sessions.json, which Grok maintains as a list of
23
+ * { pid, cwd, opened_at } for every running session. The cwd is then encoded
24
+ * into the session group dir ~/.grok/sessions/<encodeURIComponent(cwd)>/, and
25
+ * the most recently active session subdirectory is picked from it. The
26
+ * process cwd from lsof is only a fallback when the PID is not registered.
27
+ * 3. Reading the session transcript from chat_history.jsonl (the authoritative
28
+ * record of the conversation). The last user turn (the text inside
29
+ * <user_query>...</user_query>) is the summary; the file's mtime is the last
30
+ * activity time. summary.json / updates.jsonl are intentionally not used.
31
+ */
32
+
33
+ const CHAT_HISTORY_FILE = 'chat_history.jsonl';
34
+ const ACTIVE_SESSIONS_FILE = 'active_sessions.json';
35
+ const CWD_FILE = '.cwd';
36
+ const IDLE_THRESHOLD_MINUTES = 5;
37
+
38
+ /** One entry of ~/.grok/active_sessions.json. */
39
+ interface ActiveSessionEntry {
40
+ pid?: number;
41
+ cwd?: string;
42
+ opened_at?: number | string;
43
+ }
44
+
45
+ /** One line of chat_history.jsonl. */
46
+ interface ChatRecord {
47
+ type?: string;
48
+ content?: unknown;
49
+ }
50
+
51
+ interface ChatScan {
52
+ messages: ConversationMessage[];
53
+ firstUserMessage?: string;
54
+ lastUserMessage?: string;
55
+ lastRole?: ConversationMessage['role'];
56
+ }
57
+
58
+ /** Parsed state for a single ~/.grok/sessions/<cwd>/<id>/ directory. */
59
+ interface GrokSession {
60
+ sessionId: string;
61
+ projectPath: string;
62
+ summary: string;
63
+ sessionStart: Date;
64
+ lastActive: Date;
65
+ firstUserMessage?: string;
66
+ lastUserMessage?: string;
67
+ lastRole?: ConversationMessage['role'];
68
+ }
69
+
70
+ export class GrokCliAdapter implements AgentAdapter {
71
+ readonly type = 'grok_cli' as const;
72
+
73
+ private base: string;
74
+ private sessionsDir: string;
75
+
76
+ constructor() {
77
+ // GROK_HOME overrides the ~/.grok base directory; sessions live under
78
+ // <base>/sessions/ and the active-session registry at
79
+ // <base>/active_sessions.json.
80
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
81
+ this.base = process.env.GROK_HOME || path.join(homeDir, '.grok');
82
+ this.sessionsDir = path.join(this.base, 'sessions');
83
+ }
84
+
85
+ canHandle(processInfo: ProcessInfo): boolean {
86
+ return this.isGrokExecutable(processInfo.command);
87
+ }
88
+
89
+ private isGrokExecutable(command: string): boolean {
90
+ const executable = command.trim().split(/\s+/)[0] || '';
91
+ const base = path.basename(executable).toLowerCase();
92
+ return base === 'grok' || base === 'grok.exe';
93
+ }
94
+
95
+ async detectAgents(): Promise<AgentInfo[]> {
96
+ const processes = enrichProcesses(listAgentProcesses('grok'));
97
+ if (processes.length === 0) {
98
+ return [];
99
+ }
100
+
101
+ // active_sessions.json is the authoritative pid -> cwd map for live
102
+ // sessions; the lsof-derived process cwd is only a fallback.
103
+ const pidToCwd = this.readActiveSessions();
104
+
105
+ const agents: AgentInfo[] = [];
106
+ for (const proc of processes) {
107
+ const cwd = pidToCwd.get(proc.pid) || proc.cwd || '';
108
+ const sessionDir = cwd ? this.latestSessionDir(cwd) : null;
109
+ const session = sessionDir ? this.readSession(sessionDir, cwd) : null;
110
+
111
+ if (session && sessionDir) {
112
+ agents.push(this.mapSessionToAgent(session, proc, sessionDir));
113
+ } else {
114
+ agents.push(this.mapProcessOnlyAgent(proc, cwd));
115
+ }
116
+ }
117
+
118
+ return agents;
119
+ }
120
+
121
+ /**
122
+ * Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one
123
+ * { pid, cwd, opened_at } entry per running session and removes it on exit,
124
+ * so this is the reliable way to learn a live process's working directory.
125
+ */
126
+ private readActiveSessions(): Map<number, string> {
127
+ const map = new Map<number, string>();
128
+ const content = safeReadFile(path.join(this.base, ACTIVE_SESSIONS_FILE));
129
+ if (content === undefined) return map;
130
+
131
+ let entries: unknown;
132
+ try {
133
+ entries = JSON.parse(content);
134
+ } catch {
135
+ return map;
136
+ }
137
+ if (!Array.isArray(entries)) return map;
138
+
139
+ for (const entry of entries as ActiveSessionEntry[]) {
140
+ if (typeof entry?.pid === 'number' && typeof entry?.cwd === 'string' && entry.cwd) {
141
+ map.set(entry.pid, entry.cwd);
142
+ }
143
+ }
144
+ return map;
145
+ }
146
+
147
+ /**
148
+ * Full paths of the session subdirectories directly under a group dir,
149
+ * skipping any non-directory entries. Shared by latestSessionDir() and
150
+ * listSessions() so both enumerate session dirs the same way.
151
+ */
152
+ private listSessionDirs(groupDir: string): string[] {
153
+ return safeReaddir(groupDir)
154
+ .map((sessionId) => path.join(groupDir, sessionId))
155
+ .filter((sessionDir) => isDirectory(sessionDir));
156
+ }
157
+
158
+ /**
159
+ * Return the most recently active session subdirectory for a cwd, i.e. the
160
+ * ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl
161
+ * was written last. Returns null when the group dir or any transcript is
162
+ * missing.
163
+ */
164
+ private latestSessionDir(cwd: string): string | null {
165
+ const groupDir = this.getProjectDir(cwd);
166
+ if (!isDirectory(groupDir)) return null;
167
+
168
+ let best: { dir: string; mtimeMs: number } | null = null;
169
+ for (const sessionDir of this.listSessionDirs(groupDir)) {
170
+ const stat = safeStat(path.join(sessionDir, CHAT_HISTORY_FILE));
171
+ if (!stat) continue;
172
+ if (!best || stat.mtimeMs > best.mtimeMs) {
173
+ best = { dir: sessionDir, mtimeMs: stat.mtimeMs };
174
+ }
175
+ }
176
+ return best?.dir ?? null;
177
+ }
178
+
179
+ private mapSessionToAgent(session: GrokSession, processInfo: ProcessInfo, sessionDir: string): AgentInfo {
180
+ const projectPath = session.projectPath || processInfo.cwd || '';
181
+ return {
182
+ name: generateAgentName(projectPath, processInfo.pid),
183
+ type: this.type,
184
+ status: this.determineStatus(session),
185
+ summary: session.summary || 'Grok CLI session active',
186
+ pid: processInfo.pid,
187
+ projectPath,
188
+ sessionId: session.sessionId,
189
+ lastActive: session.lastActive,
190
+ sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE),
191
+ };
192
+ }
193
+
194
+ private mapProcessOnlyAgent(processInfo: ProcessInfo, cwd: string): AgentInfo {
195
+ const projectPath = cwd || processInfo.cwd || '';
196
+ return {
197
+ name: generateAgentName(projectPath, processInfo.pid),
198
+ type: this.type,
199
+ status: AgentStatus.RUNNING,
200
+ summary: 'Grok CLI process running',
201
+ pid: processInfo.pid,
202
+ projectPath,
203
+ sessionId: `pid-${processInfo.pid}`,
204
+ lastActive: new Date(),
205
+ };
206
+ }
207
+
208
+ getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {
209
+ return this.parseChatHistory(this.resolveChatPath(sessionFilePath), options?.verbose ?? false).messages;
210
+ }
211
+
212
+ async listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]> {
213
+ if (!isDirectory(this.sessionsDir)) return [];
214
+
215
+ const filterCwd = opts?.cwd;
216
+ const summaries: SessionSummary[] = [];
217
+
218
+ for (const groupName of safeReaddir(this.sessionsDir)) {
219
+ const groupDir = path.join(this.sessionsDir, groupName);
220
+ if (!isDirectory(groupDir)) continue;
221
+
222
+ const decodedCwd = this.decodeGroupCwd(groupName, groupDir);
223
+
224
+ for (const sessionDir of this.listSessionDirs(groupDir)) {
225
+ const session = this.readSession(sessionDir, decodedCwd);
226
+ if (!session) continue;
227
+
228
+ const cwd = session.projectPath || decodedCwd;
229
+ if (filterCwd !== undefined && cwd !== filterCwd) continue;
230
+
231
+ summaries.push({
232
+ type: this.type,
233
+ sessionId: session.sessionId,
234
+ cwd,
235
+ firstUserMessage: session.firstUserMessage || '',
236
+ lastActive: session.lastActive,
237
+ startedAt: session.sessionStart,
238
+ sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE),
239
+ });
240
+ }
241
+ }
242
+
243
+ return summaries;
244
+ }
245
+
246
+ // --- Session parsing (chat_history.jsonl) ---
247
+
248
+ /**
249
+ * Parse a session directory into a {@link GrokSession} from its
250
+ * chat_history.jsonl transcript. Returns null when the transcript is
251
+ * missing — i.e. there is no real session to surface.
252
+ */
253
+ private readSession(sessionDir: string, defaultCwd: string): GrokSession | null {
254
+ const chatPath = path.join(sessionDir, CHAT_HISTORY_FILE);
255
+ const chatStat = safeStat(chatPath);
256
+ if (!chatStat) return null;
257
+
258
+ const scan = this.parseChatHistory(chatPath, false);
259
+ const dirStat = safeStat(sessionDir);
260
+ const lastActive = chatStat.mtime;
261
+
262
+ return {
263
+ sessionId: path.basename(sessionDir),
264
+ projectPath: defaultCwd || '',
265
+ summary: scan.lastUserMessage || 'Grok CLI session active',
266
+ sessionStart: dirStat?.birthtime || lastActive,
267
+ lastActive,
268
+ firstUserMessage: scan.firstUserMessage,
269
+ lastUserMessage: scan.lastUserMessage,
270
+ lastRole: scan.lastRole,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Determine agent status from parsed session state.
276
+ *
277
+ * - past the idle threshold → IDLE
278
+ * - last transcript turn is an assistant message → WAITING (awaiting user)
279
+ * - otherwise (last turn was a user message, or unknown) → RUNNING
280
+ */
281
+ private determineStatus(session: GrokSession): AgentStatus {
282
+ const diffMinutes = (Date.now() - session.lastActive.getTime()) / 60000;
283
+ if (diffMinutes > IDLE_THRESHOLD_MINUTES) {
284
+ return AgentStatus.IDLE;
285
+ }
286
+ if (session.lastRole === 'assistant') {
287
+ return AgentStatus.WAITING;
288
+ }
289
+ return AgentStatus.RUNNING;
290
+ }
291
+
292
+ /**
293
+ * Single pass over chat_history.jsonl. Each line is a
294
+ * { type: 'system' | 'user' | 'assistant', content } record where content is
295
+ * either a string or an array of { type: 'text', text } blocks.
296
+ *
297
+ * Grok wraps the real user prompt in <user_query>...</user_query>; the other
298
+ * user records are context injections (<user_info>, <system-reminder>, ...)
299
+ * and are skipped so the summary is the actual prompt, not boilerplate.
300
+ */
301
+ private parseChatHistory(chatPath: string, verbose: boolean): ChatScan {
302
+ const empty: ChatScan = { messages: [] };
303
+ const content = safeReadFile(chatPath);
304
+ if (content === undefined) return empty;
305
+
306
+ const messages: ConversationMessage[] = [];
307
+ let lastRole: ConversationMessage['role'] | undefined;
308
+
309
+ for (const line of content.trim().split('\n')) {
310
+ if (!line.trim()) continue;
311
+
312
+ let record: ChatRecord;
313
+ try {
314
+ record = JSON.parse(line);
315
+ } catch {
316
+ continue;
317
+ }
318
+
319
+ const text = this.extractText(record.content);
320
+ if (record.type === 'user') {
321
+ const query = this.extractUserQuery(text);
322
+ if (query === null) continue; // context injection, not a real prompt
323
+ messages.push({ role: 'user', content: query });
324
+ lastRole = 'user';
325
+ } else if (record.type === 'assistant') {
326
+ if (!text) continue;
327
+ messages.push({ role: 'assistant', content: text });
328
+ lastRole = 'assistant';
329
+ } else if (verbose && record.type === 'system') {
330
+ if (!text) continue;
331
+ messages.push({ role: 'system', content: text });
332
+ }
333
+ }
334
+
335
+ const userTurns = messages.filter((m) => m.role === 'user');
336
+ return {
337
+ messages,
338
+ firstUserMessage: userTurns[0]?.content,
339
+ lastUserMessage: userTurns[userTurns.length - 1]?.content,
340
+ lastRole,
341
+ };
342
+ }
343
+
344
+ /** Flatten a chat record's content (string or text-block array) to text. */
345
+ private extractText(content: unknown): string {
346
+ if (typeof content === 'string') return content;
347
+ if (Array.isArray(content)) {
348
+ return content
349
+ .map((block) =>
350
+ block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
351
+ ? (block as { text: string }).text
352
+ : '',
353
+ )
354
+ .join('');
355
+ }
356
+ return '';
357
+ }
358
+
359
+ /**
360
+ * Extract the prompt inside <user_query>...</user_query>. Returns null when
361
+ * the record has no such tag (a context injection rather than a prompt).
362
+ */
363
+ private extractUserQuery(text: string): string | null {
364
+ const match = text.match(/<user_query>\s*([\s\S]*?)\s*<\/user_query>/);
365
+ return match ? match[1].trim() : null;
366
+ }
367
+
368
+ /** Resolve a session dir or an explicit chat_history.jsonl path to the file. */
369
+ private resolveChatPath(sessionPath: string): string {
370
+ return sessionPath.endsWith('.jsonl') ? sessionPath : path.join(sessionPath, CHAT_HISTORY_FILE);
371
+ }
372
+
373
+ private getProjectDir(cwd: string): string {
374
+ return path.join(this.sessionsDir, encodeURIComponent(cwd));
375
+ }
376
+
377
+ /**
378
+ * Resolve the working directory a session group dir was created for.
379
+ *
380
+ * The common case is `decodeURIComponent(<group-name>)`. For paths whose
381
+ * encoded form exceeds the filesystem limit Grok uses a slug+hash and records
382
+ * the original path in a `.cwd` file inside the group — prefer that when
383
+ * present.
384
+ */
385
+ private decodeGroupCwd(groupName: string, groupDir: string): string {
386
+ const fromFile = safeReadFile(path.join(groupDir, CWD_FILE));
387
+ if (fromFile !== undefined && fromFile.trim()) return fromFile.trim();
388
+ try {
389
+ return decodeURIComponent(groupName);
390
+ } catch {
391
+ return '';
392
+ }
393
+ }
394
+ }
@@ -2,6 +2,7 @@ export { ClaudeCodeAdapter } from './ClaudeCodeAdapter.js';
2
2
  export { CodexAdapter } from './CodexAdapter.js';
3
3
  export { CopilotAdapter } from './CopilotAdapter.js';
4
4
  export { GeminiCliAdapter } from './GeminiCliAdapter.js';
5
+ export { GrokCliAdapter } from './GrokCliAdapter.js';
5
6
  export { OpenCodeAdapter } from './OpenCodeAdapter.js';
6
7
  export { PiAdapter } from './PiAdapter.js';
7
8
  export { AgentStatus } from './AgentAdapter.js';
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ export { ClaudeCodeAdapter } from './adapters/ClaudeCodeAdapter.js';
4
4
  export { CodexAdapter } from './adapters/CodexAdapter.js';
5
5
  export { CopilotAdapter } from './adapters/CopilotAdapter.js';
6
6
  export { GeminiCliAdapter } from './adapters/GeminiCliAdapter.js';
7
+ export { GrokCliAdapter } from './adapters/GrokCliAdapter.js';
7
8
  export { OpenCodeAdapter } from './adapters/OpenCodeAdapter.js';
8
9
  export { PiAdapter } from './adapters/PiAdapter.js';
9
10
  export { AgentStatus } from './adapters/AgentAdapter.js';
@@ -33,3 +34,42 @@ export type { AgentConfig, StartableAgentType } from './utils/agents.js';
33
34
 
34
35
  export type { AgentRequest } from './utils/agent-requests.js';
35
36
  export { getAgentRequestPath, readLatestAgentRequest, writeAgentRequest } from './utils/agent-requests.js';
37
+
38
+ export {
39
+ PrintAgentError,
40
+ PrintAgentBusyError,
41
+ PrintAgentNotFoundError,
42
+ PrintAgentStoreError,
43
+ PrintAgentNameConflictError,
44
+ ClaudePrintError,
45
+ } from './print/PrintAgent.js';
46
+ export type {
47
+ PrintAgent,
48
+ PrintAgentState,
49
+ PrintSessionHealth,
50
+ PrintRunStatus,
51
+ PrintActiveRun,
52
+ PrintLastResult,
53
+ ProcessIdentity,
54
+ } from './print/PrintAgent.js';
55
+ export { PrintAgentStore } from './print/PrintAgentStore.js';
56
+ export { LocalProcessInspector } from './print/PrintAgentStore.js';
57
+ export type {
58
+ CreatePrintAgentInput,
59
+ PrintAgentStoreOptions,
60
+ ProcessInspector,
61
+ PrintRunCompletion,
62
+ } from './print/PrintAgentStore.js';
63
+ export { ClaudeCliProbe } from './print/ClaudeCliProbe.js';
64
+ export type { ClaudeCliProbeOptions } from './print/ClaudeCliProbe.js';
65
+ export { ClaudePrintRunner } from './print/ClaudePrintRunner.js';
66
+ export type {
67
+ ClaudePrintRunnerOptions,
68
+ ClaudePrintRunRequest,
69
+ ClaudePrintRunResult,
70
+ } from './print/ClaudePrintRunner.js';
71
+ export { ClaudePrintAgentService } from './print/ClaudePrintAgentService.js';
72
+ export type {
73
+ ClaudePrintAgentServiceOptions,
74
+ ClaudePrintSendResult,
75
+ } from './print/ClaudePrintAgentService.js';
@@ -0,0 +1,58 @@
1
+ import { execFile } from 'child_process';
2
+ import { promisify } from 'util';
3
+ import { ClaudePrintError } from './PrintAgent.js';
4
+
5
+ type ExecResult = { stdout: string; stderr: string };
6
+ type Exec = (file: string, args: string[]) => Promise<ExecResult>;
7
+
8
+ const execFileAsync = promisify(execFile);
9
+ const REQUIRED = ['--print', '--session-id', '--resume', '--output-format', 'stream-json'];
10
+
11
+ export interface ClaudeCliProbeOptions {
12
+ executable?: string;
13
+ exec?: Exec;
14
+ }
15
+
16
+ export class ClaudeCliProbe {
17
+ private readonly executable: string;
18
+ private readonly exec: Exec;
19
+
20
+ constructor(options: ClaudeCliProbeOptions = {}) {
21
+ this.executable = options.executable ?? 'claude';
22
+ this.exec = options.exec ?? (async (file, args) => {
23
+ const result = await execFileAsync(file, args, { encoding: 'utf8', maxBuffer: 1024 * 1024 });
24
+ return { stdout: result.stdout, stderr: result.stderr };
25
+ });
26
+ }
27
+
28
+ async validate(): Promise<{ executable: string; version: string }> {
29
+ try {
30
+ const versionResult = await this.exec(this.executable, ['--version']);
31
+ const helpResult = await this.exec(this.executable, ['--help']);
32
+ const missing = REQUIRED.filter((capability) => !helpResult.stdout.includes(capability));
33
+ if (missing.length > 0) {
34
+ throw new ClaudePrintError(
35
+ `Claude CLI does not support required print-mode capabilities: ${missing.join(', ')}.`,
36
+ 'CLAUDE_CLI_UNSUPPORTED',
37
+ );
38
+ }
39
+ return {
40
+ executable: this.executable,
41
+ version: sanitize(versionResult.stdout, 256) || 'unknown',
42
+ };
43
+ } catch (error) {
44
+ if (error instanceof ClaudePrintError) throw error;
45
+ throw new ClaudePrintError(
46
+ `Claude CLI validation failed: ${sanitize((error as Error).message, 512)}`,
47
+ 'CLAUDE_CLI_UNAVAILABLE',
48
+ );
49
+ }
50
+ }
51
+ }
52
+
53
+ function sanitize(value: string, max: number): string {
54
+ return Array.from(value, (character) => {
55
+ const code = character.charCodeAt(0);
56
+ return code <= 31 || code === 127 ? ' ' : character;
57
+ }).join('').trim().slice(0, max);
58
+ }
@@ -0,0 +1,94 @@
1
+ import type { PrintAgent, ProcessIdentity } from './PrintAgent.js';
2
+ import { ClaudePrintError, PrintAgentNotFoundError } from './PrintAgent.js';
3
+ import { ClaudeCliProbe } from './ClaudeCliProbe.js';
4
+ import { ClaudePrintRunner, type ClaudePrintRunResult } from './ClaudePrintRunner.js';
5
+ import { PrintAgentStore, type CreatePrintAgentInput, type PrintRunCompletion } from './PrintAgentStore.js';
6
+
7
+ interface StoreLike {
8
+ create(input: CreatePrintAgentInput): Promise<PrintAgent>;
9
+ list(): Promise<PrintAgent[]>;
10
+ resolve(reference: string): Promise<PrintAgent | PrintAgent[] | null>;
11
+ acquireRun(id: string): Promise<{ agent: PrintAgent; token: string }>;
12
+ recordProviderProcess(id: string, token: string, identity: ProcessIdentity): Promise<void>;
13
+ completeRun(id: string, token: string, result: PrintRunCompletion): Promise<PrintAgent>;
14
+ }
15
+
16
+ interface ProbeLike { validate(): Promise<{ executable: string; version: string }> }
17
+ interface RunnerLike { run(request: Parameters<ClaudePrintRunner['run']>[0]): Promise<ClaudePrintRunResult> }
18
+
19
+ export interface ClaudePrintAgentServiceOptions {
20
+ store?: StoreLike;
21
+ probe?: ProbeLike;
22
+ runner?: RunnerLike;
23
+ executable?: string;
24
+ }
25
+
26
+ export interface ClaudePrintSendResult extends ClaudePrintRunResult {
27
+ agentId: string;
28
+ agentName: string;
29
+ }
30
+
31
+ export class ClaudePrintAgentService {
32
+ readonly store: StoreLike;
33
+ private readonly probe: ProbeLike;
34
+ private readonly runner: RunnerLike;
35
+ private readonly executable?: string;
36
+
37
+ constructor(options: ClaudePrintAgentServiceOptions = {}) {
38
+ this.store = options.store ?? new PrintAgentStore();
39
+ this.probe = options.probe ?? new ClaudeCliProbe();
40
+ this.runner = options.runner ?? new ClaudePrintRunner();
41
+ this.executable = options.executable;
42
+ }
43
+
44
+ async create(input: CreatePrintAgentInput): Promise<PrintAgent> {
45
+ await this.probe.validate();
46
+ return this.store.create(input);
47
+ }
48
+
49
+ async send(reference: string, prompt: string): Promise<ClaudePrintSendResult> {
50
+ const resolved = await this.store.resolve(reference);
51
+ if (!resolved) throw new PrintAgentNotFoundError(reference);
52
+ if (Array.isArray(resolved)) {
53
+ throw new ClaudePrintError(`Multiple print agents match "${reference}".`, 'PRINT_AGENT_AMBIGUOUS');
54
+ }
55
+ const acquired = await this.store.acquireRun(resolved.id);
56
+ try {
57
+ const result = await this.runner.run({
58
+ agent: acquired.agent,
59
+ prompt,
60
+ executable: this.executable,
61
+ firstRun: acquired.agent.sessionHealth === 'uninitialized',
62
+ onSpawn: (identity) => this.store.recordProviderProcess(resolved.id, acquired.token, identity),
63
+ });
64
+ await this.store.completeRun(resolved.id, acquired.token, {
65
+ status: 'succeeded',
66
+ exitCode: result.exitCode,
67
+ summary: sanitize(result.result, 4096),
68
+ sessionHealth: 'healthy',
69
+ });
70
+ return { ...result, agentId: resolved.id, agentName: resolved.name };
71
+ } catch (error) {
72
+ const failure = error instanceof Error ? error : new Error(String(error));
73
+ const sessionHealth = error instanceof ClaudePrintError && error.code === 'CLAUDE_SESSION_MISMATCH'
74
+ ? 'mismatch' as const
75
+ : 'unknown' as const;
76
+ await this.store.completeRun(resolved.id, acquired.token, {
77
+ status: 'failed',
78
+ exitCode: null,
79
+ summary: sanitize(failure.message, 4096),
80
+ sessionHealth,
81
+ });
82
+ throw error;
83
+ }
84
+ }
85
+ }
86
+
87
+ function sanitize(value: string, max: number): string {
88
+ return Array.from(value, (character) => {
89
+ const code = character.charCodeAt(0);
90
+ return (code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127)
91
+ ? ' '
92
+ : character;
93
+ }).join('').trim().slice(0, max);
94
+ }