@andorra-labs/code 0.1.18 → 0.1.19

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 (277) hide show
  1. package/dist/src/account-jev-savings.d.ts +4 -0
  2. package/dist/src/account-jev-savings.js +92 -0
  3. package/dist/src/acp-agent.js +2 -2
  4. package/dist/src/agent-execution.js +347 -45
  5. package/dist/src/agent-mcp.js +7 -1
  6. package/dist/src/agent-modifiers.js +5 -7
  7. package/dist/src/analytics.d.ts +19 -1
  8. package/dist/src/analytics.js +9 -1
  9. package/dist/src/andorra/entry.js +15 -6
  10. package/dist/src/andorra/hosted.d.ts +8 -0
  11. package/dist/src/andorra/hosted.js +22 -3
  12. package/dist/src/andorra/streams.d.ts +49 -0
  13. package/dist/src/andorra/streams.js +98 -0
  14. package/dist/src/antigravity-acp.d.ts +28 -0
  15. package/dist/src/antigravity-acp.js +150 -0
  16. package/dist/src/antigravity-terminal.d.ts +2 -0
  17. package/dist/src/antigravity-terminal.js +214 -0
  18. package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
  19. package/dist/src/app-server/adaptive-routing-settings.js +69 -0
  20. package/dist/src/app-server/artifact.d.ts +14 -0
  21. package/dist/src/app-server/artifact.js +46 -0
  22. package/dist/src/app-server/legal-protocol.d.ts +33 -0
  23. package/dist/src/app-server/legal-protocol.js +16 -0
  24. package/dist/src/app-server/protocol.d.ts +23 -3
  25. package/dist/src/app-server/protocol.js +3 -1
  26. package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
  27. package/dist/src/app-server/telemetry-protocol.js +2 -0
  28. package/dist/src/app-server/telemetry.d.ts +38 -0
  29. package/dist/src/app-server/telemetry.js +163 -0
  30. package/dist/src/app-server/workspace.d.ts +3 -1
  31. package/dist/src/app-server/workspace.js +39 -8
  32. package/dist/src/app-server.d.ts +50 -25
  33. package/dist/src/app-server.js +1008 -400
  34. package/dist/src/auth/AuthManager.d.ts +11 -2
  35. package/dist/src/auth/AuthManager.js +56 -13
  36. package/dist/src/auth/index.d.ts +5 -1
  37. package/dist/src/auth/index.js +8 -1
  38. package/dist/src/auth/lifecycle.d.ts +13 -0
  39. package/dist/src/auth/lifecycle.js +109 -0
  40. package/dist/src/auth/store.d.ts +1 -0
  41. package/dist/src/auth/store.js +12 -0
  42. package/dist/src/auth/types.d.ts +12 -0
  43. package/dist/src/automation-runner.js +2 -0
  44. package/dist/src/automation-service.js +7 -2
  45. package/dist/src/benchmark-scores.d.ts +88 -0
  46. package/dist/src/benchmark-scores.js +302 -0
  47. package/dist/src/bridge/command.js +4 -1
  48. package/dist/src/bridge/control.js +2 -1
  49. package/dist/src/bridge/engines.d.ts +2 -0
  50. package/dist/src/bridge/engines.js +9 -0
  51. package/dist/src/bridge/host-ops.d.ts +2 -2
  52. package/dist/src/bridge/host-ops.js +4 -2
  53. package/dist/src/bridge/host.d.ts +2 -0
  54. package/dist/src/bridge/host.js +63 -12
  55. package/dist/src/bridge/protocol.d.ts +1 -0
  56. package/dist/src/bridge/protocol.js +1 -0
  57. package/dist/src/browser-panel-tool.d.ts +12 -0
  58. package/dist/src/browser-panel-tool.js +30 -3
  59. package/dist/src/browser-runner.js +53 -62
  60. package/dist/src/browser-server.js +10 -4
  61. package/dist/src/browser-session.d.ts +14 -0
  62. package/dist/src/browser-session.js +57 -12
  63. package/dist/src/browser-view.d.ts +40 -1
  64. package/dist/src/browser-view.js +163 -9
  65. package/dist/src/browser-window-style.d.ts +27 -0
  66. package/dist/src/browser-window-style.js +244 -0
  67. package/dist/src/claude-provider.d.ts +1 -0
  68. package/dist/src/claude-provider.js +77 -36
  69. package/dist/src/cli.js +235 -58
  70. package/dist/src/codex-provider.d.ts +1 -0
  71. package/dist/src/codex-provider.js +43 -7
  72. package/dist/src/coding-tools.d.ts +1 -0
  73. package/dist/src/coding-tools.js +19 -5
  74. package/dist/src/command-screens.d.ts +1 -1
  75. package/dist/src/command-screens.js +2 -2
  76. package/dist/src/commands.d.ts +8 -1
  77. package/dist/src/commands.js +67 -63
  78. package/dist/src/completion.js +5 -3
  79. package/dist/src/config.d.ts +14 -3
  80. package/dist/src/config.js +54 -16
  81. package/dist/src/context-budget.d.ts +11 -2
  82. package/dist/src/context-budget.js +23 -2
  83. package/dist/src/context-compaction.d.ts +10 -8
  84. package/dist/src/context-compaction.js +23 -24
  85. package/dist/src/deadline.js +1 -1
  86. package/dist/src/decision/DecisionManager.d.ts +5 -0
  87. package/dist/src/decision/DecisionManager.js +39 -2
  88. package/dist/src/decision/applyToolMenu.js +6 -2
  89. package/dist/src/decision/hostedPolicy.js +6 -4
  90. package/dist/src/decision/optimizationPolicy.d.ts +10 -0
  91. package/dist/src/decision/optimizationPolicy.js +23 -3
  92. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -1
  93. package/dist/src/decision/providers/AndorraDecisionProvider.js +17 -7
  94. package/dist/src/decision/providers/index.js +1 -1
  95. package/dist/src/decision/toolFamilies.js +1 -1
  96. package/dist/src/decision/types.d.ts +2 -0
  97. package/dist/src/efficiency.d.ts +75 -1
  98. package/dist/src/efficiency.js +114 -3
  99. package/dist/src/extensions.d.ts +2 -0
  100. package/dist/src/extensions.js +30 -20
  101. package/dist/src/github-app/agent-writes.d.ts +1 -1
  102. package/dist/src/github-app/agent-writes.js +1 -1
  103. package/dist/src/github-app/event-source.d.ts +0 -5
  104. package/dist/src/github-app/event-source.js +1 -31
  105. package/dist/src/github-app/metrics.d.ts +2 -5
  106. package/dist/src/github-app/metrics.js +2 -14
  107. package/dist/src/github-app/review-loop.d.ts +5 -5
  108. package/dist/src/github-app/review-loop.js +1 -1
  109. package/dist/src/github-app/review-node.d.ts +2 -2
  110. package/dist/src/github-app/triggers.d.ts +3 -3
  111. package/dist/src/glob-search.d.ts +1 -0
  112. package/dist/src/glob-search.js +3 -0
  113. package/dist/src/google-provider.d.ts +5 -28
  114. package/dist/src/google-provider.js +6 -141
  115. package/dist/src/graph-editor-session.d.ts +1 -0
  116. package/dist/src/graph-editor-session.js +2 -0
  117. package/dist/src/graph-health.js +3 -1
  118. package/dist/src/graph-runner.js +19 -13
  119. package/dist/src/graph-selection.d.ts +3 -1
  120. package/dist/src/graph-selection.js +2 -2
  121. package/dist/src/graph-server.d.ts +8 -1
  122. package/dist/src/graph-server.js +45 -10
  123. package/dist/src/graph-sync.d.ts +2 -1
  124. package/dist/src/graph-sync.js +13 -0
  125. package/dist/src/graph-ui/app.js +19 -8
  126. package/dist/src/graph-ui/index.html +1 -1
  127. package/dist/src/graphs.d.ts +17 -1
  128. package/dist/src/graphs.js +51 -5
  129. package/dist/src/grok-provider.js +17 -14
  130. package/dist/src/hardened-runtime.js +7 -4
  131. package/dist/src/jev-savings.d.ts +4 -0
  132. package/dist/src/jev-savings.js +13 -0
  133. package/dist/src/legal/client.d.ts +25 -0
  134. package/dist/src/legal/client.js +47 -0
  135. package/dist/src/legal/command.d.ts +13 -0
  136. package/dist/src/legal/command.js +98 -0
  137. package/dist/src/legal/documents.d.ts +2 -0
  138. package/dist/src/legal/documents.js +14 -0
  139. package/dist/src/legal/gate.d.ts +13 -0
  140. package/dist/src/legal/gate.js +96 -0
  141. package/dist/src/legal/manifest.d.ts +21 -0
  142. package/dist/src/legal/manifest.js +23 -0
  143. package/dist/src/legal/receipt.d.ts +13 -0
  144. package/dist/src/legal/receipt.js +137 -0
  145. package/dist/src/legal/release.d.ts +27 -0
  146. package/dist/src/legal/release.js +28 -0
  147. package/dist/src/managed-sign-in.d.ts +0 -1
  148. package/dist/src/managed-sign-in.js +0 -13
  149. package/dist/src/membership.d.ts +27 -1
  150. package/dist/src/membership.js +139 -7
  151. package/dist/src/model-metadata.js +3 -7
  152. package/dist/src/model-pool.d.ts +99 -0
  153. package/dist/src/model-pool.js +136 -0
  154. package/dist/src/model-relay/local.js +5 -0
  155. package/dist/src/model-relay/remote.d.ts +2 -0
  156. package/dist/src/model-relay/remote.js +4 -0
  157. package/dist/src/model-tiers.d.ts +13 -1
  158. package/dist/src/model-tiers.js +28 -4
  159. package/dist/src/opencode-cli-provider.js +59 -56
  160. package/dist/src/opencode-provider.js +16 -13
  161. package/dist/src/permissions.d.ts +5 -0
  162. package/dist/src/permissions.js +7 -0
  163. package/dist/src/plan-pass.js +2 -1
  164. package/dist/src/pool-scores.d.ts +45 -0
  165. package/dist/src/pool-scores.js +40 -0
  166. package/dist/src/provider-connection.js +3 -17
  167. package/dist/src/provider-engine.js +42 -12
  168. package/dist/src/provider-request-error.d.ts +8 -0
  169. package/dist/src/provider-request-error.js +12 -0
  170. package/dist/src/provider-settings.d.ts +1 -1
  171. package/dist/src/provider-settings.js +36 -18
  172. package/dist/src/provider-turn-deadline.d.ts +39 -0
  173. package/dist/src/provider-turn-deadline.js +139 -0
  174. package/dist/src/providers.d.ts +3 -9
  175. package/dist/src/providers.js +181 -146
  176. package/dist/src/pull-request-merge.d.ts +1 -8
  177. package/dist/src/pull-request-merge.js +0 -4
  178. package/dist/src/pull-requests.d.ts +82 -66
  179. package/dist/src/pull-requests.js +266 -276
  180. package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
  181. package/dist/src/qa/runtime/ProcessManager.js +9 -3
  182. package/dist/src/react-runtime.js +147 -56
  183. package/dist/src/reasoning-probe-cloud.d.ts +10 -0
  184. package/dist/src/reasoning-probe-cloud.js +209 -0
  185. package/dist/src/remote/engine-pool.d.ts +3 -0
  186. package/dist/src/remote/engine-pool.js +85 -18
  187. package/dist/src/remote/recovery.d.ts +6 -0
  188. package/dist/src/remote/recovery.js +37 -0
  189. package/dist/src/run-records.d.ts +13 -3
  190. package/dist/src/run-records.js +59 -34
  191. package/dist/src/runtime.d.ts +18 -1
  192. package/dist/src/runtime.js +25 -7
  193. package/dist/src/session-summary.d.ts +8 -0
  194. package/dist/src/session-summary.js +34 -0
  195. package/dist/src/sessions.d.ts +8 -0
  196. package/dist/src/sessions.js +12 -3
  197. package/dist/src/shell.js +6 -0
  198. package/dist/src/side-panel.js +36 -2
  199. package/dist/src/sign-in-detection.d.ts +1 -1
  200. package/dist/src/sign-in-detection.js +4 -10
  201. package/dist/src/sign-in-offer.js +1 -1
  202. package/dist/src/skill-commands.js +1 -1
  203. package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
  204. package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
  205. package/dist/src/skills/bundled/provenance.json +2 -2
  206. package/dist/src/subagent-run.js +50 -50
  207. package/dist/src/subscription-usage.d.ts +50 -0
  208. package/dist/src/subscription-usage.js +92 -0
  209. package/dist/src/task-checkout.d.ts +20 -4
  210. package/dist/src/task-checkout.js +78 -8
  211. package/dist/src/telemetry/access.d.ts +18 -0
  212. package/dist/src/telemetry/access.js +43 -0
  213. package/dist/src/telemetry/aggregate.d.ts +18 -2
  214. package/dist/src/telemetry/aggregate.js +22 -9
  215. package/dist/src/telemetry/capture-core.d.ts +33 -14
  216. package/dist/src/telemetry/capture-core.js +124 -25
  217. package/dist/src/telemetry/capture.d.ts +3 -2
  218. package/dist/src/telemetry/capture.js +21 -1
  219. package/dist/src/telemetry/decision-capture.js +4 -0
  220. package/dist/src/telemetry/emitter.d.ts +6 -7
  221. package/dist/src/telemetry/emitter.js +124 -29
  222. package/dist/src/telemetry/gate.d.ts +41 -2
  223. package/dist/src/telemetry/gate.js +89 -4
  224. package/dist/src/telemetry/home.d.ts +1 -0
  225. package/dist/src/telemetry/home.js +20 -0
  226. package/dist/src/telemetry/identity.d.ts +6 -3
  227. package/dist/src/telemetry/identity.js +19 -6
  228. package/dist/src/telemetry/lifecycle.d.ts +8 -0
  229. package/dist/src/telemetry/lifecycle.js +76 -0
  230. package/dist/src/telemetry/outbox.d.ts +13 -8
  231. package/dist/src/telemetry/outbox.js +68 -12
  232. package/dist/src/telemetry/permission-command.d.ts +38 -0
  233. package/dist/src/telemetry/permission-command.js +208 -0
  234. package/dist/src/telemetry/permission.d.ts +168 -0
  235. package/dist/src/telemetry/permission.js +662 -0
  236. package/dist/src/telemetry/record-installation.d.ts +1 -0
  237. package/dist/src/telemetry/record-installation.js +9 -0
  238. package/dist/src/telemetry/region-data.d.ts +12 -0
  239. package/dist/src/telemetry/region-data.js +1314 -0
  240. package/dist/src/telemetry/region.d.ts +34 -0
  241. package/dist/src/telemetry/region.js +87 -0
  242. package/dist/src/telemetry/run-privacy.d.ts +11 -0
  243. package/dist/src/telemetry/run-privacy.js +165 -0
  244. package/dist/src/telemetry/schema.d.ts +27 -6
  245. package/dist/src/telemetry/schema.js +109 -14
  246. package/dist/src/telemetry/state.d.ts +11 -7
  247. package/dist/src/telemetry/state.js +39 -6
  248. package/dist/src/telemetry/surface.d.ts +20 -3
  249. package/dist/src/telemetry/surface.js +71 -15
  250. package/dist/src/telemetry/uploader.d.ts +6 -11
  251. package/dist/src/telemetry/uploader.js +72 -46
  252. package/dist/src/telemetry/uploads.d.ts +5 -1
  253. package/dist/src/telemetry/uploads.js +25 -6
  254. package/dist/src/telemetry/version.d.ts +5 -0
  255. package/dist/src/telemetry/version.js +34 -0
  256. package/dist/src/telemetry/workspace.d.ts +4 -1
  257. package/dist/src/telemetry/workspace.js +18 -3
  258. package/dist/src/terminal-ui.d.ts +3 -0
  259. package/dist/src/terminal-ui.js +48 -6
  260. package/dist/src/thinking-level-detect.d.ts +3 -1
  261. package/dist/src/thinking-level-detect.js +8 -3
  262. package/dist/src/thinking-levels.d.ts +1 -1
  263. package/dist/src/thinking-levels.js +11 -4
  264. package/dist/src/timers.d.ts +2 -0
  265. package/dist/src/todos.d.ts +2 -1
  266. package/dist/src/todos.js +24 -4
  267. package/dist/src/tool-argument-coercion.d.ts +7 -0
  268. package/dist/src/tool-argument-coercion.js +49 -0
  269. package/dist/src/tool-catalog.d.ts +2 -2
  270. package/dist/src/tools.js +67 -22
  271. package/dist/src/transcript.js +2 -1
  272. package/dist/src/types.d.ts +14 -1
  273. package/dist/src/update.js +4 -0
  274. package/dist/src/usage-analytics.d.ts +7 -0
  275. package/dist/src/usage-analytics.js +85 -13
  276. package/dist/telemetry-consent-v1 +1 -0
  277. package/package.json +97 -96
package/dist/src/tools.js CHANGED
@@ -383,6 +383,13 @@ export async function authorize(name, args, context) {
383
383
  }
384
384
  }
385
385
  }
386
+ /** The notice a caller of files() shows when the walk skipped folders it could not open; undefined when none were skipped. */
387
+ function skippedFoldersNotice(budget, covered) {
388
+ const count = budget.unreadable ?? 0;
389
+ if (!count)
390
+ return undefined;
391
+ return `[INCOMPLETE ${covered === 'listed' ? 'LISTING' : 'SEARCH'}: ${count.toLocaleString('en-US')} folder${count === 1 ? '' : 's'} could not be opened (permission denied) and ${count === 1 ? 'was' : 'were'} skipped. Files inside ${count === 1 ? 'it' : 'them'} were not ${covered}, so this result does not show that a file or match is absent.]`;
392
+ }
386
393
  async function* files(context, directory, depth = 0, budget = { entries: 0 }) {
387
394
  if (depth > 20)
388
395
  return;
@@ -392,7 +399,21 @@ async function* files(context, directory, depth = 0, budget = { entries: 0 }) {
392
399
  ? await fileProtectedRoots(await realpath(context.workspace)) : [];
393
400
  const homeGuarded = guardsHarnessHome(context);
394
401
  const workspaceRoot = homeGuarded ? await realpath(context.workspace) : '';
395
- for await (const entry of await opendir(resolved)) {
402
+ let listing;
403
+ try {
404
+ listing = await opendir(resolved);
405
+ }
406
+ catch (error) {
407
+ // A folder the user may not open (another user's container volume, a systemd private /tmp folder) is
408
+ // skipped and counted, so one such folder no longer fails the whole listing.
409
+ const code = error?.code;
410
+ if (depth > 0 && (code === 'EACCES' || code === 'EPERM')) {
411
+ budget.unreadable = (budget.unreadable ?? 0) + 1;
412
+ return;
413
+ }
414
+ throw error;
415
+ }
416
+ for await (const entry of listing) {
396
417
  context.signal.throwIfAborted();
397
418
  if (++budget.entries > (budget.limit ?? 10_000))
398
419
  throw new Error(`Directory scan limit reached (${(budget.limit ?? 10_000).toLocaleString('en-US')} entries); use a narrower path`);
@@ -622,10 +643,19 @@ const REVIEW_END_TEXT = {
622
643
  };
623
644
  function reviewLoopEndAnswer(ended) {
624
645
  const why = REVIEW_END_TEXT[ended.reason] ?? (ended.detail === undefined ? '' : ended.detail);
625
- const next = ended.pullRequest.autoFix
626
- ? 'Auto-fix is still on: call await_review again to wait for other reviewers, or finish and report.'
627
- : 'There is no review left to wait for; finish your work and report.';
628
- return `The Andorra review loop ended: ${ended.reason}.${why ? ` ${why}` : ''} ${next}`;
646
+ return `The Andorra review loop ended: ${ended.reason}.${why ? ` ${why}` : ''} If another review is needed, call await_review again.`;
647
+ }
648
+ function reviewReactionLines(reactions) {
649
+ if (reactions.length === 0)
650
+ return '';
651
+ const icons = {
652
+ THUMBS_UP: '+1', THUMBS_DOWN: '-1', EYES: 'eyes', HEART: 'heart',
653
+ HOORAY: 'hooray', LAUGH: 'laugh', CONFUSED: 'confused', ROCKET: 'rocket',
654
+ };
655
+ const lines = reactions.slice(0, 20).map(reaction => `- ${reaction.actor ?? 'A GitHub account'} ${reaction.kind} ${icons[reaction.content] ?? reaction.content}`);
656
+ if (reactions.length > lines.length)
657
+ lines.push(`- ${reactions.length - lines.length} more reaction changes on GitHub`);
658
+ return `\nMain-post reaction changes:\n${lines.join('\n')}`;
629
659
  }
630
660
  function reviewWaitAnswer(ended, minutes, signal) {
631
661
  switch (ended.kind) {
@@ -634,10 +664,19 @@ function reviewWaitAnswer(ended, minutes, signal) {
634
664
  case 'review-ended': return reviewLoopEndAnswer(ended);
635
665
  case 'comments': return `${ended.prompt}
636
666
 
637
- When this round is pushed and its threads are answered, call pull_request with action await_review again to wait for the next review.`;
638
- case 'approved': return `Codex signed off on ${ended.pullRequest.url}${ended.headSha === undefined ? '' : ` at ${ended.headSha.slice(0, 10)}`}: it reviewed that commit and found nothing (its thumbs-up on the pull request, or a review with no findings), and no new review comment is waiting. Treat this as an approval of that commit. There is no review left to wait for; finish your work and report, and merge only if the user asked you to. Call await_review again only after you push another commit.`;
639
- case 'finished': return `${ended.pullRequest.url} is ${ended.pullRequest.state}, so Auto-fix is off and there is no review left to wait for. Finish your work and report.`;
640
- case 'off': return `Auto-fix is off for ${ended.pullRequest.url} and no Andorra review loop is running, so no review will be waited for. Finish your work and report; switch Auto-fix or Andorra review on only if the user asks.`;
667
+ If another review is needed after you push and answer its threads, call pull_request with action await_review again.`;
668
+ case 'activity': {
669
+ const comments = ended.comments.map(comment => {
670
+ const label = comment.kind === 'approval' ? 'Possible approval comment' : comment.kind === 'review' ? 'Code-review comment' : 'Review activity (unclassified)';
671
+ const location = comment.url ?? comment.threadId;
672
+ return `- ${label} from ${comment.author}${location ? ` (${location})` : ''}`;
673
+ });
674
+ const notices = comments.length > 0 ? `\n${comments.join('\n')}` : '';
675
+ return `New activity on ${ended.pullRequest.url}.${notices}${reviewReactionLines(ended.reactions)}
676
+ Read the relevant comments or reactions on GitHub before acting. Comment labels are advisory. Verify any approval against the current head, and merge only if authorized. Call pull_request with action await_review again if the task needs further monitoring.`;
677
+ }
678
+ case 'approved': return `Codex signed off on ${ended.pullRequest.url}${ended.headSha === undefined ? '' : ` at ${ended.headSha.slice(0, 10)}`}: it reviewed that commit and found nothing (its thumbs-up on the pull request, or a review with no findings), and no new review comment is waiting. Treat this as an approval of that commit. There is no review left to wait for; finish your work and report, and merge only if the user asked you to. Call await_review again if the task needs further monitoring.${reviewReactionLines(ended.reactions ?? [])}`;
679
+ case 'finished': return `${ended.pullRequest.url} is ${ended.pullRequest.state}, so there is no review left to wait for. Finish your work and report.`;
641
680
  case 'none': return 'No pull request is tracked for this session, so there is no review to wait for.';
642
681
  case 'timeout': return `No new review arrived in ${minutes} minute${minutes === 1 ? '' : 's'}. Call await_review again to keep waiting, or finish and report.`;
643
682
  case 'steered': return 'The user sent you a message while you were waiting for a review. Read and answer it; call await_review again afterwards if the review loop should continue.';
@@ -655,13 +694,17 @@ export function createTools() {
655
694
  }, ['path'], readFileTool),
656
695
  legacyTool('list_files', 'Recursively list up to 1,000 files, depth 20; skip symlinks, .git, node_modules and .andorracode.', { path: property('Workspace-relative directory, default .') }, [], async (args, context) => {
657
696
  const result = [];
658
- for await (const name of files(context, args.path === undefined ? '.' : string(args, 'path'))) {
697
+ const budget = { entries: 0 };
698
+ for await (const name of files(context, args.path === undefined ? '.' : string(args, 'path'), 0, budget)) {
659
699
  result.push(name);
660
700
  if (result.length >= 1000) {
661
701
  result.push('[file limit reached]');
662
702
  break;
663
703
  }
664
704
  }
705
+ const skipped = skippedFoldersNotice(budget, 'listed');
706
+ if (skipped)
707
+ result.unshift(skipped);
665
708
  return bounded(result.join('\n'));
666
709
  }),
667
710
  legacyTool('search_files', 'Bounded source search. Default smart mode is case-insensitive and relaxes whitespace/extra words plus simple word suffixes (for example "Create new graph" matches "Create a new Graph" and "Edit graph" matches "Edit Graphs"). Use mode=regex for an explicit JavaScript regular expression or mode=literal for substring matching. Searches at most 1,000 files and 16 MiB; returns 50 matches by default (max 200), with long matching lines clipped. Prefer repo_explore/CodeGraph first when it is available; use this as textual fallback or exact confirmation.', {
@@ -707,7 +750,8 @@ export function createTools() {
707
750
  }
708
751
  const result = [];
709
752
  let count = 0, bytes = 0, outputChars = 0;
710
- for await (const name of files(context, args.path === undefined ? '.' : string(args, 'path'))) {
753
+ const searchBudget = { entries: 0 };
754
+ for await (const name of files(context, args.path === undefined ? '.' : string(args, 'path'), 0, searchBudget)) {
711
755
  if (++count > 1000) {
712
756
  result.push('[file limit reached; narrow path]');
713
757
  break;
@@ -738,11 +782,14 @@ export function createTools() {
738
782
  result.push(match);
739
783
  outputChars += match.length + 1;
740
784
  if (result.length >= maxResults || outputChars > 12_000) {
741
- return bounded(result.join('\n') + '\n[match/output limit reached; narrow path/query or raise maxResults]');
785
+ const skippedSoFar = skippedFoldersNotice(searchBudget, 'searched');
786
+ return bounded((skippedSoFar ? skippedSoFar + '\n' : '') + result.join('\n') + '\n[match/output limit reached; narrow path/query or raise maxResults]');
742
787
  }
743
788
  }
744
789
  }
745
- return bounded(result.join('\n')) || 'No matches';
790
+ const skipped = skippedFoldersNotice(searchBudget, 'searched');
791
+ const body = bounded(result.join('\n')) || 'No matches';
792
+ return skipped ? skipped + '\n' + body : body;
746
793
  }),
747
794
  legacyTool('write_file', 'Create or overwrite a UTF-8 workspace file; obeys workspace permissions; protected or outside paths require approval.', { path: property('Workspace-relative file path'), content: property('Complete file content') }, ['path', 'content'], async (args, context) => {
748
795
  const name = string(args, 'path'), content = string(args, 'content', true);
@@ -783,27 +830,25 @@ export function createTools() {
783
830
  context.wakesArmed?.push(timer.id);
784
831
  return `Timer ${timer.id.slice(0, 8)} armed: your prompt will be delivered in ${args.seconds} second${args.seconds === 1 ? '' : 's'}, at ${new Date(timer.fireAt).toISOString()}. It fires once.`;
785
832
  }),
786
- { ...tool('pull_request', `Show or change the pull request this session tracks in the desktop Plan card. A PR you open with \`gh pr create\` is attached automatically; use attach for one opened another way. update changes its settings when the user asks: mergeWhenReady enables GitHub auto-merge (gh pr merge --auto), draft converts to a draft or marks it ready, autoFix wakes you with a prompt when a code-review bot (Codex, CodeRabbit, Greptile, Copilot) comments and switches itself off once the PR is merged or closed. review switches on Andorra review: the Andorra Code bot reviews the PR up to reviewRounds times (1 to ${REVIEW_ROUNDS_MAX}, default ${REVIEW_ROUNDS_DEFAULT}) and you are woken to fix its findings between reviews; reviewInstruction tells the reviewer what to focus on, reviewModel picks its provider/model (default: this task's), and review false switches it off. It needs a paid Andorra plan and a pull request the Andorra Code GitHub App covers; the result says why when it cannot be switched on. await_review keeps you in this run while Auto-fix or Andorra review is on: it waits, without using the model, until new review comments arrive (and returns them), Andorra review posts its next round (and returns it) or ends, Codex signs off on the head commit (its thumbs-up on the pull request, which is its approval), the PR is merged or closed, the user messages you, or timeoutMinutes pass. Use it to own the review loop: fix a round, push, resolve the threads you fixed, then call await_review again, until the PR is merged or closed. Never wait for a review with sleep, a shell loop or set_timer. Where Codex reviews the repository but shows no sign of having picked up the head commit after 30 seconds (no eyes reaction, no review, no comment), the wait posts "@codex review" on the PR once for that commit, as the gh account that reads the PR; do not post that comment yourself. reply answers a review thread (threadId, body), resolve resolves one (resolved false reopens it), and comment posts on the PR's conversation (body); they act only on the tracked PR. Where the Andorra Code GitHub App covers the PR they post as its bot, otherwise as the gh account that reads the PR; the result says who posted and why. dismiss stops tracking an open PR, and only when the user asks you to: never dismiss as cleanup after a merge, because a merged or closed PR stays on the task as its record and dismiss refuses one. Only change a setting the user asked you to change.`, {
787
- action: { type: 'string', enum: ['status', 'attach', 'update', 'await_review', 'reply', 'resolve', 'comment', 'dismiss'], description: 'status shows the tracked PR; attach starts tracking url; update changes settings; await_review waits for the next review round; reply, resolve and comment write on the tracked PR; dismiss stops tracking an open PR when the user asks (refused once it is merged or closed)' },
833
+ { ...tool('pull_request', `Show or change the pull request this session tracks in the desktop Plan card. A PR you open with \`gh pr create\` is attached automatically; use attach for one opened another way. update changes its settings when the user asks, including converting to a draft or marking it ready (draft). review switches on Andorra review: the Andorra Code bot reviews the PR up to reviewRounds times (1 to ${REVIEW_ROUNDS_MAX}, default ${REVIEW_ROUNDS_DEFAULT}) and you are woken to fix its findings between reviews; reviewInstruction tells the reviewer what to focus on, reviewModel picks its provider/model (default: this task's), and review false switches it off. It needs a paid Andorra plan and a pull request the Andorra Code GitHub App covers; the result says why when it cannot be switched on. Call await_review when the task needs you to monitor a tracked PR. It waits in the current run for new reviewer comments, additions or removals of reactions on the PR?s main post, Andorra review rounds, current-head Codex approval (its thumbs-up on the pull request, which is its approval), PR closure or merge, user input, or timeoutMinutes. Jev can classify new comments when enabled. Check the linked GitHub activity before you act on an advisory label. If review follow-up is part of the task, fix findings you agree with, push, reply and resolve the threads you fixed, and wait again when another review is needed. Stop when the requested review is complete; merge only when authorized. Never wait for a review with sleep, a shell loop or set_timer. Where Codex reviews the repository but shows no sign of having picked up the head commit after 30 seconds (no eyes reaction, no review, no comment), the wait posts "@codex review" on the PR once for that commit, as the gh account that reads the PR; do not post that comment yourself. reply answers a review thread (threadId, body), resolve resolves one (resolved false reopens it), and comment posts on the PR's conversation (body); they act only on the tracked PR. Where the Andorra Code GitHub App covers the PR they post as its bot, otherwise as the gh account that reads the PR; the result says who posted and why. dismiss stops tracking an open PR, and only when the user asks you to: never dismiss as cleanup after a merge, because a merged or closed PR stays on the task as its record and dismiss refuses one. Only change a setting the user asked you to change.`, {
834
+ action: { type: 'string', enum: ['status', 'attach', 'update', 'await_review', 'reply', 'resolve', 'comment', 'dismiss'], description: 'status shows the tracked PR; attach starts tracking url; update changes settings; await_review waits for review activity on the tracked PR; reply, resolve and comment write on the tracked PR; dismiss stops tracking an open PR when the user asks (refused once it is merged or closed)' },
788
835
  threadId: property('The review thread\'s id, PRRT_…, from gh\'s reviewThreads query (reply and resolve only)'),
789
836
  body: property('The text to post (reply and comment only)'),
790
837
  resolved: { type: 'boolean', description: 'resolve only: false reopens a resolved thread (default true)' },
791
838
  url: property('The GitHub pull request URL (attach only)'),
792
- autoFix: { type: 'boolean', description: 'Wake this session when a code-review bot (Codex, CodeRabbit, Greptile, Copilot) comments, until the PR is merged or closed' },
793
- mergeWhenReady: { type: 'boolean', description: 'GitHub auto-merge once checks and reviews pass' },
794
839
  draft: { type: 'boolean', description: 'true converts to a draft, false marks it ready for review' },
795
840
  review: { type: 'boolean', description: 'Andorra review: true has the Andorra Code bot review the PR in rounds and wakes you to fix its findings between them; false stops it' },
796
841
  reviewRounds: { type: 'integer', minimum: 1, maximum: REVIEW_ROUNDS_MAX, description: `How many reviews Andorra review posts at most (1 to ${REVIEW_ROUNDS_MAX}, default ${REVIEW_ROUNDS_DEFAULT})` },
797
842
  reviewInstruction: property(`What Andorra review's reviewer should focus on, for example "focus on security" (at most ${REVIEW_INSTRUCTION_BYTES} bytes; empty clears it)`),
798
843
  reviewModel: property('The reviewer\'s provider/model, for example anthropic/claude-sonnet-4-5 (empty: this task\'s model)'),
799
- timeoutMinutes: { type: 'integer', minimum: 1, maximum: 1440, description: `How long await_review waits for a review before returning (1 to 1440, default ${AWAIT_REVIEW_DEFAULT_MINUTES})` },
844
+ timeoutMinutes: { type: 'integer', minimum: 1, maximum: 1440, description: `How long await_review waits for PR activity before returning (1 to 1440, default ${AWAIT_REVIEW_DEFAULT_MINUTES})` },
800
845
  }, ['action'], async (args, context) => {
801
846
  const control = context.pullRequests;
802
847
  if (!control)
803
848
  throw new Error('pull_request is unavailable here; no session tracks a pull request for this run.');
804
849
  const settings = { ...pullRequestSettings(args), ...reviewLoopSettings(args) };
805
850
  const approve = () => approveOperation(context, 'pull_request', { ...args, warning: 'Changes the pull request on GitHub, or what Andorra does on its own when the PR changes.' });
806
- const describe = (pr) => `${pr.url} (${pr.state})${pr.title ? ` "${pr.title}"` : ''}: autoFix ${pr.autoFix ? 'on' : 'off'}, mergeWhenReady ${pr.mergeWhenReady ? 'on' : 'off'}, ${describeReview(pr)}`;
851
+ const describe = (pr) => `${pr.url} (${pr.state})${pr.title ? ` "${pr.title}"` : ''}: ${describeReview(pr)}`;
807
852
  switch (args.action) {
808
853
  case 'status': {
809
854
  const pr = await control.status();
@@ -817,19 +862,19 @@ export function createTools() {
817
862
  }
818
863
  case 'update': {
819
864
  if (!Object.keys(settings).length)
820
- throw new Error('update needs at least one of autoFix, mergeWhenReady, draft, review, reviewRounds, reviewInstruction, reviewModel');
865
+ throw new Error('update needs at least one of draft, review, reviewRounds, reviewInstruction, reviewModel');
821
866
  await approve();
822
867
  return `Updated ${describe(await control.update(settings, context.wakeOrigin))}`;
823
868
  }
824
869
  case 'await_review': {
825
870
  if (!control.awaitReview)
826
- throw new Error('await_review is unavailable here; this surface cannot hold a run open for a review. End your turn: Auto-fix wakes you when comments arrive.');
871
+ throw new Error('await_review is unavailable here because this surface cannot hold a run open for a review.');
827
872
  const minutes = args.timeoutMinutes === undefined ? AWAIT_REVIEW_DEFAULT_MINUTES : args.timeoutMinutes;
828
873
  if (typeof minutes !== 'number' || !Number.isSafeInteger(minutes) || minutes < 1 || minutes > 1_440)
829
874
  throw new Error('timeoutMinutes must be an integer from 1 to 1440');
830
875
  const awaitReview = control.awaitReview.bind(control);
831
876
  const approveBump = (detail) => approveOperation(context, 'pull_request', { ...args, body: REVIEW_BUMP_COMMENT, warning: `Changes the pull request on GitHub. ${detail}` });
832
- const wait = () => awaitReview(context.signal, minutes * 60_000, context.wakeOrigin, { approveBump });
877
+ const wait = () => awaitReview(context.signal, minutes * 60_000, context.wakeOrigin, { approveBump, invocationId: context.toolInvocationId });
833
878
  const ended = await (context.waitOutside ? context.waitOutside(wait) : wait());
834
879
  return reviewWaitAnswer(ended, minutes, context.signal);
835
880
  }
@@ -48,6 +48,7 @@ export function describeTool(name, value) {
48
48
  case 'wait_subagent': return 'Wait for a subagent';
49
49
  case 'message_subagent': return `Message a subagent: ${line(args.message)}`;
50
50
  case 'cancel_subagent': return 'Stop a subagent';
51
+ case 'currentAndorraStreams': return 'Check free Andorra streams';
51
52
  case 'ask_user': return 'Ask a question';
52
53
  case 'submit_bug_report': return `Send a bug report: ${line(args.title)}`;
53
54
  case 'git_read':
@@ -136,7 +137,7 @@ export function formatEvent(event) {
136
137
  return { text: `${line(data.nodeName ?? data.nodeId)} - copy ${line(data.copy)}/${line(data.copies)} started` };
137
138
  if (event.type === 'graph.todos.updated') {
138
139
  const todos = data.todos;
139
- return { text: todos.length ? `Todo\n${todos.map(todo => ` ${todo.status === 'completed' ? '✓' : todo.status === 'in_progress' ? '●' : '○'} ${line(todo.text)}`).join('\n')}` : 'Todo: cleared' };
140
+ return { text: todos.length ? `Todo\n${todos.map(todo => ` ${todo.parentId === undefined ? '' : ' '}${todo.status === 'completed' ? '✓' : todo.status === 'in_progress' ? '●' : '○'} ${line(todo.text)}`).join('\n')}` : 'Todo: cleared' };
140
141
  }
141
142
  if (event.type === 'agent.message') {
142
143
  const body = clean(data.text).replace(/^(?:[ \t]*\n)+/, '').replace(/\s+$/, '');
@@ -1,3 +1,4 @@
1
+ import type { TelemetryAuthMode } from './telemetry/schema.js';
1
2
  export interface ToolCall {
2
3
  id: string;
3
4
  name: string;
@@ -35,6 +36,8 @@ export interface ToolImage {
35
36
  export interface Message {
36
37
  role: 'system' | 'user' | 'assistant' | 'tool';
37
38
  contextSummary?: true;
39
+ /** Host-added retrieval, not user instructions. May be retired under request pressure, including after Resume. */
40
+ optionalContext?: 'memory' | 'repository';
38
41
  content: string;
39
42
  reasoningContent?: string;
40
43
  providerContinuation?: ProviderContinuation;
@@ -64,6 +67,11 @@ export interface ModelResponse {
64
67
  stopReason?: string;
65
68
  reasoningContent?: string;
66
69
  providerContinuation?: ProviderContinuation;
70
+ /** Privacy-bounded facts observed at the adapter, for aggregate usage reporting. */
71
+ servedModel?: string;
72
+ authMode?: TelemetryAuthMode;
73
+ /** Token fields the provider actually reported, when runtime usage also has synthetic defaults. */
74
+ reportedUsage?: Partial<Usage>;
67
75
  /**
68
76
  * Messages an adapter added at the end of the request this answer replies to, which the run keeps in its history right
69
77
  * before the answer: Claude's thinking comes back from Andorra's router only while its earlier conversation is unchanged.
@@ -154,7 +162,12 @@ export interface ToolContext {
154
162
  qaHostApproved?: boolean;
155
163
  approvalMode?: 'interactive' | 'headless';
156
164
  approve: (name: string, args: Record<string, unknown>, signal: AbortSignal) => Promise<boolean | 'policy-changed'>;
157
- askUser?: (question: string, signal: AbortSignal, choices?: readonly string[]) => Promise<string | undefined>;
165
+ chatHandoffs?: boolean;
166
+ askUser?: (question: string, signal: AbortSignal, choices?: readonly string[], handoff?: {
167
+ prompt: string;
168
+ model: string;
169
+ effort?: string;
170
+ }) => Promise<string | undefined>;
158
171
  approvePlan?: () => Promise<import('./permissions.js').PermissionMode>;
159
172
  waitOutside?: <T>(work: () => Promise<T>) => Promise<T>;
160
173
  onApprovalEvent?: (type: string, data: Record<string, unknown>) => void | Promise<void>;
@@ -8,6 +8,7 @@ import semver from 'semver';
8
8
  import { configDirectory } from './config.js';
9
9
  const executeFile = promisify(execFile);
10
10
  import { PACKAGE_NAME } from './package-name.js';
11
+ import { isTelemetryTest } from './telemetry/uploader.js';
11
12
  export { PACKAGE_NAME };
12
13
  const RELEASE_TAG = 'latest';
13
14
  const INSTALL_ATTEMPTS = 3;
@@ -485,6 +486,9 @@ export async function updateInstallation(options = {}) {
485
486
  if (installed !== latest) {
486
487
  throw new Error(`npm reported success, but ${entry} now holds ${installed ? `version ${installed}` : 'no readable release'} instead of ${latest}. Check it with andorra --version, then run andorra update again.`);
487
488
  }
489
+ if (!isTelemetryTest(process.env)) {
490
+ await executeFile(process.execPath, [join(entry, 'dist', 'src', 'telemetry', 'record-installation.js'), latest, current], { cwd, windowsHide: true, timeout: 4_000 }).catch(() => { });
491
+ }
488
492
  return withSweep(`Updated Andorra from ${current} to ${latest}.\nInstalled ${PACKAGE_NAME}@${latest} from npm into ${entry}.`);
489
493
  }
490
494
  finally {
@@ -6,6 +6,9 @@ export interface UsageModelRow {
6
6
  outputTokens: number;
7
7
  cacheRead: number;
8
8
  savedInputEstimate: number;
9
+ /** The part of savedInputEstimate that would have been read from the provider's cache. */
10
+ savedCacheReadEstimate: number;
11
+ savedDownstreamInputEstimate: number;
9
12
  savedOutputEstimate: number;
10
13
  bypassedTurns: number;
11
14
  }
@@ -15,6 +18,8 @@ export interface UsageDayRow {
15
18
  outputTokens: number;
16
19
  cacheRead: number;
17
20
  savedInputEstimate: number;
21
+ savedCacheReadEstimate: number;
22
+ savedDownstreamInputEstimate: number;
18
23
  savedOutputEstimate: number;
19
24
  bypassedTurns: number;
20
25
  models: UsageModelRow[];
@@ -27,6 +32,8 @@ export interface UsageAnalytics {
27
32
  outputTokens: number;
28
33
  cacheRead: number;
29
34
  savedInputEstimate: number;
35
+ savedCacheReadEstimate: number;
36
+ savedDownstreamInputEstimate: number;
30
37
  savedOutputEstimate: number;
31
38
  bypassedTurns: number;
32
39
  jevCalls: number;
@@ -3,6 +3,9 @@ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/p
3
3
  import { join } from 'node:path';
4
4
  import { loadConfig } from './config.js';
5
5
  import { providerLabel } from './providers.js';
6
+ // Saved input is split by the share of input the agent's nearest measured request read from cache: a prompt that was
7
+ // never sent would have been cached, or not, about as much as the ones sent around it.
8
+ const cachedPart = (tokens, measured) => measured && measured.inputTokens > 0 ? Math.round(tokens * Math.min(1, measured.cacheRead / measured.inputTokens)) : 0;
6
9
  const nonnegative = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
7
10
  const finiteNonnegative = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
8
11
  const asObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
@@ -13,8 +16,8 @@ const dateOf = (time, width = 10) => {
13
16
  return Number.isFinite(instant.getTime()) ? instant.toISOString().slice(0, width) : undefined;
14
17
  };
15
18
  const keyOf = (providerId, model) => JSON.stringify([providerId, model]);
16
- const emptyModel = (providerId, provider, model) => ({ providerId, provider, model, inputTokens: 0, outputTokens: 0, cacheRead: 0, savedInputEstimate: 0, savedOutputEstimate: 0, bypassedTurns: 0 });
17
- const emptyDay = (date) => ({ date, inputTokens: 0, outputTokens: 0, cacheRead: 0, savedInputEstimate: 0, savedOutputEstimate: 0, bypassedTurns: 0, models: [] });
19
+ const emptyModel = (providerId, provider, model) => ({ providerId, provider, model, inputTokens: 0, outputTokens: 0, cacheRead: 0, savedInputEstimate: 0, savedCacheReadEstimate: 0, savedDownstreamInputEstimate: 0, savedOutputEstimate: 0, bypassedTurns: 0 });
20
+ const emptyDay = (date) => ({ date, inputTokens: 0, outputTokens: 0, cacheRead: 0, savedInputEstimate: 0, savedCacheReadEstimate: 0, savedDownstreamInputEstimate: 0, savedOutputEstimate: 0, bypassedTurns: 0, models: [] });
18
21
  export function createUsageCollector(windowDays, now = new Date(), resolveProvider = provider => provider) {
19
22
  if (![1, 7, 30, 365].includes(windowDays))
20
23
  throw new Error('windowDays must be 1, 7, 30, or 365');
@@ -35,6 +38,11 @@ export function createUsageCollector(windowDays, now = new Date(), resolveProvid
35
38
  const outputs = new Map();
36
39
  const nodeTokens = new Map();
37
40
  const jevNodes = new Set();
41
+ // Output a skipped call never wrote, per run, node and invocation. Had the model made the call, its answer would have
42
+ // been sent back as input on every later request of that invocation, until a compaction dropped it.
43
+ const carried = new Map();
44
+ const invocationOf = (runId, nodeId, invocationId) => typeof runId === 'string' && typeof nodeId === 'string'
45
+ ? JSON.stringify([runId, nodeId, typeof invocationId === 'string' ? invocationId.slice(0, 8) : '']) : undefined;
38
46
  let unestimatedTurns = 0;
39
47
  let contextEstimatedTurns = 0;
40
48
  let jevCalls = 0;
@@ -73,7 +81,7 @@ export function createUsageCollector(windowDays, now = new Date(), resolveProvid
73
81
  const cache = Math.min(input, nonnegative(usage?.cacheRead) ?? 0);
74
82
  const identity = JSON.stringify([item.runId, item.nodeId]);
75
83
  if (typeof item.runId === 'string' && typeof item.nodeId === 'string') {
76
- baselines.set(identity, { providerId, model, inputTokens: input });
84
+ baselines.set(identity, { providerId, model, inputTokens: input, cacheRead: cache });
77
85
  const history = outputs.get(identity) ?? { tokens: 0, calls: 0 };
78
86
  history.tokens += output;
79
87
  history.calls++;
@@ -93,11 +101,29 @@ export function createUsageCollector(windowDays, now = new Date(), resolveProvid
93
101
  node.outputTokens += output;
94
102
  nodeTokens.set(identity, node);
95
103
  }
104
+ const invocation = invocationOf(item.runId, item.nodeId, item.invocationId);
105
+ const carry = input > 0 && invocation !== undefined ? carried.get(invocation) ?? 0 : 0;
106
+ if (carry > 0)
107
+ for (const target of [day.row, modelFor(day.models, providerId, model), modelFor(models, providerId, model)]) {
108
+ target.savedInputEstimate += carry;
109
+ target.savedCacheReadEstimate += cachedPart(carry, { inputTokens: input, cacheRead: cache });
110
+ target.savedDownstreamInputEstimate += carry;
111
+ }
96
112
  return;
97
113
  }
98
114
  if (item.type !== 'runtime.event')
99
115
  return;
100
116
  const event = asObject(item.event);
117
+ // The carry ends where a compaction starts: its summary requests share the invocation and send one batch of the
118
+ // retired history each, not the conversation the skipped answers would have been part of.
119
+ if (event?.type === 'agent.context.compacted' || event?.type === 'agent.context.compaction.started') {
120
+ const compacted = asObject(event.data);
121
+ const invocation = invocationOf(compacted?.runId, compacted?.nodeId, compacted?.invocationId);
122
+ // A requested compaction with nothing to summarize is journaled with removedExchanges 0 and leaves the conversation as it was.
123
+ if (invocation !== undefined && compacted?.removedExchanges !== 0)
124
+ carried.delete(invocation);
125
+ return;
126
+ }
101
127
  if (typeof event?.type !== 'string' || !event.type.startsWith('decision.'))
102
128
  return;
103
129
  const data = asObject(event.data);
@@ -108,11 +134,31 @@ export function createUsageCollector(windowDays, now = new Date(), resolveProvid
108
134
  jevCalls++;
109
135
  return;
110
136
  }
137
+ if (event.type === 'decision.prompt_reduced') {
138
+ const input = nonnegative(data?.estimatedInputTokens);
139
+ const providerId = data?.providerId;
140
+ const model = data?.model;
141
+ if (!input || typeof providerId !== 'string' || !providerId || typeof model !== 'string' || !model || date < cutoff)
142
+ return;
143
+ const day = dayFor(date);
144
+ const cached = cachedPart(input, typeof data?.runId === 'string' && typeof data.nodeId === 'string' ? baselines.get(JSON.stringify([data.runId, data.nodeId])) : undefined);
145
+ for (const target of [day.row, modelFor(day.models, providerId, model), modelFor(models, providerId, model)]) {
146
+ target.savedInputEstimate += input;
147
+ target.savedCacheReadEstimate += cached;
148
+ target.savedDownstreamInputEstimate += input;
149
+ }
150
+ return;
151
+ }
111
152
  if (event.type !== 'decision.turn_bypassed')
112
153
  return;
113
154
  const identity = typeof data?.runId === 'string' && typeof data.nodeId === 'string' ? JSON.stringify([data.runId, data.nodeId]) : undefined;
114
155
  const baseline = identity === undefined ? undefined : baselines.get(identity);
115
156
  const history = identity === undefined ? undefined : outputs.get(identity);
157
+ const output = nonnegative(data?.estimatedOutputTokens) ?? (history?.calls ? Math.round(history.tokens / history.calls) : 0);
158
+ // A skipped completion ends the invocation, so nothing follows it. A bypass before the range still carries into it.
159
+ const invocation = data?.kind === 'complete' ? undefined : invocationOf(data?.runId, data?.nodeId, data?.invocationId);
160
+ if (invocation !== undefined && output > 0)
161
+ carried.set(invocation, (carried.get(invocation) ?? 0) + output);
116
162
  if (date < cutoff)
117
163
  return;
118
164
  const day = dayFor(date);
@@ -125,13 +171,15 @@ export function createUsageCollector(windowDays, now = new Date(), resolveProvid
125
171
  }
126
172
  if (journaled !== undefined)
127
173
  contextEstimatedTurns++;
128
- const output = history?.calls ? Math.round(history.tokens / history.calls) : 0;
129
174
  const providerId = typeof data?.providerId === 'string' && data.providerId ? data.providerId : baseline?.providerId ?? 'unknown';
130
175
  const model = typeof data?.model === 'string' && data.model ? data.model : baseline?.model ?? 'unknown';
176
+ const cached = cachedPart(input, baseline);
131
177
  day.row.savedInputEstimate += input;
178
+ day.row.savedCacheReadEstimate += cached;
132
179
  day.row.savedOutputEstimate += output;
133
180
  for (const target of [modelFor(day.models, providerId, model), modelFor(models, providerId, model)]) {
134
181
  target.savedInputEstimate += input;
182
+ target.savedCacheReadEstimate += cached;
135
183
  target.savedOutputEstimate += output;
136
184
  target.bypassedTurns++;
137
185
  }
@@ -149,6 +197,8 @@ export function createUsageCollector(windowDays, now = new Date(), resolveProvid
149
197
  outputTokens: orderedModels.reduce((sum, row) => sum + row.outputTokens, 0),
150
198
  cacheRead: orderedModels.reduce((sum, row) => sum + row.cacheRead, 0),
151
199
  savedInputEstimate: orderedModels.reduce((sum, row) => sum + row.savedInputEstimate, 0),
200
+ savedCacheReadEstimate: orderedModels.reduce((sum, row) => sum + row.savedCacheReadEstimate, 0),
201
+ savedDownstreamInputEstimate: orderedModels.reduce((sum, row) => sum + row.savedDownstreamInputEstimate, 0),
152
202
  savedOutputEstimate: orderedModels.reduce((sum, row) => sum + row.savedOutputEstimate, 0),
153
203
  bypassedTurns: orderedDays.reduce((sum, day) => sum + day.bypassedTurns, 0),
154
204
  jevCalls,
@@ -177,7 +227,7 @@ const MAX_CACHE_RECORDS_TOTAL = 250_000;
177
227
  // Run journals keep only answered Jev calls, most of which a trajectory already holds, so they get a smaller budget of
178
228
  // their own and can never crowd out the trajectories that carry measured tokens.
179
229
  const MAX_RUN_JOURNAL_RECORDS_TOTAL = 50_000;
180
- const CACHE_VERSION = 5;
230
+ const CACHE_VERSION = 7;
181
231
  const NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}\.jsonl$/;
182
232
  const CACHE_KEY_PATTERN = /^(?:runs\/)?[a-zA-Z0-9_-]{1,64}\.jsonl$/;
183
233
  const MAX_WINDOW_DAYS = 365;
@@ -188,6 +238,8 @@ const LEGACY_CACHE_FILE = 'usage-cache.json';
188
238
  const OTHER_CACHE_FILE_PATTERN = /^usage-cache(?:\.v\d{1,6})?\.json$/;
189
239
  const UNUSED_CACHE_MS = 30 * 86400000;
190
240
  export const usageCacheTiming = { checkpointMs: 5000 };
241
+ // Eight characters tell one invocation of a run and node from the next, at a fifth of the cache space.
242
+ const invocationTag = (value) => typeof value === 'string' && value ? { v: value.slice(0, 8) } : {};
191
243
  const slimOf = (record) => {
192
244
  const item = asObject(record);
193
245
  if (!item)
@@ -207,6 +259,7 @@ const slimOf = (record) => {
207
259
  m: typeof item.model === 'string' && item.model ? item.model : 'unknown',
208
260
  ...(typeof item.runId === 'string' ? { r: item.runId } : {}),
209
261
  ...(typeof item.nodeId === 'string' ? { n: item.nodeId } : {}),
262
+ ...invocationTag(item.invocationId),
210
263
  i: input, o: output,
211
264
  ...(cacheRead === undefined ? {} : { c: cacheRead }),
212
265
  };
@@ -214,20 +267,28 @@ const slimOf = (record) => {
214
267
  if (item.type !== 'runtime.event')
215
268
  return undefined;
216
269
  const event = asObject(item.event);
270
+ const data = asObject(event?.data);
271
+ if (event?.type === 'agent.context.compacted' || event?.type === 'agent.context.compaction.started')
272
+ return typeof data?.runId === 'string' && typeof data.nodeId === 'string' && data.removedExchanges !== 0
273
+ ? { k: 'x', t: item.time, r: data.runId, n: data.nodeId, ...invocationTag(data.invocationId) } : undefined;
217
274
  if (typeof event?.type !== 'string' || !event.type.startsWith('decision.'))
218
275
  return undefined;
219
- const data = asObject(event.data);
220
276
  if (event.type === 'decision.completed')
221
277
  return { k: 'd', t: item.time, ...(typeof data?.requestId === 'string' && data.requestId ? { q: data.requestId } : {}), ...(typeof data?.runId === 'string' ? { r: data.runId } : {}), ...(typeof data?.nodeId === 'string' ? { n: data.nodeId } : {}) };
222
- if (event.type !== 'decision.turn_bypassed')
278
+ if (event.type !== 'decision.turn_bypassed' && event.type !== 'decision.prompt_reduced')
223
279
  return typeof data?.runId === 'string' && typeof data.nodeId === 'string'
224
280
  ? { k: 'j', t: item.time, r: data.runId, n: data.nodeId } : undefined;
225
281
  const wouldSend = nonnegative(data?.estimatedInputTokens);
282
+ const kind = event.type === 'decision.prompt_reduced' ? 's' : 'b';
283
+ const output = nonnegative(data?.estimatedOutputTokens);
226
284
  return {
227
- k: 'b', t: item.time,
285
+ k: kind, t: item.time,
228
286
  ...(typeof data?.runId === 'string' ? { r: data.runId } : {}),
229
287
  ...(typeof data?.nodeId === 'string' ? { n: data.nodeId } : {}),
288
+ ...(kind === 'b' ? invocationTag(data?.invocationId) : {}),
289
+ ...(kind === 'b' && data?.kind === 'complete' ? { f: 1 } : {}),
230
290
  ...(wouldSend ? { i: wouldSend } : {}),
291
+ ...(kind === 'b' && output !== undefined ? { o: output } : {}),
231
292
  ...(typeof data?.providerId === 'string' && data.providerId ? { p: data.providerId } : {}),
232
293
  ...(typeof data?.model === 'string' && data.model ? { m: data.model } : {}),
233
294
  };
@@ -236,15 +297,19 @@ const replayOf = (slim) => slim.k === 'r'
236
297
  ? {
237
298
  type: 'model.response', time: slim.t, providerId: slim.p, model: slim.m,
238
299
  ...(slim.r === undefined ? {} : { runId: slim.r }), ...(slim.n === undefined ? {} : { nodeId: slim.n }),
300
+ ...(slim.v === undefined ? {} : { invocationId: slim.v }),
239
301
  usage: { inputTokens: slim.i, outputTokens: slim.o, ...(slim.c === undefined ? {} : { cacheRead: slim.c }) },
240
302
  }
241
303
  : {
242
304
  type: 'runtime.event', time: slim.t,
243
- event: { type: slim.k === 'b' ? 'decision.turn_bypassed' : slim.k === 'd' ? 'decision.completed' : 'decision.ready', data: {
305
+ event: { type: slim.k === 'b' ? 'decision.turn_bypassed' : slim.k === 'd' ? 'decision.completed' : slim.k === 's' ? 'decision.prompt_reduced' : slim.k === 'x' ? 'agent.context.compacted' : 'decision.ready', data: {
244
306
  ...(slim.r === undefined ? {} : { runId: slim.r }), ...(slim.n === undefined ? {} : { nodeId: slim.n }),
245
- ...(slim.k === 'b' && slim.i !== undefined ? { estimatedInputTokens: slim.i } : {}),
246
- ...(slim.k === 'b' && slim.p !== undefined ? { providerId: slim.p } : {}),
247
- ...(slim.k === 'b' && slim.m !== undefined ? { model: slim.m } : {}),
307
+ ...((slim.k === 'b' || slim.k === 'x') && slim.v !== undefined ? { invocationId: slim.v } : {}),
308
+ ...(slim.k === 'b' && slim.f ? { kind: 'complete' } : {}),
309
+ ...((slim.k === 'b' || slim.k === 's') && slim.i !== undefined ? { estimatedInputTokens: slim.i } : {}),
310
+ ...(slim.k === 'b' && slim.o !== undefined ? { estimatedOutputTokens: slim.o } : {}),
311
+ ...((slim.k === 'b' || slim.k === 's') && slim.p !== undefined ? { providerId: slim.p } : {}),
312
+ ...((slim.k === 'b' || slim.k === 's') && slim.m !== undefined ? { model: slim.m } : {}),
248
313
  } },
249
314
  };
250
315
  const validSlim = (value) => {
@@ -255,8 +320,15 @@ const validSlim = (value) => {
255
320
  return false;
256
321
  if (item.n !== undefined && typeof item.n !== 'string')
257
322
  return false;
258
- if (item.k === 'b')
323
+ if (item.v !== undefined && (typeof item.v !== 'string' || !['r', 'b', 'x'].includes(item.k)))
324
+ return false;
325
+ if (item.f !== undefined && (item.f !== 1 || item.k !== 'b'))
326
+ return false;
327
+ if (item.k === 'x')
328
+ return typeof item.r === 'string' && typeof item.n === 'string';
329
+ if (item.k === 'b' || item.k === 's')
259
330
  return (item.i === undefined || nonnegative(item.i) !== undefined)
331
+ && (item.o === undefined || (item.k === 'b' && nonnegative(item.o) !== undefined))
260
332
  && (item.p === undefined || typeof item.p === 'string') && (item.m === undefined || typeof item.m === 'string');
261
333
  if (item.k === 'j')
262
334
  return typeof item.r === 'string' && typeof item.n === 'string';
@@ -0,0 +1 @@
1
+ config.analytics.consent:1