@phnx-labs/agents-cli 1.23.13 → 1.23.15

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 (164) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +30 -59
  3. package/dist/cli/command-registry.js +0 -24
  4. package/dist/commands/accounts.js +3 -3
  5. package/dist/commands/daemon.js +5 -147
  6. package/dist/commands/doctor.js +7 -0
  7. package/dist/commands/events-logs.d.ts +2 -0
  8. package/dist/commands/{logs.js → events-logs.js} +28 -127
  9. package/dist/commands/events.js +3 -1
  10. package/dist/commands/exec.d.ts +0 -1
  11. package/dist/commands/exec.js +3 -11
  12. package/dist/commands/feed.d.ts +1 -1
  13. package/dist/commands/feed.js +4 -7
  14. package/dist/commands/mcp.js +1 -1
  15. package/dist/commands/menubar.js +12 -226
  16. package/dist/commands/projects.js +1 -2
  17. package/dist/commands/{trash.d.ts → prune-trash.d.ts} +1 -1
  18. package/dist/commands/{trash.js → prune-trash.js} +8 -8
  19. package/dist/commands/prune.js +3 -1
  20. package/dist/commands/send.js +2 -5
  21. package/dist/commands/sessions.js +1 -1
  22. package/dist/commands/ssh.js +2 -2
  23. package/dist/commands/utils.d.ts +1 -5
  24. package/dist/commands/utils.js +1 -7
  25. package/dist/lib/agent-spec/agents.d.ts +0 -2
  26. package/dist/lib/agent-spec/agents.js +0 -12
  27. package/dist/lib/agent-spec/index.d.ts +0 -4
  28. package/dist/lib/agent-spec/index.js +0 -4
  29. package/dist/lib/commands.d.ts +1 -5
  30. package/dist/lib/commands.js +2 -69
  31. package/dist/lib/comms-render.d.ts +0 -7
  32. package/dist/lib/comms-render.js +0 -41
  33. package/dist/lib/config-keys.d.ts +1 -1
  34. package/dist/lib/config-keys.js +8 -0
  35. package/dist/lib/daemon/daemon.js +1 -6
  36. package/dist/lib/daemon-services.d.ts +1 -1
  37. package/dist/lib/daemon-services.js +0 -5
  38. package/dist/lib/device-config.d.ts +2 -0
  39. package/dist/lib/device-config.js +81 -8
  40. package/dist/lib/devices/doctor-findings.d.ts +6 -1
  41. package/dist/lib/devices/doctor-findings.js +34 -1
  42. package/dist/lib/git.d.ts +1 -0
  43. package/dist/lib/git.js +5 -0
  44. package/dist/lib/hooks/install.d.ts +0 -7
  45. package/dist/lib/hooks/install.js +0 -55
  46. package/dist/lib/hosts/passthrough.js +2 -4
  47. package/dist/lib/hosts/progress.js +2 -2
  48. package/dist/lib/hosts/remote-cmd.js +0 -1
  49. package/dist/lib/installations/migrate.d.ts +1 -0
  50. package/dist/lib/installations/migrate.js +18 -1
  51. package/dist/lib/installations/versions.js +2 -2
  52. package/dist/lib/loop.js +1 -1
  53. package/dist/lib/mailbox-target.d.ts +0 -31
  54. package/dist/lib/mailbox-target.js +0 -37
  55. package/dist/lib/mcp-lookup.d.ts +7 -0
  56. package/dist/lib/mcp-lookup.js +71 -0
  57. package/dist/lib/mcp.d.ts +0 -8
  58. package/dist/lib/mcp.js +0 -47
  59. package/dist/lib/menubar/install-menubar.d.ts +0 -15
  60. package/dist/lib/menubar/install-menubar.js +24 -118
  61. package/dist/lib/menubar/resolve-version.d.ts +9 -10
  62. package/dist/lib/menubar/resolve-version.js +70 -30
  63. package/dist/lib/paths.d.ts +0 -1
  64. package/dist/lib/paths.js +0 -18
  65. package/dist/lib/plugins/skills.d.ts +0 -10
  66. package/dist/lib/plugins/skills.js +2 -165
  67. package/dist/lib/project-pull.js +1 -2
  68. package/dist/lib/resources.d.ts +1 -1
  69. package/dist/lib/routines-project.js +1 -1
  70. package/dist/lib/session/local-tmux-attach.js +2 -2
  71. package/dist/lib/startup/command-registry.js +20 -7
  72. package/dist/lib/teams/agents.js +1 -1
  73. package/dist/lib/teams/placement-probe.d.ts +9 -0
  74. package/dist/lib/teams/placement-probe.js +20 -15
  75. package/dist/lib/triggers/webhook.d.ts +2 -59
  76. package/dist/lib/triggers/webhook.js +2 -422
  77. package/package.json +2 -1
  78. package/dist/commands/funnel.d.ts +0 -2
  79. package/dist/commands/funnel.js +0 -77
  80. package/dist/commands/logs.d.ts +0 -2
  81. package/dist/commands/mailboxes.d.ts +0 -2
  82. package/dist/commands/mailboxes.js +0 -400
  83. package/dist/commands/message.d.ts +0 -2
  84. package/dist/commands/message.js +0 -259
  85. package/dist/commands/packages-materialize.d.ts +0 -6
  86. package/dist/commands/packages-materialize.js +0 -90
  87. package/dist/commands/packages.d.ts +0 -5
  88. package/dist/commands/packages.js +0 -763
  89. package/dist/commands/route.d.ts +0 -2
  90. package/dist/commands/route.js +0 -259
  91. package/dist/commands/testdata/feed-hub.d.ts +0 -1
  92. package/dist/commands/testdata/feed-hub.js +0 -11
  93. package/dist/commands/tmux.d.ts +0 -7
  94. package/dist/commands/tmux.js +0 -529
  95. package/dist/commands/traces.d.ts +0 -2
  96. package/dist/commands/traces.js +0 -204
  97. package/dist/commands/webhook.d.ts +0 -5
  98. package/dist/commands/webhook.js +0 -105
  99. package/dist/lib/agent-spec/materialize.d.ts +0 -3
  100. package/dist/lib/agent-spec/materialize.js +0 -277
  101. package/dist/lib/agent-spec/package-resolve.d.ts +0 -4
  102. package/dist/lib/agent-spec/package-resolve.js +0 -231
  103. package/dist/lib/agent-spec/package-schema.d.ts +0 -3
  104. package/dist/lib/agent-spec/package-schema.js +0 -136
  105. package/dist/lib/agent-spec/package-types.d.ts +0 -94
  106. package/dist/lib/agent-spec/package-types.js +0 -10
  107. package/dist/lib/daemon/testdata/process-view-daemon.d.ts +0 -1
  108. package/dist/lib/daemon/testdata/process-view-daemon.js +0 -12
  109. package/dist/lib/daemon/testdata/process-view-start.d.ts +0 -1
  110. package/dist/lib/daemon/testdata/process-view-start.js +0 -41
  111. package/dist/lib/daemon/webhook-receiver-service.d.ts +0 -8
  112. package/dist/lib/daemon/webhook-receiver-service.js +0 -16
  113. package/dist/lib/daemon-webhooks.d.ts +0 -48
  114. package/dist/lib/daemon-webhooks.js +0 -177
  115. package/dist/lib/funnel.d.ts +0 -6
  116. package/dist/lib/funnel.js +0 -31
  117. package/dist/lib/net-close.d.ts +0 -2
  118. package/dist/lib/net-close.js +0 -20
  119. package/dist/lib/packages/output-home.d.ts +0 -9
  120. package/dist/lib/packages/output-home.js +0 -89
  121. package/dist/lib/registry.d.ts +0 -65
  122. package/dist/lib/registry.js +0 -432
  123. package/dist/lib/routers.d.ts +0 -25
  124. package/dist/lib/routers.js +0 -122
  125. package/dist/lib/run-trace-sync.d.ts +0 -7
  126. package/dist/lib/run-trace-sync.js +0 -35
  127. package/dist/lib/session/testdata/pid-registry-namespace.d.ts +0 -1
  128. package/dist/lib/session/testdata/pid-registry-namespace.js +0 -25
  129. package/dist/lib/session/testdata/process-view-namespace.d.ts +0 -1
  130. package/dist/lib/session/testdata/process-view-namespace.js +0 -56
  131. package/dist/lib/session/testdata/process-view-private.d.ts +0 -1
  132. package/dist/lib/session/testdata/process-view-private.js +0 -11
  133. package/dist/lib/testdata/daemon-health-writer.d.ts +0 -1
  134. package/dist/lib/testdata/daemon-health-writer.js +0 -8
  135. package/dist/lib/testdata/owner-notify-api.d.ts +0 -23
  136. package/dist/lib/testdata/owner-notify-api.js +0 -82
  137. package/dist/lib/testdata/refresh-coordinator-worker.d.ts +0 -1
  138. package/dist/lib/testdata/refresh-coordinator-worker.js +0 -23
  139. package/dist/lib/traces/backend.d.ts +0 -8
  140. package/dist/lib/traces/backend.js +0 -33
  141. package/dist/lib/traces/classify.d.ts +0 -40
  142. package/dist/lib/traces/classify.js +0 -70
  143. package/dist/lib/traces/config.d.ts +0 -2
  144. package/dist/lib/traces/config.js +0 -2
  145. package/dist/lib/traces/insights.d.ts +0 -30
  146. package/dist/lib/traces/insights.js +0 -198
  147. package/dist/lib/traces/phenotype.d.ts +0 -18
  148. package/dist/lib/traces/phenotype.js +0 -335
  149. package/dist/lib/traces/provision.d.ts +0 -16
  150. package/dist/lib/traces/provision.js +0 -25
  151. package/dist/lib/traces/schema2-build.d.ts +0 -28
  152. package/dist/lib/traces/schema2-build.js +0 -496
  153. package/dist/lib/traces/schema2-danger.d.ts +0 -7
  154. package/dist/lib/traces/schema2-danger.js +0 -123
  155. package/dist/lib/traces/schema2.d.ts +0 -139
  156. package/dist/lib/traces/schema2.js +0 -20
  157. package/dist/lib/traces/segments.d.ts +0 -73
  158. package/dist/lib/traces/segments.js +0 -236
  159. package/dist/lib/traces/sync.d.ts +0 -197
  160. package/dist/lib/traces/sync.js +0 -654
  161. package/dist/lib/traces/worker-template.d.ts +0 -1
  162. package/dist/lib/traces/worker-template.js +0 -292
  163. package/dist/lib/triggers/handlers.d.ts +0 -66
  164. package/dist/lib/triggers/handlers.js +0 -383
@@ -1,654 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { getDB, readSessionInsights, readSessionPhenotypes, readSessionTopics, writeSessionInsights, writeSessionPhenotypes, writeSessionTopics, } from '../session/db.js';
5
- import { parseSession } from '@phnx-labs/sessions-cli/reader';
6
- import { buildTrajectory } from '@phnx-labs/sessions-cli/reader';
7
- import { computeInsightFacets } from '@phnx-labs/sessions-cli/reader';
8
- import { knownSecretValuesFromEnv, redactSecrets } from '../redact.js';
9
- import { getRuntimeStateDir } from '../state.js';
10
- import { resolveTracesBackend } from './backend.js';
11
- import { classifyCause, classifyTopic, computeDriftSignal, } from './classify.js';
12
- import { computeBehavioralPatterns, computeInsights } from './insights.js';
13
- import { classifyPhenotype, recoveredAfterErrors } from './phenotype.js';
14
- import { buildSessionDetailV2 } from './schema2-build.js';
15
- export function buildSessionShard(traj, events, knownSecrets) {
16
- return buildSessionDetailV2(traj, events, { redact: true, knownSecrets });
17
- }
18
- export async function syncTraces(opts = {}) {
19
- const dryRun = opts.dryRun === true;
20
- const outDir = opts.outDir;
21
- if (dryRun && !outDir) {
22
- throw new Error('traces sync --dry-run requires --out <dir>');
23
- }
24
- const backend = dryRun ? null : resolveTracesBackend();
25
- const owner = backend?.userId ?? 'local';
26
- const ledger = readSyncLedger();
27
- const db = getDB();
28
- const device = localDevice();
29
- const sinceMtime = dryRun ? 0 : (ledger.lastSyncMtime ?? 0);
30
- const watermarkRows = db
31
- .prepare('SELECT * FROM sessions WHERE (machine = ? OR machine IS NULL) AND file_mtime_ms > ? ORDER BY file_mtime_ms ASC')
32
- .all(device, sinceMtime);
33
- const retryIds = dryRun
34
- ? []
35
- : (ledger.failures ?? [])
36
- .filter((f) => f.kind !== 'transcript-unavailable')
37
- .map((f) => f.id);
38
- let rows = watermarkRows;
39
- if (retryIds.length) {
40
- const seen = new Set(watermarkRows.map((r) => r.id));
41
- const retryRows = [];
42
- for (let i = 0; i < retryIds.length; i += 400) {
43
- const chunk = retryIds.slice(i, i + 400);
44
- retryRows.push(...db
45
- .prepare(`SELECT * FROM sessions WHERE (machine = ? OR machine IS NULL) AND id IN (${chunk.map(() => '?').join(',')})`)
46
- .all(device, ...chunk));
47
- }
48
- const stranded = retryRows.filter((r) => !seen.has(r.id));
49
- rows = [...watermarkRows, ...stranded].sort((a, b) => (a.file_mtime_ms ?? 0) - (b.file_mtime_ms ?? 0));
50
- }
51
- const limited = opts.limit !== undefined ? rows.slice(0, opts.limit) : rows;
52
- const knownSecrets = knownSecretValuesFromEnv();
53
- let uploaded = 0;
54
- let skipped = 0;
55
- let transcriptUnavailable = 0;
56
- let parseFailed = 0;
57
- let uploadFailed = 0;
58
- let maxSuccessMtime = ledger.lastSyncMtime ?? 0;
59
- const now = Date.now();
60
- const failures = new Map((ledger.failures ?? []).map((f) => [f.id, f]));
61
- const recordFailure = (row, kind, err) => {
62
- const raw = err instanceof Error ? err.message : String(err);
63
- const prev = failures.get(row.id);
64
- failures.set(row.id, {
65
- id: row.id,
66
- mtimeMs: row.file_mtime_ms ?? 0,
67
- kind,
68
- detail: redactSecrets(raw.split('\n')[0] ?? '', knownSecrets).slice(0, 200),
69
- firstSeen: prev?.firstSeen ?? now,
70
- attempts: (prev?.attempts ?? 0) + 1,
71
- });
72
- };
73
- if (dryRun && outDir) {
74
- fs.mkdirSync(path.join(outDir, 'sessions'), { recursive: true });
75
- }
76
- for (const row of limited) {
77
- if (!row.file_path) {
78
- skipped++;
79
- maxSuccessMtime = Math.max(maxSuccessMtime, row.file_mtime_ms ?? 0);
80
- continue;
81
- }
82
- let traj;
83
- let events = [];
84
- try {
85
- const session = rowToMeta(row);
86
- events = parseSession(row.file_path, row.agent);
87
- traj = buildTrajectory(events, session, { redact: true, knownSecrets });
88
- }
89
- catch (err) {
90
- if (!fs.existsSync(row.file_path)) {
91
- transcriptUnavailable++;
92
- recordFailure(row, 'transcript-unavailable', err);
93
- }
94
- else {
95
- parseFailed++;
96
- recordFailure(row, 'parse-failed', err);
97
- }
98
- continue;
99
- }
100
- try {
101
- if (dryRun && outDir) {
102
- fs.writeFileSync(path.join(outDir, 'sessions', `${row.id}.json`), JSON.stringify(buildSessionShard(traj, events, knownSecrets)));
103
- }
104
- else {
105
- await putSessionTrace(backend, device, row.id, traj, events, knownSecrets);
106
- }
107
- uploaded++;
108
- maxSuccessMtime = Math.max(maxSuccessMtime, row.file_mtime_ms ?? 0);
109
- failures.delete(row.id);
110
- }
111
- catch (err) {
112
- uploadFailed++;
113
- recordFailure(row, 'upload-failed', err);
114
- }
115
- }
116
- let indexError;
117
- if (!opts.skipIndex) {
118
- try {
119
- const allRows = db
120
- .prepare('SELECT * FROM sessions WHERE machine = ? OR machine IS NULL')
121
- .all(device);
122
- let prevShard = null;
123
- if (dryRun && outDir) {
124
- const prevPath = path.join(outDir, 'index.json');
125
- try {
126
- prevShard = JSON.parse(fs.readFileSync(prevPath, 'utf8'));
127
- }
128
- catch { }
129
- }
130
- else if (backend) {
131
- prevShard = await getIndexShard(backend, device);
132
- }
133
- const shard = buildIndexShard(allRows, device, owner, prevShard);
134
- if (dryRun && outDir) {
135
- fs.writeFileSync(path.join(outDir, 'index.json'), JSON.stringify(shard, null, 2));
136
- }
137
- else {
138
- await putIndexShard(backend, device, owner, shard);
139
- }
140
- }
141
- catch (err) {
142
- indexError = err instanceof Error ? err.message : String(err);
143
- }
144
- }
145
- if (!dryRun) {
146
- const persistedFailures = [...failures.values()].filter((f) => !(f.kind === 'transcript-unavailable' &&
147
- now - f.firstSeen > TRANSCRIPT_UNAVAILABLE_TTL_MS));
148
- writeSyncLedger({ lastSyncMtime: maxSuccessMtime, failures: persistedFailures });
149
- if (backend && backend.userId !== 'byo') {
150
- fetch('https://api.prix.dev/api/v1/traces/link', {
151
- method: 'POST',
152
- headers: { Authorization: `Bearer ${backend.token}` },
153
- signal: AbortSignal.timeout(8_000),
154
- }).catch(() => { });
155
- }
156
- }
157
- return {
158
- uploaded,
159
- skipped,
160
- errors: transcriptUnavailable + parseFailed + uploadFailed,
161
- transcriptUnavailable,
162
- parseFailed,
163
- uploadFailed,
164
- indexError,
165
- };
166
- }
167
- const UTILITY_PROMPT_SIGNATURES = [
168
- /generate a 3-4 word title/i,
169
- /generate a concise session headline/i,
170
- /you are a watchdog|watchdog monitoring/i,
171
- /conventional[- ]commit/i,
172
- /factory worker/i,
173
- ];
174
- export function classifySessionKind(row, toolCallCount) {
175
- const haystack = `${row.topic ?? ''}\n${row.label ?? ''}`;
176
- if (UTILITY_PROMPT_SIGNATURES.some((re) => re.test(haystack)))
177
- return 'utility';
178
- const hasToolCalls = toolCallCount > 0 || (row.tool_call_count ?? 0) > 0;
179
- const messages = row.message_count ?? 0;
180
- if (!hasToolCalls && messages <= 2)
181
- return 'utility';
182
- return 'agent';
183
- }
184
- function percentile(values, ratio) {
185
- if (values.length === 0)
186
- return 0;
187
- const sorted = [...values].sort((a, b) => a - b);
188
- return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * ratio) - 1)];
189
- }
190
- const IDLE_GAP_THRESHOLD_MS = 120_000;
191
- const TOPIC_SESSION_CAP = 30;
192
- export function sessionActiveMs(spanMs, sessionCalls, sessionStartMs) {
193
- if (spanMs <= 0)
194
- return Math.max(0, spanMs);
195
- if (!Number.isFinite(sessionStartMs))
196
- return spanMs;
197
- const spanEndMs = sessionStartMs + spanMs;
198
- const ordered = sessionCalls
199
- .map((c) => ({ startMs: Date.parse(c.timestamp), endMs: Date.parse(c.end_timestamp ?? c.timestamp) }))
200
- .filter((c) => Number.isFinite(c.startMs))
201
- .sort((a, b) => a.startMs - b.startMs);
202
- if (ordered.length === 0)
203
- return spanMs;
204
- let idleMs = 0;
205
- let cursor = sessionStartMs;
206
- for (const call of ordered) {
207
- if (call.startMs > cursor + IDLE_GAP_THRESHOLD_MS)
208
- idleMs += call.startMs - cursor;
209
- const endMs = Number.isFinite(call.endMs) ? Math.max(call.endMs, call.startMs) : call.startMs;
210
- if (endMs > cursor)
211
- cursor = endMs;
212
- }
213
- if (spanEndMs > cursor + IDLE_GAP_THRESHOLD_MS)
214
- idleMs += spanEndMs - cursor;
215
- return Math.max(0, spanMs - Math.min(idleMs, spanMs));
216
- }
217
- export function activeMsFromTrajectory(traj) {
218
- const idleMs = traj.gaps.reduce((sum, gap) => sum + gap.durationMs, 0);
219
- return Math.max(0, traj.spanMs - Math.min(idleMs, traj.spanMs));
220
- }
221
- export function failureDescription(call, cause) {
222
- if (cause === 'guard')
223
- return /main-branch-guard/i.test(`${call.error_code ?? ''} ${call.error ?? ''}`)
224
- ? 'main branch guard' : 'git guard';
225
- if (cause === 'hook')
226
- return 'auto-mode hook denial';
227
- if (call.status_code != null)
228
- return `HTTP ${call.status_code}`;
229
- if (call.exit_code != null)
230
- return `exit ${call.exit_code}`;
231
- if (call.error_code)
232
- return 'tool error code';
233
- if (call.parse_error)
234
- return 'parse error';
235
- return 'tool error';
236
- }
237
- function attentionFlags(errorCount, facets) {
238
- const flags = [];
239
- if (errorCount > 0)
240
- flags.push(`${errorCount} error${errorCount === 1 ? '' : 's'}`);
241
- const friction = facets?.frictionSignals ?? {};
242
- const corrections = facets?.correctionSignals ?? {};
243
- const retryCount = Object.entries(friction)
244
- .filter(([key]) => key.startsWith('failed tool loop:'))
245
- .reduce((sum, [, count]) => sum + count, 0);
246
- if (retryCount > 0)
247
- flags.push('retry loop');
248
- const stall = Object.entries(friction).find(([key, count]) => key.startsWith('silent stall:') && count > 0);
249
- if (stall)
250
- flags.push(stall[0].replace('silent stall: ', 'stalled '));
251
- const correctionCount = Object.values(corrections).reduce((sum, count) => sum + count, 0);
252
- if (correctionCount > 0)
253
- flags.push(`${correctionCount} correction${correctionCount === 1 ? '' : 's'}`);
254
- return flags;
255
- }
256
- function persistDerivedCache(label, write) {
257
- try {
258
- write();
259
- }
260
- catch (err) {
261
- const msg = err instanceof Error ? err.message : String(err);
262
- console.warn(`traces: ${label} cache warm-up skipped (${msg}) — index still built`);
263
- }
264
- }
265
- export function buildIndexShard(rows, device, owner, prevShard) {
266
- const db = getDB();
267
- const knownSecrets = knownSecretValuesFromEnv();
268
- const ids = rows.map((row) => row.id);
269
- const calls = [];
270
- for (let i = 0; i < ids.length; i += 400) {
271
- const chunk = ids.slice(i, i + 400);
272
- calls.push(...db.prepare(`
273
- SELECT session_id, ordinal, timestamp, end_timestamp, tool, outcome, exit_code, status_code, error_code, error, parse_error
274
- FROM tool_calls
275
- WHERE session_id IN (${chunk.map(() => '?').join(',')})
276
- `).all(...chunk));
277
- }
278
- const toolMix = new Map();
279
- const errorCounts = new Map();
280
- const callsBySession = new Map();
281
- for (const call of calls) {
282
- const mix = toolMix.get(call.session_id) ?? {};
283
- mix[call.tool] = (mix[call.tool] ?? 0) + 1;
284
- toolMix.set(call.session_id, mix);
285
- if (call.outcome === 'error') {
286
- errorCounts.set(call.session_id, (errorCounts.get(call.session_id) ?? 0) + 1);
287
- }
288
- const list = callsBySession.get(call.session_id);
289
- if (list)
290
- list.push(call);
291
- else
292
- callsBySession.set(call.session_id, [call]);
293
- }
294
- const kindOf = new Map(rows.map((row) => [row.id, classifySessionKind(row, callsBySession.get(row.id)?.length ?? 0)]));
295
- const agentRows = rows.filter((row) => kindOf.get(row.id) === 'agent');
296
- const agentIds = agentRows.map((row) => row.id);
297
- const utilityCount = rows.length - agentRows.length;
298
- const agentCalls = calls.filter((call) => kindOf.get(call.session_id) === 'agent');
299
- const topics = readSessionTopics(agentIds);
300
- const missingTopics = agentRows.filter((row) => !topics.has(row.id)).map((row) => {
301
- const topic = classifyTopic({
302
- cwd: row.cwd,
303
- gitBranch: row.git_branch,
304
- topic: row.topic,
305
- label: row.label,
306
- toolMix: toolMix.get(row.id),
307
- });
308
- topics.set(row.id, topic);
309
- return { id: row.id, fileMtimeMs: row.file_mtime_ms, fileSize: row.file_size, topic };
310
- });
311
- persistDerivedCache('session-topics', () => writeSessionTopics(missingTopics));
312
- const insights = readSessionInsights(agentIds);
313
- const phenotypes = readSessionPhenotypes(agentIds);
314
- const missingInsights = [];
315
- const missingPhenotypes = [];
316
- for (const row of agentRows) {
317
- const needInsights = !insights.has(row.id);
318
- const needPhenotype = !phenotypes.has(row.id);
319
- if (!needInsights && !needPhenotype)
320
- continue;
321
- let events;
322
- try {
323
- events = parseSession(row.file_path, row.agent);
324
- }
325
- catch {
326
- continue;
327
- }
328
- if (needInsights) {
329
- try {
330
- const facets = computeInsightFacets(events);
331
- insights.set(row.id, facets);
332
- missingInsights.push({ id: row.id, fileMtimeMs: row.file_mtime_ms, fileSize: row.file_size, facets });
333
- }
334
- catch { }
335
- }
336
- if (needPhenotype) {
337
- try {
338
- const traj = buildTrajectory(events, rowToMeta(row), { redact: true, knownSecrets });
339
- const phenotype = classifyPhenotype(buildSessionDetail(traj));
340
- phenotypes.set(row.id, phenotype);
341
- missingPhenotypes.push({ id: row.id, fileMtimeMs: row.file_mtime_ms, fileSize: row.file_size, phenotype });
342
- }
343
- catch { }
344
- }
345
- }
346
- persistDerivedCache('session-insights', () => writeSessionInsights(missingInsights));
347
- persistDerivedCache('session-phenotypes', () => writeSessionPhenotypes(missingPhenotypes));
348
- const needsAttention = agentRows.flatMap((row) => {
349
- const facets = insights.get(row.id);
350
- const errorCount = errorCounts.get(row.id) ?? 0;
351
- const flags = attentionFlags(errorCount, facets);
352
- if (flags.length === 0)
353
- return [];
354
- const friction = Object.values(facets?.frictionSignals ?? {}).reduce((sum, count) => sum + count, 0);
355
- const corrections = Object.values(facets?.correctionSignals ?? {}).reduce((sum, count) => sum + count, 0);
356
- return [{
357
- id: row.id,
358
- title: redactSecrets(row.label ?? row.topic ?? topics.get(row.id)?.label ?? 'Untitled session', knownSecrets),
359
- repo: row.project ?? (row.cwd ? path.basename(row.cwd) : 'unknown'),
360
- device,
361
- agent: row.agent,
362
- model: row.model ?? 'unknown',
363
- kind: 'agent',
364
- severity: errorCount * 2 + friction * 3 + corrections * 2,
365
- flags,
366
- }];
367
- }).sort((a, b) => b.severity - a.severity || a.id.localeCompare(b.id));
368
- const topicCounts = new Map();
369
- for (const row of agentRows) {
370
- const topic = topics.get(row.id);
371
- if (!topic)
372
- continue;
373
- const bucket = topicCounts.get(topic.key)
374
- ?? { key: topic.key, label: topic.label, group: topic.group, count: 0, refs: [] };
375
- bucket.count++;
376
- bucket.refs.push({
377
- id: row.id,
378
- title: redactSecrets(row.label ?? row.topic ?? topic.label ?? 'Untitled session', knownSecrets),
379
- harness: row.agent,
380
- recencyMs: Date.parse(row.last_activity ?? row.timestamp) || 0,
381
- });
382
- topicCounts.set(topic.key, bucket);
383
- }
384
- const failedCalls = agentCalls.filter((call) => call.outcome === 'error');
385
- const byCause = { real: 0, guard: 0, hook: 0, behavioral: 0 };
386
- const failureCounts = new Map();
387
- for (const call of failedCalls) {
388
- const cause = classifyCause(call);
389
- const desc = failureDescription(call, cause);
390
- byCause[cause]++;
391
- const key = `${call.tool}\u0000${desc}\u0000${cause}`;
392
- const current = failureCounts.get(key) ?? { tool: call.tool, desc, cause, count: 0 };
393
- current.count++;
394
- failureCounts.set(key, current);
395
- }
396
- const activeDurations = agentRows.flatMap((row) => row.duration_ms == null
397
- ? []
398
- : [sessionActiveMs(row.duration_ms, callsBySession.get(row.id) ?? [], Date.parse(row.timestamp))]);
399
- const agentActive = [];
400
- const interactiveActive = [];
401
- let measured = 0;
402
- for (const row of agentRows) {
403
- if (row.duration_ms == null)
404
- continue;
405
- measured++;
406
- const active = sessionActiveMs(row.duration_ms, callsBySession.get(row.id) ?? [], Date.parse(row.timestamp));
407
- const isAgent = (callsBySession.get(row.id)?.length ?? 0) > 0 || (row.message_count ?? 0) > 8;
408
- (isAgent ? agentActive : interactiveActive).push(active);
409
- }
410
- const measuredFraction = agentRows.length === 0 ? 0 : measured / agentRows.length;
411
- const todayDate = new Date().toISOString().slice(0, 10);
412
- const todayStats = [...topicCounts.values()].map(({ key }) => {
413
- const sessionsInBucket = [...topics.entries()]
414
- .filter(([, t]) => t.key === key)
415
- .map(([id]) => id);
416
- const bucketCalls = agentCalls.filter((c) => sessionsInBucket.includes(c.session_id));
417
- const bucketErrors = bucketCalls.filter((c) => c.outcome === 'error').length;
418
- const errorRate = bucketCalls.length === 0 ? 0 : bucketErrors / bucketCalls.length;
419
- const stallCount = sessionsInBucket.filter((id) => {
420
- const facets = insights.get(id);
421
- return Object.entries(facets?.frictionSignals ?? {})
422
- .some(([k, v]) => k.startsWith('silent stall:') && v > 0);
423
- }).length;
424
- const stallRate = sessionsInBucket.length === 0 ? 0 : stallCount / sessionsInBucket.length;
425
- return { key, date: todayDate, count: topicCounts.get(key).count, errorRate, stallRate };
426
- });
427
- const prevHistory = prevShard?.bucketHistory ?? [];
428
- const bucketHistory = [...prevHistory, todayStats].slice(-14);
429
- const driftSignals = computeDriftSignal(prevHistory, todayStats);
430
- const behavioralPatterns = computeBehavioralPatterns(insights, prevShard);
431
- const patternInsights = computeInsights(agentRows, agentCalls, prevShard, phenotypes, behavioralPatterns);
432
- const needsAttentionIds = new Set(needsAttention.map((s) => s.id));
433
- const sessions = agentRows.map((row) => {
434
- const isAgent = (callsBySession.get(row.id)?.length ?? 0) > 0 || (row.message_count ?? 0) > 8;
435
- const durationMs = row.duration_ms == null
436
- ? 0
437
- : sessionActiveMs(row.duration_ms, callsBySession.get(row.id) ?? [], Date.parse(row.timestamp));
438
- const rosterRow = {
439
- id: row.id,
440
- title: redactSecrets(row.label ?? row.topic ?? topics.get(row.id)?.label ?? 'Untitled session', knownSecrets),
441
- harness: row.agent,
442
- model: row.model ?? 'unknown',
443
- repo: row.project ?? (row.cwd ? path.basename(row.cwd) : (row.git_branch ?? 'unknown')),
444
- mode: isAgent ? 'headless' : 'interactive',
445
- projectType: topics.get(row.id)?.group ?? 'code',
446
- startedAt: Date.parse(row.timestamp) || 0,
447
- durationMs,
448
- toolCount: row.tool_call_count ?? 0,
449
- errorCount: errorCounts.get(row.id) ?? 0,
450
- needsAttention: needsAttentionIds.has(row.id),
451
- };
452
- if (row.cost_usd != null)
453
- rosterRow.costUsd = row.cost_usd;
454
- return rosterRow;
455
- });
456
- return {
457
- schema: 1,
458
- device,
459
- syncedAt: Date.now(),
460
- owner,
461
- stats: {
462
- sessionsImported: agentRows.length,
463
- medianMs: percentile(activeDurations, 0.5),
464
- p90Ms: percentile(activeDurations, 0.9),
465
- agentMedianMs: percentile(agentActive, 0.5),
466
- agentP90Ms: percentile(agentActive, 0.9),
467
- interactiveMedianMs: percentile(interactiveActive, 0.5),
468
- measuredFraction,
469
- needAttention: needsAttention.length,
470
- toolErrorRate: agentCalls.length === 0 ? 0 : failedCalls.length / agentCalls.length,
471
- },
472
- utilityCount,
473
- needsAttention,
474
- topics: [...topicCounts.values()]
475
- .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key))
476
- .map((bucket) => ({
477
- key: bucket.key,
478
- label: bucket.label,
479
- count: bucket.count,
480
- group: bucket.group,
481
- sessions: bucket.refs
482
- .sort((a, b) => b.recencyMs - a.recencyMs)
483
- .slice(0, TOPIC_SESSION_CAP)
484
- .map(({ id, title, harness }) => ({ id, title, kind: 'agent', harness })),
485
- })),
486
- failures: {
487
- byToolError: [...failureCounts.values()].sort((a, b) => b.count - a.count || a.tool.localeCompare(b.tool)),
488
- byCause,
489
- },
490
- bucketHistory,
491
- driftSignals,
492
- failurePatterns: patternInsights.failurePatterns,
493
- wastedMsTotal: patternInsights.wastedMsTotal,
494
- latency: patternInsights.latency,
495
- sessions,
496
- };
497
- }
498
- export function buildWhereItWentWrong(traj) {
499
- const errorSteps = traj.steps.filter((s) => s.outcome === 'error');
500
- const biggestGap = traj.gaps.reduce((max, g) => (!max || g.durationMs > max.durationMs ? g : max), null);
501
- const parts = [];
502
- if (errorSteps.length > 0) {
503
- const first = errorSteps[0];
504
- const who = first.tool ?? first.lane;
505
- parts.push(`${errorSteps.length} tool error${errorSteps.length === 1 ? '' : 's'} (first: ${who} — ${first.label})`);
506
- }
507
- if (biggestGap && biggestGap.durationMs >= 60_000) {
508
- parts.push(`stalled ${Math.round(biggestGap.durationMs / 60_000)}m`);
509
- }
510
- if (parts.length === 0)
511
- return null;
512
- return `This run hit ${parts.join('; ')}.`;
513
- }
514
- export function deriveRunOutcome(traj) {
515
- if (traj.errorCount === 0)
516
- return 'completed';
517
- return recoveredAfterErrors({ steps: traj.steps }) ? 'completed' : 'errored';
518
- }
519
- export function buildDetailMeta(traj) {
520
- const s = traj.session;
521
- const stats = traj.stats;
522
- const repo = s.project ?? (s.cwd ? path.basename(s.cwd) : 'unknown');
523
- return {
524
- spanMs: traj.spanMs,
525
- activeMs: activeMsFromTrajectory(traj),
526
- turns: (stats.userTurns ?? 0) + (stats.assistantTurns ?? 0),
527
- tools: stats.toolCount ?? 0,
528
- errorCount: traj.errorCount,
529
- tokens: stats.outputTokens ?? 0,
530
- costUsd: s.costUsd ?? 0,
531
- outcome: deriveRunOutcome(traj),
532
- repo,
533
- agent: s.agent,
534
- model: s.model ?? 'unknown',
535
- };
536
- }
537
- export function buildSessionDetail(traj) {
538
- const s = traj.session;
539
- return {
540
- schema: 1,
541
- id: s.id,
542
- meta: buildDetailMeta(traj),
543
- steps: traj.steps,
544
- gaps: traj.gaps,
545
- truncatedSteps: traj.truncatedSteps,
546
- whereItWentWrong: buildWhereItWentWrong(traj),
547
- surfacedToolFailures: traj.steps
548
- .filter((step) => step.outcome === 'error')
549
- .map((step) => ({ tool: step.tool, label: step.label, detail: step.detail })),
550
- };
551
- }
552
- async function getIndexShard(backend, device) {
553
- const url = `${backend.baseUrl}/${backend.userId}/${device}/index.json`;
554
- try {
555
- const res = await fetch(url, {
556
- headers: { authorization: `Bearer ${backend.token}` },
557
- });
558
- if (!res.ok)
559
- return null;
560
- return await res.json();
561
- }
562
- catch {
563
- return null;
564
- }
565
- }
566
- async function putSessionTrace(backend, device, sessionId, traj, events, knownSecrets) {
567
- const url = `${backend.baseUrl}/${backend.userId}/${device}/sessions/${sessionId}.json`;
568
- const res = await fetch(url, {
569
- method: 'PUT',
570
- headers: {
571
- authorization: `Bearer ${backend.token}`,
572
- 'content-type': 'application/json; charset=utf-8',
573
- },
574
- body: JSON.stringify(buildSessionShard(traj, events, knownSecrets)),
575
- });
576
- if (!res.ok) {
577
- throw new Error(`PUT ${url} → ${res.status}`);
578
- }
579
- }
580
- async function putIndexShard(backend, device, owner, shard) {
581
- const full = { ...shard, device, owner, syncedAt: Date.now() };
582
- const url = `${backend.baseUrl}/${backend.userId}/${device}/index.json`;
583
- const res = await fetch(url, {
584
- method: 'PUT',
585
- headers: {
586
- authorization: `Bearer ${backend.token}`,
587
- 'content-type': 'application/json; charset=utf-8',
588
- },
589
- body: JSON.stringify(full),
590
- });
591
- if (!res.ok) {
592
- throw new Error(`PUT ${url} → ${res.status}`);
593
- }
594
- }
595
- const TRANSCRIPT_UNAVAILABLE_TTL_MS = 14 * 24 * 60 * 60 * 1000;
596
- function ledgerPath() {
597
- return path.join(getRuntimeStateDir(), 'traces-sync.json');
598
- }
599
- export function readSyncLedger() {
600
- try {
601
- const raw = fs.readFileSync(ledgerPath(), 'utf8');
602
- return JSON.parse(raw);
603
- }
604
- catch {
605
- return {};
606
- }
607
- }
608
- function writeSyncLedger(ledger) {
609
- const p = ledgerPath();
610
- fs.mkdirSync(path.dirname(p), { recursive: true });
611
- fs.writeFileSync(p, JSON.stringify(ledger, null, 2) + '\n', 'utf8');
612
- }
613
- export function hasSyncedBefore() {
614
- return fs.existsSync(ledgerPath());
615
- }
616
- function localDevice() {
617
- return (process.env['AGENTS_SYNC_MACHINE_ID'] ?? os.hostname()).toLowerCase().replace(/\.local$/, '');
618
- }
619
- function rowToMeta(row) {
620
- const SESSION_RUN_MODES = ['plan', 'edit', 'auto', 'skip'];
621
- return {
622
- id: row.id,
623
- shortId: row.short_id,
624
- agent: row.agent,
625
- origin: row.origin === 'routine' ? 'routine' : 'cli',
626
- routineName: row.routine_name ?? undefined,
627
- routineRunId: row.routine_run_id ?? undefined,
628
- timestamp: row.timestamp,
629
- lastActivity: row.last_activity ?? undefined,
630
- project: row.project ?? undefined,
631
- cwd: row.cwd ?? undefined,
632
- filePath: row.file_path,
633
- gitBranch: row.git_branch ?? undefined,
634
- messageCount: row.message_count ?? undefined,
635
- tokenCount: row.token_count ?? undefined,
636
- outputTokens: row.output_tokens ?? undefined,
637
- inputTokens: row.input_tokens ?? undefined,
638
- cacheReadTokens: row.cache_read_tokens ?? undefined,
639
- cacheWriteTokens: row.cache_write_tokens ?? undefined,
640
- costUsd: row.cost_usd ?? undefined,
641
- costUsdNoCache: row.cost_usd_nocache ?? undefined,
642
- durationMs: row.duration_ms ?? undefined,
643
- model: row.model ?? undefined,
644
- toolCallCount: row.tool_call_count ?? undefined,
645
- version: row.version ?? undefined,
646
- account: row.account ?? undefined,
647
- accountKey: row.account_key ?? undefined,
648
- accountOrg: row.account_org ?? undefined,
649
- mode: SESSION_RUN_MODES.includes(row.mode ?? '') ? row.mode : undefined,
650
- topic: row.topic ?? undefined,
651
- label: row.label ?? undefined,
652
- machine: row.machine ?? undefined,
653
- };
654
- }
@@ -1 +0,0 @@
1
- export declare function renderTracesWorkerScript(): string;