@ai-devkit/agent-manager 0.25.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 (59) hide show
  1. package/README.md +14 -0
  2. package/dist/__tests__/print/ClaudeCliProbe.test.js +53 -0
  3. package/dist/__tests__/print/ClaudeCliProbe.test.js.map +1 -0
  4. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js +69 -0
  5. package/dist/__tests__/print/ClaudePrintAgent.integration.test.js.map +1 -0
  6. package/dist/__tests__/print/ClaudePrintAgentService.test.js +108 -0
  7. package/dist/__tests__/print/ClaudePrintAgentService.test.js.map +1 -0
  8. package/dist/__tests__/print/ClaudePrintRunner.test.js +187 -0
  9. package/dist/__tests__/print/ClaudePrintRunner.test.js.map +1 -0
  10. package/dist/__tests__/print/PrintAgent.test.js +17 -0
  11. package/dist/__tests__/print/PrintAgent.test.js.map +1 -0
  12. package/dist/__tests__/print/PrintAgentStore.test.js +307 -0
  13. package/dist/__tests__/print/PrintAgentStore.test.js.map +1 -0
  14. package/dist/__tests__/terminal/TmuxManager.test.js +9 -0
  15. package/dist/__tests__/terminal/TmuxManager.test.js.map +1 -1
  16. package/dist/index.d.ts +11 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +6 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/print/ClaudeCliProbe.d.ts +20 -0
  21. package/dist/print/ClaudeCliProbe.d.ts.map +1 -0
  22. package/dist/print/ClaudeCliProbe.js +57 -0
  23. package/dist/print/ClaudeCliProbe.js.map +1 -0
  24. package/dist/print/ClaudePrintAgentService.d.ts +44 -0
  25. package/dist/print/ClaudePrintAgentService.d.ts.map +1 -0
  26. package/dist/print/ClaudePrintAgentService.js +66 -0
  27. package/dist/print/ClaudePrintAgentService.js.map +1 -0
  28. package/dist/print/ClaudePrintRunner.d.ts +32 -0
  29. package/dist/print/ClaudePrintRunner.d.ts.map +1 -0
  30. package/dist/print/ClaudePrintRunner.js +128 -0
  31. package/dist/print/ClaudePrintRunner.js.map +1 -0
  32. package/dist/print/PrintAgent.d.ts +57 -0
  33. package/dist/print/PrintAgent.d.ts.map +1 -0
  34. package/dist/print/PrintAgent.js +42 -0
  35. package/dist/print/PrintAgent.js.map +1 -0
  36. package/dist/print/PrintAgentStore.d.ts +69 -0
  37. package/dist/print/PrintAgentStore.d.ts.map +1 -0
  38. package/dist/print/PrintAgentStore.js +484 -0
  39. package/dist/print/PrintAgentStore.js.map +1 -0
  40. package/dist/terminal/TmuxManager.d.ts +2 -2
  41. package/dist/terminal/TmuxManager.d.ts.map +1 -1
  42. package/dist/terminal/TmuxManager.js +5 -7
  43. package/dist/terminal/TmuxManager.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/__tests__/fixtures/fake-claude.cjs +24 -0
  46. package/src/__tests__/print/ClaudeCliProbe.test.ts +32 -0
  47. package/src/__tests__/print/ClaudePrintAgent.integration.test.ts +56 -0
  48. package/src/__tests__/print/ClaudePrintAgentService.test.ts +46 -0
  49. package/src/__tests__/print/ClaudePrintRunner.test.ts +105 -0
  50. package/src/__tests__/print/PrintAgent.test.ts +21 -0
  51. package/src/__tests__/print/PrintAgentStore.test.ts +192 -0
  52. package/src/__tests__/terminal/TmuxManager.test.ts +10 -0
  53. package/src/index.ts +39 -0
  54. package/src/print/ClaudeCliProbe.ts +58 -0
  55. package/src/print/ClaudePrintAgentService.ts +94 -0
  56. package/src/print/ClaudePrintRunner.ts +139 -0
  57. package/src/print/PrintAgent.ts +86 -0
  58. package/src/print/PrintAgentStore.ts +503 -0
  59. package/src/terminal/TmuxManager.ts +5 -7
@@ -0,0 +1,484 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { randomUUID } from 'crypto';
5
+ import { execFileSync } from 'child_process';
6
+ import { PrintAgentBusyError, PrintAgentNameConflictError, PrintAgentNotFoundError, PrintAgentStoreError } from './PrintAgent.js';
7
+ const DEFAULT_FILE = path.join(os.homedir(), '.ai-devkit', 'print-agents.json');
8
+ export class PrintAgentStore {
9
+ filePath;
10
+ lockPath;
11
+ lockTimeoutMs;
12
+ now;
13
+ processInspector;
14
+ runLocksRoot;
15
+ incompleteLockGraceMs;
16
+ mutationLockStaleMs;
17
+ constructor(options = {}){
18
+ this.filePath = options.filePath ?? DEFAULT_FILE;
19
+ this.lockPath = `${this.filePath}.lock`;
20
+ this.lockTimeoutMs = options.lockTimeoutMs ?? 2000;
21
+ this.now = options.now ?? (()=>new Date());
22
+ this.processInspector = options.processInspector ?? new LocalProcessInspector();
23
+ this.runLocksRoot = path.join(path.dirname(this.filePath), 'print-agent-locks');
24
+ this.incompleteLockGraceMs = options.incompleteLockGraceMs ?? 30_000;
25
+ this.mutationLockStaleMs = options.mutationLockStaleMs ?? 30_000;
26
+ }
27
+ async create(input) {
28
+ const cwd = this.canonicalDirectory(input.cwd);
29
+ return this.withMutationLock(async ()=>{
30
+ const data = this.readFile();
31
+ if (data.agents.some((agent)=>agent.name.toLowerCase() === input.name.toLowerCase())) {
32
+ throw new PrintAgentNameConflictError(input.name);
33
+ }
34
+ const timestamp = this.now().toISOString();
35
+ let id = randomUUID();
36
+ let providerSessionId = randomUUID();
37
+ while(providerSessionId === id)providerSessionId = randomUUID();
38
+ while(data.agents.some((agent)=>agent.id === id))id = randomUUID();
39
+ const agent = {
40
+ id,
41
+ name: input.name,
42
+ provider: 'claude',
43
+ mode: 'print',
44
+ cwd,
45
+ providerSessionId,
46
+ state: 'ready',
47
+ sessionHealth: 'uninitialized',
48
+ createdAt: timestamp,
49
+ updatedAt: timestamp,
50
+ lastActiveAt: null,
51
+ lastResult: null,
52
+ activeRun: null
53
+ };
54
+ data.agents.push(agent);
55
+ this.writeFile(data);
56
+ return structuredClone(agent);
57
+ });
58
+ }
59
+ async list() {
60
+ await this.reconcile();
61
+ return this.listRaw();
62
+ }
63
+ async getById(id) {
64
+ return (await this.list()).find((agent)=>agent.id === id) ?? null;
65
+ }
66
+ async reconcile() {
67
+ const running = this.listRaw().filter((agent)=>agent.state === 'running' && agent.activeRun);
68
+ for (const snapshot of running){
69
+ const lockPath = this.runLockPath(snapshot.id);
70
+ const metadata = this.readRunLock(snapshot.id);
71
+ if (metadata && this.isActive(metadata)) continue;
72
+ if (!metadata && this.isYoungLock(lockPath)) continue;
73
+ if (fs.existsSync(lockPath)) {
74
+ const quarantine = `${lockPath}.stale-${randomUUID()}`;
75
+ try {
76
+ fs.renameSync(lockPath, quarantine);
77
+ this.removeLockDirectory(quarantine);
78
+ } catch {
79
+ continue;
80
+ }
81
+ }
82
+ const completedAt = this.now().toISOString();
83
+ await this.updateAgent(snapshot.id, (current)=>{
84
+ if (current.state !== 'running' || current.activeRun?.token !== snapshot.activeRun?.token) return current;
85
+ return {
86
+ ...current,
87
+ state: 'degraded',
88
+ sessionHealth: 'unknown',
89
+ activeRun: null,
90
+ updatedAt: completedAt,
91
+ lastActiveAt: completedAt,
92
+ lastResult: {
93
+ status: 'interrupted',
94
+ completedAt,
95
+ exitCode: null,
96
+ summary: 'Previous print run was interrupted.'
97
+ }
98
+ };
99
+ });
100
+ }
101
+ }
102
+ async resolve(reference) {
103
+ const agents = await this.list();
104
+ const byId = agents.find((agent)=>agent.id === reference);
105
+ if (byId) return byId;
106
+ const matches = agents.filter((agent)=>agent.name.toLowerCase() === reference.toLowerCase());
107
+ if (matches.length === 0) return null;
108
+ return matches.length === 1 ? matches[0] : matches;
109
+ }
110
+ async acquireRun(id) {
111
+ const existing = await this.getById(id);
112
+ if (!existing) throw new PrintAgentNotFoundError(id);
113
+ this.validateBoundCwd(existing.cwd);
114
+ const runLock = this.runLockPath(id);
115
+ let recoveredStale = false;
116
+ for(;;){
117
+ this.ensureRunLocksRoot();
118
+ this.assertNotSymlink(runLock);
119
+ try {
120
+ fs.mkdirSync(runLock, {
121
+ mode: 0o700
122
+ });
123
+ break;
124
+ } catch (error) {
125
+ if (error.code !== 'EEXIST') {
126
+ throw new PrintAgentStoreError(`Cannot acquire print-agent run lock: ${error.message}`);
127
+ }
128
+ const metadata = this.readRunLock(id);
129
+ if (!metadata || this.isActive(metadata)) {
130
+ throw new PrintAgentBusyError(id, existing.name);
131
+ }
132
+ const quarantine = `${runLock}.stale-${randomUUID()}`;
133
+ try {
134
+ fs.renameSync(runLock, quarantine);
135
+ this.removeLockDirectory(quarantine);
136
+ recoveredStale = true;
137
+ } catch {
138
+ // Another contender changed the lock. Retry and inspect the winner.
139
+ }
140
+ }
141
+ }
142
+ const owner = this.processInspector.getIdentity(process.pid);
143
+ if (!owner) {
144
+ this.removeLockDirectory(runLock);
145
+ throw new PrintAgentStoreError('Cannot determine the current process identity.');
146
+ }
147
+ const token = randomUUID();
148
+ const startedAt = this.now().toISOString();
149
+ const activeRun = {
150
+ token,
151
+ owner,
152
+ provider: null,
153
+ startedAt
154
+ };
155
+ this.writeRunLock(id, activeRun);
156
+ try {
157
+ const agent = await this.updateAgent(id, (current)=>({
158
+ ...current,
159
+ state: 'running',
160
+ activeRun,
161
+ updatedAt: startedAt,
162
+ ...recoveredStale ? {
163
+ sessionHealth: 'unknown',
164
+ lastResult: {
165
+ status: 'interrupted',
166
+ completedAt: startedAt,
167
+ exitCode: null,
168
+ summary: 'Previous print run was interrupted.'
169
+ }
170
+ } : {}
171
+ }));
172
+ return {
173
+ agent,
174
+ token
175
+ };
176
+ } catch (error) {
177
+ this.removeOwnedRunLock(id, token);
178
+ throw error;
179
+ }
180
+ }
181
+ async recordProviderProcess(id, token, identity) {
182
+ const metadata = this.requireOwnedRun(id, token);
183
+ const next = {
184
+ ...metadata,
185
+ provider: identity
186
+ };
187
+ this.writeRunLock(id, next);
188
+ await this.updateAgent(id, (agent)=>{
189
+ if (agent.activeRun?.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');
190
+ return {
191
+ ...agent,
192
+ activeRun: next,
193
+ updatedAt: this.now().toISOString()
194
+ };
195
+ });
196
+ }
197
+ async completeRun(id, token, result) {
198
+ this.requireOwnedRun(id, token);
199
+ const completedAt = this.now().toISOString();
200
+ const agent = await this.updateAgent(id, (current)=>{
201
+ if (current.activeRun?.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');
202
+ return {
203
+ ...current,
204
+ state: result.status === 'succeeded' ? 'ready' : 'degraded',
205
+ sessionHealth: result.sessionHealth,
206
+ activeRun: null,
207
+ lastActiveAt: completedAt,
208
+ updatedAt: completedAt,
209
+ lastResult: {
210
+ status: result.status,
211
+ completedAt,
212
+ exitCode: result.exitCode,
213
+ summary: result.summary.slice(0, 4096)
214
+ }
215
+ };
216
+ });
217
+ this.removeOwnedRunLock(id, token);
218
+ return agent;
219
+ }
220
+ canonicalDirectory(input) {
221
+ try {
222
+ const resolved = fs.realpathSync(input);
223
+ if (!fs.statSync(resolved).isDirectory()) throw new Error('not a directory');
224
+ return resolved;
225
+ } catch {
226
+ throw new PrintAgentStoreError(`Print agent cwd is not an existing directory: ${input}`);
227
+ }
228
+ }
229
+ validateBoundCwd(bound) {
230
+ try {
231
+ const stat = fs.lstatSync(bound);
232
+ if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(bound) !== bound) {
233
+ throw new Error('binding changed');
234
+ }
235
+ } catch {
236
+ throw new PrintAgentStoreError(`Print agent cwd binding is no longer safe: ${bound}`);
237
+ }
238
+ }
239
+ ensureSafeParent() {
240
+ const parent = path.dirname(this.filePath);
241
+ fs.mkdirSync(parent, {
242
+ recursive: true,
243
+ mode: 0o700
244
+ });
245
+ const stat = fs.lstatSync(parent);
246
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
247
+ throw new PrintAgentStoreError(`Unsafe print-agent store directory: ${parent}`);
248
+ }
249
+ return parent;
250
+ }
251
+ ensureRunLocksRoot() {
252
+ this.ensureSafeParent();
253
+ fs.mkdirSync(this.runLocksRoot, {
254
+ recursive: true,
255
+ mode: 0o700
256
+ });
257
+ const stat = fs.lstatSync(this.runLocksRoot);
258
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
259
+ throw new PrintAgentStoreError(`Unsafe print-agent lock directory: ${this.runLocksRoot}`);
260
+ }
261
+ }
262
+ assertNotSymlink(target) {
263
+ try {
264
+ if (fs.lstatSync(target).isSymbolicLink()) {
265
+ throw new PrintAgentStoreError(`Unsafe symbolic link in print-agent storage: ${target}`);
266
+ }
267
+ } catch (error) {
268
+ if (error instanceof PrintAgentStoreError) throw error;
269
+ if (error.code !== 'ENOENT') {
270
+ throw new PrintAgentStoreError(`Cannot inspect print-agent storage: ${target}`);
271
+ }
272
+ }
273
+ }
274
+ readFile() {
275
+ this.ensureSafeParent();
276
+ this.assertNotSymlink(this.filePath);
277
+ if (!fs.existsSync(this.filePath)) return {
278
+ version: 1,
279
+ agents: []
280
+ };
281
+ try {
282
+ const parsed = JSON.parse(fs.readFileSync(this.filePath, 'utf8'));
283
+ if (!this.isStoreFile(parsed)) throw new Error('invalid schema');
284
+ return parsed;
285
+ } catch {
286
+ throw new PrintAgentStoreError(`Invalid print-agent store: ${this.filePath}`);
287
+ }
288
+ }
289
+ listRaw() {
290
+ return this.readFile().agents.map((agent)=>structuredClone(agent));
291
+ }
292
+ isStoreFile(value) {
293
+ if (!value || typeof value !== 'object') return false;
294
+ const record = value;
295
+ return record.version === 1 && Array.isArray(record.agents);
296
+ }
297
+ writeFile(data) {
298
+ const parent = this.ensureSafeParent();
299
+ this.assertNotSymlink(this.filePath);
300
+ const temp = path.join(parent, `.print-agents-${process.pid}-${randomUUID()}.tmp`);
301
+ this.assertNotSymlink(temp);
302
+ let fd;
303
+ try {
304
+ fd = fs.openSync(temp, 'wx', 0o600);
305
+ fs.writeFileSync(fd, JSON.stringify(data, null, 2), 'utf8');
306
+ fs.fsyncSync(fd);
307
+ fs.closeSync(fd);
308
+ fd = undefined;
309
+ fs.renameSync(temp, this.filePath);
310
+ fs.chmodSync(this.filePath, 0o600);
311
+ } catch (error) {
312
+ if (fd !== undefined) fs.closeSync(fd);
313
+ try {
314
+ fs.unlinkSync(temp);
315
+ } catch {}
316
+ if (error instanceof PrintAgentStoreError) throw error;
317
+ throw new PrintAgentStoreError(`Failed to update print-agent store: ${error.message}`);
318
+ }
319
+ }
320
+ async withMutationLock(operation) {
321
+ this.ensureSafeParent();
322
+ const started = Date.now();
323
+ for(;;){
324
+ this.assertNotSymlink(this.lockPath);
325
+ try {
326
+ fs.mkdirSync(this.lockPath, {
327
+ mode: 0o700
328
+ });
329
+ break;
330
+ } catch (error) {
331
+ if (error.code !== 'EEXIST') {
332
+ throw new PrintAgentStoreError(`Cannot acquire print-agent store lock: ${error.message}`);
333
+ }
334
+ if (!this.isYoungMutationLock()) {
335
+ const quarantine = `${this.lockPath}.stale-${randomUUID()}`;
336
+ try {
337
+ fs.renameSync(this.lockPath, quarantine);
338
+ fs.rmdirSync(quarantine);
339
+ continue;
340
+ } catch {
341
+ // Another contender changed the lock. Retry until the bounded timeout.
342
+ }
343
+ }
344
+ if (Date.now() - started >= this.lockTimeoutMs) {
345
+ throw new PrintAgentStoreError('Timed out acquiring print-agent store lock.');
346
+ }
347
+ await new Promise((resolve)=>setTimeout(resolve, 10));
348
+ }
349
+ }
350
+ try {
351
+ return await operation();
352
+ } finally{
353
+ try {
354
+ fs.rmdirSync(this.lockPath);
355
+ } catch {}
356
+ }
357
+ }
358
+ isYoungMutationLock() {
359
+ try {
360
+ this.assertNotSymlink(this.lockPath);
361
+ const stat = fs.statSync(this.lockPath);
362
+ return stat.isDirectory() && Date.now() - stat.mtimeMs < this.mutationLockStaleMs;
363
+ } catch {
364
+ return false;
365
+ }
366
+ }
367
+ async updateAgent(id, update) {
368
+ return this.withMutationLock(async ()=>{
369
+ const data = this.readFile();
370
+ const index = data.agents.findIndex((agent)=>agent.id === id);
371
+ if (index < 0) throw new PrintAgentNotFoundError(id);
372
+ const next = update(data.agents[index]);
373
+ data.agents[index] = next;
374
+ this.writeFile(data);
375
+ return structuredClone(next);
376
+ });
377
+ }
378
+ runLockPath(id) {
379
+ if (!/^[0-9a-f-]{36}$/i.test(id)) throw new PrintAgentStoreError('Invalid print-agent id.');
380
+ return path.join(this.runLocksRoot, `${id}.lock`);
381
+ }
382
+ readRunLock(id) {
383
+ const ownerPath = path.join(this.runLockPath(id), 'owner.json');
384
+ try {
385
+ this.assertNotSymlink(ownerPath);
386
+ const value = JSON.parse(fs.readFileSync(ownerPath, 'utf8'));
387
+ if (!value || typeof value.token !== 'string' || !value.owner || typeof value.owner.pid !== 'number') return null;
388
+ return value;
389
+ } catch {
390
+ return null;
391
+ }
392
+ }
393
+ writeRunLock(id, metadata) {
394
+ const lockPath = this.runLockPath(id);
395
+ const ownerPath = path.join(lockPath, 'owner.json');
396
+ const tempPath = path.join(lockPath, `.owner-${randomUUID()}.tmp`);
397
+ this.assertNotSymlink(lockPath);
398
+ this.assertNotSymlink(ownerPath);
399
+ fs.writeFileSync(tempPath, JSON.stringify(metadata), {
400
+ encoding: 'utf8',
401
+ mode: 0o600,
402
+ flag: 'wx'
403
+ });
404
+ fs.renameSync(tempPath, ownerPath);
405
+ }
406
+ requireOwnedRun(id, token) {
407
+ const metadata = this.readRunLock(id);
408
+ if (!metadata || metadata.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');
409
+ return metadata;
410
+ }
411
+ isActive(metadata) {
412
+ return this.sameProcess(metadata.owner) || metadata.provider !== null && this.sameProcess(metadata.provider);
413
+ }
414
+ sameProcess(expected) {
415
+ const actual = this.processInspector.getIdentity(expected.pid);
416
+ return actual !== null && actual.startedAt === expected.startedAt;
417
+ }
418
+ isYoungLock(lockPath) {
419
+ try {
420
+ this.assertNotSymlink(lockPath);
421
+ return Date.now() - fs.statSync(lockPath).mtimeMs < this.incompleteLockGraceMs;
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
426
+ removeOwnedRunLock(id, token) {
427
+ const metadata = this.readRunLock(id);
428
+ if (!metadata || metadata.token !== token) return;
429
+ this.removeLockDirectory(this.runLockPath(id));
430
+ }
431
+ removeLockDirectory(lockPath) {
432
+ this.assertNotSymlink(lockPath);
433
+ try {
434
+ for (const name of fs.readdirSync(lockPath)){
435
+ const entry = path.join(lockPath, name);
436
+ this.assertNotSymlink(entry);
437
+ if (!fs.lstatSync(entry).isFile()) throw new PrintAgentStoreError(`Unsafe entry in print-agent lock: ${entry}`);
438
+ fs.unlinkSync(entry);
439
+ }
440
+ fs.rmdirSync(lockPath);
441
+ } catch (error) {
442
+ if (error.code !== 'ENOENT') throw error;
443
+ }
444
+ }
445
+ }
446
+ export class LocalProcessInspector {
447
+ getIdentity(pid) {
448
+ if (!Number.isInteger(pid) || pid <= 0) return null;
449
+ try {
450
+ if (process.platform === 'linux') {
451
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
452
+ const close = stat.lastIndexOf(')');
453
+ const fields = stat.slice(close + 2).split(' ');
454
+ const startTicks = fields[19];
455
+ if (!startTicks) return null;
456
+ return {
457
+ pid,
458
+ startedAt: `linux:${startTicks}`
459
+ };
460
+ }
461
+ const startedAt = execFileSync('ps', [
462
+ '-o',
463
+ 'lstart=',
464
+ '-p',
465
+ String(pid)
466
+ ], {
467
+ encoding: 'utf8',
468
+ stdio: [
469
+ 'ignore',
470
+ 'pipe',
471
+ 'ignore'
472
+ ]
473
+ }).trim();
474
+ return startedAt ? {
475
+ pid,
476
+ startedAt
477
+ } : null;
478
+ } catch {
479
+ return null;
480
+ }
481
+ }
482
+ }
483
+
484
+ //# sourceMappingURL=PrintAgentStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/print/PrintAgentStore.ts"],"sourcesContent":["import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport { randomUUID } from 'crypto';\nimport { execFileSync } from 'child_process';\nimport type { PrintAgent, ProcessIdentity, PrintRunStatus, PrintSessionHealth } from './PrintAgent.js';\nimport {\n PrintAgentBusyError,\n PrintAgentNameConflictError,\n PrintAgentNotFoundError,\n PrintAgentStoreError,\n} from './PrintAgent.js';\n\ninterface PrintAgentStoreFile {\n version: 1;\n agents: PrintAgent[];\n}\n\nexport interface CreatePrintAgentInput {\n name: string;\n cwd: string;\n}\n\nexport interface PrintAgentStoreOptions {\n filePath?: string;\n lockTimeoutMs?: number;\n now?: () => Date;\n processInspector?: ProcessInspector;\n incompleteLockGraceMs?: number;\n mutationLockStaleMs?: number;\n}\n\nexport interface ProcessInspector {\n getIdentity(pid: number): ProcessIdentity | null;\n}\n\nexport interface PrintRunCompletion {\n status: PrintRunStatus;\n exitCode: number | null;\n summary: string;\n sessionHealth: PrintSessionHealth;\n}\n\nconst DEFAULT_FILE = path.join(os.homedir(), '.ai-devkit', 'print-agents.json');\n\nexport class PrintAgentStore {\n readonly filePath: string;\n private readonly lockPath: string;\n private readonly lockTimeoutMs: number;\n private readonly now: () => Date;\n private readonly processInspector: ProcessInspector;\n private readonly runLocksRoot: string;\n private readonly incompleteLockGraceMs: number;\n private readonly mutationLockStaleMs: number;\n\n constructor(options: PrintAgentStoreOptions = {}) {\n this.filePath = options.filePath ?? DEFAULT_FILE;\n this.lockPath = `${this.filePath}.lock`;\n this.lockTimeoutMs = options.lockTimeoutMs ?? 2000;\n this.now = options.now ?? (() => new Date());\n this.processInspector = options.processInspector ?? new LocalProcessInspector();\n this.runLocksRoot = path.join(path.dirname(this.filePath), 'print-agent-locks');\n this.incompleteLockGraceMs = options.incompleteLockGraceMs ?? 30_000;\n this.mutationLockStaleMs = options.mutationLockStaleMs ?? 30_000;\n }\n\n async create(input: CreatePrintAgentInput): Promise<PrintAgent> {\n const cwd = this.canonicalDirectory(input.cwd);\n return this.withMutationLock(async () => {\n const data = this.readFile();\n if (data.agents.some((agent) => agent.name.toLowerCase() === input.name.toLowerCase())) {\n throw new PrintAgentNameConflictError(input.name);\n }\n const timestamp = this.now().toISOString();\n let id = randomUUID();\n let providerSessionId = randomUUID();\n while (providerSessionId === id) providerSessionId = randomUUID();\n while (data.agents.some((agent) => agent.id === id)) id = randomUUID();\n const agent: PrintAgent = {\n id,\n name: input.name,\n provider: 'claude',\n mode: 'print',\n cwd,\n providerSessionId,\n state: 'ready',\n sessionHealth: 'uninitialized',\n createdAt: timestamp,\n updatedAt: timestamp,\n lastActiveAt: null,\n lastResult: null,\n activeRun: null,\n };\n data.agents.push(agent);\n this.writeFile(data);\n return structuredClone(agent);\n });\n }\n\n async list(): Promise<PrintAgent[]> {\n await this.reconcile();\n return this.listRaw();\n }\n\n async getById(id: string): Promise<PrintAgent | null> {\n return (await this.list()).find((agent) => agent.id === id) ?? null;\n }\n\n async reconcile(): Promise<void> {\n const running = this.listRaw().filter((agent) => agent.state === 'running' && agent.activeRun);\n for (const snapshot of running) {\n const lockPath = this.runLockPath(snapshot.id);\n const metadata = this.readRunLock(snapshot.id);\n if (metadata && this.isActive(metadata)) continue;\n if (!metadata && this.isYoungLock(lockPath)) continue;\n\n if (fs.existsSync(lockPath)) {\n const quarantine = `${lockPath}.stale-${randomUUID()}`;\n try {\n fs.renameSync(lockPath, quarantine);\n this.removeLockDirectory(quarantine);\n } catch {\n continue;\n }\n }\n const completedAt = this.now().toISOString();\n await this.updateAgent(snapshot.id, (current) => {\n if (current.state !== 'running' || current.activeRun?.token !== snapshot.activeRun?.token) return current;\n return {\n ...current,\n state: 'degraded',\n sessionHealth: 'unknown',\n activeRun: null,\n updatedAt: completedAt,\n lastActiveAt: completedAt,\n lastResult: {\n status: 'interrupted',\n completedAt,\n exitCode: null,\n summary: 'Previous print run was interrupted.',\n },\n };\n });\n }\n }\n\n async resolve(reference: string): Promise<PrintAgent | PrintAgent[] | null> {\n const agents = await this.list();\n const byId = agents.find((agent) => agent.id === reference);\n if (byId) return byId;\n const matches = agents.filter((agent) => agent.name.toLowerCase() === reference.toLowerCase());\n if (matches.length === 0) return null;\n return matches.length === 1 ? matches[0]! : matches;\n }\n\n async acquireRun(id: string): Promise<{ agent: PrintAgent; token: string }> {\n const existing = await this.getById(id);\n if (!existing) throw new PrintAgentNotFoundError(id);\n this.validateBoundCwd(existing.cwd);\n const runLock = this.runLockPath(id);\n let recoveredStale = false;\n\n for (;;) {\n this.ensureRunLocksRoot();\n this.assertNotSymlink(runLock);\n try {\n fs.mkdirSync(runLock, { mode: 0o700 });\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw new PrintAgentStoreError(`Cannot acquire print-agent run lock: ${(error as Error).message}`);\n }\n const metadata = this.readRunLock(id);\n if (!metadata || this.isActive(metadata)) {\n throw new PrintAgentBusyError(id, existing.name);\n }\n const quarantine = `${runLock}.stale-${randomUUID()}`;\n try {\n fs.renameSync(runLock, quarantine);\n this.removeLockDirectory(quarantine);\n recoveredStale = true;\n } catch {\n // Another contender changed the lock. Retry and inspect the winner.\n }\n }\n }\n\n const owner = this.processInspector.getIdentity(process.pid);\n if (!owner) {\n this.removeLockDirectory(runLock);\n throw new PrintAgentStoreError('Cannot determine the current process identity.');\n }\n const token = randomUUID();\n const startedAt = this.now().toISOString();\n const activeRun = { token, owner, provider: null, startedAt };\n this.writeRunLock(id, activeRun);\n\n try {\n const agent = await this.updateAgent(id, (current) => ({\n ...current,\n state: 'running',\n activeRun,\n updatedAt: startedAt,\n ...(recoveredStale ? {\n sessionHealth: 'unknown' as const,\n lastResult: {\n status: 'interrupted' as const,\n completedAt: startedAt,\n exitCode: null,\n summary: 'Previous print run was interrupted.',\n },\n } : {}),\n }));\n return { agent, token };\n } catch (error) {\n this.removeOwnedRunLock(id, token);\n throw error;\n }\n }\n\n async recordProviderProcess(id: string, token: string, identity: ProcessIdentity): Promise<void> {\n const metadata = this.requireOwnedRun(id, token);\n const next = { ...metadata, provider: identity };\n this.writeRunLock(id, next);\n await this.updateAgent(id, (agent) => {\n if (agent.activeRun?.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');\n return { ...agent, activeRun: next, updatedAt: this.now().toISOString() };\n });\n }\n\n async completeRun(id: string, token: string, result: PrintRunCompletion): Promise<PrintAgent> {\n this.requireOwnedRun(id, token);\n const completedAt = this.now().toISOString();\n const agent = await this.updateAgent(id, (current) => {\n if (current.activeRun?.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');\n return {\n ...current,\n state: result.status === 'succeeded' ? 'ready' : 'degraded',\n sessionHealth: result.sessionHealth,\n activeRun: null,\n lastActiveAt: completedAt,\n updatedAt: completedAt,\n lastResult: {\n status: result.status,\n completedAt,\n exitCode: result.exitCode,\n summary: result.summary.slice(0, 4096),\n },\n };\n });\n this.removeOwnedRunLock(id, token);\n return agent;\n }\n\n private canonicalDirectory(input: string): string {\n try {\n const resolved = fs.realpathSync(input);\n if (!fs.statSync(resolved).isDirectory()) throw new Error('not a directory');\n return resolved;\n } catch {\n throw new PrintAgentStoreError(`Print agent cwd is not an existing directory: ${input}`);\n }\n }\n\n private validateBoundCwd(bound: string): void {\n try {\n const stat = fs.lstatSync(bound);\n if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(bound) !== bound) {\n throw new Error('binding changed');\n }\n } catch {\n throw new PrintAgentStoreError(`Print agent cwd binding is no longer safe: ${bound}`);\n }\n }\n\n private ensureSafeParent(): string {\n const parent = path.dirname(this.filePath);\n fs.mkdirSync(parent, { recursive: true, mode: 0o700 });\n const stat = fs.lstatSync(parent);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new PrintAgentStoreError(`Unsafe print-agent store directory: ${parent}`);\n }\n return parent;\n }\n\n private ensureRunLocksRoot(): void {\n this.ensureSafeParent();\n fs.mkdirSync(this.runLocksRoot, { recursive: true, mode: 0o700 });\n const stat = fs.lstatSync(this.runLocksRoot);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new PrintAgentStoreError(`Unsafe print-agent lock directory: ${this.runLocksRoot}`);\n }\n }\n\n private assertNotSymlink(target: string): void {\n try {\n if (fs.lstatSync(target).isSymbolicLink()) {\n throw new PrintAgentStoreError(`Unsafe symbolic link in print-agent storage: ${target}`);\n }\n } catch (error) {\n if (error instanceof PrintAgentStoreError) throw error;\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw new PrintAgentStoreError(`Cannot inspect print-agent storage: ${target}`);\n }\n }\n }\n\n private readFile(): PrintAgentStoreFile {\n this.ensureSafeParent();\n this.assertNotSymlink(this.filePath);\n if (!fs.existsSync(this.filePath)) return { version: 1, agents: [] };\n try {\n const parsed = JSON.parse(fs.readFileSync(this.filePath, 'utf8')) as unknown;\n if (!this.isStoreFile(parsed)) throw new Error('invalid schema');\n return parsed;\n } catch {\n throw new PrintAgentStoreError(`Invalid print-agent store: ${this.filePath}`);\n }\n }\n\n private listRaw(): PrintAgent[] {\n return this.readFile().agents.map((agent) => structuredClone(agent));\n }\n\n private isStoreFile(value: unknown): value is PrintAgentStoreFile {\n if (!value || typeof value !== 'object') return false;\n const record = value as Record<string, unknown>;\n return record.version === 1 && Array.isArray(record.agents);\n }\n\n private writeFile(data: PrintAgentStoreFile): void {\n const parent = this.ensureSafeParent();\n this.assertNotSymlink(this.filePath);\n const temp = path.join(parent, `.print-agents-${process.pid}-${randomUUID()}.tmp`);\n this.assertNotSymlink(temp);\n let fd: number | undefined;\n try {\n fd = fs.openSync(temp, 'wx', 0o600);\n fs.writeFileSync(fd, JSON.stringify(data, null, 2), 'utf8');\n fs.fsyncSync(fd);\n fs.closeSync(fd);\n fd = undefined;\n fs.renameSync(temp, this.filePath);\n fs.chmodSync(this.filePath, 0o600);\n } catch (error) {\n if (fd !== undefined) fs.closeSync(fd);\n try { fs.unlinkSync(temp); } catch { /* best effort */ }\n if (error instanceof PrintAgentStoreError) throw error;\n throw new PrintAgentStoreError(`Failed to update print-agent store: ${(error as Error).message}`);\n }\n }\n\n private async withMutationLock<T>(operation: () => Promise<T>): Promise<T> {\n this.ensureSafeParent();\n const started = Date.now();\n for (;;) {\n this.assertNotSymlink(this.lockPath);\n try {\n fs.mkdirSync(this.lockPath, { mode: 0o700 });\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw new PrintAgentStoreError(`Cannot acquire print-agent store lock: ${(error as Error).message}`);\n }\n if (!this.isYoungMutationLock()) {\n const quarantine = `${this.lockPath}.stale-${randomUUID()}`;\n try {\n fs.renameSync(this.lockPath, quarantine);\n fs.rmdirSync(quarantine);\n continue;\n } catch {\n // Another contender changed the lock. Retry until the bounded timeout.\n }\n }\n if (Date.now() - started >= this.lockTimeoutMs) {\n throw new PrintAgentStoreError('Timed out acquiring print-agent store lock.');\n }\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n }\n try {\n return await operation();\n } finally {\n try { fs.rmdirSync(this.lockPath); } catch { /* surfaced by later contention */ }\n }\n }\n\n private isYoungMutationLock(): boolean {\n try {\n this.assertNotSymlink(this.lockPath);\n const stat = fs.statSync(this.lockPath);\n return stat.isDirectory() && Date.now() - stat.mtimeMs < this.mutationLockStaleMs;\n } catch {\n return false;\n }\n }\n\n private async updateAgent(id: string, update: (agent: PrintAgent) => PrintAgent): Promise<PrintAgent> {\n return this.withMutationLock(async () => {\n const data = this.readFile();\n const index = data.agents.findIndex((agent) => agent.id === id);\n if (index < 0) throw new PrintAgentNotFoundError(id);\n const next = update(data.agents[index]!);\n data.agents[index] = next;\n this.writeFile(data);\n return structuredClone(next);\n });\n }\n\n private runLockPath(id: string): string {\n if (!/^[0-9a-f-]{36}$/i.test(id)) throw new PrintAgentStoreError('Invalid print-agent id.');\n return path.join(this.runLocksRoot, `${id}.lock`);\n }\n\n private readRunLock(id: string): import('./PrintAgent.js').PrintActiveRun | null {\n const ownerPath = path.join(this.runLockPath(id), 'owner.json');\n try {\n this.assertNotSymlink(ownerPath);\n const value = JSON.parse(fs.readFileSync(ownerPath, 'utf8')) as import('./PrintAgent.js').PrintActiveRun;\n if (!value || typeof value.token !== 'string' || !value.owner || typeof value.owner.pid !== 'number') return null;\n return value;\n } catch {\n return null;\n }\n }\n\n private writeRunLock(id: string, metadata: import('./PrintAgent.js').PrintActiveRun): void {\n const lockPath = this.runLockPath(id);\n const ownerPath = path.join(lockPath, 'owner.json');\n const tempPath = path.join(lockPath, `.owner-${randomUUID()}.tmp`);\n this.assertNotSymlink(lockPath);\n this.assertNotSymlink(ownerPath);\n fs.writeFileSync(tempPath, JSON.stringify(metadata), { encoding: 'utf8', mode: 0o600, flag: 'wx' });\n fs.renameSync(tempPath, ownerPath);\n }\n\n private requireOwnedRun(id: string, token: string): import('./PrintAgent.js').PrintActiveRun {\n const metadata = this.readRunLock(id);\n if (!metadata || metadata.token !== token) throw new PrintAgentStoreError('Print run ownership changed.');\n return metadata;\n }\n\n private isActive(metadata: import('./PrintAgent.js').PrintActiveRun): boolean {\n return this.sameProcess(metadata.owner) || (metadata.provider !== null && this.sameProcess(metadata.provider));\n }\n\n private sameProcess(expected: ProcessIdentity): boolean {\n const actual = this.processInspector.getIdentity(expected.pid);\n return actual !== null && actual.startedAt === expected.startedAt;\n }\n\n private isYoungLock(lockPath: string): boolean {\n try {\n this.assertNotSymlink(lockPath);\n return Date.now() - fs.statSync(lockPath).mtimeMs < this.incompleteLockGraceMs;\n } catch {\n return false;\n }\n }\n\n private removeOwnedRunLock(id: string, token: string): void {\n const metadata = this.readRunLock(id);\n if (!metadata || metadata.token !== token) return;\n this.removeLockDirectory(this.runLockPath(id));\n }\n\n private removeLockDirectory(lockPath: string): void {\n this.assertNotSymlink(lockPath);\n try {\n for (const name of fs.readdirSync(lockPath)) {\n const entry = path.join(lockPath, name);\n this.assertNotSymlink(entry);\n if (!fs.lstatSync(entry).isFile()) throw new PrintAgentStoreError(`Unsafe entry in print-agent lock: ${entry}`);\n fs.unlinkSync(entry);\n }\n fs.rmdirSync(lockPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n }\n}\n\nexport class LocalProcessInspector implements ProcessInspector {\n getIdentity(pid: number): ProcessIdentity | null {\n if (!Number.isInteger(pid) || pid <= 0) return null;\n try {\n if (process.platform === 'linux') {\n const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');\n const close = stat.lastIndexOf(')');\n const fields = stat.slice(close + 2).split(' ');\n const startTicks = fields[19];\n if (!startTicks) return null;\n return { pid, startedAt: `linux:${startTicks}` };\n }\n const startedAt = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {\n encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n return startedAt ? { pid, startedAt } : null;\n } catch {\n return null;\n }\n }\n}\n"],"names":["fs","os","path","randomUUID","execFileSync","PrintAgentBusyError","PrintAgentNameConflictError","PrintAgentNotFoundError","PrintAgentStoreError","DEFAULT_FILE","join","homedir","PrintAgentStore","filePath","lockPath","lockTimeoutMs","now","processInspector","runLocksRoot","incompleteLockGraceMs","mutationLockStaleMs","options","Date","LocalProcessInspector","dirname","create","input","cwd","canonicalDirectory","withMutationLock","data","readFile","agents","some","agent","name","toLowerCase","timestamp","toISOString","id","providerSessionId","provider","mode","state","sessionHealth","createdAt","updatedAt","lastActiveAt","lastResult","activeRun","push","writeFile","structuredClone","list","reconcile","listRaw","getById","find","running","filter","snapshot","runLockPath","metadata","readRunLock","isActive","isYoungLock","existsSync","quarantine","renameSync","removeLockDirectory","completedAt","updateAgent","current","token","status","exitCode","summary","resolve","reference","byId","matches","length","acquireRun","existing","validateBoundCwd","runLock","recoveredStale","ensureRunLocksRoot","assertNotSymlink","mkdirSync","error","code","message","owner","getIdentity","process","pid","startedAt","writeRunLock","removeOwnedRunLock","recordProviderProcess","identity","requireOwnedRun","next","completeRun","result","slice","resolved","realpathSync","statSync","isDirectory","Error","bound","stat","lstatSync","isSymbolicLink","ensureSafeParent","parent","recursive","target","version","parsed","JSON","parse","readFileSync","isStoreFile","map","value","record","Array","isArray","temp","fd","openSync","writeFileSync","stringify","fsyncSync","closeSync","undefined","chmodSync","unlinkSync","operation","started","isYoungMutationLock","rmdirSync","Promise","setTimeout","mtimeMs","update","index","findIndex","test","ownerPath","tempPath","encoding","flag","sameProcess","expected","actual","readdirSync","entry","isFile","Number","isInteger","platform","close","lastIndexOf","fields","split","startTicks","String","stdio","trim"],"mappings":"AAAA,OAAOA,QAAQ,KAAK;AACpB,OAAOC,QAAQ,KAAK;AACpB,OAAOC,UAAU,OAAO;AACx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AAE,OAAM;YACJ,OAAO;QACX;IACJ;AACJ"}
@@ -7,7 +7,7 @@ export declare class TmuxManager {
7
7
  /**
8
8
  * Find the actual agent process PID inside a tmux pane.
9
9
  *
10
- * Strategy: BFS the process tree, return the deepest descendant whose
10
+ * Strategy: BFS the process tree, return the deepest process whose
11
11
  * `ps` command line is accepted by `matches`. The caller supplies the
12
12
  * matcher so this method has no agent-type knowledge.
13
13
  *
@@ -17,7 +17,7 @@ export declare class TmuxManager {
17
17
  * - Subprocess case: shell → claude (matches) → MCP server child (doesn't match)
18
18
  * → returns claude, not the subprocess
19
19
  *
20
- * Returns null when no descendant matches yet (agent still starting); the
20
+ * Returns null when no process matches yet (agent still starting); the
21
21
  * caller's poll loop retries.
22
22
  */
23
23
  findAgentPid(session: string, matches: (psCommand: string) => boolean): Promise<number | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"TmuxManager.d.ts","sourceRoot":"","sources":["../../src/terminal/TmuxManager.ts"],"names":[],"mappings":"AAKA,qBAAa,WAAW;IACd,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAS/B,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAS7C,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIvD,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAItD,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ9C;;;;;;;;;;;;;;;OAeG;IACG,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;YA2BtF,UAAU;YAYV,aAAa;YAab,iBAAiB;CASlC"}
1
+ {"version":3,"file":"TmuxManager.d.ts","sourceRoot":"","sources":["../../src/terminal/TmuxManager.ts"],"names":[],"mappings":"AAKA,qBAAa,WAAW;IACd,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAS/B,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAS7C,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIvD,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAItD,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ9C;;;;;;;;;;;;;;;OAeG;IACG,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;YAyBtF,UAAU;YAYV,aAAa;YAab,iBAAiB;CASlC"}
@@ -57,7 +57,7 @@ export class TmuxManager {
57
57
  /**
58
58
  * Find the actual agent process PID inside a tmux pane.
59
59
  *
60
- * Strategy: BFS the process tree, return the deepest descendant whose
60
+ * Strategy: BFS the process tree, return the deepest process whose
61
61
  * `ps` command line is accepted by `matches`. The caller supplies the
62
62
  * matcher so this method has no agent-type knowledge.
63
63
  *
@@ -67,7 +67,7 @@ export class TmuxManager {
67
67
  * - Subprocess case: shell → claude (matches) → MCP server child (doesn't match)
68
68
  * → returns claude, not the subprocess
69
69
  *
70
- * Returns null when no descendant matches yet (agent still starting); the
70
+ * Returns null when no process matches yet (agent still starting); the
71
71
  * caller's poll loop retries.
72
72
  */ async findAgentPid(session, matches) {
73
73
  const panePid = await this.getPanePid(session);
@@ -81,11 +81,9 @@ export class TmuxManager {
81
81
  const pid = queue.shift();
82
82
  if (visited.has(pid)) continue;
83
83
  visited.add(pid);
84
- if (pid !== panePid) {
85
- const command = await this.getProcessCommand(pid);
86
- if (command && matches(command)) {
87
- deepestMatch = pid;
88
- }
84
+ const command = await this.getProcessCommand(pid);
85
+ if (command && matches(command)) {
86
+ deepestMatch = pid;
89
87
  }
90
88
  const children = await this.pgrepChildren(pid);
91
89
  queue.push(...children);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/terminal/TmuxManager.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\n\nconst execFileAsync = promisify(execFile);\n\nexport class TmuxManager {\n async isAvailable(): Promise<boolean> {\n try {\n await execFileAsync('tmux', ['-V']);\n return true;\n } catch {\n return false;\n }\n }\n\n async sessionExists(name: string): Promise<boolean> {\n try {\n await execFileAsync('tmux', ['has-session', '-t', name]);\n return true;\n } catch {\n return false;\n }\n }\n\n async createSession(name: string, cwd: string): Promise<void> {\n await execFileAsync('tmux', ['new-session', '-d', '-s', name, '-c', cwd]);\n }\n\n async sendKeys(session: string, keys: string): Promise<void> {\n await execFileAsync('tmux', ['send-keys', '-t', session, keys, 'Enter']);\n }\n\n async killSession(name: string): Promise<void> {\n try {\n await execFileAsync('tmux', ['kill-session', '-t', name]);\n } catch {\n // Already gone — ignore\n }\n }\n\n /**\n * Find the actual agent process PID inside a tmux pane.\n *\n * Strategy: BFS the process tree, return the deepest descendant whose\n * `ps` command line is accepted by `matches`. The caller supplies the\n * matcher so this method has no agent-type knowledge.\n *\n * This handles two real-world process shapes:\n * - Wrapper case: shell → claude-wrapper (matches) → claude (matches, deeper)\n * → returns the deeper one\n * - Subprocess case: shell → claude (matches) → MCP server child (doesn't match)\n * → returns claude, not the subprocess\n *\n * Returns null when no descendant matches yet (agent still starting); the\n * caller's poll loop retries.\n */\n async findAgentPid(session: string, matches: (psCommand: string) => boolean): Promise<number | null> {\n const panePid = await this.getPanePid(session);\n if (panePid === null) return null;\n\n const visited = new Set<number>();\n const queue: number[] = [panePid];\n let deepestMatch: number | null = null;\n\n while (queue.length > 0) {\n const pid = queue.shift()!;\n if (visited.has(pid)) continue;\n visited.add(pid);\n\n if (pid !== panePid) {\n const command = await this.getProcessCommand(pid);\n if (command && matches(command)) {\n deepestMatch = pid;\n }\n }\n\n const children = await this.pgrepChildren(pid);\n queue.push(...children);\n }\n\n return deepestMatch;\n }\n\n private async getPanePid(session: string): Promise<number | null> {\n try {\n const { stdout } = await execFileAsync('tmux', [\n 'list-panes', '-t', session, '-F', '#{pane_pid}',\n ]);\n const panePid = parseInt(stdout.trim().split('\\n')[0], 10);\n return isNaN(panePid) ? null : panePid;\n } catch {\n return null;\n }\n }\n\n private async pgrepChildren(pid: number): Promise<number[]> {\n try {\n const { stdout } = await execFileAsync('pgrep', ['-P', String(pid)]);\n return stdout\n .trim()\n .split('\\n')\n .map((s) => parseInt(s, 10))\n .filter((n) => !isNaN(n));\n } catch {\n return [];\n }\n }\n\n private async getProcessCommand(pid: number): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'command=']);\n const trimmed = stdout.trim();\n return trimmed || null;\n } catch {\n return null;\n }\n }\n}\n"],"names":["execFile","promisify","execFileAsync","TmuxManager","isAvailable","sessionExists","name","createSession","cwd","sendKeys","session","keys","killSession","findAgentPid","matches","panePid","getPanePid","visited","Set","queue","deepestMatch","length","pid","shift","has","add","command","getProcessCommand","children","pgrepChildren","push","stdout","parseInt","trim","split","isNaN","String","map","s","filter","n","trimmed"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC,gBAAgBD,UAAUD;AAEhC,OAAO,MAAMG;IACT,MAAMC,cAAgC;QAClC,IAAI;YACA,MAAMF,cAAc,QAAQ;gBAAC;aAAK;YAClC,OAAO;QACX,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;IAEA,MAAMG,cAAcC,IAAY,EAAoB;QAChD,IAAI;YACA,MAAMJ,cAAc,QAAQ;gBAAC;gBAAe;gBAAMI;aAAK;YACvD,OAAO;QACX,EAAE,OAAM;YACJ,OA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,KAAK,CAAC,KAAK,CAAC,EAAE,EAAE;YACvD,OAAOC,MAAMpB,WAAW,OAAOA;QACnC,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;IAEA,MAAcc,cAAcP,GAAW,EAAqB;QACxD,IAAI;YACA,MAAM,EAAES,MAAM,EAAE,GAAG,MAAM7B,cAAc,SAAS;gBAAC;gBAAMkC,OAAOd;aAAK;YACnE,OAAOS,OACFE,IAAI,GACJC,KAAK,CAAC,MACNG,GAAG,CAAC,CAACC,IAAMN,SAASM,GAAG,KACvBC,MAAM,CAAC,CAACC,IAAM,CAACL,MAAMK;QAC9B,EAAE,OAAM;YACJ,OAAO,EAAE;QACb;IACJ;IAEA,MAAcb,kBAAkBL,GAAW,EAA0B;QACjE,IAAI;YACA,MAAM,EAAES,MAAM,EAAE,GAAG,MAAM7B,cAAc,MAAM;gBAAC;gBAAMkC,OAAOd;gBAAM;gBAAM;aAAW;YAClF,MAAMmB,UAAUV,OAAOE,IAAI;YAC3B,OAAOQ,WAAW;QACtB,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;AACJ"}
1
+ {"version":3,"sources":["../../src/terminal/TmuxManager.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\n\nconst execFileAsync = promisify(execFile);\n\nexport class TmuxManager {\n async isAvailable(): Promise<boolean> {\n try {\n await execFileAsync('tmux', ['-V']);\n return true;\n } catch {\n return false;\n }\n }\n\n async sessionExists(name: string): Promise<boolean> {\n try {\n await execFileAsync('tmux', ['has-session', '-t', name]);\n return true;\n } catch {\n return false;\n }\n }\n\n async createSession(name: string, cwd: string): Promise<void> {\n await execFileAsync('tmux', ['new-session', '-d', '-s', name, '-c', cwd]);\n }\n\n async sendKeys(session: string, keys: string): Promise<void> {\n await execFileAsync('tmux', ['send-keys', '-t', session, keys, 'Enter']);\n }\n\n async killSession(name: string): Promise<void> {\n try {\n await execFileAsync('tmux', ['kill-session', '-t', name]);\n } catch {\n // Already gone — ignore\n }\n }\n\n /**\n * Find the actual agent process PID inside a tmux pane.\n *\n * Strategy: BFS the process tree, return the deepest process whose\n * `ps` command line is accepted by `matches`. The caller supplies the\n * matcher so this method has no agent-type knowledge.\n *\n * This handles two real-world process shapes:\n * - Wrapper case: shell → claude-wrapper (matches) → claude (matches, deeper)\n * → returns the deeper one\n * - Subprocess case: shell → claude (matches) → MCP server child (doesn't match)\n * → returns claude, not the subprocess\n *\n * Returns null when no process matches yet (agent still starting); the\n * caller's poll loop retries.\n */\n async findAgentPid(session: string, matches: (psCommand: string) => boolean): Promise<number | null> {\n const panePid = await this.getPanePid(session);\n if (panePid === null) return null;\n\n const visited = new Set<number>();\n const queue: number[] = [panePid];\n let deepestMatch: number | null = null;\n\n while (queue.length > 0) {\n const pid = queue.shift()!;\n if (visited.has(pid)) continue;\n visited.add(pid);\n\n const command = await this.getProcessCommand(pid);\n if (command && matches(command)) {\n deepestMatch = pid;\n }\n\n const children = await this.pgrepChildren(pid);\n queue.push(...children);\n }\n\n return deepestMatch;\n }\n\n private async getPanePid(session: string): Promise<number | null> {\n try {\n const { stdout } = await execFileAsync('tmux', [\n 'list-panes', '-t', session, '-F', '#{pane_pid}',\n ]);\n const panePid = parseInt(stdout.trim().split('\\n')[0], 10);\n return isNaN(panePid) ? null : panePid;\n } catch {\n return null;\n }\n }\n\n private async pgrepChildren(pid: number): Promise<number[]> {\n try {\n const { stdout } = await execFileAsync('pgrep', ['-P', String(pid)]);\n return stdout\n .trim()\n .split('\\n')\n .map((s) => parseInt(s, 10))\n .filter((n) => !isNaN(n));\n } catch {\n return [];\n }\n }\n\n private async getProcessCommand(pid: number): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'command=']);\n const trimmed = stdout.trim();\n return trimmed || null;\n } catch {\n return null;\n }\n }\n}\n"],"names":["execFile","promisify","execFileAsync","TmuxManager","isAvailable","sessionExists","name","createSession","cwd","sendKeys","session","keys","killSession","findAgentPid","matches","panePid","getPanePid","visited","Set","queue","deepestMatch","length","pid","shift","has","add","command","getProcessCommand","children","pgrepChildren","push","stdout","parseInt","trim","split","isNaN","String","map","s","filter","n","trimmed"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC,gBAAgBD,UAAUD;AAEhC,OAAO,MAAMG;IACT,MAAMC,cAAgC;QAClC,IAAI;YACA,MAAMF,cAAc,QAAQ;gBAAC;aAAK;YAClC,OAAO;QACX,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;IAEA,MAAMG,cAAcC,IAAY,EAAoB;QAChD,IAAI;YACA,MAAMJ,cAAc,QAAQ;gBAAC;gBAAe;gBAAMI;aAAK;YACvD,OAAO;QACX,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;IAEA,MAAMC,cAAcD,IAAY,EAAEE,GAAW,EAAiB;QAC1D,MAAMN,cAAc,QAAQ;YAAC;YAAe;YAAM;YAAMI;YAAM;YAAME;SAAI;IAC5E;IAEA,MAAMC,SAASC,OAAe,EAAEC,IAAY,EAAiB;QACzD,MAAMT,cAAc,QAAQ;YAAC;YAAa;YAAMQ;YAASC;YAAM;SAAQ;IAC3E;IAEA,MAAMC,YAAYN,IAAY,EAAiB;QAC3C,IAAI;YACA,MAAMJ,cAAc,QAAQ;gBAAC;gBAAgB;gBAAMI;aAAK;QAC5D,EAAE,OAAM;QACJ,wBAAwB;QAC5B;IACJ;IAEA;;;;;;;;;;;;;;;KAeC,GACD,MAAMO,aAAaH,OAAe,EAAEI,OAAuC,EAA0B;QACjG,MAAMC,UAAU,MAAM,IAAI,CAACC,UAAU,CAACN;QACtC,IAAIK,YAAY,MAAM,OAAO;QAE7B,MAAME,UAAU,IAAIC;QACpB,MAAMC,QAAkB;YAACJ;SAAQ;QACjC,IAAIK,eAA8B;QAElC,MAAOD,MAAME,MAAM,GAAG,EAAG;YACrB,MAAMC,MAAMH,MAAMI,KAAK;YACvB,IAAIN,QAAQO,GAAG,CAACF,MA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