@agent-relay/wrapper 0.1.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 (115) hide show
  1. package/dist/__fixtures__/claude-outputs.d.ts +49 -0
  2. package/dist/__fixtures__/claude-outputs.d.ts.map +1 -0
  3. package/dist/__fixtures__/claude-outputs.js +443 -0
  4. package/dist/__fixtures__/claude-outputs.js.map +1 -0
  5. package/dist/__fixtures__/codex-outputs.d.ts +9 -0
  6. package/dist/__fixtures__/codex-outputs.d.ts.map +1 -0
  7. package/dist/__fixtures__/codex-outputs.js +94 -0
  8. package/dist/__fixtures__/codex-outputs.js.map +1 -0
  9. package/dist/__fixtures__/gemini-outputs.d.ts +19 -0
  10. package/dist/__fixtures__/gemini-outputs.d.ts.map +1 -0
  11. package/dist/__fixtures__/gemini-outputs.js +144 -0
  12. package/dist/__fixtures__/gemini-outputs.js.map +1 -0
  13. package/dist/__fixtures__/index.d.ts +68 -0
  14. package/dist/__fixtures__/index.d.ts.map +1 -0
  15. package/dist/__fixtures__/index.js +44 -0
  16. package/dist/__fixtures__/index.js.map +1 -0
  17. package/dist/auth-detection.d.ts +49 -0
  18. package/dist/auth-detection.d.ts.map +1 -0
  19. package/dist/auth-detection.js +199 -0
  20. package/dist/auth-detection.js.map +1 -0
  21. package/dist/base-wrapper.d.ts +225 -0
  22. package/dist/base-wrapper.d.ts.map +1 -0
  23. package/dist/base-wrapper.js +572 -0
  24. package/dist/base-wrapper.js.map +1 -0
  25. package/dist/client.d.ts +254 -0
  26. package/dist/client.d.ts.map +1 -0
  27. package/dist/client.js +801 -0
  28. package/dist/client.js.map +1 -0
  29. package/dist/id-generator.d.ts +35 -0
  30. package/dist/id-generator.d.ts.map +1 -0
  31. package/dist/id-generator.js +60 -0
  32. package/dist/id-generator.js.map +1 -0
  33. package/dist/idle-detector.d.ts +110 -0
  34. package/dist/idle-detector.d.ts.map +1 -0
  35. package/dist/idle-detector.js +304 -0
  36. package/dist/idle-detector.js.map +1 -0
  37. package/dist/inbox.d.ts +37 -0
  38. package/dist/inbox.d.ts.map +1 -0
  39. package/dist/inbox.js +73 -0
  40. package/dist/inbox.js.map +1 -0
  41. package/dist/index.d.ts +37 -0
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +47 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/parser.d.ts +236 -0
  46. package/dist/parser.d.ts.map +1 -0
  47. package/dist/parser.js +1238 -0
  48. package/dist/parser.js.map +1 -0
  49. package/dist/prompt-composer.d.ts +67 -0
  50. package/dist/prompt-composer.d.ts.map +1 -0
  51. package/dist/prompt-composer.js +168 -0
  52. package/dist/prompt-composer.js.map +1 -0
  53. package/dist/relay-pty-orchestrator.d.ts +407 -0
  54. package/dist/relay-pty-orchestrator.d.ts.map +1 -0
  55. package/dist/relay-pty-orchestrator.js +1885 -0
  56. package/dist/relay-pty-orchestrator.js.map +1 -0
  57. package/dist/shared.d.ts +201 -0
  58. package/dist/shared.d.ts.map +1 -0
  59. package/dist/shared.js +341 -0
  60. package/dist/shared.js.map +1 -0
  61. package/dist/stuck-detector.d.ts +161 -0
  62. package/dist/stuck-detector.d.ts.map +1 -0
  63. package/dist/stuck-detector.js +402 -0
  64. package/dist/stuck-detector.js.map +1 -0
  65. package/dist/tmux-resolver.d.ts +55 -0
  66. package/dist/tmux-resolver.d.ts.map +1 -0
  67. package/dist/tmux-resolver.js +175 -0
  68. package/dist/tmux-resolver.js.map +1 -0
  69. package/dist/tmux-wrapper.d.ts +345 -0
  70. package/dist/tmux-wrapper.d.ts.map +1 -0
  71. package/dist/tmux-wrapper.js +1747 -0
  72. package/dist/tmux-wrapper.js.map +1 -0
  73. package/dist/trajectory-integration.d.ts +292 -0
  74. package/dist/trajectory-integration.d.ts.map +1 -0
  75. package/dist/trajectory-integration.js +979 -0
  76. package/dist/trajectory-integration.js.map +1 -0
  77. package/dist/wrapper-types.d.ts +41 -0
  78. package/dist/wrapper-types.d.ts.map +1 -0
  79. package/dist/wrapper-types.js +7 -0
  80. package/dist/wrapper-types.js.map +1 -0
  81. package/package.json +63 -0
  82. package/src/__fixtures__/claude-outputs.ts +471 -0
  83. package/src/__fixtures__/codex-outputs.ts +99 -0
  84. package/src/__fixtures__/gemini-outputs.ts +151 -0
  85. package/src/__fixtures__/index.ts +47 -0
  86. package/src/auth-detection.ts +244 -0
  87. package/src/base-wrapper.test.ts +540 -0
  88. package/src/base-wrapper.ts +741 -0
  89. package/src/client.test.ts +262 -0
  90. package/src/client.ts +984 -0
  91. package/src/id-generator.test.ts +71 -0
  92. package/src/id-generator.ts +69 -0
  93. package/src/idle-detector.test.ts +390 -0
  94. package/src/idle-detector.ts +370 -0
  95. package/src/inbox.test.ts +233 -0
  96. package/src/inbox.ts +89 -0
  97. package/src/index.ts +170 -0
  98. package/src/parser.regression.test.ts +251 -0
  99. package/src/parser.test.ts +1359 -0
  100. package/src/parser.ts +1477 -0
  101. package/src/prompt-composer.test.ts +219 -0
  102. package/src/prompt-composer.ts +231 -0
  103. package/src/relay-pty-orchestrator.test.ts +1027 -0
  104. package/src/relay-pty-orchestrator.ts +2270 -0
  105. package/src/shared.test.ts +221 -0
  106. package/src/shared.ts +454 -0
  107. package/src/stuck-detector.test.ts +303 -0
  108. package/src/stuck-detector.ts +511 -0
  109. package/src/tmux-resolver.test.ts +104 -0
  110. package/src/tmux-resolver.ts +207 -0
  111. package/src/tmux-wrapper.test.ts +316 -0
  112. package/src/tmux-wrapper.ts +2010 -0
  113. package/src/trajectory-detection.test.ts +151 -0
  114. package/src/trajectory-integration.ts +1261 -0
  115. package/src/wrapper-types.ts +45 -0
@@ -0,0 +1,979 @@
1
+ /**
2
+ * Trajectory Integration Module
3
+ *
4
+ * Integrates with the agent-trajectories package to provide
5
+ * PDERO paradigm tracking within agent-relay.
6
+ *
7
+ * This module provides a bridge between agent-relay and the
8
+ * external `trail` CLI / agent-trajectories library.
9
+ *
10
+ * Key integration points:
11
+ * - Auto-starts trajectory when agent is instantiated with a task
12
+ * - Records all inter-agent messages
13
+ * - Auto-detects PDERO phase transitions from output
14
+ * - Provides hooks for key agent lifecycle events
15
+ */
16
+ import { spawn, execSync } from 'node:child_process';
17
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { getProjectPaths } from '@agent-relay/config/project-namespace';
20
+ import { getPrimaryTrajectoriesDir, getAllTrajectoriesDirs, getTrajectoryEnvVars, } from '@agent-relay/config/trajectory-config';
21
+ /**
22
+ * Read a single trajectory index file from a directory
23
+ */
24
+ function resolveIndexEntryPath(trajectoriesDir, entryPath) {
25
+ if (!entryPath) {
26
+ return entryPath;
27
+ }
28
+ if (existsSync(entryPath)) {
29
+ return entryPath;
30
+ }
31
+ const normalized = entryPath.replace(/\\/g, '/');
32
+ const marker = '/.trajectories/';
33
+ const markerIndex = normalized.indexOf(marker);
34
+ if (markerIndex >= 0) {
35
+ const relative = normalized.slice(markerIndex + marker.length);
36
+ const candidate = join(trajectoriesDir, relative);
37
+ if (existsSync(candidate)) {
38
+ return candidate;
39
+ }
40
+ }
41
+ const subdirMatch = normalized.match(/\/(active|completed)\/.+$/);
42
+ if (subdirMatch) {
43
+ const relative = subdirMatch[0].slice(1);
44
+ const candidate = join(trajectoriesDir, relative);
45
+ if (existsSync(candidate)) {
46
+ return candidate;
47
+ }
48
+ }
49
+ return entryPath;
50
+ }
51
+ function readSingleTrajectoryIndex(trajectoriesDir) {
52
+ try {
53
+ const indexPath = join(trajectoriesDir, 'index.json');
54
+ if (!existsSync(indexPath)) {
55
+ return null;
56
+ }
57
+ const content = readFileSync(indexPath, 'utf-8');
58
+ const index = JSON.parse(content);
59
+ const trajectories = index.trajectories ?? {};
60
+ for (const [id, entry] of Object.entries(trajectories)) {
61
+ trajectories[id] = {
62
+ ...entry,
63
+ path: resolveIndexEntryPath(trajectoriesDir, entry.path),
64
+ };
65
+ }
66
+ return { ...index, trajectories };
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ /**
73
+ * Read and merge trajectory indexes from all locations (repo + user-level)
74
+ * This allows reading trajectories from both places
75
+ */
76
+ function readTrajectoryIndex() {
77
+ const dirs = getAllTrajectoriesDirs();
78
+ if (dirs.length === 0) {
79
+ return null;
80
+ }
81
+ // Read and merge all indexes
82
+ let mergedIndex = null;
83
+ for (const dir of dirs) {
84
+ const index = readSingleTrajectoryIndex(dir);
85
+ if (!index)
86
+ continue;
87
+ if (!mergedIndex) {
88
+ mergedIndex = index;
89
+ }
90
+ else {
91
+ // Merge trajectories, preferring more recent entries
92
+ for (const [id, entry] of Object.entries(index.trajectories)) {
93
+ const existing = mergedIndex.trajectories[id];
94
+ if (!existing) {
95
+ mergedIndex.trajectories[id] = entry;
96
+ }
97
+ else {
98
+ // Keep the more recently updated one
99
+ const existingTime = new Date(existing.completedAt || existing.startedAt).getTime();
100
+ const newTime = new Date(entry.completedAt || entry.startedAt).getTime();
101
+ if (newTime > existingTime) {
102
+ mergedIndex.trajectories[id] = entry;
103
+ }
104
+ }
105
+ }
106
+ // Update lastUpdated to most recent
107
+ if (new Date(index.lastUpdated) > new Date(mergedIndex.lastUpdated)) {
108
+ mergedIndex.lastUpdated = index.lastUpdated;
109
+ }
110
+ }
111
+ }
112
+ return mergedIndex;
113
+ }
114
+ /**
115
+ * Read a specific trajectory file directly from filesystem
116
+ */
117
+ function readTrajectoryFile(trajectoryPath) {
118
+ try {
119
+ if (!existsSync(trajectoryPath)) {
120
+ return null;
121
+ }
122
+ const content = readFileSync(trajectoryPath, 'utf-8');
123
+ return JSON.parse(content);
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ }
129
+ function getCurrentPhaseFromTrajectory(trajectory) {
130
+ if (!trajectory?.chapters?.length) {
131
+ return undefined;
132
+ }
133
+ const lastChapter = trajectory.chapters[trajectory.chapters.length - 1];
134
+ for (const event of [...(lastChapter.events || [])].reverse()) {
135
+ if (event.type === 'phase_transition' || event.type === 'phase') {
136
+ const phaseMatch = event.content?.match(/phase[:\s]+(\w+)/i);
137
+ if (phaseMatch) {
138
+ return phaseMatch[1].toLowerCase();
139
+ }
140
+ }
141
+ }
142
+ return undefined;
143
+ }
144
+ function listActiveTrajectoryFiles(trajectoriesDir) {
145
+ const activeDir = join(trajectoriesDir, 'active');
146
+ if (!existsSync(activeDir)) {
147
+ return [];
148
+ }
149
+ return readdirSync(activeDir, { withFileTypes: true })
150
+ .filter(entry => entry.isFile() && entry.name.endsWith('.json'))
151
+ .map(entry => join(activeDir, entry.name));
152
+ }
153
+ function findActiveTrajectoryPathById(trajectoryDirs, trajectoryId) {
154
+ for (const dir of trajectoryDirs) {
155
+ const candidate = join(dir, 'active', `${trajectoryId}.json`);
156
+ if (existsSync(candidate)) {
157
+ return candidate;
158
+ }
159
+ }
160
+ return null;
161
+ }
162
+ /**
163
+ * Run a trail CLI command
164
+ * Uses config-based environment to control trajectory storage location
165
+ */
166
+ async function runTrail(args) {
167
+ return new Promise((resolve) => {
168
+ // Get trajectory env vars to set correct storage location
169
+ const trajectoryEnv = getTrajectoryEnvVars();
170
+ const proc = spawn('trail', args, {
171
+ cwd: getProjectPaths().projectRoot,
172
+ env: { ...process.env, ...trajectoryEnv },
173
+ stdio: ['pipe', 'pipe', 'pipe'],
174
+ });
175
+ let stdout = '';
176
+ let stderr = '';
177
+ proc.stdout?.on('data', (data) => {
178
+ stdout += data.toString();
179
+ });
180
+ proc.stderr?.on('data', (data) => {
181
+ stderr += data.toString();
182
+ });
183
+ proc.on('error', (err) => {
184
+ resolve({ success: false, output: '', error: `Failed to run trail: ${err.message}` });
185
+ });
186
+ proc.on('close', (code) => {
187
+ if (code === 0) {
188
+ resolve({ success: true, output: stdout.trim() });
189
+ }
190
+ else {
191
+ resolve({ success: false, output: stdout.trim(), error: stderr.trim() || `Exit code: ${code}` });
192
+ }
193
+ });
194
+ });
195
+ }
196
+ /**
197
+ * Check if trail CLI is available
198
+ */
199
+ export async function isTrailAvailable() {
200
+ const result = await runTrail(['--version']);
201
+ return result.success;
202
+ }
203
+ /**
204
+ * Start a new trajectory
205
+ */
206
+ export async function startTrajectory(options) {
207
+ const args = ['start', options.task];
208
+ if (options.taskId) {
209
+ args.push('--task-id', options.taskId);
210
+ }
211
+ if (options.source) {
212
+ args.push('--source', options.source);
213
+ }
214
+ if (options.agentName) {
215
+ args.push('--agent', options.agentName);
216
+ }
217
+ if (options.phase) {
218
+ args.push('--phase', options.phase);
219
+ }
220
+ const result = await runTrail(args);
221
+ if (result.success) {
222
+ // Parse trajectory ID from output like "✓ Trajectory started: traj_xxx"
223
+ const match = result.output.match(/traj_[a-z0-9]+/i);
224
+ return { success: true, trajectoryId: match?.[0] };
225
+ }
226
+ return { success: false, error: result.error };
227
+ }
228
+ /**
229
+ * Get current trajectory status
230
+ * Reads directly from .trajectories/index.json instead of using CLI
231
+ */
232
+ export async function getTrajectoryStatus() {
233
+ const index = readTrajectoryIndex();
234
+ const trajectoryDirs = getAllTrajectoriesDirs();
235
+ if (!index && trajectoryDirs.length === 0) {
236
+ return { active: false };
237
+ }
238
+ // Find an active trajectory
239
+ if (index) {
240
+ for (const [id, entry] of Object.entries(index.trajectories)) {
241
+ if (entry.status === 'active') {
242
+ // Read the full trajectory file to get phase info
243
+ const trajectory = readTrajectoryFile(entry.path);
244
+ const currentPhase = getCurrentPhaseFromTrajectory(trajectory);
245
+ return {
246
+ active: true,
247
+ trajectoryId: id,
248
+ phase: currentPhase,
249
+ task: entry.title,
250
+ };
251
+ }
252
+ }
253
+ }
254
+ for (const dir of trajectoryDirs) {
255
+ for (const activePath of listActiveTrajectoryFiles(dir)) {
256
+ const trajectory = readTrajectoryFile(activePath);
257
+ if (!trajectory) {
258
+ continue;
259
+ }
260
+ return {
261
+ active: true,
262
+ trajectoryId: trajectory.id,
263
+ phase: getCurrentPhaseFromTrajectory(trajectory),
264
+ task: trajectory.task?.title,
265
+ };
266
+ }
267
+ }
268
+ return { active: false };
269
+ }
270
+ /**
271
+ * Transition to a new PDERO phase
272
+ */
273
+ export async function transitionPhase(phase, reason, agentName) {
274
+ const args = ['phase', phase];
275
+ if (reason) {
276
+ args.push('--reason', reason);
277
+ }
278
+ if (agentName) {
279
+ args.push('--agent', agentName);
280
+ }
281
+ const result = await runTrail(args);
282
+ return { success: result.success, error: result.error };
283
+ }
284
+ /**
285
+ * Record a decision
286
+ */
287
+ export async function recordDecision(options) {
288
+ const args = ['decision', options.choice];
289
+ if (options.question) {
290
+ args.push('--question', options.question);
291
+ }
292
+ if (options.alternatives && options.alternatives.length > 0) {
293
+ args.push('--alternatives', options.alternatives.join(','));
294
+ }
295
+ if (options.reasoning) {
296
+ args.push('--reasoning', options.reasoning);
297
+ }
298
+ if (options.confidence !== undefined) {
299
+ args.push('--confidence', options.confidence.toString());
300
+ }
301
+ const result = await runTrail(args);
302
+ return { success: result.success, error: result.error };
303
+ }
304
+ /**
305
+ * Record an event/observation
306
+ */
307
+ export async function recordEvent(content, type = 'observation', agentName) {
308
+ const args = ['event', content, '--type', type];
309
+ if (agentName) {
310
+ args.push('--agent', agentName);
311
+ }
312
+ const result = await runTrail(args);
313
+ return { success: result.success, error: result.error };
314
+ }
315
+ /**
316
+ * Record a message (sent or received)
317
+ */
318
+ export async function recordMessage(direction, from, to, body) {
319
+ const content = `Message ${direction}: ${direction === 'sent' ? `→ ${to}` : `← ${from}`}: ${body.slice(0, 100)}${body.length > 100 ? '...' : ''}`;
320
+ return recordEvent(content, 'observation');
321
+ }
322
+ /**
323
+ * Complete the current trajectory
324
+ */
325
+ export async function completeTrajectory(options = {}) {
326
+ const args = ['complete'];
327
+ if (options.summary) {
328
+ args.push('--summary', options.summary);
329
+ }
330
+ if (options.confidence !== undefined) {
331
+ args.push('--confidence', options.confidence.toString());
332
+ }
333
+ if (options.challenges && options.challenges.length > 0) {
334
+ args.push('--challenges', options.challenges.join(','));
335
+ }
336
+ if (options.learnings && options.learnings.length > 0) {
337
+ args.push('--learnings', options.learnings.join(','));
338
+ }
339
+ const result = await runTrail(args);
340
+ return { success: result.success, error: result.error };
341
+ }
342
+ /**
343
+ * Abandon the current trajectory
344
+ */
345
+ export async function abandonTrajectory(reason) {
346
+ const args = ['abandon'];
347
+ if (reason) {
348
+ args.push('--reason', reason);
349
+ }
350
+ const result = await runTrail(args);
351
+ return { success: result.success, error: result.error };
352
+ }
353
+ /**
354
+ * List trajectory steps/events
355
+ * Returns steps for the current or specified trajectory
356
+ * Reads directly from filesystem instead of using CLI
357
+ */
358
+ export async function listTrajectorySteps(trajectoryId) {
359
+ const trajectoryDirs = getAllTrajectoriesDirs();
360
+ const index = readTrajectoryIndex();
361
+ if (!index && trajectoryDirs.length === 0) {
362
+ return { success: true, steps: [] };
363
+ }
364
+ // Collect all trajectory paths to load
365
+ const trajectoryPaths = new Set();
366
+ if (trajectoryId) {
367
+ // Use specified trajectory - try multiple lookup strategies
368
+ let foundPath = null;
369
+ // Strategy 1: Look up by index key
370
+ const entry = index?.trajectories[trajectoryId];
371
+ if (entry) {
372
+ foundPath = entry.path;
373
+ }
374
+ // Strategy 2: If not found by key, search index entries by file's internal ID
375
+ // This handles cases where the index key differs from the file's internal ID
376
+ if (!foundPath && index) {
377
+ for (const [_key, indexEntry] of Object.entries(index.trajectories)) {
378
+ const trajectory = readTrajectoryFile(indexEntry.path);
379
+ if (trajectory && trajectory.id === trajectoryId) {
380
+ foundPath = indexEntry.path;
381
+ break;
382
+ }
383
+ }
384
+ }
385
+ // Strategy 3: Fall back to active directory filename match
386
+ if (!foundPath) {
387
+ foundPath = findActiveTrajectoryPathById(trajectoryDirs, trajectoryId);
388
+ }
389
+ if (foundPath) {
390
+ trajectoryPaths.add(foundPath);
391
+ }
392
+ }
393
+ else {
394
+ // Collect ALL active trajectories (not just the first one)
395
+ if (index) {
396
+ for (const [_id, entry] of Object.entries(index.trajectories)) {
397
+ if (entry.status === 'active') {
398
+ trajectoryPaths.add(entry.path);
399
+ }
400
+ }
401
+ }
402
+ for (const dir of trajectoryDirs) {
403
+ for (const activePath of listActiveTrajectoryFiles(dir)) {
404
+ trajectoryPaths.add(activePath);
405
+ }
406
+ }
407
+ }
408
+ if (trajectoryPaths.size === 0) {
409
+ return { success: true, steps: [] };
410
+ }
411
+ // Load all trajectories and merge their steps
412
+ const steps = [];
413
+ let stepIndex = 0;
414
+ for (const trajectoryPath of trajectoryPaths) {
415
+ const trajectory = readTrajectoryFile(trajectoryPath);
416
+ if (!trajectory) {
417
+ continue;
418
+ }
419
+ // Extract events from all chapters
420
+ // Include trajectory ID in step IDs to ensure uniqueness across trajectories
421
+ // This prevents React key collisions when switching between trajectories
422
+ const trajId = trajectory.id || 'unknown';
423
+ for (const chapter of trajectory.chapters || []) {
424
+ for (const event of chapter.events || []) {
425
+ steps.push({
426
+ id: `${trajId}-step-${stepIndex++}`,
427
+ timestamp: event.ts || Date.now(),
428
+ type: mapEventType(event.type),
429
+ title: event.content?.slice(0, 50) || event.type || 'Event',
430
+ description: event.content,
431
+ metadata: event.raw,
432
+ status: mapEventStatus(trajectory.status),
433
+ });
434
+ }
435
+ }
436
+ }
437
+ // Sort steps by timestamp to maintain chronological order across all trajectories
438
+ steps.sort((a, b) => {
439
+ const timeA = typeof a.timestamp === 'number' ? a.timestamp : new Date(a.timestamp).getTime();
440
+ const timeB = typeof b.timestamp === 'number' ? b.timestamp : new Date(b.timestamp).getTime();
441
+ return timeA - timeB;
442
+ });
443
+ return { success: true, steps };
444
+ }
445
+ /**
446
+ * Get trajectory history - list all trajectories
447
+ * Reads directly from filesystem
448
+ */
449
+ export async function getTrajectoryHistory() {
450
+ const trajectoryDirs = getAllTrajectoriesDirs();
451
+ const index = readTrajectoryIndex();
452
+ if (!index && trajectoryDirs.length === 0) {
453
+ return { success: true, trajectories: [] };
454
+ }
455
+ const trajectories = [];
456
+ const seenIds = new Set();
457
+ if (index) {
458
+ for (const [indexKey, entry] of Object.entries(index.trajectories)) {
459
+ // Read the trajectory file to get the actual internal ID
460
+ // This ensures consistency between history list IDs and file content
461
+ const trajectory = entry.path ? readTrajectoryFile(entry.path) : null;
462
+ // Use the file's internal ID if available, otherwise fall back to index key
463
+ // This fixes the mismatch where index key differs from file's internal ID
464
+ const actualId = trajectory?.id || indexKey;
465
+ // Skip if we've already seen this ID (from a previous directory's index)
466
+ if (seenIds.has(actualId)) {
467
+ continue;
468
+ }
469
+ const historyEntry = {
470
+ id: actualId,
471
+ title: trajectory?.task?.title || entry.title,
472
+ status: entry.status,
473
+ startedAt: trajectory?.startedAt || entry.startedAt,
474
+ completedAt: trajectory?.completedAt || entry.completedAt,
475
+ };
476
+ // Add additional details from trajectory file
477
+ if (trajectory) {
478
+ historyEntry.agents = trajectory.agents?.map(a => a.name);
479
+ if (trajectory.retrospective) {
480
+ historyEntry.summary = trajectory.retrospective.summary;
481
+ historyEntry.confidence = trajectory.retrospective.confidence;
482
+ }
483
+ }
484
+ trajectories.push(historyEntry);
485
+ seenIds.add(actualId);
486
+ }
487
+ }
488
+ for (const dir of trajectoryDirs) {
489
+ for (const activePath of listActiveTrajectoryFiles(dir)) {
490
+ const trajectory = readTrajectoryFile(activePath);
491
+ if (!trajectory || seenIds.has(trajectory.id)) {
492
+ continue;
493
+ }
494
+ const historyEntry = {
495
+ id: trajectory.id,
496
+ title: trajectory.task?.title || 'Untitled trajectory',
497
+ status: trajectory.status ?? 'active',
498
+ startedAt: trajectory.startedAt,
499
+ completedAt: trajectory.completedAt,
500
+ agents: trajectory.agents?.map(a => a.name),
501
+ };
502
+ if (trajectory.retrospective) {
503
+ historyEntry.summary = trajectory.retrospective.summary;
504
+ historyEntry.confidence = trajectory.retrospective.confidence;
505
+ }
506
+ trajectories.push(historyEntry);
507
+ seenIds.add(trajectory.id);
508
+ }
509
+ }
510
+ // Sort by startedAt descending (most recent first)
511
+ trajectories.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());
512
+ return { success: true, trajectories };
513
+ }
514
+ /**
515
+ * Map trail event type to dashboard type
516
+ */
517
+ function mapEventType(type) {
518
+ switch (type?.toLowerCase()) {
519
+ case 'tool':
520
+ case 'tool_call':
521
+ case 'tool_use':
522
+ return 'tool_call';
523
+ case 'decision':
524
+ case 'choice':
525
+ return 'decision';
526
+ case 'message':
527
+ case 'observation':
528
+ return 'message';
529
+ case 'phase':
530
+ case 'phase_change':
531
+ case 'phase_transition':
532
+ return 'phase_transition';
533
+ case 'error':
534
+ case 'failure':
535
+ return 'error';
536
+ default:
537
+ return 'state_change';
538
+ }
539
+ }
540
+ /**
541
+ * Map trail status to dashboard status
542
+ */
543
+ function mapEventStatus(status) {
544
+ switch (status?.toLowerCase()) {
545
+ case 'running':
546
+ case 'in_progress':
547
+ case 'active':
548
+ return 'running';
549
+ case 'success':
550
+ case 'completed':
551
+ case 'done':
552
+ return 'success';
553
+ case 'error':
554
+ case 'failed':
555
+ case 'abandoned':
556
+ return 'error';
557
+ case 'pending':
558
+ case 'queued':
559
+ return 'pending';
560
+ default:
561
+ return undefined;
562
+ }
563
+ }
564
+ /**
565
+ * Detect PDERO phase from content
566
+ */
567
+ export function detectPhaseFromContent(content) {
568
+ const lowerContent = content.toLowerCase();
569
+ const phasePatterns = [
570
+ { phase: 'plan', patterns: ['planning', 'analyzing requirements', 'breaking down', 'creating plan', 'task list', 'todo', 'outline'] },
571
+ { phase: 'design', patterns: ['designing', 'architecting', 'choosing pattern', 'interface design', 'schema design', 'architecture'] },
572
+ { phase: 'execute', patterns: ['implementing', 'writing', 'coding', 'building', 'creating file', 'modifying', 'editing'] },
573
+ { phase: 'review', patterns: ['testing', 'reviewing', 'validating', 'checking', 'verifying', 'running tests', 'test passed', 'test failed'] },
574
+ { phase: 'observe', patterns: ['observing', 'monitoring', 'reflecting', 'documenting', 'retrospective', 'learnings', 'summary'] },
575
+ ];
576
+ for (const { phase, patterns } of phasePatterns) {
577
+ for (const pattern of patterns) {
578
+ if (lowerContent.includes(pattern)) {
579
+ return phase;
580
+ }
581
+ }
582
+ }
583
+ return undefined;
584
+ }
585
+ /**
586
+ * All known Claude Code tool names
587
+ */
588
+ const TOOL_NAMES = [
589
+ 'Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep', 'Task', 'TaskOutput',
590
+ 'WebFetch', 'WebSearch', 'NotebookEdit', 'TodoWrite', 'AskUserQuestion',
591
+ 'KillShell', 'EnterPlanMode', 'ExitPlanMode', 'Skill', 'SlashCommand',
592
+ ];
593
+ const TOOL_NAME_PATTERN = TOOL_NAMES.join('|');
594
+ /**
595
+ * Tool call patterns for Claude Code and similar AI CLIs
596
+ */
597
+ const TOOL_PATTERNS = [
598
+ // Claude Code tool invocations (displayed in output with parenthesis/braces)
599
+ new RegExp(`(?:^|\\n)\\s*(?:${TOOL_NAME_PATTERN})\\s*[({]`, 'i'),
600
+ // Tool completion markers (checkmarks, spinners)
601
+ new RegExp(`(?:^|\\n)\\s*(?:✓|✔|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏)\\s*(${TOOL_NAME_PATTERN})`, 'i'),
602
+ // Function call patterns (explicit mentions)
603
+ new RegExp(`(?:^|\\n)\\s*(?:Calling|Using|Invoking)\\s+(?:tool\\s+)?['"]?(${TOOL_NAME_PATTERN})['"]?`, 'i'),
604
+ // Tool result patterns
605
+ new RegExp(`(?:^|\\n)\\s*(?:Tool result|Result from)\\s*:?\\s*(${TOOL_NAME_PATTERN})`, 'i'),
606
+ ];
607
+ /**
608
+ * Error patterns for detecting failures in output
609
+ * Note: Patterns are ordered from most specific to least specific
610
+ */
611
+ const ERROR_PATTERNS = [
612
+ // JavaScript/TypeScript runtime errors (most specific)
613
+ /(?:^|\n)((?:TypeError|ReferenceError|SyntaxError|RangeError|EvalError|URIError):\s*.+)/i,
614
+ // Named Error with message (e.g., "Error: Something went wrong")
615
+ /(?:^|\n)(Error:\s+.+)/,
616
+ // Failed assertions
617
+ /(?:^|\n)\s*(AssertionError:\s*.+)/i,
618
+ // Test failures (Vitest, Jest patterns)
619
+ /(?:^|\n)\s*(FAIL\s+\S+\.(?:ts|js|tsx|jsx))/i,
620
+ /(?:^|\n)\s*(✗|✘|×)\s+(.+)/,
621
+ // Command/process failures
622
+ /(?:^|\n)\s*(Command failed[^\n]+)/i,
623
+ /(?:^|\n)\s*((?:Exit|exit)\s+code[:\s]+[1-9]\d*)/i,
624
+ /(?:^|\n)\s*(exited with (?:code\s+)?[1-9]\d*)/i,
625
+ // Node.js/system errors
626
+ /(?:^|\n)\s*(EACCES|EPERM|ENOENT|ECONNREFUSED|ETIMEDOUT|ENOTFOUND)(?::\s*.+)?/,
627
+ // Build/compile errors (webpack, tsc, etc.)
628
+ /(?:^|\n)\s*(error TS\d+:\s*.+)/i,
629
+ /(?:^|\n)\s*(error\[\S+\]:\s*.+)/i,
630
+ ];
631
+ /**
632
+ * Warning patterns for detecting potential issues
633
+ */
634
+ const WARNING_PATTERNS = [
635
+ /(?:^|\n)\s*(?:warning|WARN|⚠️?)\s*[:\[]?\s*(.+)/i,
636
+ /(?:^|\n)\s*(?:deprecated|DEPRECATED):\s*(.+)/i,
637
+ ];
638
+ /**
639
+ * Detect tool calls from agent output
640
+ *
641
+ * @example
642
+ * ```typescript
643
+ * const tools = detectToolCalls(output);
644
+ * // Returns: [{ tool: 'Read', args: 'file.ts' }, { tool: 'Bash', status: 'completed' }]
645
+ * ```
646
+ */
647
+ export function detectToolCalls(content) {
648
+ const detected = [];
649
+ const seenTools = new Set();
650
+ const toolNameExtractor = new RegExp(`\\b(${TOOL_NAME_PATTERN})\\b`, 'i');
651
+ for (const pattern of TOOL_PATTERNS) {
652
+ const matches = content.matchAll(new RegExp(pattern.source, 'gi'));
653
+ for (const match of matches) {
654
+ // Extract tool name from the match
655
+ const fullMatch = match[0];
656
+ const toolNameMatch = fullMatch.match(toolNameExtractor);
657
+ if (toolNameMatch) {
658
+ const tool = toolNameMatch[1];
659
+ // Avoid duplicates by position (same tool at same position)
660
+ const key = `${tool}:${match.index}`;
661
+ if (!seenTools.has(key)) {
662
+ seenTools.add(key);
663
+ detected.push({
664
+ tool,
665
+ status: fullMatch.includes('✓') || fullMatch.includes('✔') ? 'completed' : 'started',
666
+ });
667
+ }
668
+ }
669
+ }
670
+ }
671
+ return detected;
672
+ }
673
+ /**
674
+ * Detect errors from agent output
675
+ *
676
+ * @example
677
+ * ```typescript
678
+ * const errors = detectErrors(output);
679
+ * // Returns: [{ type: 'error', message: 'TypeError: Cannot read property...' }]
680
+ * ```
681
+ */
682
+ export function detectErrors(content) {
683
+ const detected = [];
684
+ const seenMessages = new Set();
685
+ // Check for error patterns
686
+ for (const pattern of ERROR_PATTERNS) {
687
+ const matches = content.matchAll(new RegExp(pattern, 'gi'));
688
+ for (const match of matches) {
689
+ const message = match[1] || match[0];
690
+ const cleanMessage = message.trim().slice(0, 200); // Limit length
691
+ if (!seenMessages.has(cleanMessage)) {
692
+ seenMessages.add(cleanMessage);
693
+ detected.push({
694
+ type: 'error',
695
+ message: cleanMessage,
696
+ });
697
+ }
698
+ }
699
+ }
700
+ // Check for warning patterns
701
+ for (const pattern of WARNING_PATTERNS) {
702
+ const matches = content.matchAll(new RegExp(pattern, 'gi'));
703
+ for (const match of matches) {
704
+ const message = match[1] || match[0];
705
+ const cleanMessage = message.trim().slice(0, 200);
706
+ if (!seenMessages.has(cleanMessage)) {
707
+ seenMessages.add(cleanMessage);
708
+ detected.push({
709
+ type: 'warning',
710
+ message: cleanMessage,
711
+ });
712
+ }
713
+ }
714
+ }
715
+ return detected;
716
+ }
717
+ /**
718
+ * TrajectoryIntegration class for managing trajectory state
719
+ *
720
+ * This class enforces trajectory tracking during agent lifecycle:
721
+ * - Auto-starts trajectory when agent is instantiated with a task
722
+ * - Records all inter-agent messages
723
+ * - Auto-detects PDERO phase transitions
724
+ * - Provides lifecycle hooks for tmux/pty wrappers
725
+ */
726
+ export class TrajectoryIntegration {
727
+ projectId;
728
+ agentName;
729
+ trailAvailable = null;
730
+ currentPhase = null;
731
+ trajectoryId = null;
732
+ initialized = false;
733
+ task = null;
734
+ constructor(projectId, agentName) {
735
+ this.projectId = projectId;
736
+ this.agentName = agentName;
737
+ }
738
+ /**
739
+ * Check if trail is available (cached)
740
+ */
741
+ async isAvailable() {
742
+ if (this.trailAvailable === null) {
743
+ this.trailAvailable = await isTrailAvailable();
744
+ }
745
+ return this.trailAvailable;
746
+ }
747
+ /**
748
+ * Check if trail CLI is installed synchronously
749
+ */
750
+ isTrailInstalledSync() {
751
+ try {
752
+ execSync('which trail', { stdio: 'pipe' });
753
+ return true;
754
+ }
755
+ catch {
756
+ return false;
757
+ }
758
+ }
759
+ /**
760
+ * Initialize trajectory tracking for agent lifecycle
761
+ * Called automatically when agent starts with a task
762
+ */
763
+ async initialize(task, taskId, source) {
764
+ if (this.initialized)
765
+ return true;
766
+ if (!(await this.isAvailable())) {
767
+ return false;
768
+ }
769
+ // If task provided, auto-start trajectory
770
+ if (task) {
771
+ const success = await this.start(task, taskId, source);
772
+ if (success) {
773
+ this.initialized = true;
774
+ this.task = task;
775
+ }
776
+ return success;
777
+ }
778
+ this.initialized = true;
779
+ return true;
780
+ }
781
+ /**
782
+ * Start tracking a trajectory
783
+ */
784
+ async start(task, taskId, source) {
785
+ if (!(await this.isAvailable()))
786
+ return false;
787
+ const result = await startTrajectory({
788
+ task,
789
+ taskId,
790
+ source,
791
+ agentName: this.agentName,
792
+ phase: 'plan',
793
+ });
794
+ if (result.success) {
795
+ this.currentPhase = 'plan';
796
+ this.trajectoryId = result.trajectoryId || null;
797
+ this.task = task;
798
+ }
799
+ return result.success;
800
+ }
801
+ /**
802
+ * Check if there's an active trajectory
803
+ */
804
+ hasActiveTrajectory() {
805
+ return this.currentPhase !== null;
806
+ }
807
+ /**
808
+ * Get the current task
809
+ */
810
+ getTask() {
811
+ return this.task;
812
+ }
813
+ /**
814
+ * Get trajectory ID
815
+ */
816
+ getTrajectoryId() {
817
+ return this.trajectoryId;
818
+ }
819
+ /**
820
+ * Record a message
821
+ */
822
+ async message(direction, from, to, body) {
823
+ if (!(await this.isAvailable()))
824
+ return;
825
+ await recordMessage(direction, from, to, body);
826
+ // Check for phase transition based on content
827
+ const detectedPhase = detectPhaseFromContent(body);
828
+ if (detectedPhase && detectedPhase !== this.currentPhase) {
829
+ await this.transition(detectedPhase, 'Auto-detected from message content');
830
+ }
831
+ }
832
+ /**
833
+ * Transition to a new phase
834
+ */
835
+ async transition(phase, reason) {
836
+ if (!(await this.isAvailable()))
837
+ return false;
838
+ if (phase === this.currentPhase)
839
+ return true;
840
+ const result = await transitionPhase(phase, reason, this.agentName);
841
+ if (result.success) {
842
+ this.currentPhase = phase;
843
+ }
844
+ return result.success;
845
+ }
846
+ /**
847
+ * Record a decision
848
+ */
849
+ async decision(choice, options) {
850
+ if (!(await this.isAvailable()))
851
+ return false;
852
+ const result = await recordDecision({
853
+ choice,
854
+ ...options,
855
+ });
856
+ return result.success;
857
+ }
858
+ /**
859
+ * Record an event
860
+ */
861
+ async event(content, type = 'observation') {
862
+ if (!(await this.isAvailable()))
863
+ return false;
864
+ const result = await recordEvent(content, type, this.agentName);
865
+ // Check for phase transition
866
+ const detectedPhase = detectPhaseFromContent(content);
867
+ if (detectedPhase && detectedPhase !== this.currentPhase) {
868
+ await this.transition(detectedPhase, 'Auto-detected from event content');
869
+ }
870
+ return result.success;
871
+ }
872
+ /**
873
+ * Complete the trajectory
874
+ */
875
+ async complete(options) {
876
+ if (!(await this.isAvailable()))
877
+ return false;
878
+ const result = await completeTrajectory(options);
879
+ if (result.success) {
880
+ this.currentPhase = null;
881
+ }
882
+ return result.success;
883
+ }
884
+ /**
885
+ * Abandon the trajectory
886
+ */
887
+ async abandon(reason) {
888
+ if (!(await this.isAvailable()))
889
+ return false;
890
+ const result = await abandonTrajectory(reason);
891
+ if (result.success) {
892
+ this.currentPhase = null;
893
+ }
894
+ return result.success;
895
+ }
896
+ /**
897
+ * Get current phase
898
+ */
899
+ getPhase() {
900
+ return this.currentPhase;
901
+ }
902
+ }
903
+ /**
904
+ * Global trajectory integration instances
905
+ */
906
+ const instances = new Map();
907
+ /**
908
+ * Get or create a TrajectoryIntegration instance
909
+ */
910
+ export function getTrajectoryIntegration(projectId, agentName) {
911
+ const key = `${projectId}:${agentName}`;
912
+ let instance = instances.get(key);
913
+ if (!instance) {
914
+ instance = new TrajectoryIntegration(projectId, agentName);
915
+ instances.set(key, instance);
916
+ }
917
+ return instance;
918
+ }
919
+ /**
920
+ * Generate trail usage instructions for agents
921
+ */
922
+ export function getTrailInstructions() {
923
+ return [
924
+ '📍 TRAJECTORY TRACKING (PDERO Paradigm)',
925
+ '',
926
+ 'You MUST use trail commands to track your work:',
927
+ '',
928
+ 'PHASES: plan → design → execute → review → observe',
929
+ '',
930
+ 'COMMANDS:',
931
+ ' trail start "task" Start trajectory for a task',
932
+ ' trail phase <phase> Transition to new phase',
933
+ ' trail decision "choice" Record key decisions',
934
+ ' trail event "what happened" Log significant events',
935
+ ' trail complete Complete with summary',
936
+ '',
937
+ 'WHEN TO USE:',
938
+ ' - Start: At beginning of any task',
939
+ ' - Phase: When shifting focus (planning→implementing, etc.)',
940
+ ' - Decision: For architecture/approach choices',
941
+ ' - Event: For tool calls, errors, milestones',
942
+ ' - Complete: When task is done',
943
+ '',
944
+ 'Example workflow:',
945
+ ' trail start "Implement auth feature"',
946
+ ' trail phase design',
947
+ ' trail decision "Use JWT" --reasoning "Stateless, scalable"',
948
+ ' trail phase execute',
949
+ ' trail event "Created auth middleware"',
950
+ ' trail phase review',
951
+ ' trail event "All tests passing"',
952
+ ' trail complete --summary "Auth implemented" --confidence 0.9',
953
+ ];
954
+ }
955
+ /**
956
+ * Get a compact trail instruction string for injection
957
+ */
958
+ export function getCompactTrailInstructions() {
959
+ return [
960
+ '[TRAIL] Track work with PDERO: plan→design→execute→review→observe.',
961
+ 'Commands: trail start "task" | trail phase <phase> | trail decision "choice" | trail event "log" | trail complete',
962
+ 'Use trail often to document your thought process.',
963
+ ].join(' ');
964
+ }
965
+ /**
966
+ * Get environment variables for trail CLI
967
+ * If dataDir is not provided, uses config-based storage location
968
+ */
969
+ export function getTrailEnvVars(projectId, agentName, dataDir) {
970
+ // Use config-based path if dataDir not explicitly provided
971
+ const effectiveDataDir = dataDir ?? getPrimaryTrajectoriesDir();
972
+ return {
973
+ TRAJECTORIES_PROJECT: projectId,
974
+ TRAJECTORIES_DATA_DIR: effectiveDataDir,
975
+ TRAJECTORIES_AGENT: agentName,
976
+ TRAIL_AUTO_PHASE: '1', // Enable auto phase detection
977
+ };
978
+ }
979
+ //# sourceMappingURL=trajectory-integration.js.map