@phnx-labs/agents-cli 1.23.13 → 1.23.14

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 (162) hide show
  1. package/CHANGELOG.md +38 -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/triggers/webhook.d.ts +2 -59
  74. package/dist/lib/triggers/webhook.js +2 -422
  75. package/package.json +2 -1
  76. package/dist/commands/funnel.d.ts +0 -2
  77. package/dist/commands/funnel.js +0 -77
  78. package/dist/commands/logs.d.ts +0 -2
  79. package/dist/commands/mailboxes.d.ts +0 -2
  80. package/dist/commands/mailboxes.js +0 -400
  81. package/dist/commands/message.d.ts +0 -2
  82. package/dist/commands/message.js +0 -259
  83. package/dist/commands/packages-materialize.d.ts +0 -6
  84. package/dist/commands/packages-materialize.js +0 -90
  85. package/dist/commands/packages.d.ts +0 -5
  86. package/dist/commands/packages.js +0 -763
  87. package/dist/commands/route.d.ts +0 -2
  88. package/dist/commands/route.js +0 -259
  89. package/dist/commands/testdata/feed-hub.d.ts +0 -1
  90. package/dist/commands/testdata/feed-hub.js +0 -11
  91. package/dist/commands/tmux.d.ts +0 -7
  92. package/dist/commands/tmux.js +0 -529
  93. package/dist/commands/traces.d.ts +0 -2
  94. package/dist/commands/traces.js +0 -204
  95. package/dist/commands/webhook.d.ts +0 -5
  96. package/dist/commands/webhook.js +0 -105
  97. package/dist/lib/agent-spec/materialize.d.ts +0 -3
  98. package/dist/lib/agent-spec/materialize.js +0 -277
  99. package/dist/lib/agent-spec/package-resolve.d.ts +0 -4
  100. package/dist/lib/agent-spec/package-resolve.js +0 -231
  101. package/dist/lib/agent-spec/package-schema.d.ts +0 -3
  102. package/dist/lib/agent-spec/package-schema.js +0 -136
  103. package/dist/lib/agent-spec/package-types.d.ts +0 -94
  104. package/dist/lib/agent-spec/package-types.js +0 -10
  105. package/dist/lib/daemon/testdata/process-view-daemon.d.ts +0 -1
  106. package/dist/lib/daemon/testdata/process-view-daemon.js +0 -12
  107. package/dist/lib/daemon/testdata/process-view-start.d.ts +0 -1
  108. package/dist/lib/daemon/testdata/process-view-start.js +0 -41
  109. package/dist/lib/daemon/webhook-receiver-service.d.ts +0 -8
  110. package/dist/lib/daemon/webhook-receiver-service.js +0 -16
  111. package/dist/lib/daemon-webhooks.d.ts +0 -48
  112. package/dist/lib/daemon-webhooks.js +0 -177
  113. package/dist/lib/funnel.d.ts +0 -6
  114. package/dist/lib/funnel.js +0 -31
  115. package/dist/lib/net-close.d.ts +0 -2
  116. package/dist/lib/net-close.js +0 -20
  117. package/dist/lib/packages/output-home.d.ts +0 -9
  118. package/dist/lib/packages/output-home.js +0 -89
  119. package/dist/lib/registry.d.ts +0 -65
  120. package/dist/lib/registry.js +0 -432
  121. package/dist/lib/routers.d.ts +0 -25
  122. package/dist/lib/routers.js +0 -122
  123. package/dist/lib/run-trace-sync.d.ts +0 -7
  124. package/dist/lib/run-trace-sync.js +0 -35
  125. package/dist/lib/session/testdata/pid-registry-namespace.d.ts +0 -1
  126. package/dist/lib/session/testdata/pid-registry-namespace.js +0 -25
  127. package/dist/lib/session/testdata/process-view-namespace.d.ts +0 -1
  128. package/dist/lib/session/testdata/process-view-namespace.js +0 -56
  129. package/dist/lib/session/testdata/process-view-private.d.ts +0 -1
  130. package/dist/lib/session/testdata/process-view-private.js +0 -11
  131. package/dist/lib/testdata/daemon-health-writer.d.ts +0 -1
  132. package/dist/lib/testdata/daemon-health-writer.js +0 -8
  133. package/dist/lib/testdata/owner-notify-api.d.ts +0 -23
  134. package/dist/lib/testdata/owner-notify-api.js +0 -82
  135. package/dist/lib/testdata/refresh-coordinator-worker.d.ts +0 -1
  136. package/dist/lib/testdata/refresh-coordinator-worker.js +0 -23
  137. package/dist/lib/traces/backend.d.ts +0 -8
  138. package/dist/lib/traces/backend.js +0 -33
  139. package/dist/lib/traces/classify.d.ts +0 -40
  140. package/dist/lib/traces/classify.js +0 -70
  141. package/dist/lib/traces/config.d.ts +0 -2
  142. package/dist/lib/traces/config.js +0 -2
  143. package/dist/lib/traces/insights.d.ts +0 -30
  144. package/dist/lib/traces/insights.js +0 -198
  145. package/dist/lib/traces/phenotype.d.ts +0 -18
  146. package/dist/lib/traces/phenotype.js +0 -335
  147. package/dist/lib/traces/provision.d.ts +0 -16
  148. package/dist/lib/traces/provision.js +0 -25
  149. package/dist/lib/traces/schema2-build.d.ts +0 -28
  150. package/dist/lib/traces/schema2-build.js +0 -496
  151. package/dist/lib/traces/schema2-danger.d.ts +0 -7
  152. package/dist/lib/traces/schema2-danger.js +0 -123
  153. package/dist/lib/traces/schema2.d.ts +0 -139
  154. package/dist/lib/traces/schema2.js +0 -20
  155. package/dist/lib/traces/segments.d.ts +0 -73
  156. package/dist/lib/traces/segments.js +0 -236
  157. package/dist/lib/traces/sync.d.ts +0 -197
  158. package/dist/lib/traces/sync.js +0 -654
  159. package/dist/lib/traces/worker-template.d.ts +0 -1
  160. package/dist/lib/traces/worker-template.js +0 -292
  161. package/dist/lib/triggers/handlers.d.ts +0 -66
  162. package/dist/lib/triggers/handlers.js +0 -383
@@ -1,56 +0,0 @@
1
- import fs from 'node:fs';
2
- import { spawnSync } from 'node:child_process';
3
- import { getTerminalsDir } from '../../state.js';
4
- import { hostProcessView, requireWriterProcessView, recordDaemonProcessView } from '../process-view.js';
5
- const mode = process.argv[2];
6
- try {
7
- if (mode === 'hook-first') {
8
- const hook = process.env.AGENTS_SESSION_IDENTITY_TEST_HOOK;
9
- const child = hook
10
- ? spawnSync('bash', [hook], { input: JSON.stringify({ session_id: 'init-hook', cwd: process.cwd() }), encoding: 'utf8', env: process.env })
11
- : spawnSync('bun', [import.meta.filename, 'once'], { encoding: 'utf8', env: process.env });
12
- if (child.status !== 0)
13
- throw new Error(child.stderr);
14
- if (!fs.existsSync(`${getTerminalsDir()}/process-view.json`))
15
- throw new Error('child did not enroll its namespace');
16
- }
17
- if (mode === 'daemon')
18
- recordDaemonProcessView();
19
- if (mode === 'read') {
20
- console.log(hostProcessView() ? 'owned' : 'unowned');
21
- process.exit(0);
22
- }
23
- if (mode === 'publish' || mode === 'snapshot') {
24
- const { loadLocalActiveSessions, loadFleetActiveSessions, writeActiveSessionsCache } = await import('../session-cache.js');
25
- if (mode === 'publish') {
26
- writeActiveSessionsCache('local', [], { capturedAt: 1 });
27
- writeActiveSessionsCache('fleet', [], { capturedAt: 1 });
28
- }
29
- else {
30
- const gather = async () => { throw new Error('foreign observer gathered'); };
31
- const local = await loadLocalActiveSessions({ forceRefresh: true, gather });
32
- const fleet = await loadFleetActiveSessions({ forceRefresh: true, gather });
33
- if (!local.servedFromCache || !fleet.servedFromCache || local.capturedAt !== 1 || fleet.capturedAt !== 1)
34
- throw new Error('foreign snapshot changed');
35
- console.log('observed');
36
- process.exit(0);
37
- }
38
- }
39
- if (mode === 'sessions') {
40
- const { loadLocalActiveSessions } = await import('../session-cache.js');
41
- const result = await loadLocalActiveSessions({ forceRefresh: true });
42
- if (result.servedFromCache || !Array.isArray(result.sessions))
43
- throw new Error('cold discovery did not run');
44
- }
45
- requireWriterProcessView();
46
- console.log('owned');
47
- if (mode === 'hold' || mode === 'hook-first') {
48
- process.on('SIGTERM', () => process.exit(0));
49
- setInterval(() => { }, 1000);
50
- }
51
- }
52
- catch (error) {
53
- console.error(error.message);
54
- console.log('denied');
55
- process.exitCode = 2;
56
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,11 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import fs from 'node:fs';
3
- import { writePidSessionEntry, readLivePidSessionEntry } from '../pid-registry.js';
4
- import { writeActiveSessionsCache, readActiveSessionsCache } from '../session-cache.js';
5
- assert.equal(process.pid, 1);
6
- fs.writeFileSync('/proc/self/comm', process.argv[2]);
7
- writePidSessionEntry({ pid: process.pid, agent: 'codex', sessionId: 'private-home', startedAtMs: Date.now() });
8
- assert.equal(readLivePidSessionEntry(process.pid)?.sessionId, 'private-home');
9
- writeActiveSessionsCache('local', [{ context: 'headless', kind: 'codex', sessionId: 'private-home', status: 'running' }]);
10
- assert.equal(readActiveSessionsCache('local')?.sessions[0]?.sessionId, 'private-home');
11
- console.log('private home: registry and snapshot published');
@@ -1 +0,0 @@
1
- export {};
@@ -1,8 +0,0 @@
1
- import { recordSubsystemError } from '../daemon-health.js';
2
- const [subsystem, countRaw] = process.argv.slice(2);
3
- const count = Number(countRaw);
4
- if (!subsystem || !Number.isInteger(count) || count < 1)
5
- process.exit(2);
6
- for (let i = 0; i < count; i++) {
7
- recordSubsystemError(subsystem, `${process.pid}:${i}`);
8
- }
@@ -1,23 +0,0 @@
1
- export interface RecordedRequest {
2
- method: string;
3
- path: string;
4
- bearer: string | null;
5
- body: unknown;
6
- }
7
- interface DeviceToken {
8
- id: string;
9
- token: string;
10
- device: string;
11
- createdAt: string;
12
- }
13
- export interface OwnerNotifyApi {
14
- url: string;
15
- requests: RecordedRequest[];
16
- sessionToken: string;
17
- deviceTokens: DeviceToken[];
18
- dedupKeys: string[];
19
- preferencesStatus: number;
20
- close(): Promise<void>;
21
- }
22
- export declare function startOwnerNotifyApi(sessionToken?: string): Promise<OwnerNotifyApi>;
23
- export {};
@@ -1,82 +0,0 @@
1
- import * as http from 'node:http';
2
- const EVENTS = new Set(['needs_you', 'completed', 'failed', 'spend_threshold', 'message']);
3
- function send(res, status, body) {
4
- res.writeHead(status, { 'Content-Type': 'application/json' });
5
- res.end(body === undefined ? undefined : JSON.stringify(body));
6
- }
7
- export async function startOwnerNotifyApi(sessionToken = 'phx-session-token') {
8
- let seq = 0;
9
- const seen = new Set();
10
- const api = {
11
- url: '',
12
- requests: [],
13
- sessionToken,
14
- deviceTokens: [],
15
- dedupKeys: [],
16
- preferencesStatus: 200,
17
- close: async () => { },
18
- };
19
- const server = http.createServer((req, res) => {
20
- let raw = '';
21
- req.on('data', (chunk) => { raw += chunk.toString('utf-8'); });
22
- req.on('end', () => {
23
- const url = new URL(req.url ?? '/', 'http://fixture');
24
- const bearer = req.headers.authorization?.replace(/^Bearer /, '') ?? null;
25
- const body = raw ? JSON.parse(raw) : null;
26
- api.requests.push({ method: req.method ?? '', path: url.pathname, bearer, body });
27
- const device = api.deviceTokens.find((t) => t.token === bearer);
28
- const isSession = bearer === api.sessionToken;
29
- if (!isSession && !device)
30
- return send(res, 401, { error: 'Unauthorized', code: 'UNAUTHORIZED' });
31
- const tokenId = url.pathname.match(/^\/api\/v1\/auth\/tokens\/([^/]+)$/);
32
- if (tokenId && req.method === 'DELETE') {
33
- if (!isSession)
34
- return send(res, 403, { error: 'device_token_forbidden' });
35
- const before = api.deviceTokens.length;
36
- api.deviceTokens = api.deviceTokens.filter((t) => t.id !== decodeURIComponent(tokenId[1]));
37
- return send(res, before === api.deviceTokens.length ? 404 : 204);
38
- }
39
- if (url.pathname === '/api/v1/auth/tokens') {
40
- if (!isSession)
41
- return send(res, 403, { error: 'device_token_forbidden' });
42
- if (req.method === 'GET') {
43
- return send(res, 200, api.deviceTokens.map((t) => ({ id: t.id, kind: 'device', device: t.device, scopes: ['notify'], createdAt: t.createdAt })));
44
- }
45
- const name = String(body?.device);
46
- api.deviceTokens = api.deviceTokens.filter((t) => t.device !== name);
47
- const minted = { id: `tok-${++seq}`, token: `phx-device-${name}-${seq}`, device: name, createdAt: new Date().toISOString() };
48
- api.deviceTokens.push(minted);
49
- return send(res, 201, { id: minted.id, token: minted.token, kind: 'device', device: name, scopes: ['notify'], createdAt: minted.createdAt });
50
- }
51
- if (url.pathname === '/me/preferences' && req.method === 'PUT') {
52
- if (!isSession)
53
- return send(res, 403, { error: 'device_token_scope', code: 'DEVICE_TOKEN_SCOPE' });
54
- return api.preferencesStatus === 200
55
- ? send(res, 200, { ok: true })
56
- : send(res, api.preferencesStatus, { error: 'unknown event: message', code: 'INVALID_EVENT' });
57
- }
58
- if (url.pathname === '/me/notifications' && req.method === 'POST') {
59
- if (!body || !EVENTS.has(String(body.event)) || typeof body.title !== 'string' || typeof body.body !== 'string' || typeof body.dedupKey !== 'string') {
60
- return send(res, 400, { error: 'invalid notification', code: 'INVALID_BODY' });
61
- }
62
- api.dedupKeys.push(body.dedupKey);
63
- const key = `${body.event}\0${body.dedupKey}`;
64
- if (seen.has(key))
65
- return send(res, 200, { dispatchId: null, delivered: [], queued: [], skipped: [], suppressed: 'duplicate' });
66
- seen.add(key);
67
- return send(res, 200, {
68
- dispatchId: `dsp-${++seq}`,
69
- delivered: [],
70
- queued: ['slack', 'imessage'],
71
- skipped: [],
72
- suppressed: null,
73
- });
74
- }
75
- return send(res, 404, { error: `no route ${req.method} ${url.pathname}` });
76
- });
77
- });
78
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
79
- api.url = `http://127.0.0.1:${server.address().port}`;
80
- api.close = () => new Promise((resolve) => server.close(() => resolve()));
81
- return api;
82
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,23 +0,0 @@
1
- import * as fs from 'node:fs';
2
- import { setRefreshLockRootForTest, withRefreshLease } from '../refresh-coordinator.js';
3
- const [lockRoot, resultPath, countPath, key] = process.argv.slice(2);
4
- setRefreshLockRootForTest(lockRoot);
5
- await withRefreshLease({
6
- scope: 'cross-process-test',
7
- key,
8
- readCompleted: () => {
9
- try {
10
- return Number(fs.readFileSync(resultPath, 'utf-8'));
11
- }
12
- catch {
13
- return null;
14
- }
15
- },
16
- isCompleted: (value) => value === 1,
17
- refresh: async () => {
18
- fs.appendFileSync(countPath, 'refresh\n');
19
- await new Promise((resolve) => setTimeout(resolve, 100));
20
- fs.writeFileSync(resultPath, '1');
21
- return 1;
22
- },
23
- });
@@ -1,8 +0,0 @@
1
- export declare const DEFAULT_TRACES_DOMAIN = "traces.agents-cli.sh";
2
- export interface TracesBackend {
3
- baseUrl: string;
4
- token: string;
5
- userId: string;
6
- }
7
- export declare function resolveTracesBackend(): TracesBackend;
8
- export declare function managedTracesBaseUrl(): string;
@@ -1,33 +0,0 @@
1
- import { readSession } from '../identity/client.js';
2
- import { selectStorageBackendKind } from '../storage/selection.js';
3
- export const DEFAULT_TRACES_DOMAIN = 'traces.agents-cli.sh';
4
- export function resolveTracesBackend() {
5
- const envBase = (process.env['AGENTS_TRACES_BASE_URL'] ?? '').replace(/\/+$/, '').trim();
6
- const envToken = (process.env['AGENTS_TRACES_WRITE_TOKEN'] ?? '').trim();
7
- const byoOverride = Boolean(envBase && envToken);
8
- if (selectStorageBackendKind({ byoOverride }) === 'byo') {
9
- if (byoOverride) {
10
- return { baseUrl: envBase, token: envToken, userId: 'byo' };
11
- }
12
- throw new Error("Not signed in. Run 'agents auth login' to sync traces to your Phoenix account.");
13
- }
14
- const session = readSession();
15
- if (!session) {
16
- throw new Error("Not signed in. Run 'agents auth login' to sync traces to your Phoenix account.");
17
- }
18
- if (!session.access_token) {
19
- throw new Error("Session has no access token. Run 'agents auth login' again.");
20
- }
21
- const userId = (session.userId ?? '').trim();
22
- if (!userId) {
23
- throw new Error("Signed in but the session has no user id. Run 'agents auth login' again.");
24
- }
25
- return {
26
- baseUrl: managedTracesBaseUrl(),
27
- token: session.access_token,
28
- userId,
29
- };
30
- }
31
- export function managedTracesBaseUrl() {
32
- return `https://${DEFAULT_TRACES_DOMAIN}`;
33
- }
@@ -1,40 +0,0 @@
1
- export type TraceTopicGroup = 'code' | 'research' | 'review' | 'content' | 'ops';
2
- export type TraceFailureCause = 'real' | 'guard' | 'hook' | 'behavioral';
3
- export interface BucketStats {
4
- key: string;
5
- date: string;
6
- count: number;
7
- errorRate: number;
8
- stallRate: number;
9
- }
10
- export interface DriftSignal {
11
- bucket: string;
12
- errorDelta: number;
13
- stallDelta: number;
14
- severity: 'degrading' | 'stable' | 'improving';
15
- }
16
- interface TopicEvidence {
17
- cwd?: string | null;
18
- gitBranch?: string | null;
19
- topic?: string | null;
20
- label?: string | null;
21
- toolMix?: Record<string, number>;
22
- }
23
- export interface ClassifiedTopic {
24
- group: TraceTopicGroup;
25
- key: string;
26
- label: string;
27
- }
28
- interface ToolCallFailure {
29
- tool: string;
30
- exit_code?: number | null;
31
- status_code?: number | null;
32
- error_code?: string | null;
33
- error?: string | null;
34
- parse_error?: string | null;
35
- outcome?: string | null;
36
- }
37
- export declare function classifyTopic(input: TopicEvidence): ClassifiedTopic;
38
- export declare function classifyCause(call: ToolCallFailure): TraceFailureCause;
39
- export declare function computeDriftSignal(history: BucketStats[][], today: BucketStats[]): DriftSignal[];
40
- export {};
@@ -1,70 +0,0 @@
1
- function normalizedEvidence(input) {
2
- return [input.cwd, input.gitBranch, input.topic, input.label]
3
- .filter((value) => typeof value === 'string')
4
- .join(' ')
5
- .toLowerCase();
6
- }
7
- const TOPIC_RULES = [
8
- { group: 'review', key: 'code-review', label: 'Code review',
9
- text: /\b(review|audit|pr[-_/ ]?review|code[-_/ ]?review)\b/, tool: /review|comment/ },
10
- { group: 'ops', key: 'release', label: 'Release',
11
- text: /\b(release|deploy|publish|rollout|changelog)\b/ },
12
- { group: 'research', key: 'debugging', label: 'Debugging',
13
- text: /\b(debug|investigat|repro|root[-_ ]?cause|traceback|stack ?trace)\b/ },
14
- { group: 'content', key: 'content', label: 'Blog & docs',
15
- text: /\b(blog|docs?|documentation|readme|post|article|content|caption)\b/ },
16
- { group: 'research', key: 'research', label: 'Research',
17
- text: /\b(research|analysis|benchmark|paper|explore|spike)\b/, tool: /web_search|search_query|webfetch|browser/ },
18
- { group: 'code', key: 'bugfix', label: 'Bug fixes',
19
- text: /\b(fix|bug|hotfix|patch)\b/ },
20
- { group: 'code', key: 'refactor', label: 'Refactor',
21
- text: /\b(refactor|cleanup|clean[-_ ]?up|restructure|rename|tidy)\b/ },
22
- { group: 'ops', key: 'operations', label: 'Fleet / ops',
23
- text: /\b(fleet|ci|infra|daemon|provision|ops|pipeline)\b/, tool: /ssh|deploy|computer/ },
24
- { group: 'code', key: 'feature', label: 'Feature work',
25
- text: /\b(feat|feature|implement|add|build|code|test)\b/, tool: /edit|write|apply_patch|exec|bash|shell/ },
26
- ];
27
- export function classifyTopic(input) {
28
- const text = normalizedEvidence(input);
29
- const tools = Object.keys(input.toolMix ?? {}).map((tool) => tool.toLowerCase());
30
- for (const rule of TOPIC_RULES) {
31
- if ((rule.text && rule.text.test(text)) || (rule.tool && tools.some((tool) => rule.tool.test(tool)))) {
32
- return { group: rule.group, key: rule.key, label: rule.label };
33
- }
34
- }
35
- return { group: 'research', key: 'general', label: 'General' };
36
- }
37
- export function classifyCause(call) {
38
- const evidence = [call.error_code, call.error, call.parse_error]
39
- .filter((value) => typeof value === 'string')
40
- .join(' ')
41
- .toLowerCase();
42
- if (/\b(?:git-guard|main-branch-guard)\b/.test(evidence))
43
- return 'guard';
44
- if (/permission\b.*\bdenied\b.*\b(?:auto[- ]mode|classifier)\b/.test(evidence)) {
45
- return 'hook';
46
- }
47
- return 'real';
48
- }
49
- const DRIFT_THRESHOLD = 0.20;
50
- export function computeDriftSignal(history, today) {
51
- const signals = [];
52
- for (const stat of today) {
53
- const pastStats = history
54
- .flatMap((day) => day.filter((b) => b.key === stat.key))
55
- .slice(-7);
56
- if (pastStats.length < 3)
57
- continue;
58
- const avgError = pastStats.reduce((sum, b) => sum + b.errorRate, 0) / pastStats.length;
59
- const avgStall = pastStats.reduce((sum, b) => sum + b.stallRate, 0) / pastStats.length;
60
- const errorDelta = stat.errorRate - avgError;
61
- const stallDelta = stat.stallRate - avgStall;
62
- const severity = errorDelta > DRIFT_THRESHOLD || stallDelta > DRIFT_THRESHOLD
63
- ? 'degrading'
64
- : errorDelta < -DRIFT_THRESHOLD || stallDelta < -DRIFT_THRESHOLD
65
- ? 'improving'
66
- : 'stable';
67
- signals.push({ bucket: stat.key, errorDelta, stallDelta, severity });
68
- }
69
- return signals.sort((a, b) => b.errorDelta - a.errorDelta);
70
- }
@@ -1,2 +0,0 @@
1
- export declare const DEFAULT_WORKER_NAME = "agents-traces";
2
- export declare const DEFAULT_BUCKET_NAME = "agents-traces";
@@ -1,2 +0,0 @@
1
- export const DEFAULT_WORKER_NAME = 'agents-traces';
2
- export const DEFAULT_BUCKET_NAME = 'agents-traces';
@@ -1,30 +0,0 @@
1
- import { type TraceFailureCause } from './classify.js';
2
- import type { FailurePhenotype } from './phenotype.js';
3
- import { type LatencyInsight } from './segments.js';
4
- import { type SyncRow, type ToolCallRow, type TracesIndexShard } from './sync.js';
5
- import type { InsightFacets } from '@phnx-labs/sessions-cli/reader';
6
- export interface FailureSignature {
7
- tool: string;
8
- cause: TraceFailureCause;
9
- key: string;
10
- }
11
- export interface FailurePattern {
12
- id: string;
13
- label: string;
14
- signature: FailureSignature;
15
- phenotype: FailurePhenotype | null;
16
- sessions: number;
17
- occurrences: number;
18
- wastedMs: number;
19
- exampleSessionIds: string[];
20
- drift: 'up' | 'flat' | 'down';
21
- }
22
- interface ComputedInsights {
23
- failurePatterns: FailurePattern[];
24
- wastedMsTotal: number;
25
- latency: LatencyInsight;
26
- }
27
- export declare function normalizeErrorKey(desc: string, raw: string | null): string;
28
- export declare function computeInsights(rows: readonly SyncRow[], calls: readonly ToolCallRow[], prevShard?: TracesIndexShard | null, phenotypes?: ReadonlyMap<string, FailurePhenotype | null>, behavioralPatterns?: readonly FailurePattern[]): ComputedInsights;
29
- export declare function computeBehavioralPatterns(facetsBySession: ReadonlyMap<string, Pick<InsightFacets, 'frictionSignals'>>, prevShard?: TracesIndexShard | null): FailurePattern[];
30
- export {};
@@ -1,198 +0,0 @@
1
- import { classifyCause } from './classify.js';
2
- import { computeLatency } from './segments.js';
3
- import { failureDescription } from './sync.js';
4
- const TOP_K_PATTERNS = 25;
5
- const MAX_EXAMPLE_SESSIONS = 5;
6
- const STALL_MS = 60_000;
7
- const MAX_GAP_ATTRIBUTION_MS = 30 * 60_000;
8
- const VOLATILE_TOKEN_PATTERNS = [
9
- { pattern: /\bfor user [\w.-]+/gi, replacement: 'for user _' },
10
- { pattern: /\btry again in [\w.]+s?\b/gi, replacement: 'try again in _s' },
11
- { pattern: /\b[0-9a-f]{7,40}\b/gi, replacement: '_sha_' },
12
- { pattern: /\b[\w.-]+@[\w.-]+\.\w+\b/gi, replacement: '_email_' },
13
- { pattern: /\b\d+\b/g, replacement: '_n_' },
14
- ];
15
- export function normalizeErrorKey(desc, raw) {
16
- let text = (raw && raw.trim().length > 0 ? raw : desc).toLowerCase();
17
- for (const { pattern, replacement } of VOLATILE_TOKEN_PATTERNS) {
18
- text = text.replace(pattern, replacement);
19
- }
20
- return text.replace(/\s+/g, ' ').trim().slice(0, 160);
21
- }
22
- function hashSignature(tool, cause, key, phenotype) {
23
- const input = `${tool} ${cause} ${key} ${phenotype ?? ''}`;
24
- let hash = 5381;
25
- for (let i = 0; i < input.length; i++) {
26
- hash = ((hash << 5) + hash + input.charCodeAt(i)) >>> 0;
27
- }
28
- return hash.toString(16).padStart(8, '0');
29
- }
30
- const LABEL_RULES = [
31
- { pattern: /rate limit/i, label: 'rate limit back-off loop' },
32
- { pattern: /permission denied/i, label: 'permission denied' },
33
- { pattern: /not found|no such file/i, label: 'missing resource' },
34
- { pattern: /timed? ?out/i, label: 'timeout' },
35
- { pattern: /econnrefused|connection refused|network/i, label: 'network error' },
36
- { pattern: /conflict|diverged/i, label: 'git conflict' },
37
- ];
38
- function labelFor(tool, cause, key) {
39
- if (cause === 'guard')
40
- return `${tool}: git guard denial`;
41
- if (cause === 'hook')
42
- return `${tool}: hook denial`;
43
- const rule = LABEL_RULES.find((row) => row.pattern.test(key));
44
- return `${tool}: ${rule ? rule.label : key.slice(0, 48)}`;
45
- }
46
- export function computeInsights(rows, calls, prevShard, phenotypes, behavioralPatterns = []) {
47
- const bySession = new Map();
48
- for (const call of calls) {
49
- const list = bySession.get(call.session_id);
50
- if (list)
51
- list.push(call);
52
- else
53
- bySession.set(call.session_id, [call]);
54
- }
55
- const groups = new Map();
56
- for (const [sessionId, sessionCalls] of bySession) {
57
- const phenotype = phenotypes?.get(sessionId) ?? null;
58
- const ordered = [...sessionCalls].sort((a, b) => a.ordinal - b.ordinal);
59
- for (let i = 0; i < ordered.length; i++) {
60
- const call = ordered[i];
61
- if (call.outcome !== 'error')
62
- continue;
63
- const cause = classifyCause(call);
64
- const key = normalizeErrorKey(failureDescription(call, cause), call.error);
65
- const groupKey = `${call.tool} ${cause} ${key} ${phenotype ?? ''}`;
66
- let group = groups.get(groupKey);
67
- if (!group) {
68
- group = { tool: call.tool, cause, key, phenotype, sessions: new Set(), occurrences: 0, wastedMs: 0, examples: [] };
69
- groups.set(groupKey, group);
70
- }
71
- group.occurrences++;
72
- group.sessions.add(sessionId);
73
- if (group.examples.length < MAX_EXAMPLE_SESSIONS && !group.examples.includes(sessionId)) {
74
- group.examples.push(sessionId);
75
- }
76
- const startMs = Date.parse(call.timestamp);
77
- const endMs = call.end_timestamp ? Date.parse(call.end_timestamp) : NaN;
78
- const hasEnd = Number.isFinite(endMs) && Number.isFinite(startMs);
79
- if (hasEnd) {
80
- const ownMs = endMs - startMs;
81
- if (ownMs > 0)
82
- group.wastedMs += Math.min(ownMs, MAX_GAP_ATTRIBUTION_MS);
83
- }
84
- const next = ordered[i + 1];
85
- if (!next)
86
- continue;
87
- const gapFromMs = hasEnd ? endMs : startMs;
88
- const gapMs = Date.parse(next.timestamp) - gapFromMs;
89
- if (!Number.isFinite(gapMs) || gapMs <= 0)
90
- continue;
91
- const nextIsSameFailure = next.outcome === 'error' &&
92
- next.tool === call.tool &&
93
- classifyCause(next) === cause &&
94
- normalizeErrorKey(failureDescription(next, cause), next.error) === key;
95
- if (nextIsSameFailure) {
96
- group.wastedMs += Math.min(gapMs, MAX_GAP_ATTRIBUTION_MS);
97
- }
98
- else if (gapMs >= STALL_MS) {
99
- group.wastedMs += Math.min(gapMs, MAX_GAP_ATTRIBUTION_MS);
100
- }
101
- }
102
- }
103
- const prevById = new Map((prevShard?.failurePatterns ?? []).map((p) => [p.id, p]));
104
- const allPatterns = [...groups.values()].map((group) => {
105
- const id = hashSignature(group.tool, group.cause, group.key, group.phenotype);
106
- const prev = prevById.get(id);
107
- const drift = !prev
108
- ? 'up'
109
- : group.occurrences > prev.occurrences
110
- ? 'up'
111
- : group.occurrences < prev.occurrences
112
- ? 'down'
113
- : 'flat';
114
- return {
115
- id,
116
- label: labelFor(group.tool, group.cause, group.key),
117
- signature: { tool: group.tool, cause: group.cause, key: group.key },
118
- phenotype: group.phenotype,
119
- sessions: group.sessions.size,
120
- occurrences: group.occurrences,
121
- wastedMs: group.wastedMs,
122
- exampleSessionIds: group.examples,
123
- drift,
124
- };
125
- });
126
- const combined = [...allPatterns, ...behavioralPatterns];
127
- const wastedMsTotal = combined.reduce((sum, p) => sum + p.wastedMs, 0);
128
- const failurePatterns = [...combined]
129
- .sort((a, b) => b.wastedMs - a.wastedMs || b.occurrences - a.occurrences || a.id.localeCompare(b.id))
130
- .slice(0, TOP_K_PATTERNS);
131
- const latency = computeLatency(firstToolSegments(rows, bySession));
132
- return { failurePatterns, wastedMsTotal, latency };
133
- }
134
- const SILENT_STALL_WASTED_MS = {
135
- '5-15m': 10 * 60_000,
136
- '15-60m': MAX_GAP_ATTRIBUTION_MS,
137
- '1h+': MAX_GAP_ATTRIBUTION_MS,
138
- };
139
- export function computeBehavioralPatterns(facetsBySession, prevShard) {
140
- const groups = new Map();
141
- for (const [sessionId, facets] of facetsBySession) {
142
- for (const [signal, count] of Object.entries(facets.frictionSignals ?? {})) {
143
- if (count <= 0)
144
- continue;
145
- const match = /^silent stall: (.+)$/.exec(signal);
146
- if (!match)
147
- continue;
148
- const bucket = match[1];
149
- let group = groups.get(bucket);
150
- if (!group) {
151
- group = { bucket, sessions: new Set(), occurrences: 0, wastedMs: 0, examples: [] };
152
- groups.set(bucket, group);
153
- }
154
- group.occurrences += count;
155
- group.sessions.add(sessionId);
156
- group.wastedMs += (SILENT_STALL_WASTED_MS[bucket] ?? MAX_GAP_ATTRIBUTION_MS) * count;
157
- if (group.examples.length < MAX_EXAMPLE_SESSIONS && !group.examples.includes(sessionId)) {
158
- group.examples.push(sessionId);
159
- }
160
- }
161
- }
162
- const prevById = new Map((prevShard?.failurePatterns ?? []).map((p) => [p.id, p]));
163
- return [...groups.values()].map((group) => {
164
- const id = hashSignature('silent-stall', 'behavioral', group.bucket, null);
165
- const prev = prevById.get(id);
166
- const drift = !prev
167
- ? 'up'
168
- : group.occurrences > prev.occurrences
169
- ? 'up'
170
- : group.occurrences < prev.occurrences
171
- ? 'down'
172
- : 'flat';
173
- return {
174
- id,
175
- label: `Agent silent stall (${group.bucket}) — idle until nudged`,
176
- signature: { tool: 'silent-stall', cause: 'behavioral', key: group.bucket },
177
- phenotype: null,
178
- sessions: group.sessions.size,
179
- occurrences: group.occurrences,
180
- wastedMs: group.wastedMs,
181
- exampleSessionIds: group.examples,
182
- drift,
183
- };
184
- });
185
- }
186
- function firstToolSegments(rows, bySession) {
187
- return rows.flatMap((row) => {
188
- const sessionCalls = bySession.get(row.id);
189
- if (!sessionCalls || sessionCalls.length === 0)
190
- return [];
191
- const first = sessionCalls.reduce((min, call) => (call.ordinal < min.ordinal ? call : min));
192
- const sessionStartMs = Date.parse(row.timestamp);
193
- const firstCallMs = Date.parse(first.timestamp);
194
- if (!Number.isFinite(sessionStartMs) || !Number.isFinite(firstCallMs))
195
- return [];
196
- return [{ steps: [{ startMs: Math.max(0, firstCallMs - sessionStartMs) }] }];
197
- });
198
- }
@@ -1,18 +0,0 @@
1
- import type { SessionDetail } from './sync.js';
2
- export type FailurePhenotype = 'false-termination' | 'premature-completion' | 'out-of-order' | 'failure-to-act';
3
- type TraceOutcome = 'merged' | 'tests-green' | 'partial' | 'abandoned' | 'human-takeover' | 'invalid-env';
4
- interface PhenotypeResult {
5
- phenotype: FailurePhenotype | null;
6
- reason: string;
7
- }
8
- interface OutcomeResult {
9
- outcome: TraceOutcome;
10
- confidence: 'high' | 'medium' | 'low';
11
- reason: string;
12
- }
13
- export declare function recoveredAfterErrors(session: Pick<SessionDetail, 'steps'>): boolean;
14
- export declare function classifyPhenotype(session: SessionDetail): FailurePhenotype | null;
15
- export declare function classifyPhenotypeDetailed(session: SessionDetail): PhenotypeResult;
16
- export declare function deriveOutcome(session: SessionDetail): TraceOutcome;
17
- export declare function deriveOutcomeDetailed(session: SessionDetail): OutcomeResult;
18
- export type { SessionDetail } from './sync.js';