@phnx-labs/agents-cli 1.23.12 → 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 (163) hide show
  1. package/CHANGELOG.md +42 -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/setup.js +1 -1
  23. package/dist/commands/ssh.js +2 -2
  24. package/dist/commands/utils.d.ts +1 -5
  25. package/dist/commands/utils.js +1 -7
  26. package/dist/lib/agent-spec/agents.d.ts +0 -2
  27. package/dist/lib/agent-spec/agents.js +0 -12
  28. package/dist/lib/agent-spec/index.d.ts +0 -4
  29. package/dist/lib/agent-spec/index.js +0 -4
  30. package/dist/lib/commands.d.ts +1 -5
  31. package/dist/lib/commands.js +2 -69
  32. package/dist/lib/comms-render.d.ts +0 -7
  33. package/dist/lib/comms-render.js +0 -41
  34. package/dist/lib/config-keys.d.ts +1 -1
  35. package/dist/lib/config-keys.js +8 -0
  36. package/dist/lib/daemon/daemon.js +1 -6
  37. package/dist/lib/daemon-services.d.ts +1 -1
  38. package/dist/lib/daemon-services.js +0 -5
  39. package/dist/lib/device-config.d.ts +2 -0
  40. package/dist/lib/device-config.js +81 -8
  41. package/dist/lib/devices/doctor-findings.d.ts +6 -1
  42. package/dist/lib/devices/doctor-findings.js +34 -1
  43. package/dist/lib/git.d.ts +1 -0
  44. package/dist/lib/git.js +5 -0
  45. package/dist/lib/hooks/install.d.ts +0 -7
  46. package/dist/lib/hooks/install.js +0 -55
  47. package/dist/lib/hosts/passthrough.js +2 -4
  48. package/dist/lib/hosts/progress.js +2 -2
  49. package/dist/lib/hosts/remote-cmd.js +0 -1
  50. package/dist/lib/installations/migrate.d.ts +1 -0
  51. package/dist/lib/installations/migrate.js +18 -1
  52. package/dist/lib/installations/versions.js +2 -2
  53. package/dist/lib/loop.js +1 -1
  54. package/dist/lib/mailbox-target.d.ts +0 -31
  55. package/dist/lib/mailbox-target.js +0 -37
  56. package/dist/lib/mcp-lookup.d.ts +7 -0
  57. package/dist/lib/mcp-lookup.js +71 -0
  58. package/dist/lib/mcp.d.ts +0 -8
  59. package/dist/lib/mcp.js +0 -47
  60. package/dist/lib/menubar/install-menubar.d.ts +0 -15
  61. package/dist/lib/menubar/install-menubar.js +24 -118
  62. package/dist/lib/menubar/resolve-version.d.ts +9 -10
  63. package/dist/lib/menubar/resolve-version.js +70 -30
  64. package/dist/lib/paths.d.ts +0 -1
  65. package/dist/lib/paths.js +0 -18
  66. package/dist/lib/plugins/skills.d.ts +0 -10
  67. package/dist/lib/plugins/skills.js +2 -165
  68. package/dist/lib/project-pull.js +1 -2
  69. package/dist/lib/resources.d.ts +1 -1
  70. package/dist/lib/routines-project.js +1 -1
  71. package/dist/lib/session/local-tmux-attach.js +2 -2
  72. package/dist/lib/startup/command-registry.js +20 -7
  73. package/dist/lib/teams/agents.js +1 -1
  74. package/dist/lib/triggers/webhook.d.ts +2 -59
  75. package/dist/lib/triggers/webhook.js +2 -422
  76. package/package.json +2 -1
  77. package/dist/commands/funnel.d.ts +0 -2
  78. package/dist/commands/funnel.js +0 -77
  79. package/dist/commands/logs.d.ts +0 -2
  80. package/dist/commands/mailboxes.d.ts +0 -2
  81. package/dist/commands/mailboxes.js +0 -400
  82. package/dist/commands/message.d.ts +0 -2
  83. package/dist/commands/message.js +0 -259
  84. package/dist/commands/packages-materialize.d.ts +0 -6
  85. package/dist/commands/packages-materialize.js +0 -90
  86. package/dist/commands/packages.d.ts +0 -5
  87. package/dist/commands/packages.js +0 -763
  88. package/dist/commands/route.d.ts +0 -2
  89. package/dist/commands/route.js +0 -259
  90. package/dist/commands/testdata/feed-hub.d.ts +0 -1
  91. package/dist/commands/testdata/feed-hub.js +0 -11
  92. package/dist/commands/tmux.d.ts +0 -7
  93. package/dist/commands/tmux.js +0 -529
  94. package/dist/commands/traces.d.ts +0 -2
  95. package/dist/commands/traces.js +0 -204
  96. package/dist/commands/webhook.d.ts +0 -5
  97. package/dist/commands/webhook.js +0 -105
  98. package/dist/lib/agent-spec/materialize.d.ts +0 -3
  99. package/dist/lib/agent-spec/materialize.js +0 -277
  100. package/dist/lib/agent-spec/package-resolve.d.ts +0 -4
  101. package/dist/lib/agent-spec/package-resolve.js +0 -231
  102. package/dist/lib/agent-spec/package-schema.d.ts +0 -3
  103. package/dist/lib/agent-spec/package-schema.js +0 -136
  104. package/dist/lib/agent-spec/package-types.d.ts +0 -94
  105. package/dist/lib/agent-spec/package-types.js +0 -10
  106. package/dist/lib/daemon/testdata/process-view-daemon.d.ts +0 -1
  107. package/dist/lib/daemon/testdata/process-view-daemon.js +0 -12
  108. package/dist/lib/daemon/testdata/process-view-start.d.ts +0 -1
  109. package/dist/lib/daemon/testdata/process-view-start.js +0 -41
  110. package/dist/lib/daemon/webhook-receiver-service.d.ts +0 -8
  111. package/dist/lib/daemon/webhook-receiver-service.js +0 -16
  112. package/dist/lib/daemon-webhooks.d.ts +0 -48
  113. package/dist/lib/daemon-webhooks.js +0 -177
  114. package/dist/lib/funnel.d.ts +0 -6
  115. package/dist/lib/funnel.js +0 -31
  116. package/dist/lib/net-close.d.ts +0 -2
  117. package/dist/lib/net-close.js +0 -20
  118. package/dist/lib/packages/output-home.d.ts +0 -9
  119. package/dist/lib/packages/output-home.js +0 -89
  120. package/dist/lib/registry.d.ts +0 -65
  121. package/dist/lib/registry.js +0 -432
  122. package/dist/lib/routers.d.ts +0 -25
  123. package/dist/lib/routers.js +0 -122
  124. package/dist/lib/run-trace-sync.d.ts +0 -7
  125. package/dist/lib/run-trace-sync.js +0 -35
  126. package/dist/lib/session/testdata/pid-registry-namespace.d.ts +0 -1
  127. package/dist/lib/session/testdata/pid-registry-namespace.js +0 -25
  128. package/dist/lib/session/testdata/process-view-namespace.d.ts +0 -1
  129. package/dist/lib/session/testdata/process-view-namespace.js +0 -56
  130. package/dist/lib/session/testdata/process-view-private.d.ts +0 -1
  131. package/dist/lib/session/testdata/process-view-private.js +0 -11
  132. package/dist/lib/testdata/daemon-health-writer.d.ts +0 -1
  133. package/dist/lib/testdata/daemon-health-writer.js +0 -8
  134. package/dist/lib/testdata/owner-notify-api.d.ts +0 -23
  135. package/dist/lib/testdata/owner-notify-api.js +0 -82
  136. package/dist/lib/testdata/refresh-coordinator-worker.d.ts +0 -1
  137. package/dist/lib/testdata/refresh-coordinator-worker.js +0 -23
  138. package/dist/lib/traces/backend.d.ts +0 -8
  139. package/dist/lib/traces/backend.js +0 -33
  140. package/dist/lib/traces/classify.d.ts +0 -40
  141. package/dist/lib/traces/classify.js +0 -70
  142. package/dist/lib/traces/config.d.ts +0 -2
  143. package/dist/lib/traces/config.js +0 -2
  144. package/dist/lib/traces/insights.d.ts +0 -30
  145. package/dist/lib/traces/insights.js +0 -198
  146. package/dist/lib/traces/phenotype.d.ts +0 -18
  147. package/dist/lib/traces/phenotype.js +0 -335
  148. package/dist/lib/traces/provision.d.ts +0 -16
  149. package/dist/lib/traces/provision.js +0 -25
  150. package/dist/lib/traces/schema2-build.d.ts +0 -28
  151. package/dist/lib/traces/schema2-build.js +0 -496
  152. package/dist/lib/traces/schema2-danger.d.ts +0 -7
  153. package/dist/lib/traces/schema2-danger.js +0 -123
  154. package/dist/lib/traces/schema2.d.ts +0 -139
  155. package/dist/lib/traces/schema2.js +0 -20
  156. package/dist/lib/traces/segments.d.ts +0 -73
  157. package/dist/lib/traces/segments.js +0 -236
  158. package/dist/lib/traces/sync.d.ts +0 -197
  159. package/dist/lib/traces/sync.js +0 -654
  160. package/dist/lib/traces/worker-template.d.ts +0 -1
  161. package/dist/lib/traces/worker-template.js +0 -292
  162. package/dist/lib/triggers/handlers.d.ts +0 -66
  163. package/dist/lib/triggers/handlers.js +0 -383
@@ -1,496 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { redactSecrets } from '../redact.js';
3
- import { classifyBashCommand, tokenizeBash, unwrapCommand, } from '@phnx-labs/sessions-cli/reader';
4
- import { computeSummaryStats } from '@phnx-labs/sessions-cli/reader';
5
- import { extractShellPrograms } from '@phnx-labs/sessions-cli/reader';
6
- import { effectiveProgram, eventTimestampsMs, pairSteps, } from '@phnx-labs/sessions-cli/reader';
7
- import { classifyActionDanger } from './schema2-danger.js';
8
- import { activeMsFromTrajectory, buildDetailMeta, buildWhereItWentWrong, } from './sync.js';
9
- const PREVIEW_MAX = 2000;
10
- function shortHash(text) {
11
- return createHash('sha256').update(text).digest('hex').slice(0, 16);
12
- }
13
- function textPreview(raw, redact, knownSecrets) {
14
- if (raw === undefined || raw === null || raw.length === 0)
15
- return undefined;
16
- const originalBytes = Buffer.byteLength(raw, 'utf8');
17
- const clipped = raw.length > PREVIEW_MAX ? raw.slice(0, PREVIEW_MAX) : raw;
18
- const text = redact ? redactSecrets(clipped, knownSecrets) : clipped;
19
- return { text, truncated: raw.length > PREVIEW_MAX, originalBytes };
20
- }
21
- function stringArg(args, ...keys) {
22
- if (!args)
23
- return undefined;
24
- for (const key of keys) {
25
- const v = args[key];
26
- if (typeof v === 'string' && v.length > 0)
27
- return v;
28
- }
29
- return undefined;
30
- }
31
- function numberArg(args, ...keys) {
32
- if (!args)
33
- return undefined;
34
- for (const key of keys) {
35
- const v = args[key];
36
- if (typeof v === 'number' && Number.isFinite(v))
37
- return v;
38
- }
39
- return undefined;
40
- }
41
- function resultOf(resultEvent, redact, knownSecrets) {
42
- const result = {};
43
- if (!resultEvent)
44
- return result;
45
- if (typeof resultEvent.exitCode === 'number')
46
- result.exitCode = resultEvent.exitCode;
47
- if (typeof resultEvent.statusCode === 'number')
48
- result.statusCode = resultEvent.statusCode;
49
- if (typeof resultEvent.errorCode === 'string')
50
- result.errorCode = resultEvent.errorCode;
51
- const combined = textPreview(resultEvent.output ?? resultEvent.content, redact, knownSecrets);
52
- if (combined)
53
- result.combined = combined;
54
- return result;
55
- }
56
- function stepOutcome(step) {
57
- const o = step.outcome;
58
- if (o === 'ok' || o === 'error' || o === 'unknown')
59
- return o;
60
- return 'unknown';
61
- }
62
- function countLines(resultEvent) {
63
- if (!resultEvent)
64
- return undefined;
65
- const text = resultEvent.output ?? resultEvent.content;
66
- if (typeof text !== 'string' || text.length === 0)
67
- return undefined;
68
- const lines = text.split('\n');
69
- const value = lines.length > 0 && lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
70
- const truncated = text.length >= PREVIEW_MAX;
71
- return { value, relation: truncated ? 'at-least' : 'exact' };
72
- }
73
- export function unwrapShellExec(command) {
74
- const s = command.trim();
75
- const m = s.match(/^(?:\S*\/)?(?:bash|zsh|sh|dash|ksh)\s+(?:-[a-zA-Z]*c[a-zA-Z]*)\s+(['"])([\s\S]*)\1\s*$/);
76
- if (m)
77
- return unwrapShellExec(m[2]);
78
- return unwrapCommand(s);
79
- }
80
- export function mapBashCategory(cat, argv) {
81
- switch (cat) {
82
- case 'vcs':
83
- return 'git';
84
- case 'remote':
85
- case 'http':
86
- return 'network';
87
- case 'build-test': {
88
- const lower = argv.map((t) => t.toLowerCase());
89
- const looksTest = lower.some((t) => t === 'test' || t === 't' || /vitest|jest|pytest|mocha/.test(t) ||
90
- t === '--test' || /(^|:)test(:|$)/.test(t));
91
- return looksTest ? 'test' : 'build';
92
- }
93
- default:
94
- return 'other';
95
- }
96
- }
97
- function argvComplete(source) {
98
- if (/\$\(|\$\{|`|<\(|\)\s*$/.test(source) && /\$\(|\$\{|`|<\(/.test(source))
99
- return false;
100
- if (/\$[A-Za-z_]/.test(source))
101
- return false;
102
- if (/[*?]/.test(source) && !/['"][^'"]*[*?]/.test(source))
103
- return false;
104
- return true;
105
- }
106
- export function buildBashActions(unwrapped) {
107
- const segments = tokenizeBash(unwrapped);
108
- const actions = [];
109
- segments.forEach((argv, i) => {
110
- if (argv.length === 0)
111
- return;
112
- const source = argv.join(' ');
113
- const info = classifyBashCommand(source);
114
- const prog = effectiveProgram(source);
115
- const complete = argvComplete(source);
116
- const categories = [mapBashCategory(info.category, argv)];
117
- const verdict = classifyActionDanger(argv, complete);
118
- const action = {
119
- ordinal: i + 1,
120
- source,
121
- argv,
122
- argvComplete: complete,
123
- program: prog ?? info.tool,
124
- categories,
125
- danger: verdict.danger,
126
- };
127
- if (verdict.destructiveOperation)
128
- action.destructiveOperation = verdict.destructiveOperation;
129
- actions.push(action);
130
- });
131
- return actions;
132
- }
133
- function bashExecution(step, useEvent, resultEvent, ctx) {
134
- const rawCommand = useEvent.command ?? stringArg(useEvent.args, 'command', 'cmd', 'script') ?? '';
135
- const unwrapped = unwrapShellExec(rawCommand);
136
- const command = ctx.redact ? redactSecrets(rawCommand, ctx.knownSecrets) : rawCommand;
137
- const unwrappedCommand = ctx.redact ? redactSecrets(unwrapped, ctx.knownSecrets) : unwrapped;
138
- const { diagnostics } = extractShellPrograms(unwrapped);
139
- const actions = buildBashActions(unwrapped);
140
- let parseStatus;
141
- if (actions.length === 0)
142
- parseStatus = rawCommand.trim().length === 0 ? 'parsed' : 'unparseable';
143
- else if (diagnostics.length > 0)
144
- parseStatus = 'partial';
145
- else
146
- parseStatus = 'parsed';
147
- return {
148
- ...executionBase(step, 'execution'),
149
- executionType: 'bash',
150
- tool: step.tool ?? 'Bash',
151
- result: resultOf(resultEvent, ctx.redact, ctx.knownSecrets),
152
- command,
153
- unwrappedCommand,
154
- parseStatus,
155
- parseDiagnostics: diagnostics,
156
- actions,
157
- };
158
- }
159
- function readExecution(step, useEvent, resultEvent, ctx) {
160
- const file = stringArg(useEvent.args, 'file_path', 'path', 'notebook_path', 'filePath') ?? useEvent.path ?? '';
161
- const exec = {
162
- ...executionBase(step, 'execution'),
163
- executionType: 'read',
164
- tool: step.tool ?? 'Read',
165
- result: resultOf(resultEvent, ctx.redact, ctx.knownSecrets),
166
- file: ctx.redact ? redactSecrets(file, ctx.knownSecrets) : file,
167
- };
168
- const offset = numberArg(useEvent.args, 'offset');
169
- const limit = numberArg(useEvent.args, 'limit');
170
- if (offset !== undefined)
171
- exec.offset = offset;
172
- if (limit !== undefined)
173
- exec.limit = limit;
174
- const returnedLines = countLines(resultEvent);
175
- if (returnedLines)
176
- exec.returnedLines = returnedLines;
177
- return exec;
178
- }
179
- function grepExecution(step, useEvent, resultEvent, ctx) {
180
- const query = stringArg(useEvent.args, 'pattern', 'query', 'q') ?? '';
181
- const grepPath = stringArg(useEvent.args, 'path');
182
- const glob = stringArg(useEvent.args, 'glob');
183
- const outputModeRaw = stringArg(useEvent.args, 'output_mode');
184
- const outputMode = outputModeRaw === 'content' || outputModeRaw === 'files' || outputModeRaw === 'count'
185
- ? (outputModeRaw === 'files' ? 'files' : outputModeRaw)
186
- : outputModeRaw
187
- ? 'unknown'
188
- : undefined;
189
- const exec = {
190
- ...executionBase(step, 'execution'),
191
- executionType: 'grep',
192
- tool: step.tool ?? 'Grep',
193
- result: resultOf(resultEvent, ctx.redact, ctx.knownSecrets),
194
- query: ctx.redact ? redactSecrets(query, ctx.knownSecrets) : query,
195
- };
196
- if (grepPath)
197
- exec.path = ctx.redact ? redactSecrets(grepPath, ctx.knownSecrets) : grepPath;
198
- if (glob)
199
- exec.glob = glob;
200
- if (outputMode)
201
- exec.outputMode = outputMode;
202
- const hits = countLines(resultEvent);
203
- if (hits)
204
- exec.hits = hits;
205
- return exec;
206
- }
207
- function fileMutationFromEdit(useEvent) {
208
- const path = stringArg(useEvent.args, 'file_path', 'path', 'filePath') ?? useEvent.path;
209
- if (!path)
210
- return null;
211
- const oldStr = stringArg(useEvent.args, 'old_string', 'old_str');
212
- const newStr = stringArg(useEvent.args, 'new_string', 'new_str');
213
- if (oldStr === undefined && newStr === undefined) {
214
- return { path, operation: 'update', hunks: [] };
215
- }
216
- const before = oldStr ?? '';
217
- const after = newStr ?? '';
218
- const removedLines = countStringLines(before);
219
- const addedLines = countStringLines(after);
220
- const hunk = {
221
- id: 'h1',
222
- addedLines,
223
- removedLines,
224
- beforeHash: shortHash(before),
225
- afterHash: shortHash(after),
226
- };
227
- return { path, operation: 'update', hunks: [hunk] };
228
- }
229
- function fileMutationFromWrite(useEvent) {
230
- const path = stringArg(useEvent.args, 'file_path', 'path', 'filePath') ?? useEvent.path;
231
- if (!path)
232
- return null;
233
- const content = stringArg(useEvent.args, 'content', 'contents');
234
- if (content === undefined) {
235
- return { path, operation: 'overwrite', hunks: [] };
236
- }
237
- const addedLines = countStringLines(content);
238
- const hunk = {
239
- id: 'h1',
240
- addedLines,
241
- removedLines: 0,
242
- afterHash: shortHash(content),
243
- };
244
- return { path, operation: 'overwrite', hunks: [hunk] };
245
- }
246
- function countStringLines(text) {
247
- if (text.length === 0)
248
- return 0;
249
- const lines = text.split('\n');
250
- return lines.length > 0 && lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
251
- }
252
- function editExecution(step, useEvent, resultEvent, ctx) {
253
- const mutation = fileMutationFromEdit(useEvent);
254
- const files = mutation ? [redactMutationPath(mutation, ctx)] : [];
255
- return {
256
- ...executionBase(step, 'execution'),
257
- executionType: 'edit',
258
- tool: step.tool ?? 'Edit',
259
- result: resultOf(resultEvent, ctx.redact, ctx.knownSecrets),
260
- files,
261
- reverts: [],
262
- };
263
- }
264
- function writeExecution(step, useEvent, resultEvent, ctx) {
265
- const mutation = fileMutationFromWrite(useEvent);
266
- const files = mutation ? [redactMutationPath(mutation, ctx)] : [];
267
- return {
268
- ...executionBase(step, 'execution'),
269
- executionType: 'write',
270
- tool: step.tool ?? 'Write',
271
- result: resultOf(resultEvent, ctx.redact, ctx.knownSecrets),
272
- files,
273
- reverts: [],
274
- };
275
- }
276
- function redactMutationPath(m, ctx) {
277
- // Mutation paths cross the device boundary and must be scrubbed with other projected data.
278
- if (!ctx.redact)
279
- return m;
280
- return { ...m, path: redactSecrets(m.path, ctx.knownSecrets) };
281
- }
282
- function genericExecution(step, useEvent, resultEvent, ctx) {
283
- const inputText = stringArg(useEvent.args, 'command', 'cmd', 'file_path', 'path', 'query', 'pattern', 'url', 'description', 'prompt') ?? (useEvent.args ? JSON.stringify(useEvent.args).slice(0, PREVIEW_MAX) : undefined);
284
- const exec = {
285
- ...executionBase(step, 'execution'),
286
- executionType: 'generic',
287
- tool: step.tool ?? 'unknown',
288
- result: resultOf(resultEvent, ctx.redact, ctx.knownSecrets),
289
- };
290
- const input = textPreview(inputText, ctx.redact, ctx.knownSecrets);
291
- if (input)
292
- exec.input = input;
293
- return exec;
294
- }
295
- /**
296
- * A hook firing → HookExecution. parse.ts emits `type: 'hook'` with `hookName`,
297
- * `hookEvent`, and `success` (boolean). It does NOT preserve the raw
298
- * blocked-vs-error distinction (both land as `success: false`), so `decision` is
299
- * conservative: `allowed` on success, else `unknown` — never a confident `blocked`
300
- * we cannot prove. `phase` is derived from the lifecycle event name.
301
- *
302
- * Hooks are NOT tool_use events, so `pairSteps` never draws them; the build draws
303
- * them separately from the raw event stream and merges by startMs (see below).
304
- *
305
- * TODO(PHNX-3442): (1) if parse.ts is extended to preserve the raw `hook_blocked`
306
- * vs `hook_error` attachment type, map those to `blocked`/`error` here instead of
307
- * the conservative `unknown`. (2) parse.ts emits NO permission events today (its
308
- * `permission-mode` lines are skipped, parse.ts:569), so `PermissionExecution` is
309
- * never produced — wire it once permission events are parsed.
310
- */
311
- function hookExecution(event, ordinal, startMs) {
312
- const hookEvent = event.hookEvent;
313
- const phase = hookEvent === undefined
314
- ? 'other'
315
- : /^Pre/i.test(hookEvent)
316
- ? 'pre'
317
- : /^Post/i.test(hookEvent)
318
- ? 'post'
319
- : /Session/i.test(hookEvent)
320
- ? 'session'
321
- : 'other';
322
- const decision = event.success === true ? 'allowed' : 'unknown';
323
- const exec = {
324
- kind: 'execution',
325
- lane: 'hook',
326
- ordinal,
327
- startMs,
328
- durationMs: 0,
329
- durationEstimated: true,
330
- outcome: event.success === true ? 'ok' : 'unknown',
331
- label: event.hookName ?? 'hook',
332
- executionType: 'hook',
333
- phase,
334
- decision,
335
- result: {},
336
- };
337
- if (event.hookName)
338
- exec.hookName = event.hookName;
339
- if (hookEvent)
340
- exec.hookEvent = hookEvent;
341
- return exec;
342
- }
343
- function executionBase(step, kind) {
344
- const base = {
345
- kind,
346
- ordinal: step.ordinal,
347
- startMs: step.startMs,
348
- durationMs: step.durationMs,
349
- durationEstimated: step.durationEstimated,
350
- outcome: stepOutcome(step),
351
- label: step.label,
352
- lane: step.lane,
353
- };
354
- const withCall = step.callId ? { ...base, callId: step.callId } : base;
355
- return withCall;
356
- }
357
- function thinkingStep(step) {
358
- const outcome = step.outcome === 'error' ? 'unknown' : (step.outcome === 'ok' ? 'ok' : 'unknown');
359
- return {
360
- kind: 'thinking',
361
- lane: 'think',
362
- ordinal: step.ordinal,
363
- startMs: step.startMs,
364
- durationMs: step.durationMs,
365
- durationEstimated: step.durationEstimated,
366
- outcome,
367
- label: step.label,
368
- };
369
- }
370
- function applyRevertLedger(steps) {
371
- const earlier = [];
372
- for (const step of steps) {
373
- if (step.kind !== 'execution')
374
- continue;
375
- if (step.executionType !== 'edit' && step.executionType !== 'write')
376
- continue;
377
- const mut = step;
378
- for (const file of mut.files) {
379
- for (const hunk of file.hunks) {
380
- if (hunk.beforeHash && hunk.afterHash) {
381
- const match = earlier.find((e) => e.path === file.path &&
382
- e.hunk.revertedByStep === undefined &&
383
- e.hunk.afterHash !== undefined &&
384
- e.hunk.beforeHash !== undefined &&
385
- e.hunk.afterHash === hunk.beforeHash &&
386
- e.hunk.beforeHash === hunk.afterHash);
387
- if (match) {
388
- match.hunk.revertedByStep = mut.ordinal;
389
- const parentFile = match.step.files.find((f) => f.path === match.path);
390
- if (parentFile && parentFile.hunks.every((h) => h.revertedByStep !== undefined)) {
391
- parentFile.revertedByStep = mut.ordinal;
392
- }
393
- mut.reverts.push({
394
- revertedStep: match.ordinal,
395
- path: file.path,
396
- revertedHunkIds: [match.hunk.id],
397
- });
398
- }
399
- }
400
- earlier.push({ step: mut, ordinal: mut.ordinal, path: file.path, hunk });
401
- }
402
- }
403
- }
404
- }
405
- const TOOL_KINDS = {
406
- bash: new Set(['bash', 'exec', 'execute', 'exec_command', 'run_command', 'run_shell_command', 'shell']),
407
- read: new Set(['read', 'view', 'cat_file']),
408
- grep: new Set(['grep', 'search', 'codebase_search', 'grep_search']),
409
- edit: new Set(['edit', 'multiedit', 'str_replace', 'apply_patch', 'replace_file_content']),
410
- write: new Set(['write', 'create_file', 'write_file']),
411
- };
412
- function toolExecutionKind(tool) {
413
- const t = tool.toLowerCase();
414
- for (const [kind, names] of Object.entries(TOOL_KINDS)) {
415
- if (names.has(t))
416
- return kind;
417
- }
418
- return 'generic';
419
- }
420
- export function buildSessionDetailV2(traj, events, options = {}) {
421
- // Projection defaults to secret redaction; previews are bounded while structured inputs remain.
422
- const redact = options.redact !== false;
423
- const knownSecrets = options.knownSecrets;
424
- const ctx = { redact, knownSecrets };
425
- const stats = computeSummaryStats(events);
426
- const firstTs = stats.firstTs;
427
- const eventMs = eventTimestampsMs(events);
428
- const drafts = pairSteps(events, eventMs, firstTs, redact, knownSecrets);
429
- const cappedDrafts = drafts.slice(0, traj.steps.length);
430
- const steps = [];
431
- for (let i = 0; i < cappedDrafts.length; i++) {
432
- const draft = cappedDrafts[i];
433
- const step = traj.steps[i];
434
- if (draft.step.kind !== step.kind || draft.step.callId !== step.callId) {
435
- throw new Error(`schema-2 step/draft misalignment at ordinal ${step.ordinal}: ` +
436
- `draft(kind=${draft.step.kind},callId=${draft.step.callId ?? '∅'}) vs ` +
437
- `step(kind=${step.kind},callId=${step.callId ?? '∅'})`);
438
- }
439
- if (step.kind === 'thinking') {
440
- steps.push(thinkingStep(step));
441
- continue;
442
- }
443
- const useEvent = events[draft.eventIndex];
444
- const resultEvent = draft.resultEventIndex !== undefined ? events[draft.resultEventIndex] : undefined;
445
- const tool = step.tool ?? 'unknown';
446
- const kind = toolExecutionKind(tool);
447
- switch (kind) {
448
- case 'bash':
449
- steps.push(bashExecution(step, useEvent, resultEvent, ctx));
450
- break;
451
- case 'read':
452
- steps.push(readExecution(step, useEvent, resultEvent, ctx));
453
- break;
454
- case 'grep':
455
- steps.push(grepExecution(step, useEvent, resultEvent, ctx));
456
- break;
457
- case 'edit':
458
- steps.push(editExecution(step, useEvent, resultEvent, ctx));
459
- break;
460
- case 'write':
461
- steps.push(writeExecution(step, useEvent, resultEvent, ctx));
462
- break;
463
- default:
464
- steps.push(genericExecution(step, useEvent, resultEvent, ctx));
465
- break;
466
- }
467
- }
468
- const hookSteps = [];
469
- for (let i = 0; i < events.length; i++) {
470
- const e = events[i];
471
- if (e.type !== 'hook')
472
- continue;
473
- const startMs = Number.isNaN(eventMs[i]) ? 0 : Math.max(0, eventMs[i] - firstTs);
474
- hookSteps.push(hookExecution(e, 0, startMs));
475
- }
476
- let merged = steps;
477
- if (hookSteps.length > 0) {
478
- merged = [...steps, ...hookSteps].sort((a, b) => a.startMs - b.startMs);
479
- merged.forEach((step, idx) => { step.ordinal = idx + 1; });
480
- }
481
- applyRevertLedger(merged);
482
- const s = traj.session;
483
- return {
484
- schema: 2,
485
- id: s.id,
486
- meta: buildDetailMeta(traj),
487
- steps: merged,
488
- gaps: traj.gaps,
489
- truncatedSteps: traj.truncatedSteps,
490
- whereItWentWrong: buildWhereItWentWrong(traj),
491
- surfacedToolFailures: traj.steps
492
- .filter((step) => step.outcome === 'error')
493
- .map((step) => ({ tool: step.tool, label: step.label, detail: step.detail })),
494
- };
495
- }
496
- export { activeMsFromTrajectory };
@@ -1,7 +0,0 @@
1
- import type { BashDanger } from './schema2.js';
2
- interface DangerVerdict {
3
- danger: BashDanger;
4
- destructiveOperation?: string;
5
- }
6
- export declare function classifyActionDanger(argv: string[], _argvComplete?: boolean): DangerVerdict;
7
- export {};
@@ -1,123 +0,0 @@
1
- const NORMAL = { danger: 'normal' };
2
- function baseName(token) {
3
- const noArgs = token.replace(/^.*\//, '');
4
- return noArgs.toLowerCase();
5
- }
6
- function hasToken(argv, names) {
7
- return argv.some((t) => names.has(t));
8
- }
9
- function hasClusterFlag(argv, letters) {
10
- return argv.some((t) => {
11
- if (!/^-[a-zA-Z]+$/.test(t))
12
- return false;
13
- const body = t.slice(1);
14
- return letters.every((l) => body.includes(l));
15
- });
16
- }
17
- function hasLongFlag(argv, flag) {
18
- return argv.includes(flag);
19
- }
20
- const RM_TOKEN = new Set(['rm']);
21
- const KILL_TOKEN = new Set(['kill', 'pkill', 'killall']);
22
- const IMPORTANT_REDIRECT_TARGET = /^\/dev\/(?:sd|nvme|disk|hd|mmcblk|vd)/i;
23
- function joinedSql(argv) {
24
- return argv.join(' ').toLowerCase();
25
- }
26
- export function classifyActionDanger(argv, _argvComplete = true) {
27
- if (argv.length === 0)
28
- return NORMAL;
29
- const exe = baseName(argv[0]);
30
- const rest = argv.slice(1);
31
- if (exe === 'rm' || hasToken(argv, RM_TOKEN)) {
32
- if (exe === 'rm') {
33
- const recursive = hasClusterFlag(rest, ['r']) || hasLongFlag(rest, '--recursive');
34
- const force = hasClusterFlag(rest, ['f']) || hasLongFlag(rest, '--force');
35
- if (recursive && force) {
36
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'recursive-force-delete' };
37
- }
38
- if (recursive) {
39
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'recursive-delete' };
40
- }
41
- return { danger: 'potentially-destructive', destructiveOperation: 'delete' };
42
- }
43
- }
44
- if (exe === 'git') {
45
- const sub = rest.find((t) => !t.startsWith('-'));
46
- if (sub === 'reset') {
47
- if (hasLongFlag(rest, '--hard')) {
48
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'git-reset-hard' };
49
- }
50
- return { danger: 'potentially-destructive', destructiveOperation: 'git-reset' };
51
- }
52
- if (sub === 'clean') {
53
- if (hasClusterFlag(rest, ['f'])) {
54
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'git-clean-force' };
55
- }
56
- return { danger: 'potentially-destructive', destructiveOperation: 'git-clean' };
57
- }
58
- if (sub === 'push') {
59
- const forceRefspec = rest.some((t) => /^\+[^-\s]/.test(t));
60
- if (hasLongFlag(rest, '--force') ||
61
- hasClusterFlag(rest, ['f']) ||
62
- rest.includes('--force-with-lease') ||
63
- forceRefspec) {
64
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'git-push-force' };
65
- }
66
- }
67
- if (sub === 'checkout') {
68
- if (rest.includes('--')) {
69
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'git-checkout-discard' };
70
- }
71
- }
72
- if (sub === 'stash') {
73
- const after = rest.slice(rest.indexOf('stash') + 1);
74
- if (after.includes('drop') || after.includes('clear')) {
75
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'git-stash-drop' };
76
- }
77
- }
78
- return NORMAL;
79
- }
80
- if (exe === 'kill' || exe === 'pkill' || exe === 'killall') {
81
- if (hasToken(rest, new Set(['-9', '-SIGKILL', '-KILL']))) {
82
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'kill-9' };
83
- }
84
- if (hasToken(argv, KILL_TOKEN)) {
85
- return { danger: 'potentially-destructive', destructiveOperation: 'kill' };
86
- }
87
- }
88
- if (exe === 'mv') {
89
- return { danger: 'potentially-destructive', destructiveOperation: 'move-overwrite' };
90
- }
91
- if (exe === 'dd') {
92
- if (rest.some((t) => /^of=/.test(t))) {
93
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'dd-write' };
94
- }
95
- }
96
- if (/^mkfs(\.|$)/.test(exe)) {
97
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'mkfs' };
98
- }
99
- for (let i = 0; i < argv.length; i++) {
100
- const t = argv[i];
101
- if (t === '>' || t === '>>') {
102
- const target = argv[i + 1];
103
- if (target && IMPORTANT_REDIRECT_TARGET.test(target)) {
104
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'overwrite-device' };
105
- }
106
- }
107
- const fused = t.match(/^>>?(\/\S+)$/);
108
- if (fused && IMPORTANT_REDIRECT_TARGET.test(fused[1])) {
109
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'overwrite-device' };
110
- }
111
- }
112
- const sql = joinedSql(argv);
113
- if (/\bdrop\s+table\b/.test(sql)) {
114
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'sql-drop-table' };
115
- }
116
- if (/\btruncate\b/.test(sql)) {
117
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'sql-truncate' };
118
- }
119
- if (/\bdelete\s+from\b/.test(sql) && !/\bwhere\b/.test(sql)) {
120
- return { danger: 'DESTRUCTIVE', destructiveOperation: 'sql-delete-no-where' };
121
- }
122
- return NORMAL;
123
- }