@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
package/README.md CHANGED
@@ -24,6 +24,20 @@ ai-devkit agent send "run the tests and report back" --id <agent-name> --wait
24
24
  npm test 2>&1 | ai-devkit agent send --id <agent-name> --stdin
25
25
  ```
26
26
 
27
+ Claude Code can also be registered as a durable print-mode agent. Registration
28
+ does not launch Claude; each send starts one synchronous process and later sends
29
+ resume the same Claude session:
30
+
31
+ ```bash
32
+ ai-devkit agent start --type claude --mode print --name reviewer --cwd /path/to/project
33
+ ai-devkit agent send "review the current diff" --id reviewer
34
+ ```
35
+
36
+ Print mode inherits Claude Code's settings, permissions, hooks, MCP servers, and
37
+ tool side effects for that working directory. AI DevKit adds no permission bypass
38
+ or automatic retry, and prompts are delivered over stdin rather than command-line
39
+ arguments. `--timeout` is not supported for print agents in this first release.
40
+
27
41
  Use this package directly only when building custom tooling around AI DevKit's agent detection and control surface.
28
42
 
29
43
  ## Documentation
@@ -0,0 +1,403 @@
1
+ /**
2
+ * Tests for GrokCliAdapter
3
+ *
4
+ * The adapter resolves a live process to its cwd via ~/.grok/active_sessions.json
5
+ * and reads session details from chat_history.jsonl (not summary.json/updates.jsonl).
6
+ */ import * as fs from 'fs';
7
+ import * as os from 'os';
8
+ import * as path from 'path';
9
+ import { GrokCliAdapter } from '../../adapters/GrokCliAdapter.js';
10
+ import { AgentStatus } from '../../adapters/AgentAdapter.js';
11
+ import { listAgentProcesses, enrichProcesses } from '../../utils/process.js';
12
+ import { generateAgentName } from '../../utils/matching.js';
13
+ vi.mock('../../utils/process.js', async (importOriginal)=>{
14
+ const actual = await importOriginal();
15
+ return {
16
+ ...actual,
17
+ listAgentProcesses: vi.fn(),
18
+ enrichProcesses: vi.fn()
19
+ };
20
+ });
21
+ vi.mock('../../utils/matching.js', async (importOriginal)=>{
22
+ const actual = await importOriginal();
23
+ return {
24
+ ...actual,
25
+ generateAgentName: vi.fn()
26
+ };
27
+ });
28
+ const mockedListAgentProcesses = listAgentProcesses;
29
+ const mockedEnrichProcesses = enrichProcesses;
30
+ const mockedGenerateAgentName = generateAgentName;
31
+ const SESSION_ID = '019f16c3-5d5d-7dc3-85d1-bc629416ca2d';
32
+ /** A user transcript record: the real prompt wrapped in <user_query> like Grok writes it. */ const userRecord = (text)=>({
33
+ type: 'user',
34
+ content: [
35
+ {
36
+ type: 'text',
37
+ text: `<user_query>\n${text}\n</user_query>`
38
+ }
39
+ ]
40
+ });
41
+ /** A user context-injection record (no <user_query>) — should be ignored as a prompt. */ const contextRecord = (text)=>({
42
+ type: 'user',
43
+ content: [
44
+ {
45
+ type: 'text',
46
+ text
47
+ }
48
+ ]
49
+ });
50
+ const assistantRecord = (text)=>({
51
+ type: 'assistant',
52
+ content: [
53
+ {
54
+ type: 'text',
55
+ text
56
+ }
57
+ ]
58
+ });
59
+ const systemRecord = (text)=>({
60
+ type: 'system',
61
+ content: text
62
+ });
63
+ describe('GrokCliAdapter', ()=>{
64
+ let adapter;
65
+ let tmpHome;
66
+ let cwd;
67
+ beforeEach(()=>{
68
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-adapter-test-'));
69
+ process.env.HOME = tmpHome;
70
+ delete process.env.GROK_HOME;
71
+ cwd = '/Users/dev/my-project';
72
+ adapter = new GrokCliAdapter();
73
+ mockedListAgentProcesses.mockReset();
74
+ mockedEnrichProcesses.mockReset();
75
+ mockedGenerateAgentName.mockReset();
76
+ mockedEnrichProcesses.mockImplementation((procs)=>procs);
77
+ mockedGenerateAgentName.mockImplementation((c, pid)=>`${path.basename(c) || 'unknown'}-${pid}`);
78
+ });
79
+ afterEach(()=>{
80
+ fs.rmSync(tmpHome, {
81
+ recursive: true,
82
+ force: true
83
+ });
84
+ });
85
+ /** Write a session dir under ~/.grok/sessions/<enc(cwd)>/<id>/chat_history.jsonl. */ function writeSession(opts) {
86
+ const sessionCwd = opts.sessionCwd ?? cwd;
87
+ const id = opts.id ?? SESSION_ID;
88
+ const sessionDir = path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(sessionCwd), id);
89
+ fs.mkdirSync(sessionDir, {
90
+ recursive: true
91
+ });
92
+ if (opts.chat !== false) {
93
+ const records = opts.records ?? [
94
+ userRecord('fix the bug')
95
+ ];
96
+ const chatPath = path.join(sessionDir, 'chat_history.jsonl');
97
+ fs.writeFileSync(chatPath, records.map((r)=>JSON.stringify(r)).join('\n'));
98
+ if (opts.mtime) fs.utimesSync(chatPath, opts.mtime, opts.mtime);
99
+ }
100
+ return sessionDir;
101
+ }
102
+ /** Write ~/.grok/active_sessions.json (the live pid -> cwd registry). */ function writeActiveSessions(entries) {
103
+ fs.mkdirSync(path.join(tmpHome, '.grok'), {
104
+ recursive: true
105
+ });
106
+ fs.writeFileSync(path.join(tmpHome, '.grok', 'active_sessions.json'), JSON.stringify(entries));
107
+ }
108
+ function proc(overrides = {}) {
109
+ return {
110
+ pid: 4242,
111
+ ppid: 1,
112
+ command: 'grok',
113
+ cwd,
114
+ tty: 'ttys010',
115
+ startTime: new Date(),
116
+ ...overrides
117
+ };
118
+ }
119
+ describe('initialization', ()=>{
120
+ it('exposes the grok_cli type', ()=>{
121
+ expect(adapter.type).toBe('grok_cli');
122
+ });
123
+ });
124
+ describe('canHandle', ()=>{
125
+ it('returns true for a plain grok command', ()=>{
126
+ expect(adapter.canHandle(proc({
127
+ command: 'grok'
128
+ }))).toBe(true);
129
+ });
130
+ it('returns true for grok with a full path and args', ()=>{
131
+ expect(adapter.canHandle(proc({
132
+ command: '/Users/dev/.grok/bin/grok --always-approve'
133
+ }))).toBe(true);
134
+ });
135
+ it('returns false for non-grok processes', ()=>{
136
+ expect(adapter.canHandle(proc({
137
+ command: 'node app.js'
138
+ }))).toBe(false);
139
+ });
140
+ it('returns false when "grok" appears only in an argument path', ()=>{
141
+ expect(adapter.canHandle(proc({
142
+ command: 'node /path/to/grok-thing.js'
143
+ }))).toBe(false);
144
+ });
145
+ });
146
+ describe('detectAgents', ()=>{
147
+ it('returns [] when there are no grok processes', async ()=>{
148
+ mockedListAgentProcesses.mockReturnValue([]);
149
+ expect(await adapter.detectAgents()).toEqual([]);
150
+ });
151
+ it('resolves the cwd via active_sessions.json (authoritative over the process cwd)', async ()=>{
152
+ const realCwd = '/Users/dev/real-project';
153
+ writeSession({
154
+ sessionCwd: realCwd
155
+ });
156
+ // The process cwd is stale/wrong; active_sessions.json has the truth.
157
+ writeActiveSessions([
158
+ {
159
+ pid: 4242,
160
+ cwd: realCwd,
161
+ opened_at: 1
162
+ }
163
+ ]);
164
+ mockedListAgentProcesses.mockReturnValue([
165
+ proc({
166
+ cwd: '/wrong/path'
167
+ })
168
+ ]);
169
+ const agents = await adapter.detectAgents();
170
+ expect(agents).toHaveLength(1);
171
+ expect(agents[0]).toMatchObject({
172
+ type: 'grok_cli',
173
+ pid: 4242,
174
+ projectPath: realCwd,
175
+ sessionId: SESSION_ID,
176
+ summary: 'fix the bug'
177
+ });
178
+ expect(agents[0].sessionFilePath).toBe(path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(realCwd), SESSION_ID, 'chat_history.jsonl'));
179
+ });
180
+ it('falls back to the process cwd when the pid is not in active_sessions.json', async ()=>{
181
+ writeSession({});
182
+ writeActiveSessions([
183
+ {
184
+ pid: 9999,
185
+ cwd: '/somewhere/else'
186
+ }
187
+ ]);
188
+ mockedListAgentProcesses.mockReturnValue([
189
+ proc()
190
+ ]);
191
+ const agents = await adapter.detectAgents();
192
+ expect(agents[0]).toMatchObject({
193
+ projectPath: cwd,
194
+ sessionId: SESSION_ID
195
+ });
196
+ });
197
+ it('picks the most recently active session dir when a cwd has several', async ()=>{
198
+ const older = new Date(Date.now() - 60 * 60 * 1000);
199
+ writeSession({
200
+ id: '019f0000-0000-7000-8000-00000000000a',
201
+ records: [
202
+ userRecord('old one')
203
+ ],
204
+ mtime: older
205
+ });
206
+ writeSession({
207
+ id: '019f0000-0000-7000-8000-00000000000b',
208
+ records: [
209
+ userRecord('newest one')
210
+ ]
211
+ });
212
+ mockedListAgentProcesses.mockReturnValue([
213
+ proc()
214
+ ]);
215
+ const agents = await adapter.detectAgents();
216
+ expect(agents[0].sessionId).toBe('019f0000-0000-7000-8000-00000000000b');
217
+ expect(agents[0].summary).toBe('newest one');
218
+ });
219
+ it('falls back to a process-only RUNNING agent when no session matches', async ()=>{
220
+ mockedListAgentProcesses.mockReturnValue([
221
+ proc()
222
+ ]);
223
+ const agents = await adapter.detectAgents();
224
+ expect(agents).toHaveLength(1);
225
+ expect(agents[0].status).toBe(AgentStatus.RUNNING);
226
+ expect(agents[0].sessionId).toBe('pid-4242');
227
+ expect(agents[0].sessionFilePath).toBeUndefined();
228
+ });
229
+ it('treats a session dir without chat_history.jsonl as no match (process-only)', async ()=>{
230
+ writeSession({
231
+ chat: false
232
+ });
233
+ mockedListAgentProcesses.mockReturnValue([
234
+ proc()
235
+ ]);
236
+ const agents = await adapter.detectAgents();
237
+ expect(agents).toHaveLength(1);
238
+ expect(agents[0].sessionId).toBe('pid-4242');
239
+ });
240
+ });
241
+ describe('getConversation', ()=>{
242
+ it('maps user (<user_query>) and assistant records to roles', ()=>{
243
+ const dir = writeSession({
244
+ records: [
245
+ userRecord('hi'),
246
+ assistantRecord('hello')
247
+ ]
248
+ });
249
+ expect(adapter.getConversation(path.join(dir, 'chat_history.jsonl'))).toEqual([
250
+ {
251
+ role: 'user',
252
+ content: 'hi'
253
+ },
254
+ {
255
+ role: 'assistant',
256
+ content: 'hello'
257
+ }
258
+ ]);
259
+ });
260
+ it('accepts a session dir path and skips context-injection user records', ()=>{
261
+ const dir = writeSession({
262
+ records: [
263
+ contextRecord('<user_info>OS: macos</user_info>'),
264
+ userRecord('do the thing')
265
+ ]
266
+ });
267
+ expect(adapter.getConversation(dir)).toEqual([
268
+ {
269
+ role: 'user',
270
+ content: 'do the thing'
271
+ }
272
+ ]);
273
+ });
274
+ it('skips malformed lines', ()=>{
275
+ const dir = writeSession({
276
+ records: [
277
+ userRecord('hi')
278
+ ]
279
+ });
280
+ fs.appendFileSync(path.join(dir, 'chat_history.jsonl'), '\n{bad json');
281
+ expect(adapter.getConversation(dir)).toEqual([
282
+ {
283
+ role: 'user',
284
+ content: 'hi'
285
+ }
286
+ ]);
287
+ });
288
+ it('excludes system records unless verbose', ()=>{
289
+ const dir = writeSession({
290
+ records: [
291
+ systemRecord('You are Grok'),
292
+ userRecord('go')
293
+ ]
294
+ });
295
+ expect(adapter.getConversation(dir)).toEqual([
296
+ {
297
+ role: 'user',
298
+ content: 'go'
299
+ }
300
+ ]);
301
+ expect(adapter.getConversation(dir, {
302
+ verbose: true
303
+ }).map((m)=>m.role)).toEqual([
304
+ 'system',
305
+ 'user'
306
+ ]);
307
+ });
308
+ });
309
+ describe('detectAgents status + summary mapping', ()=>{
310
+ const detectFirst = async ()=>(await adapter.detectAgents())[0];
311
+ it('marks WAITING when the last transcript turn is an assistant message', async ()=>{
312
+ writeSession({
313
+ records: [
314
+ userRecord('go'),
315
+ assistantRecord('done')
316
+ ]
317
+ });
318
+ mockedListAgentProcesses.mockReturnValue([
319
+ proc()
320
+ ]);
321
+ expect((await detectFirst()).status).toBe(AgentStatus.WAITING);
322
+ });
323
+ it('marks RUNNING when the last transcript turn is a user message', async ()=>{
324
+ writeSession({
325
+ records: [
326
+ userRecord('still there?')
327
+ ]
328
+ });
329
+ mockedListAgentProcesses.mockReturnValue([
330
+ proc()
331
+ ]);
332
+ expect((await detectFirst()).status).toBe(AgentStatus.RUNNING);
333
+ });
334
+ it('marks IDLE when chat_history.jsonl is older than the threshold', async ()=>{
335
+ const old = new Date(Date.now() - 10 * 60 * 1000);
336
+ writeSession({
337
+ records: [
338
+ userRecord('go')
339
+ ],
340
+ mtime: old
341
+ });
342
+ mockedListAgentProcesses.mockReturnValue([
343
+ proc()
344
+ ]);
345
+ expect((await detectFirst()).status).toBe(AgentStatus.IDLE);
346
+ });
347
+ it('uses the last user prompt as the agent summary', async ()=>{
348
+ writeSession({
349
+ records: [
350
+ userRecord('refactor the parser'),
351
+ assistantRecord('on it')
352
+ ]
353
+ });
354
+ mockedListAgentProcesses.mockReturnValue([
355
+ proc()
356
+ ]);
357
+ expect((await detectFirst()).summary).toBe('refactor the parser');
358
+ });
359
+ });
360
+ describe('listSessions', ()=>{
361
+ it('returns [] when the sessions dir does not exist', async ()=>{
362
+ expect(await adapter.listSessions()).toEqual([]);
363
+ });
364
+ it('lists historical sessions with cwd decoded from the group dir', async ()=>{
365
+ writeSession({});
366
+ const summaries = await adapter.listSessions();
367
+ expect(summaries).toHaveLength(1);
368
+ expect(summaries[0]).toMatchObject({
369
+ type: 'grok_cli',
370
+ sessionId: SESSION_ID,
371
+ cwd,
372
+ firstUserMessage: 'fix the bug'
373
+ });
374
+ expect(summaries[0].sessionFilePath).toBe(path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), SESSION_ID, 'chat_history.jsonl'));
375
+ });
376
+ it('applies the cwd filter against the decoded cwd', async ()=>{
377
+ writeSession({
378
+ sessionCwd: '/Users/dev/project-a',
379
+ id: '019f0000-0000-7000-8000-00000000000a'
380
+ });
381
+ writeSession({
382
+ sessionCwd: '/Users/dev/project-b',
383
+ id: '019f0000-0000-7000-8000-00000000000b'
384
+ });
385
+ const all = await adapter.listSessions();
386
+ expect(all).toHaveLength(2);
387
+ const filtered = await adapter.listSessions({
388
+ cwd: '/Users/dev/project-a'
389
+ });
390
+ expect(filtered).toHaveLength(1);
391
+ expect(filtered[0].cwd).toBe('/Users/dev/project-a');
392
+ });
393
+ it('skips non-session entries (e.g. prompt_history.jsonl) in a group dir', async ()=>{
394
+ writeSession({});
395
+ // Grok writes a group-level prompt_history.jsonl alongside session dirs.
396
+ fs.writeFileSync(path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), 'prompt_history.jsonl'), '{"text":"noise"}');
397
+ const summaries = await adapter.listSessions();
398
+ expect(summaries).toHaveLength(1);
399
+ });
400
+ });
401
+ });
402
+
403
+ //# sourceMappingURL=GrokCliAdapter.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/__tests__/adapters/GrokCliAdapter.test.ts"],"sourcesContent":["/**\n * Tests for GrokCliAdapter\n *\n * The adapter resolves a live process to its cwd via ~/.grok/active_sessions.json\n * and reads session details from chat_history.jsonl (not summary.json/updates.jsonl).\n */\n\nimport type { MockedFunction } from 'vitest';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\nimport { GrokCliAdapter } from '../../adapters/GrokCliAdapter.js';\nimport type { ProcessInfo } from '../../adapters/AgentAdapter.js';\nimport { AgentStatus } from '../../adapters/AgentAdapter.js';\nimport { listAgentProcesses, enrichProcesses } from '../../utils/process.js';\nimport { generateAgentName } from '../../utils/matching.js';\n\nvi.mock('../../utils/process.js', async (importOriginal) => {\n const actual = (await importOriginal()) as typeof import('../../utils/process.js');\n return {\n ...actual,\n listAgentProcesses: vi.fn(),\n enrichProcesses: vi.fn(),\n };\n});\n\nvi.mock('../../utils/matching.js', async (importOriginal) => {\n const actual = (await importOriginal()) as typeof import('../../utils/matching.js');\n return {\n ...actual,\n generateAgentName: vi.fn(),\n };\n});\n\nconst mockedListAgentProcesses = listAgentProcesses as MockedFunction<typeof listAgentProcesses>;\nconst mockedEnrichProcesses = enrichProcesses as MockedFunction<typeof enrichProcesses>;\nconst mockedGenerateAgentName = generateAgentName as MockedFunction<typeof generateAgentName>;\n\nconst SESSION_ID = '019f16c3-5d5d-7dc3-85d1-bc629416ca2d';\n\n/** A user transcript record: the real prompt wrapped in <user_query> like Grok writes it. */\nconst userRecord = (text: string) => ({\n type: 'user',\n content: [{ type: 'text', text: `<user_query>\\n${text}\\n</user_query>` }],\n});\n/** A user context-injection record (no <user_query>) — should be ignored as a prompt. */\nconst contextRecord = (text: string) => ({ type: 'user', content: [{ type: 'text', text }] });\nconst assistantRecord = (text: string) => ({ type: 'assistant', content: [{ type: 'text', text }] });\nconst systemRecord = (text: string) => ({ type: 'system', content: text });\n\ndescribe('GrokCliAdapter', () => {\n let adapter: GrokCliAdapter;\n let tmpHome: string;\n let cwd: string;\n\n beforeEach(() => {\n tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-adapter-test-'));\n process.env.HOME = tmpHome;\n delete process.env.GROK_HOME;\n cwd = '/Users/dev/my-project';\n\n adapter = new GrokCliAdapter();\n\n mockedListAgentProcesses.mockReset();\n mockedEnrichProcesses.mockReset();\n mockedGenerateAgentName.mockReset();\n\n mockedEnrichProcesses.mockImplementation((procs) => procs);\n mockedGenerateAgentName.mockImplementation((c: string, pid: number) => `${path.basename(c) || 'unknown'}-${pid}`);\n });\n\n afterEach(() => {\n fs.rmSync(tmpHome, { recursive: true, force: true });\n });\n\n /** Write a session dir under ~/.grok/sessions/<enc(cwd)>/<id>/chat_history.jsonl. */\n function writeSession(opts: {\n sessionCwd?: string;\n id?: string;\n records?: object[];\n chat?: boolean;\n mtime?: Date;\n }): string {\n const sessionCwd = opts.sessionCwd ?? cwd;\n const id = opts.id ?? SESSION_ID;\n const sessionDir = path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(sessionCwd), id);\n fs.mkdirSync(sessionDir, { recursive: true });\n\n if (opts.chat !== false) {\n const records = opts.records ?? [userRecord('fix the bug')];\n const chatPath = path.join(sessionDir, 'chat_history.jsonl');\n fs.writeFileSync(chatPath, records.map((r) => JSON.stringify(r)).join('\\n'));\n if (opts.mtime) fs.utimesSync(chatPath, opts.mtime, opts.mtime);\n }\n\n return sessionDir;\n }\n\n /** Write ~/.grok/active_sessions.json (the live pid -> cwd registry). */\n function writeActiveSessions(entries: Array<{ pid: number; cwd: string; opened_at?: number }>): void {\n fs.mkdirSync(path.join(tmpHome, '.grok'), { recursive: true });\n fs.writeFileSync(path.join(tmpHome, '.grok', 'active_sessions.json'), JSON.stringify(entries));\n }\n\n function proc(overrides: Partial<ProcessInfo> = {}): ProcessInfo {\n return { pid: 4242, ppid: 1, command: 'grok', cwd, tty: 'ttys010', startTime: new Date(), ...overrides };\n }\n\n describe('initialization', () => {\n it('exposes the grok_cli type', () => {\n expect(adapter.type).toBe('grok_cli');\n });\n });\n\n describe('canHandle', () => {\n it('returns true for a plain grok command', () => {\n expect(adapter.canHandle(proc({ command: 'grok' }))).toBe(true);\n });\n\n it('returns true for grok with a full path and args', () => {\n expect(adapter.canHandle(proc({ command: '/Users/dev/.grok/bin/grok --always-approve' }))).toBe(true);\n });\n\n it('returns false for non-grok processes', () => {\n expect(adapter.canHandle(proc({ command: 'node app.js' }))).toBe(false);\n });\n\n it('returns false when \"grok\" appears only in an argument path', () => {\n expect(adapter.canHandle(proc({ command: 'node /path/to/grok-thing.js' }))).toBe(false);\n });\n });\n\n describe('detectAgents', () => {\n it('returns [] when there are no grok processes', async () => {\n mockedListAgentProcesses.mockReturnValue([]);\n expect(await adapter.detectAgents()).toEqual([]);\n });\n\n it('resolves the cwd via active_sessions.json (authoritative over the process cwd)', async () => {\n const realCwd = '/Users/dev/real-project';\n writeSession({ sessionCwd: realCwd });\n // The process cwd is stale/wrong; active_sessions.json has the truth.\n writeActiveSessions([{ pid: 4242, cwd: realCwd, opened_at: 1 }]);\n mockedListAgentProcesses.mockReturnValue([proc({ cwd: '/wrong/path' })]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0]).toMatchObject({\n type: 'grok_cli',\n pid: 4242,\n projectPath: realCwd,\n sessionId: SESSION_ID,\n summary: 'fix the bug',\n });\n expect(agents[0].sessionFilePath).toBe(\n path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(realCwd), SESSION_ID, 'chat_history.jsonl'),\n );\n });\n\n it('falls back to the process cwd when the pid is not in active_sessions.json', async () => {\n writeSession({});\n writeActiveSessions([{ pid: 9999, cwd: '/somewhere/else' }]);\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents[0]).toMatchObject({ projectPath: cwd, sessionId: SESSION_ID });\n });\n\n it('picks the most recently active session dir when a cwd has several', async () => {\n const older = new Date(Date.now() - 60 * 60 * 1000);\n writeSession({ id: '019f0000-0000-7000-8000-00000000000a', records: [userRecord('old one')], mtime: older });\n writeSession({ id: '019f0000-0000-7000-8000-00000000000b', records: [userRecord('newest one')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents[0].sessionId).toBe('019f0000-0000-7000-8000-00000000000b');\n expect(agents[0].summary).toBe('newest one');\n });\n\n it('falls back to a process-only RUNNING agent when no session matches', async () => {\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0].status).toBe(AgentStatus.RUNNING);\n expect(agents[0].sessionId).toBe('pid-4242');\n expect(agents[0].sessionFilePath).toBeUndefined();\n });\n\n it('treats a session dir without chat_history.jsonl as no match (process-only)', async () => {\n writeSession({ chat: false });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0].sessionId).toBe('pid-4242');\n });\n });\n\n describe('getConversation', () => {\n it('maps user (<user_query>) and assistant records to roles', () => {\n const dir = writeSession({ records: [userRecord('hi'), assistantRecord('hello')] });\n expect(adapter.getConversation(path.join(dir, 'chat_history.jsonl'))).toEqual([\n { role: 'user', content: 'hi' },\n { role: 'assistant', content: 'hello' },\n ]);\n });\n\n it('accepts a session dir path and skips context-injection user records', () => {\n const dir = writeSession({\n records: [contextRecord('<user_info>OS: macos</user_info>'), userRecord('do the thing')],\n });\n expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'do the thing' }]);\n });\n\n it('skips malformed lines', () => {\n const dir = writeSession({ records: [userRecord('hi')] });\n fs.appendFileSync(path.join(dir, 'chat_history.jsonl'), '\\n{bad json');\n expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'hi' }]);\n });\n\n it('excludes system records unless verbose', () => {\n const dir = writeSession({ records: [systemRecord('You are Grok'), userRecord('go')] });\n expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'go' }]);\n expect(adapter.getConversation(dir, { verbose: true }).map((m) => m.role)).toEqual(['system', 'user']);\n });\n });\n\n describe('detectAgents status + summary mapping', () => {\n const detectFirst = async () => (await adapter.detectAgents())[0];\n\n it('marks WAITING when the last transcript turn is an assistant message', async () => {\n writeSession({ records: [userRecord('go'), assistantRecord('done')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.WAITING);\n });\n\n it('marks RUNNING when the last transcript turn is a user message', async () => {\n writeSession({ records: [userRecord('still there?')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.RUNNING);\n });\n\n it('marks IDLE when chat_history.jsonl is older than the threshold', async () => {\n const old = new Date(Date.now() - 10 * 60 * 1000);\n writeSession({ records: [userRecord('go')], mtime: old });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.IDLE);\n });\n\n it('uses the last user prompt as the agent summary', async () => {\n writeSession({ records: [userRecord('refactor the parser'), assistantRecord('on it')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).summary).toBe('refactor the parser');\n });\n });\n\n describe('listSessions', () => {\n it('returns [] when the sessions dir does not exist', async () => {\n expect(await adapter.listSessions()).toEqual([]);\n });\n\n it('lists historical sessions with cwd decoded from the group dir', async () => {\n writeSession({});\n const summaries = await adapter.listSessions();\n expect(summaries).toHaveLength(1);\n expect(summaries[0]).toMatchObject({\n type: 'grok_cli',\n sessionId: SESSION_ID,\n cwd,\n firstUserMessage: 'fix the bug',\n });\n expect(summaries[0].sessionFilePath).toBe(\n path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), SESSION_ID, 'chat_history.jsonl'),\n );\n });\n\n it('applies the cwd filter against the decoded cwd', async () => {\n writeSession({ sessionCwd: '/Users/dev/project-a', id: '019f0000-0000-7000-8000-00000000000a' });\n writeSession({ sessionCwd: '/Users/dev/project-b', id: '019f0000-0000-7000-8000-00000000000b' });\n\n const all = await adapter.listSessions();\n expect(all).toHaveLength(2);\n\n const filtered = await adapter.listSessions({ cwd: '/Users/dev/project-a' });\n expect(filtered).toHaveLength(1);\n expect(filtered[0].cwd).toBe('/Users/dev/project-a');\n });\n\n it('skips non-session entries (e.g. prompt_history.jsonl) in a group dir', async () => {\n writeSession({});\n // Grok writes a group-level prompt_history.jsonl alongside session dirs.\n fs.writeFileSync(\n path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), 'prompt_history.jsonl'),\n '{\"text\":\"noise\"}',\n );\n const summaries = await adapter.listSessions();\n expect(summaries).toHaveLength(1);\n });\n });\n});\n"],"names":["fs","os","path","GrokCliAdapter","AgentStatus","listAgentProcesses","enrichProcesses","generateAgentName","vi","mock","importOriginal","actual","fn","mockedListAgentProcesses","mockedEnrichProcesses","mockedGenerateAgentName","SESSION_ID","userRecord","text","type","content","contextRecord","assistantRecord","systemRecord","describe","adapter","tmpHome","cwd","beforeEach","mkdtempSync","join","tmpdir","process","env","HOME","GROK_HOME","mockReset","mockImplementation","procs","c","pid","basename","afterEach","rmSync","recursive","force","writeSession","opts","sessionCwd","id","sessionDir","encodeURIComponent","mkdirSync","chat","records","chatPath","writeFileSync","map","r","JSON","stringify","mtime","utimesSync","writeActiveSessions","entries","proc","overrides","ppid","command","tty","startTime","Date","it","expect","toBe","canHandle","mockReturnValue","detectAgents","toEqual","realCwd","opened_at","agents","toHaveLength","toMatchObject","projectPath","sessionId","summary","sessionFilePath","older","now","status","RUNNING","toBeUndefined","dir","getConversation","role","appendFileSync","verbose","m","detectFirst","WAITING","old","IDLE","listSessions","summaries","firstUserMessage","all","filtered"],"mappings":"AAAA;;;;;CAKC,GAGD,YAAYA,QAAQ,KAAK;AACzB,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAE7B,SAASC,cAAc,QAAQ,mCAAmC;AAElE,SAASC,WAAW,QAAQ,iCAAiC;AAC7D,SAASC,kBAAkB,EAAEC,eAAe,QAAQ,yBAAyB;AAC7E,SAASC,iBAAiB,QAAQ,0BAA0B;AAE5DC,GAAGC,IAAI,CAAC,0BAA0B,OAAOC;IACrC,MAAMC,SAAU,MAAMD;IACtB,OAAO;QACH,GAAGC,MAAM;QACTN,oBAAoBG,GAAGI,EAAE;QACzBN,iBAAiBE,GAAGI,EAAE;IAC1B;AACJ;AAEAJ,GAAGC,IAAI,CAAC,2BAA2B,OAAOC;IACtC,MAAMC,SAAU,MAAMD;IACtB,OAAO;QACH,GAAGC,MAAM;QACTJ,mBAAmBC,GAAGI,EAAE;IAC5B;AACJ;AAEA,MAAMC,2BAA2BR;AACjC,MAAMS,wBAAwBR;AAC9B,MAAMS,0BAA0BR;AAEhC,MAAMS,aAAa;AAEnB,2FAA2F,GAC3F,MAAMC,aAAa,CAACC,OAAkB,CAAA;QAClCC,MAAM;QACNC,SAAS;YAAC;gBAAED,MAAM;gBAAQD,MAAM,CAAC,cAAc,EAAEA,KAAK,eAAe,CAAC;YAAC;SAAE;IAC7E,CAAA;AACA,uFAAuF,GACvF,MA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kBAAkB;YACtB;YACAhC,OAAO+B,SAAS,CAAC,EAAE,CAACjB,eAAe,EAAEb,IAAI,CACrCxE,KAAK4B,IAAI,CAACJ,SAAS,SAAS,YAAYyB,mBAAmBxB,MAAMX,YAAY;QAErF;QAEAwD,GAAG,kDAAkD;YACjD1B,aAAa;gBAAEE,YAAY;gBAAwBC,IAAI;YAAuC;YAC9FH,aAAa;gBAAEE,YAAY;gBAAwBC,IAAI;YAAuC;YAE9F,MAAMyD,MAAM,MAAMjF,QAAQ8E,YAAY;YACtC9B,OAAOiC,KAAKxB,YAAY,CAAC;YAEzB,MAAMyB,WAAW,MAAMlF,QAAQ8E,YAAY,CAAC;gBAAE5E,KAAK;YAAuB;YAC1E8C,OAAOkC,UAAUzB,YAAY,CAAC;YAC9BT,OAAOkC,QAAQ,CAAC,EAAE,CAAChF,GAAG,EAAE+C,IAAI,CAAC;QACjC;QAEAF,GAAG,wEAAwE;YACvE1B,aAAa,CAAC;YACd,yEAAyE;YACzE9C,GAAGwD,aAAa,CACZtD,KAAK4B,IAAI,CAACJ,SAAS,SAAS,YAAYyB,mBAAmBxB,MAAM,yBACjE;YAEJ,MAAM6E,YAAY,MAAM/E,QAAQ8E,YAAY;YAC5C9B,OAAO+B,WAAWtB,YAAY,CAAC;QACnC;IACJ;AACJ"}
@@ -0,0 +1,53 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ describe('ClaudeCliProbe', ()=>{
3
+ it('validates only version/help and requires the print session flags', async ()=>{
4
+ const api = await import('../../index.js');
5
+ expect(api).toHaveProperty('ClaudeCliProbe');
6
+ const exec = vi.fn().mockResolvedValueOnce({
7
+ stdout: '2.1.220\n',
8
+ stderr: ''
9
+ }).mockResolvedValueOnce({
10
+ stdout: '--print --session-id --resume --output-format stream-json',
11
+ stderr: ''
12
+ });
13
+ const Probe = api.ClaudeCliProbe;
14
+ await expect(new Probe({
15
+ exec
16
+ }).validate()).resolves.toEqual({
17
+ executable: 'claude',
18
+ version: '2.1.220'
19
+ });
20
+ expect(exec.mock.calls).toEqual([
21
+ [
22
+ 'claude',
23
+ [
24
+ '--version'
25
+ ]
26
+ ],
27
+ [
28
+ 'claude',
29
+ [
30
+ '--help'
31
+ ]
32
+ ]
33
+ ]);
34
+ });
35
+ it('rejects a CLI missing a required capability', async ()=>{
36
+ const api = await import('../../index.js');
37
+ const exec = vi.fn().mockResolvedValueOnce({
38
+ stdout: 'old',
39
+ stderr: ''
40
+ }).mockResolvedValueOnce({
41
+ stdout: '--print only',
42
+ stderr: ''
43
+ });
44
+ const Probe = api.ClaudeCliProbe;
45
+ await expect(new Probe({
46
+ exec
47
+ }).validate()).rejects.toMatchObject({
48
+ code: 'CLAUDE_CLI_UNSUPPORTED'
49
+ });
50
+ });
51
+ });
52
+
53
+ //# sourceMappingURL=ClaudeCliProbe.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/__tests__/print/ClaudeCliProbe.test.ts"],"sourcesContent":["import { describe, expect, it, vi } from 'vitest';\n\ndescribe('ClaudeCliProbe', () => {\n it('validates only version/help and requires the print session flags', async () => {\n const api = await import('../../index.js') as Record<string, unknown>;\n expect(api).toHaveProperty('ClaudeCliProbe');\n const exec = vi.fn()\n .mockResolvedValueOnce({ stdout: '2.1.220\\n', stderr: '' })\n .mockResolvedValueOnce({\n stdout: '--print --session-id --resume --output-format stream-json', stderr: '',\n });\n const Probe = api.ClaudeCliProbe as new (options: unknown) => { validate(): Promise<unknown> };\n\n await expect(new Probe({ exec }).validate()).resolves.toEqual({\n executable: 'claude', version: '2.1.220',\n });\n expect(exec.mock.calls).toEqual([\n ['claude', ['--version']],\n ['claude', ['--help']],\n ]);\n });\n\n it('rejects a CLI missing a required capability', async () => {\n const api = await import('../../index.js') as Record<string, unknown>;\n const exec = vi.fn()\n .mockResolvedValueOnce({ stdout: 'old', stderr: '' })\n .mockResolvedValueOnce({ stdout: '--print only', stderr: '' });\n const Probe = api.ClaudeCliProbe as new (options: unknown) => { validate(): Promise<unknown> };\n\n await expect(new Probe({ exec }).validate()).rejects.toMatchObject({ code: 'CLAUDE_CLI_UNSUPPORTED' });\n });\n});\n"],"names":["describe","expect","it","vi","api","toHaveProperty","exec","fn","mockResolvedValueOnce","stdout","stderr","Probe","ClaudeCliProbe","validate","resolves","toEqual","executable","version","mock","calls","rejects","toMatchObject","code"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAS;AAElDH,SAAS,kBAAkB;IACvBE,GAAG,oEAAoE;QACnE,MAAME,MAAM,MAAM,MAAM,CAAC;QACzBH,OAAOG,KAAKC,cAAc,CAAC;QAC3B,MAAMC,OAAOH,GAAGI,EAAE,GACbC,qBAAqB,CAAC;YAAEC,QAAQ;YAAaC,QAAQ;QAAG,GACxDF,qBAAqB,CAAC;YACnBC,QAAQ;YAA6DC,QAAQ;QACjF;QACJ,MAAMC,QAAQP,IAAIQ,cAAc;QAEhC,MAAMX,OAAO,IAAIU,MAAM;YAAEL;QAAK,GAAGO,QAAQ,IAAIC,QAAQ,CAACC,OAAO,CAAC;YAC1DC,YAAY;YAAUC,SAAS;QACnC;QACAhB,OAAOK,KAAKY,IAAI,CAACC,KAAK,EAAEJ,OAAO,CAAC;YAC5B;gBAAC;gBAAU;oBAAC;iBAAY;aAAC;YACzB;gBAAC;gBAAU;oBAAC;iBAAS;aAAC;SACzB;IACL;IAEAb,GAAG,+CAA+C;QAC9C,MAAME,MAAM,MAAM,MAAM,CAAC;QACzB,MAAME,OAAOH,GAAGI,EAAE,GACbC,qBAAqB,CAAC;YAAEC,QAAQ;YAAOC,QAAQ;QAAG,GAClDF,qBAAqB,CAAC;YAAEC,QAAQ;YAAgBC,QAAQ;QAAG;QAChE,MAAMC,QAAQP,IAAIQ,cAAc;QAEhC,MAAMX,OAAO,IAAIU,MAAM;YAAEL;QAAK,GAAGO,QAAQ,IAAIO,OAAO,CAACC,aAAa,CAAC;YAAEC,MAAM;QAAyB;IACxG;AACJ"}
@@ -0,0 +1,69 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+ import { ClaudeCliProbe, ClaudePrintAgentService, ClaudePrintRunner, PrintAgentStore } from '../../index.js';
7
+ const roots = [];
8
+ const originalCapture = process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE;
9
+ afterEach(()=>{
10
+ if (originalCapture === undefined) delete process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE;
11
+ else process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE = originalCapture;
12
+ for (const root of roots.splice(0))fs.rmSync(root, {
13
+ recursive: true,
14
+ force: true
15
+ });
16
+ });
17
+ describe('Claude print-agent fake-provider journey', ()=>{
18
+ it('creates without invocation, then starts and resumes the same session through stdin', async ()=>{
19
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'print-agent-integration-'));
20
+ roots.push(root);
21
+ const cwd = path.join(root, 'project');
22
+ fs.mkdirSync(cwd);
23
+ const capture = path.join(root, 'capture.jsonl');
24
+ process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE = capture;
25
+ const executable = fileURLToPath(new URL('../fixtures/fake-claude.cjs', import.meta.url));
26
+ const store = new PrintAgentStore({
27
+ filePath: path.join(root, 'state', 'print-agents.json')
28
+ });
29
+ const service = new ClaudePrintAgentService({
30
+ store,
31
+ probe: new ClaudeCliProbe({
32
+ executable
33
+ }),
34
+ runner: new ClaudePrintRunner(),
35
+ executable
36
+ });
37
+ const created = await service.create({
38
+ name: 'reviewer',
39
+ cwd
40
+ });
41
+ expect(fs.existsSync(capture)).toBe(false);
42
+ await expect(service.send(created.id, 'first secret')).resolves.toMatchObject({
43
+ result: 'answer:first secret'
44
+ });
45
+ await expect(service.send(created.id, 'follow up')).resolves.toMatchObject({
46
+ result: 'answer:follow up'
47
+ });
48
+ const invocations = fs.readFileSync(capture, 'utf8').trim().split('\n').map((line)=>JSON.parse(line));
49
+ expect(invocations[0]).toMatchObject({
50
+ prompt: 'first secret',
51
+ cwd: fs.realpathSync(cwd)
52
+ });
53
+ expect(invocations[0].args).toContain('--session-id');
54
+ expect(invocations[0].args).not.toContain('first secret');
55
+ expect(invocations[1]).toMatchObject({
56
+ prompt: 'follow up',
57
+ cwd: fs.realpathSync(cwd)
58
+ });
59
+ expect(invocations[1].args).toContain('--resume');
60
+ expect(invocations[1].args[invocations[1].args.indexOf('--resume') + 1]).toBe(created.providerSessionId);
61
+ const persisted = await store.getById(created.id);
62
+ expect(persisted).toMatchObject({
63
+ state: 'ready',
64
+ sessionHealth: 'healthy'
65
+ });
66
+ });
67
+ });
68
+
69
+ //# sourceMappingURL=ClaudePrintAgent.integration.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/__tests__/print/ClaudePrintAgent.integration.test.ts"],"sourcesContent":["import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { afterEach, describe, expect, it } from 'vitest';\nimport {\n ClaudeCliProbe,\n ClaudePrintAgentService,\n ClaudePrintRunner,\n PrintAgentStore,\n} from '../../index.js';\n\nconst roots: string[] = [];\nconst originalCapture = process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE;\n\nafterEach(() => {\n if (originalCapture === undefined) delete process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE;\n else process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE = originalCapture;\n for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });\n});\n\ndescribe('Claude print-agent fake-provider journey', () => {\n it('creates without invocation, then starts and resumes the same session through stdin', async () => {\n const root = fs.mkdtempSync(path.join(os.tmpdir(), 'print-agent-integration-'));\n roots.push(root);\n const cwd = path.join(root, 'project');\n fs.mkdirSync(cwd);\n const capture = path.join(root, 'capture.jsonl');\n process.env.AI_DEVKIT_FAKE_CLAUDE_CAPTURE = capture;\n const executable = fileURLToPath(new URL('../fixtures/fake-claude.cjs', import.meta.url));\n const store = new PrintAgentStore({ filePath: path.join(root, 'state', 'print-agents.json') });\n const service = new ClaudePrintAgentService({\n store,\n probe: new ClaudeCliProbe({ executable }),\n runner: new ClaudePrintRunner(),\n executable,\n });\n\n const created = await service.create({ name: 'reviewer', cwd });\n expect(fs.existsSync(capture)).toBe(false);\n\n await expect(service.send(created.id, 'first secret')).resolves.toMatchObject({ result: 'answer:first secret' });\n await expect(service.send(created.id, 'follow up')).resolves.toMatchObject({ result: 'answer:follow up' });\n\n const invocations = fs.readFileSync(capture, 'utf8').trim().split('\\n').map((line) => JSON.parse(line));\n expect(invocations[0]).toMatchObject({ prompt: 'first secret', cwd: fs.realpathSync(cwd) });\n expect(invocations[0].args).toContain('--session-id');\n expect(invocations[0].args).not.toContain('first secret');\n expect(invocations[1]).toMatchObject({ prompt: 'follow up', cwd: fs.realpathSync(cwd) });\n expect(invocations[1].args).toContain('--resume');\n expect(invocations[1].args[invocations[1].args.indexOf('--resume') + 1]).toBe(created.providerSessionId);\n\n const persisted = await store.getById(created.id);\n expect(persisted).toMatchObject({ state: 'ready', sessionHealth: 'healthy' });\n });\n});\n"],"names":["fs","os","path","fileURLToPath","afterEach","describe","expect","it","ClaudeCliProbe","ClaudePrintAgentService","ClaudePrintRunner","PrintAgentStore","roots","originalCapture","process","env","AI_DEVKIT_FAKE_CLAUDE_CAPTURE","undefined","root","splice","rmSync","recursive","force","mkdtempSync","join","tmpdir","push","cwd","mkdirSync","capture","executable","URL","url","store","filePath","service","probe","runner","created","create","name","existsSync","toBe","send","id","resolves","toMatchObject","result","invocations","readFileSync","trim","split","map","line","JSON","parse","prompt","realpathSync","args","toContain","not","indexOf","providerSessionId","persisted","getById","state","sessionHealth"],"mappings":"AAAA,OAAOA,QAAQ,UAAU;AACzB,OAAOC,QAAQ,UAAU;AACzB,OAAOC,UAAU,YAAY;AAC7B,SAASC,aAAa,QAAQ,WAAW;AACzC,SAASC,SAAS,EA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