@openai/codex-security 0.1.4 → 0.1.6

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 (106) hide show
  1. package/README.md +127 -13
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +8 -1
  4. package/_bundled_plugin/examples/completed-scan/findings.json +6 -0
  5. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  6. package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
  7. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  8. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  9. package/_bundled_plugin/preflight/capability-profiles.toml +0 -57
  10. package/_bundled_plugin/references/config-preflight.md +1 -1
  11. package/_bundled_plugin/references/final-report.md +15 -7
  12. package/_bundled_plugin/references/finding-detail-fields.md +10 -2
  13. package/_bundled_plugin/references/scan-artifacts.md +11 -9
  14. package/_bundled_plugin/references/scan-contract.md +3 -1
  15. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +42 -0
  16. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +100 -0
  17. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +181 -0
  18. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +166 -0
  19. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +120 -0
  20. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +83 -0
  21. package/_bundled_plugin/schemas/tools/review-items.schema.json +80 -0
  22. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +572 -0
  23. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +18 -0
  24. package/_bundled_plugin/scripts/deep_scan_config.py +11 -3
  25. package/_bundled_plugin/scripts/deep_scan_workbench.py +153 -133
  26. package/_bundled_plugin/scripts/finalize_scan_contract.py +39 -0
  27. package/_bundled_plugin/scripts/generate_in_scope_files.py +134 -0
  28. package/_bundled_plugin/scripts/workbench_cli.py +33 -1
  29. package/_bundled_plugin/scripts/workbench_db.py +181 -118
  30. package/_bundled_plugin/scripts/workbench_feedback.py +2 -0
  31. package/_bundled_plugin/scripts/workbench_native_indexes.py +5 -49
  32. package/_bundled_plugin/scripts/workbench_progress.py +86 -3
  33. package/_bundled_plugin/scripts/workbench_remediation.py +19 -1
  34. package/_bundled_plugin/scripts/workbench_scan_history.py +7 -1
  35. package/_bundled_plugin/scripts/workbench_scan_start.py +11 -5
  36. package/_bundled_plugin/scripts/workbench_scan_usage.py +557 -0
  37. package/_bundled_plugin/scripts/workbench_schema.py +501 -0
  38. package/_bundled_plugin/scripts/workbench_target.py +14 -1
  39. package/_bundled_plugin/scripts/workbench_validation.py +117 -13
  40. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -4
  41. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +34 -28
  42. package/_bundled_plugin/skills/finding-discovery/SKILL.md +1 -1
  43. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +11 -8
  44. package/_bundled_plugin/skills/security-scan/SKILL.md +16 -9
  45. package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +26 -14
  46. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +1 -1
  47. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
  48. package/_bundled_plugin/skills/validation/SKILL.md +5 -5
  49. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +145 -227
  50. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +53 -68
  51. package/dist/api.d.ts +30 -8
  52. package/dist/api.d.ts.map +1 -1
  53. package/dist/api.js +438 -66
  54. package/dist/api.js.map +1 -1
  55. package/dist/auth.d.ts.map +1 -1
  56. package/dist/auth.js +262 -44
  57. package/dist/auth.js.map +1 -1
  58. package/dist/cli.d.ts +4 -3
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js +713 -148
  61. package/dist/cli.js.map +1 -1
  62. package/dist/config.d.ts +28 -0
  63. package/dist/config.d.ts.map +1 -1
  64. package/dist/config.js +39 -2
  65. package/dist/config.js.map +1 -1
  66. package/dist/contract.d.ts.map +1 -1
  67. package/dist/contract.js +14 -0
  68. package/dist/contract.js.map +1 -1
  69. package/dist/cost.d.ts +7 -0
  70. package/dist/cost.d.ts.map +1 -1
  71. package/dist/cost.js +397 -26
  72. package/dist/cost.js.map +1 -1
  73. package/dist/errors.d.ts +2 -0
  74. package/dist/errors.d.ts.map +1 -1
  75. package/dist/errors.js +48 -0
  76. package/dist/errors.js.map +1 -1
  77. package/dist/index.d.ts +3 -2
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js.map +1 -1
  80. package/dist/multiscan.d.ts +1 -0
  81. package/dist/multiscan.d.ts.map +1 -1
  82. package/dist/multiscan.js +5 -7
  83. package/dist/multiscan.js.map +1 -1
  84. package/dist/runtime.d.ts +40 -1
  85. package/dist/runtime.d.ts.map +1 -1
  86. package/dist/runtime.js +742 -46
  87. package/dist/runtime.js.map +1 -1
  88. package/dist/scan-activity.d.ts +13 -0
  89. package/dist/scan-activity.d.ts.map +1 -0
  90. package/dist/scan-activity.js +319 -0
  91. package/dist/scan-activity.js.map +1 -0
  92. package/dist/scan-dashboard.d.ts +47 -0
  93. package/dist/scan-dashboard.d.ts.map +1 -0
  94. package/dist/scan-dashboard.js +444 -0
  95. package/dist/scan-dashboard.js.map +1 -0
  96. package/dist/scan-history-renderer.d.ts.map +1 -1
  97. package/dist/scan-history-renderer.js +4 -1
  98. package/dist/scan-history-renderer.js.map +1 -1
  99. package/dist/version.d.ts +1 -1
  100. package/dist/version.js +1 -1
  101. package/dist/version.js.map +1 -1
  102. package/dist/worker-progress.d.ts +7 -0
  103. package/dist/worker-progress.d.ts.map +1 -1
  104. package/dist/worker-progress.js +68 -0
  105. package/dist/worker-progress.js.map +1 -1
  106. package/package.json +3 -3
package/dist/cost.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { type ScanActivity } from "./scan-activity.js";
2
+ import { type ScanProgress } from "./worker-progress.js";
1
3
  export interface ScanCost {
2
4
  model: string;
3
5
  inputTokens: number;
@@ -9,8 +11,12 @@ export interface ScanCost {
9
11
  interface ScanCostTrackerOptions {
10
12
  codexHome: string;
11
13
  model: string;
14
+ repository?: string;
12
15
  maxCostUsd?: number;
16
+ expectedFilesTotal?: number;
13
17
  onCost?: (cost: Readonly<ScanCost>) => void;
18
+ onActivity?: (activity: ScanActivity) => void;
19
+ onProgress?: (progress: ScanProgress) => void;
14
20
  onError?: (error: unknown) => void;
15
21
  }
16
22
  interface ScanCostSnapshot {
@@ -20,6 +26,7 @@ interface ScanCostSnapshot {
20
26
  export declare class ScanCostTracker {
21
27
  #private;
22
28
  constructor(options: ScanCostTrackerOptions);
29
+ setExpectedFilesTotal(filesTotal: number): void;
23
30
  start(threadId: string): void;
24
31
  refresh(): Promise<ScanCostSnapshot>;
25
32
  stop(fallbackUsage?: unknown): Promise<ScanCostSnapshot>;
@@ -1 +1 @@
1
- {"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../src/cost.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;CACtB;AA0BD,UAAU,sBAAsB;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC;IAC5C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACpC;AAED,UAAU,gBAAgB;IACxB,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,QAAQ,GAAG,IAAI,CAAC;CACvB;AAYD,qBAAa,eAAe;;gBASP,OAAO,EAAE,sBAAsB;IAI3C,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAcvB,OAAO,IAAI,OAAO,CAAC,gBAAgB,CAAC;IASpC,IAAI,CAAC,aAAa,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC;CAsEtE;AAwJD,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,KAAK,EAAE,OAAO,GACb,QAAQ,GAAG,IAAI,CA4BjB;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAO/C"}
1
+ {"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../src/cost.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,YAAY,EAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEL,KAAK,YAAY,EAClB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;CACtB;AA8CD,UAAU,sBAAsB;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC;IAC5C,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,KAAK,IAAI,CAAC;IAC9C,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,KAAK,IAAI,CAAC;IAC9C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACpC;AAED,UAAU,gBAAgB;IACxB,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,QAAQ,GAAG,IAAI,CAAC;CACvB;AAaD,qBAAa,eAAe;;gBAcP,OAAO,EAAE,sBAAsB;IAK3C,qBAAqB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAI/C,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAoCvB,OAAO,IAAI,OAAO,CAAC,gBAAgB,CAAC;IASpC,IAAI,CAAC,aAAa,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC;CAwJtE;AA+dD,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,KAAK,EAAE,OAAO,GACb,QAAQ,GAAG,IAAI,CA4BjB;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAO/C"}
package/dist/cost.js CHANGED
@@ -1,33 +1,64 @@
1
1
  import { open, readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { scanActivityFromSessionEvent, } from "./scan-activity.js";
4
+ import { scanProgressUpdatesFromEvent, } from "./worker-progress.js";
3
5
  const MODEL_PRICING_NANODOLLARS = {
4
6
  "gpt-5.6": [5_000, 500, 6_250, 30_000],
5
7
  "gpt-5.6-sol": [5_000, 500, 6_250, 30_000],
6
- "gpt-5.6-terra": [2_500, 250, 3_125, 15_000],
7
- "gpt-5.6-luna": [1_000, 100, 1_250, 6_000],
8
+ "gpt-5.6-terra": [2_000, 200, 2_500, 12_000],
9
+ "gpt-5.6-luna": [200, 20, 250, 1_200],
8
10
  };
9
11
  const COST_POLL_INTERVAL_MS = 100;
10
12
  const SESSION_READ_SIZE = 64 * 1_024;
13
+ const MAX_SESSION_EVENT_BYTES = 1 * 1_024 * 1_024;
11
14
  export class ScanCostTracker {
12
15
  #options;
13
16
  #sessions = new Map();
17
+ #workers = new Map();
18
+ #workerProgress = new Map();
19
+ #reportedProgress = new Set();
14
20
  #threadId = null;
15
21
  #timer = null;
16
22
  #pending = Promise.resolve();
17
23
  #snapshot = { usage: null, cost: null };
18
24
  #lastCost = null;
25
+ #highestFilesCompleted = 0;
26
+ #expectedFilesTotal;
19
27
  constructor(options) {
20
28
  this.#options = options;
29
+ this.#expectedFilesTotal = options.expectedFilesTotal;
30
+ }
31
+ setExpectedFilesTotal(filesTotal) {
32
+ this.#expectedFilesTotal = filesTotal;
21
33
  }
22
34
  start(threadId) {
23
35
  if (this.#threadId !== null)
24
36
  return;
25
37
  this.#threadId = threadId;
26
- if (this.#options.maxCostUsd === undefined)
38
+ if (this.#options.maxCostUsd === undefined &&
39
+ this.#options.onCost === undefined &&
40
+ this.#options.onActivity === undefined &&
41
+ this.#options.onProgress === undefined) {
27
42
  return;
43
+ }
44
+ let polling = false;
45
+ let rerun = false;
28
46
  const poll = () => {
29
- void this.refresh().catch((error) => {
47
+ if (polling) {
48
+ rerun = true;
49
+ return;
50
+ }
51
+ polling = true;
52
+ void this.refresh()
53
+ .catch((error) => {
30
54
  this.#options.onError?.(error);
55
+ })
56
+ .finally(() => {
57
+ polling = false;
58
+ if (rerun && this.#timer !== null) {
59
+ rerun = false;
60
+ poll();
61
+ }
31
62
  });
32
63
  };
33
64
  this.#timer = setInterval(poll, COST_POLL_INTERVAL_MS);
@@ -58,19 +89,40 @@ export class ScanCostTracker {
58
89
  async #readSessions() {
59
90
  if (this.#threadId === null)
60
91
  return;
92
+ const unreadable = [];
61
93
  for await (const path of sessionFiles(join(this.#options.codexHome, "sessions"))) {
62
94
  let session = this.#sessions.get(path);
63
95
  if (session === undefined) {
64
96
  session = {
65
97
  offset: 0,
66
- remainder: Buffer.alloc(0),
98
+ pendingLine: [],
99
+ pendingLineBytes: 0,
100
+ unreadable: false,
67
101
  threadId: null,
68
102
  parentThreadId: null,
103
+ startedAt: null,
104
+ inheritedUsage: null,
105
+ replaying: false,
69
106
  usage: null,
107
+ calls: new Map(),
108
+ activities: [],
109
+ progress: [],
110
+ filesCompleted: 0,
111
+ filesTotal: null,
112
+ prose: new Set(),
113
+ reasoning: null,
114
+ reasoningCount: 0,
70
115
  };
71
116
  this.#sessions.set(path, session);
72
117
  }
73
- await readSessionUsage(path, session);
118
+ try {
119
+ await readSessionUsage(path, session, this.#options.repository);
120
+ }
121
+ catch (error) {
122
+ if (session.threadId === null)
123
+ throw error;
124
+ unreadable.push({ session, error });
125
+ }
74
126
  }
75
127
  const included = new Set([this.#threadId]);
76
128
  let changed = true;
@@ -86,12 +138,20 @@ export class ScanCostTracker {
86
138
  }
87
139
  }
88
140
  }
141
+ for (const { session, error } of unreadable) {
142
+ if (included.has(session.threadId))
143
+ throw error;
144
+ }
89
145
  let usage = null;
90
146
  for (const session of this.#sessions.values()) {
91
- if (session.threadId !== null &&
92
- included.has(session.threadId) &&
93
- session.usage !== null) {
94
- usage = addTokenUsage(usage, session.usage);
147
+ if (session.threadId !== null && included.has(session.threadId)) {
148
+ if (session.threadId !== this.#threadId) {
149
+ this.#reportWorkerActivities(session);
150
+ this.#reportWorkerProgress(session);
151
+ }
152
+ if (session.usage !== null) {
153
+ usage = addTokenUsage(usage, session.usage);
154
+ }
95
155
  }
96
156
  }
97
157
  if (usage === null)
@@ -100,6 +160,55 @@ export class ScanCostTracker {
100
160
  this.#snapshot = { usage, cost };
101
161
  this.#reportCost(cost);
102
162
  }
163
+ #reportWorkerActivities(session) {
164
+ if (this.#options.onActivity === undefined || session.threadId === null) {
165
+ return;
166
+ }
167
+ let worker = this.#workers.get(session.threadId);
168
+ if (worker === undefined) {
169
+ worker = this.#workers.size + 1;
170
+ this.#workers.set(session.threadId, worker);
171
+ }
172
+ for (const activity of session.activities.splice(0)) {
173
+ this.#options.onActivity({
174
+ ...activity,
175
+ id: `${session.threadId}:${activity.id}`,
176
+ worker,
177
+ });
178
+ }
179
+ }
180
+ #reportWorkerProgress(session) {
181
+ if (this.#options.onProgress === undefined || session.threadId === null) {
182
+ return;
183
+ }
184
+ for (const progress of session.progress.splice(0)) {
185
+ const expectedFilesTotal = this.#expectedFilesTotal;
186
+ if ((expectedFilesTotal !== undefined &&
187
+ progress.filesTotal > expectedFilesTotal) ||
188
+ (session.filesTotal !== null &&
189
+ progress.filesTotal !== session.filesTotal) ||
190
+ progress.filesCompleted < session.filesCompleted) {
191
+ continue;
192
+ }
193
+ session.filesTotal = progress.filesTotal;
194
+ session.filesCompleted = progress.filesCompleted;
195
+ this.#workerProgress.set(session.threadId, progress.filesCompleted);
196
+ const filesCompleted = Math.min(expectedFilesTotal ?? Number.MAX_SAFE_INTEGER, [...this.#workerProgress.values()].reduce((total, reviewed) => total + reviewed, 0));
197
+ if (filesCompleted < this.#highestFilesCompleted)
198
+ continue;
199
+ const update = {
200
+ ...progress,
201
+ filesCompleted,
202
+ filesTotal: expectedFilesTotal ?? Math.max(progress.filesTotal, filesCompleted),
203
+ };
204
+ const key = `${update.phase}:${update.filesCompleted}:${update.filesTotal}`;
205
+ if (this.#reportedProgress.has(key))
206
+ continue;
207
+ this.#reportedProgress.add(key);
208
+ this.#highestFilesCompleted = update.filesCompleted;
209
+ this.#options.onProgress(update);
210
+ }
211
+ }
103
212
  #reportCost(cost) {
104
213
  if (cost === null || cost.estimatedUsd === this.#lastCost)
105
214
  return;
@@ -127,7 +236,9 @@ async function* sessionFiles(directory) {
127
236
  }
128
237
  }
129
238
  }
130
- async function readSessionUsage(path, session) {
239
+ async function readSessionUsage(path, session, repository) {
240
+ if (session.unreadable)
241
+ return;
131
242
  let file;
132
243
  try {
133
244
  file = await open(path, "r");
@@ -144,26 +255,52 @@ async function readSessionUsage(path, session) {
144
255
  if (bytesRead === 0)
145
256
  return;
146
257
  session.offset += bytesRead;
147
- const contents = Buffer.concat([
148
- session.remainder,
149
- buffer.subarray(0, bytesRead),
150
- ]);
151
- let lineStart = 0;
152
- while (true) {
153
- const lineEnd = contents.indexOf(0x0a, lineStart);
154
- if (lineEnd === -1)
155
- break;
156
- readSessionEvent(contents.subarray(lineStart, lineEnd).toString("utf8"), session);
157
- lineStart = lineEnd + 1;
258
+ try {
259
+ readSessionChunk(buffer.subarray(0, bytesRead), session, repository);
260
+ }
261
+ catch (error) {
262
+ session.unreadable = true;
263
+ session.pendingLine = [];
264
+ session.pendingLineBytes = 0;
265
+ throw error;
158
266
  }
159
- session.remainder = Buffer.from(contents.subarray(lineStart));
160
267
  }
161
268
  }
162
269
  finally {
163
270
  await file.close();
164
271
  }
165
272
  }
166
- function readSessionEvent(line, session) {
273
+ function readSessionChunk(contents, session, repository) {
274
+ let lineStart = 0;
275
+ while (lineStart < contents.length) {
276
+ const newline = contents.indexOf(0x0a, lineStart);
277
+ const lineEnd = newline === -1 ? contents.length : newline;
278
+ const fragment = contents.subarray(lineStart, lineEnd);
279
+ const lineBytes = session.pendingLineBytes + fragment.length;
280
+ if (lineBytes > MAX_SESSION_EVENT_BYTES) {
281
+ throw new Error("Codex session event exceeds the 1 MiB safety limit.");
282
+ }
283
+ if (newline === -1) {
284
+ if (fragment.length > 0) {
285
+ session.pendingLine.push(Buffer.from(fragment));
286
+ session.pendingLineBytes = lineBytes;
287
+ }
288
+ return;
289
+ }
290
+ if (session.pendingLineBytes === 0) {
291
+ readSessionEvent(fragment.toString("utf8"), session, repository);
292
+ }
293
+ else {
294
+ if (fragment.length > 0)
295
+ session.pendingLine.push(Buffer.from(fragment));
296
+ readSessionEvent(Buffer.concat(session.pendingLine, lineBytes).toString("utf8"), session, repository);
297
+ session.pendingLine = [];
298
+ session.pendingLineBytes = 0;
299
+ }
300
+ lineStart = newline + 1;
301
+ }
302
+ }
303
+ function readSessionEvent(line, session, repository) {
167
304
  if (line.length === 0)
168
305
  return;
169
306
  let event;
@@ -177,9 +314,16 @@ function readSessionEvent(line, session) {
177
314
  return;
178
315
  const payload = event["payload"];
179
316
  if (event["type"] === "session_meta") {
317
+ if (session.threadId !== null) {
318
+ session.replaying = payload["id"] !== session.threadId;
319
+ return;
320
+ }
180
321
  if (typeof payload["id"] === "string") {
181
322
  session.threadId = payload["id"];
182
323
  }
324
+ if (typeof payload["timestamp"] === "string") {
325
+ session.startedAt = Math.floor(Date.parse(payload["timestamp"]) / 1_000);
326
+ }
183
327
  const source = payload["source"];
184
328
  const subagent = isRecord(source) ? source["subagent"] : undefined;
185
329
  const spawn = isRecord(subagent) ? subagent["thread_spawn"] : undefined;
@@ -189,14 +333,232 @@ function readSessionEvent(line, session) {
189
333
  session.parentThreadId = parent;
190
334
  return;
191
335
  }
336
+ if (session.replaying) {
337
+ if (event["type"] !== "event_msg")
338
+ return;
339
+ if (payload["type"] === "token_count" && isRecord(payload["info"])) {
340
+ const usage = tokenUsage(payload["info"]["total_token_usage"]);
341
+ if (usage !== null)
342
+ session.inheritedUsage = usage;
343
+ }
344
+ if (payload["type"] === "task_started" &&
345
+ typeof payload["started_at"] === "number" &&
346
+ session.startedAt !== null &&
347
+ payload["started_at"] >= session.startedAt) {
348
+ session.replaying = false;
349
+ }
350
+ return;
351
+ }
352
+ if (event["type"] === "response_item") {
353
+ session.progress.push(...sessionProgressUpdates(payload));
354
+ if (repository === undefined)
355
+ return;
356
+ if (payload["type"] === "reasoning" &&
357
+ typeof payload["id"] === "string" &&
358
+ Array.isArray(payload["summary"]) &&
359
+ payload["summary"].length > 1 &&
360
+ session.reasoning?.raw !== true) {
361
+ for (const [index, summary] of payload["summary"].entries()) {
362
+ const activity = scanActivityFromSessionEvent({
363
+ ...event,
364
+ payload: {
365
+ ...payload,
366
+ id: `${payload["id"]}:${index}`,
367
+ summary: [summary],
368
+ },
369
+ }, repository);
370
+ if (activity === null ||
371
+ session.prose.has(`${activity.kind}:${activity.description}`)) {
372
+ continue;
373
+ }
374
+ session.reasoning = {
375
+ id: activity.id,
376
+ text: activity.description,
377
+ raw: false,
378
+ activity: null,
379
+ };
380
+ recordReasoningActivity(session, activity);
381
+ }
382
+ return;
383
+ }
384
+ const activity = scanActivityFromSessionEvent(event, repository);
385
+ if (activity !== null) {
386
+ if (activity.kind === "reasoning") {
387
+ const reasoning = (session.reasoning ??= {
388
+ id: activity.id,
389
+ text: activity.description,
390
+ raw: false,
391
+ activity: null,
392
+ });
393
+ recordReasoningActivity(session, {
394
+ ...activity,
395
+ id: reasoning.id,
396
+ description: reasoning.raw && reasoning.activity !== null
397
+ ? reasoning.activity.description
398
+ : activity.description,
399
+ });
400
+ return;
401
+ }
402
+ session.reasoning = null;
403
+ if (activity.kind === "message" &&
404
+ session.prose.has(`${activity.kind}:${activity.description}`)) {
405
+ return;
406
+ }
407
+ if (activity.kind === "message") {
408
+ session.prose.add(`${activity.kind}:${activity.description}`);
409
+ }
410
+ if (activity.status === "running") {
411
+ session.calls.set(activity.id, activity);
412
+ }
413
+ session.activities.push(activity);
414
+ return;
415
+ }
416
+ if ((payload["type"] === "function_call_output" ||
417
+ payload["type"] === "custom_tool_call_output") &&
418
+ typeof payload["call_id"] === "string") {
419
+ const call = session.calls.get(payload["call_id"]);
420
+ if (call !== undefined) {
421
+ session.activities.push({
422
+ ...call,
423
+ status: payload["status"] === "failed" ? "failed" : "completed",
424
+ });
425
+ session.calls.delete(call.id);
426
+ }
427
+ }
428
+ return;
429
+ }
430
+ if (event["type"] === "event_msg" &&
431
+ (payload["type"] === "agent_reasoning" ||
432
+ payload["type"] === "agent_reasoning_delta" ||
433
+ payload["type"] === "agent_reasoning_raw_content" ||
434
+ payload["type"] === "agent_reasoning_raw_content_delta" ||
435
+ payload["type"] === "agent_message")) {
436
+ if (payload["type"] === "agent_message" &&
437
+ typeof payload["message"] === "string") {
438
+ session.progress.push(...scanProgressUpdatesFromEvent({
439
+ type: "item.completed",
440
+ item: { type: "agent_message", text: payload["message"] },
441
+ }));
442
+ }
443
+ if (repository === undefined)
444
+ return;
445
+ if (payload["type"] !== "agent_message") {
446
+ readSessionReasoning(event, payload, session, repository);
447
+ return;
448
+ }
449
+ session.reasoning = null;
450
+ const activity = scanActivityFromSessionEvent(event, repository);
451
+ if (activity !== null &&
452
+ !session.prose.has(`${activity.kind}:${activity.description}`)) {
453
+ session.prose.add(`${activity.kind}:${activity.description}`);
454
+ session.activities.push(activity);
455
+ }
456
+ return;
457
+ }
192
458
  if (event["type"] !== "event_msg" ||
193
459
  payload["type"] !== "token_count" ||
194
460
  !isRecord(payload["info"])) {
195
461
  return;
196
462
  }
197
463
  const usage = tokenUsage(payload["info"]["total_token_usage"]);
198
- if (usage !== null)
199
- session.usage = usage;
464
+ if (usage === null)
465
+ return;
466
+ const ownUsage = session.inheritedUsage === null
467
+ ? usage
468
+ : subtractTokenUsage(usage, session.inheritedUsage);
469
+ if (ownUsage !== null)
470
+ session.usage = ownUsage;
471
+ }
472
+ function readSessionReasoning(event, payload, session, repository) {
473
+ const type = payload["type"];
474
+ const raw = type === "agent_reasoning_raw_content" ||
475
+ type === "agent_reasoning_raw_content_delta";
476
+ const delta = type === "agent_reasoning_delta" ||
477
+ type === "agent_reasoning_raw_content_delta";
478
+ const text = payload[delta ? "delta" : "text"];
479
+ if (typeof text !== "string")
480
+ return;
481
+ if (!delta &&
482
+ !raw &&
483
+ session.reasoning?.raw !== true &&
484
+ session.reasoning?.activity?.status === "completed" &&
485
+ session.reasoning.text !== text) {
486
+ session.reasoning = null;
487
+ }
488
+ const reasoning = (session.reasoning ??= {
489
+ id: `reasoning-${++session.reasoningCount}`,
490
+ text: "",
491
+ raw: false,
492
+ activity: null,
493
+ });
494
+ if (reasoning.raw && !raw)
495
+ return;
496
+ if (raw && !reasoning.raw) {
497
+ reasoning.text = "";
498
+ reasoning.raw = true;
499
+ }
500
+ reasoning.text = delta ? `${reasoning.text}${text}` : text;
501
+ const activity = scanActivityFromSessionEvent({
502
+ ...event,
503
+ payload: {
504
+ ...payload,
505
+ [delta ? "delta" : "text"]: reasoning.text,
506
+ },
507
+ }, repository);
508
+ if (activity === null)
509
+ return;
510
+ recordReasoningActivity(session, { ...activity, id: reasoning.id });
511
+ }
512
+ function recordReasoningActivity(session, activity) {
513
+ const reasoning = session.reasoning;
514
+ if (reasoning.activity?.description === activity.description &&
515
+ reasoning.activity.status === activity.status) {
516
+ return;
517
+ }
518
+ reasoning.activity = activity;
519
+ session.prose.add(`${activity.kind}:${activity.description}`);
520
+ session.activities.push(activity);
521
+ }
522
+ function sessionProgressUpdates(payload) {
523
+ if (payload["type"] === "message" && payload["role"] === "assistant") {
524
+ const content = payload["content"];
525
+ if (!Array.isArray(content))
526
+ return [];
527
+ return scanProgressUpdatesFromEvent({
528
+ type: "item.completed",
529
+ item: {
530
+ type: "agent_message",
531
+ text: sessionContentText(content, false),
532
+ },
533
+ });
534
+ }
535
+ if (payload["type"] !== "function_call_output" &&
536
+ payload["type"] !== "custom_tool_call_output" &&
537
+ payload["type"] !== "local_shell_call_output") {
538
+ return [];
539
+ }
540
+ const value = payload["output"];
541
+ const output = typeof value === "string"
542
+ ? value
543
+ : Array.isArray(value)
544
+ ? sessionContentText(value, true)
545
+ : null;
546
+ if (payload["status"] === "failed" || output === null) {
547
+ return [];
548
+ }
549
+ return scanProgressUpdatesFromEvent({
550
+ type: "item.completed",
551
+ item: { type: "command_execution", aggregated_output: output },
552
+ });
553
+ }
554
+ function sessionContentText(content, includeInputText) {
555
+ return content
556
+ .filter((item) => isRecord(item) &&
557
+ (item["type"] === "output_text" ||
558
+ (includeInputText && item["type"] === "input_text")) &&
559
+ typeof item["text"] === "string")
560
+ .map((item) => item.text)
561
+ .join("\n");
200
562
  }
201
563
  function tokenUsage(value) {
202
564
  if (!isRecord(value))
@@ -236,6 +598,15 @@ function addTokenUsage(previous, next) {
236
598
  total_tokens: previous.total_tokens + next.total_tokens,
237
599
  };
238
600
  }
601
+ function subtractTokenUsage(usage, inherited) {
602
+ return tokenUsage({
603
+ input_tokens: usage.input_tokens - inherited.input_tokens,
604
+ cached_input_tokens: usage.cached_input_tokens - inherited.cached_input_tokens,
605
+ cache_write_input_tokens: usage.cache_write_input_tokens - inherited.cache_write_input_tokens,
606
+ output_tokens: usage.output_tokens - inherited.output_tokens,
607
+ reasoning_output_tokens: usage.reasoning_output_tokens - inherited.reasoning_output_tokens,
608
+ });
609
+ }
239
610
  function isRecord(value) {
240
611
  return typeof value === "object" && value !== null && !Array.isArray(value);
241
612
  }