@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
@@ -1,4 +1,5 @@
1
1
  import { execFile } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
2
3
  import { mkdir, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
3
4
  import { homedir, hostname } from 'node:os';
4
5
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
@@ -6,8 +7,11 @@ const GIT_TIMEOUT_MS = 15_000;
6
7
  const FETCH_TIMEOUT_MS = 15_000;
7
8
  const MAX_BRANCHES = 1_000;
8
9
  const MAX_SLUG = 40;
9
- const MAX_SUFFIX = 99;
10
+ const MAX_NAME_TRIES = 99;
10
11
  const KEY = /^[A-Za-z0-9_-]{8,64}$/;
12
+ /** The branch a start creates itself, before the model names the task: `task/` plus a random 8-character id. */
13
+ const AUTO_TASK_BRANCH = /^task\/[0-9a-z]{8}$/;
14
+ const MAX_BRANCH_SUFFIXES = 9;
11
15
  /** Git asks no one for credentials or host keys: a start never waits on a prompt nobody can see. */
12
16
  const QUIET_GIT = { GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', GCM_INTERACTIVE: 'never', GIT_OPTIONAL_LOCKS: '0' };
13
17
  export class TaskCheckoutError extends Error {
@@ -132,18 +136,27 @@ export async function taskStartPoints(root) {
132
136
  ...(others.length > MAX_BRANCHES ? { truncated: true } : {}),
133
137
  };
134
138
  }
135
- /** A task branch's name from the prompt: lower case, hyphens, at most 40 characters. */
139
+ /** The name a caller picked for a task branch, made a safe slug: lower case, hyphens, at most 40 characters. */
136
140
  export function taskSlug(text) {
137
141
  const slug = text.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
138
142
  .replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, MAX_SLUG).replace(/-+$/, '');
139
143
  // A Windows device name cannot be a folder there.
140
144
  return !slug ? 'task' : /^(con|prn|aux|nul|com\d|lpt\d)$/.test(slug) ? `${slug}-task` : slug;
141
145
  }
146
+ const NAME_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';
147
+ /** A random 8-character task name (`a92x9dwe`): what a worktree, its `task/<name>` branch and a session start under. */
148
+ export function randomTaskName() {
149
+ const bytes = randomBytes(8);
150
+ let name = '';
151
+ for (const byte of bytes)
152
+ name += NAME_CHARS.charAt(byte % NAME_CHARS.length);
153
+ return name;
154
+ }
142
155
  function folderName(root) {
143
156
  return basename(root).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[.-]+/, '').slice(0, 64) || 'project';
144
157
  }
145
158
  /**
146
- * Where task worktrees go: `~/worktrees/<project>/<slug>`, outside Andorra's home, whose files the permission rules
159
+ * Where task worktrees go: `~/worktrees/<project>/<name>`, outside Andorra's home, whose files the permission rules
147
160
  * protect from the agent.
148
161
  */
149
162
  export function worktreesRoot() {
@@ -206,8 +219,10 @@ export async function takePrepared(home, root, key) {
206
219
  }
207
220
  /**
208
221
  * Makes a writing task's worktree: resolves `base` to a commit (refreshing the default branch from its remote first),
209
- * then adds a worktree on a new `task/<slug>` branch in `~/worktrees/<project>`. Names stay distinct across simultaneous
210
- * starts. The same `key` returns the same worktree while it still stands, so a retried start reuses its preparation.
222
+ * then adds a worktree on a new `task/<name>` branch in `~/worktrees/<project>`, where `name` is the random id the
223
+ * caller picked. A collision with an existing branch or folder is rare; a start that hits one draws a fresh random
224
+ * name instead of growing a suffix. The same `key` returns the same worktree while it still stands, so a retried
225
+ * start reuses its preparation.
211
226
  */
212
227
  export async function prepareTaskWorktree(options) {
213
228
  const { home, root, key } = options;
@@ -271,8 +286,9 @@ export async function prepareTaskWorktree(options) {
271
286
  throw new TaskCheckoutError(`The worktree could not be created: ${folder} ${code === 'EEXIST' || code === 'ENOTDIR' ? 'is a file, not a folder' : code === 'EACCES' || code === 'EPERM' ? 'cannot be written' : `could not be made (${code ?? 'unknown error'})`}.`);
272
287
  }
273
288
  const slug = taskSlug(options.slug);
274
- for (let suffix = 1; suffix <= MAX_SUFFIX; suffix++) {
275
- const name = suffix === 1 ? slug : `${slug}-${suffix}`;
289
+ for (let attempt = 1; attempt <= MAX_NAME_TRIES; attempt++) {
290
+ // The name the caller picked first; a collision draws a fresh random name instead of a growing suffix.
291
+ const name = attempt === 1 ? slug : randomTaskName();
276
292
  const branch = `task/${name}`;
277
293
  const worktree = join(folder, name);
278
294
  if (await refExists(root, `refs/heads/${branch}`))
@@ -303,7 +319,61 @@ export async function prepareTaskWorktree(options) {
303
319
  await writePrepared(home, { key, root: resolve(root), prepared });
304
320
  return prepared;
305
321
  }
306
- throw new TaskCheckoutError(`Every task branch name for ${slug} is taken. Rename the task and start again.`);
322
+ throw new TaskCheckoutError('Every worktree name came up taken. Try starting the task again.');
323
+ }
324
+ /** Whether a task branch still carries the automatic name its start gave it (`task/<random id>`). */
325
+ export function isAutoTaskBranch(branch) {
326
+ return AUTO_TASK_BRANCH.test(branch ?? '');
327
+ }
328
+ /**
329
+ * Renames a task's own branch to the name the model gave the task (`task/fix-login-redirect-loop`), replacing the
330
+ * random id the start created. Only a branch that still carries the automatic name is renamed — a branch a person or
331
+ * the agent already moved is never touched, and neither is one that has a remote upstream, which means it was pushed,
332
+ * perhaps under review. A name that is taken gets a `-2`, `-3`… suffix. Returns the new branch name, or undefined
333
+ * when nothing was renamed.
334
+ */
335
+ export async function renameTaskBranch(checkout, name) {
336
+ const slug = taskSlug(name);
337
+ if (!slug || checkout.kind !== 'worktree' || checkout.removedAt !== undefined || !isAutoTaskBranch(checkout.branch))
338
+ return undefined;
339
+ const top = checkoutTop(checkout);
340
+ if (!await exists(top))
341
+ return undefined;
342
+ const here = await git(top, ['rev-parse', '--abbrev-ref', 'HEAD']);
343
+ if (here.code !== 0 || here.stdout.trim() !== checkout.branch)
344
+ return undefined;
345
+ if ((await git(top, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])).code === 0)
346
+ return undefined;
347
+ // A published branch can lack an upstream (`git push` without `--set-upstream`): any remote-tracking branch
348
+ // carrying this name means the branch was pushed, so its name must not change under an open review.
349
+ const published = await git(top, ['for-each-ref', '--format=%(refname:short)', 'refs/remotes']);
350
+ if (published.code === 0 && published.stdout.split(/\r?\n/).some(line => line.trim().endsWith(`/${checkout.branch}`)))
351
+ return undefined;
352
+ for (let suffix = 0; suffix <= MAX_BRANCH_SUFFIXES; suffix++) {
353
+ const branch = suffix === 0 ? `task/${slug}` : `task/${slug}-${suffix}`;
354
+ if (await refExists(top, `refs/heads/${branch}`))
355
+ continue;
356
+ const renamed = await git(top, ['branch', '-m', checkout.branch, branch]);
357
+ if (renamed.code === 0)
358
+ return branch;
359
+ if (!/already exists/i.test(renamed.stderr))
360
+ return undefined;
361
+ }
362
+ return undefined;
363
+ }
364
+ /** Puts a task branch back under its previous name, when a rename succeeded but could not be recorded. */
365
+ export async function revertTaskBranchRename(checkout, from, to) {
366
+ if (checkout.kind !== 'worktree' || checkout.removedAt !== undefined)
367
+ throw new TaskCheckoutError('Only a task worktree branch can be renamed back.');
368
+ const top = checkoutTop(checkout);
369
+ if (!await exists(top))
370
+ throw new TaskCheckoutError(`The worktree ${top} is gone, so ${from} cannot be renamed back to ${to}.`);
371
+ const here = await git(top, ['rev-parse', '--abbrev-ref', 'HEAD']);
372
+ if (here.code !== 0 || here.stdout.trim() !== from)
373
+ throw new TaskCheckoutError(`The worktree is no longer on ${from}, so it cannot be renamed back to ${to}.`);
374
+ const renamed = await git(top, ['branch', '-m', from, to]);
375
+ if (renamed.code !== 0)
376
+ throw new TaskCheckoutError(firstLine(renamed.stderr) || `git branch -m ${from} ${to} failed`);
307
377
  }
308
378
  /** What an in-place task records: the project folder, and the branch and commit it began on. */
309
379
  export async function inPlaceCheckout(root) {
@@ -0,0 +1,18 @@
1
+ import { sameTelemetryLease, type TelemetryAdmission, type TelemetryLease, type TelemetryPermissionInput } from './permission.js';
2
+ export interface TelemetryAccess {
3
+ lease?: TelemetryLease;
4
+ signals?: TelemetryPermissionInput['signals'];
5
+ }
6
+ /** Local-only revocation metadata; never spread into an event body. */
7
+ export interface TelemetryEpoch {
8
+ mode: 'consent';
9
+ revision: number;
10
+ activationId: string;
11
+ }
12
+ export declare function telemetryEpoch(lease: TelemetryLease): TelemetryEpoch | undefined;
13
+ export declare function epochMatches(epoch: unknown, lease: TelemetryLease): boolean;
14
+ export declare function epochLease(home: string, epoch: unknown): TelemetryLease | undefined;
15
+ export declare function telemetryDirectoryHome(directory: string): string;
16
+ export declare function spoolTelemetryDirectory(path: string): string;
17
+ export declare function admitTelemetryDirectory<T>(directory: string, run: (admission: TelemetryAdmission) => Promise<T>, access?: TelemetryAccess): Promise<T | undefined>;
18
+ export { sameTelemetryLease };
@@ -0,0 +1,43 @@
1
+ /** Shared path/epoch plumbing. Privacy admission ALWAYS precedes analytics/spool locks. */
2
+ import { basename, dirname, resolve } from 'node:path';
3
+ import { telemetryHome } from './home.js';
4
+ import { currentTelemetryAdmission, withTelemetryAdmission, sameTelemetryLease } from './permission.js';
5
+ export function telemetryEpoch(lease) {
6
+ return lease.mode === 'consent' ? { mode: 'consent', revision: lease.revision, activationId: lease.activationId } : undefined;
7
+ }
8
+ export function epochMatches(epoch, lease) {
9
+ if (epoch === undefined)
10
+ return lease.mode === 'out'; // unchanged legacy outside backlog
11
+ if (!epoch || typeof epoch !== 'object' || lease.mode !== 'consent')
12
+ return false;
13
+ const value = epoch;
14
+ return value.mode === 'consent' && value.revision === lease.revision && value.activationId === lease.activationId;
15
+ }
16
+ export function epochLease(home, epoch) {
17
+ if (!epoch || typeof epoch !== 'object')
18
+ return undefined;
19
+ const value = epoch;
20
+ return value.mode === 'consent' && Number.isSafeInteger(value.revision) && value.revision > 0 && typeof value.activationId === 'string' && /^[a-f0-9]{32}$/.test(value.activationId)
21
+ ? { home: telemetryHome(home), mode: 'consent', revision: value.revision, activationId: value.activationId } : undefined;
22
+ }
23
+ export function telemetryDirectoryHome(directory) {
24
+ const path = resolve(directory);
25
+ if (basename(path) !== 'telemetry')
26
+ throw new Error('Expected an installation telemetry directory');
27
+ return telemetryHome(dirname(path));
28
+ }
29
+ export function spoolTelemetryDirectory(path) {
30
+ const directory = dirname(resolve(path));
31
+ if (basename(directory) !== 'outbox' || !basename(path).endsWith('.jsonl'))
32
+ throw new Error('Expected a telemetry spool path');
33
+ return dirname(directory);
34
+ }
35
+ export function admitTelemetryDirectory(directory, run, access = {}) {
36
+ const parent = currentTelemetryAdmission();
37
+ return withTelemetryAdmission({ home: telemetryDirectoryHome(directory), signals: access.signals }, async (admission) => {
38
+ if (admission.lease.mode === 'consent' && !access.lease && parent !== admission)
39
+ return undefined;
40
+ return run(admission);
41
+ }, access.lease);
42
+ }
43
+ export { sameTelemetryLease };
@@ -1,6 +1,7 @@
1
1
  import type { Usage } from '../types.js';
2
2
  import { type TelemetryModelRecord, type TelemetryToolRecord } from './schema.js';
3
- export interface ModelObservation {
3
+ type ModelAttribution = Pick<TelemetryModelRecord, 'provider' | 'authMode' | 'servedModel'>;
4
+ export interface ModelObservation extends ModelAttribution {
4
5
  providerType: string;
5
6
  baseUrl: string;
6
7
  model: string;
@@ -9,7 +10,7 @@ export interface ModelObservation {
9
10
  costMicroUsd?: number;
10
11
  pricingVersion?: string;
11
12
  }
12
- export interface ModelTuple {
13
+ export interface ModelTuple extends ModelAttribution {
13
14
  providerType: string;
14
15
  endpoint: string;
15
16
  model: string;
@@ -30,6 +31,20 @@ export interface ModelTuple {
30
31
  costVersions: Set<string | undefined>;
31
32
  };
32
33
  }
34
+ export declare function modelTupleIdentity(input: ModelAttribution & {
35
+ providerType?: string;
36
+ baseUrl?: string;
37
+ model?: string;
38
+ role: string;
39
+ }): {
40
+ providerType: "other" | "openai-compatible" | "anthropic" | "codex";
41
+ endpoint: "other" | "hosted" | "local";
42
+ model: string;
43
+ role: string;
44
+ provider: "andorra" | "other" | "anthropic" | "codex" | "claude" | "google" | "grok" | "opencode" | "opencode-go" | "openai" | "deepseek" | "openrouter" | "ollama" | undefined;
45
+ authMode: "other" | "linked-account" | "api-key" | undefined;
46
+ servedModel: string | undefined;
47
+ };
33
48
  export declare function aggregateModels(observations: ModelObservation[]): TelemetryModelRecord[];
34
49
  export declare function aggregateModelTuples(input: ModelTuple[]): TelemetryModelRecord[];
35
50
  export interface ToolObservation {
@@ -41,3 +56,4 @@ export declare function countToolObservations(observations: ToolObservation[]):
41
56
  calls: number;
42
57
  failures: number;
43
58
  };
59
+ export {};
@@ -1,18 +1,26 @@
1
- import { TELEMETRY_ENDPOINTS, TELEMETRY_MODELS, TELEMETRY_PROVIDER_TYPES, TELEMETRY_ROLES, TELEMETRY_TOOL_NAMES, bucketEndpoint, bucketModel, bucketProviderType, bucketToolName, isMetadataTool, rankByTable, } from './schema.js';
1
+ import { TELEMETRY_ENDPOINTS, TELEMETRY_MODELS, TELEMETRY_PROVIDER_TYPES, TELEMETRY_ROLES, TELEMETRY_TOOL_NAMES, bucketEndpoint, bucketModel, bucketProvider, bucketProviderType, bucketToolName, isMetadataTool, modelTupleKey, rankByTable, reportedModel, } from './schema.js';
2
2
  const rankIndex = (table, value) => {
3
3
  const index = table.indexOf(value);
4
4
  return index < 0 ? table.length : index;
5
5
  };
6
+ export function modelTupleIdentity(input) {
7
+ return {
8
+ providerType: bucketProviderType(input.providerType),
9
+ endpoint: bucketEndpoint(input.baseUrl),
10
+ model: bucketModel(input.model),
11
+ role: input.role,
12
+ provider: input.provider ?? bucketProvider(input.providerType, input.baseUrl),
13
+ authMode: input.authMode,
14
+ servedModel: reportedModel(input.servedModel),
15
+ };
16
+ }
6
17
  function fold(observations) {
7
18
  const tuples = new Map();
8
19
  for (const observation of observations) {
9
- const providerType = bucketProviderType(observation.providerType);
10
- const endpoint = bucketEndpoint(observation.baseUrl);
11
- const model = bucketModel(observation.model);
12
- const role = observation.role;
13
- const key = `${providerType}\0${endpoint}\0${model}\0${role}`;
20
+ const identity = modelTupleIdentity(observation);
21
+ const key = modelTupleKey(identity);
14
22
  const tuple = tuples.get(key) ?? {
15
- providerType, endpoint, model, role, requests: 0,
23
+ ...identity, requests: 0,
16
24
  reported: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, costVersions: new Set() },
17
25
  };
18
26
  tuple.requests += 1;
@@ -50,6 +58,9 @@ function ordinary(tuple) {
50
58
  model: tuple.model,
51
59
  role: tuple.role,
52
60
  requests: tuple.requests,
61
+ ...(tuple.provider === undefined ? {} : { provider: tuple.provider }),
62
+ ...(tuple.authMode === undefined ? {} : { authMode: tuple.authMode }),
63
+ ...(tuple.servedModel === undefined ? {} : { servedModel: tuple.servedModel }),
53
64
  };
54
65
  if (complete(tuple.reported.input))
55
66
  record.inputTokens = tuple.inputTokens;
@@ -130,7 +141,8 @@ export function aggregateModelTuples(input) {
130
141
  || rankIndex(TELEMETRY_PROVIDER_TYPES, a.providerType) - rankIndex(TELEMETRY_PROVIDER_TYPES, b.providerType)
131
142
  || rankIndex(TELEMETRY_ENDPOINTS, a.endpoint) - rankIndex(TELEMETRY_ENDPOINTS, b.endpoint)
132
143
  || rankIndex(TELEMETRY_MODELS, a.model) - rankIndex(TELEMETRY_MODELS, b.model)
133
- || rankIndex(TELEMETRY_ROLES, a.role) - rankIndex(TELEMETRY_ROLES, b.role));
144
+ || rankIndex(TELEMETRY_ROLES, a.role) - rankIndex(TELEMETRY_ROLES, b.role)
145
+ || modelTupleKey(a).localeCompare(modelTupleKey(b), 'en'));
134
146
  const overflowNeeded = tuples.length > 16;
135
147
  if (!overflowNeeded)
136
148
  return tuples.map(ordinary);
@@ -144,7 +156,8 @@ export function aggregateModelTuples(input) {
144
156
  return records;
145
157
  }
146
158
  function isOverflowIdentity(tuple) {
147
- return tuple.providerType === 'other' && tuple.endpoint === 'other' && tuple.model === 'other' && tuple.role === 'other';
159
+ return tuple.providerType === 'other' && tuple.endpoint === 'other' && tuple.model === 'other' && tuple.role === 'other' &&
160
+ tuple.provider === undefined && tuple.authMode === undefined && tuple.servedModel === undefined;
148
161
  }
149
162
  export function aggregateTools(observations) {
150
163
  const counts = new Map();
@@ -1,6 +1,8 @@
1
+ import { type JevSavings } from '../jev-savings.js';
1
2
  import type { Usage } from '../types.js';
2
- import { type TelemetryErrorRecord, type TelemetrySavings } from './schema.js';
3
- import type { ModelTuple } from './aggregate.js';
3
+ import { type TelemetryLease, type TelemetryPermissionInput } from './permission.js';
4
+ import { type TelemetryAuthMode, type TelemetryErrorRecord, type TelemetrySavings } from './schema.js';
5
+ import { type ModelTuple } from './aggregate.js';
4
6
  import type { ModelPricing } from '../efficiency.js';
5
7
  export interface JevTally {
6
8
  requested: number;
@@ -88,33 +90,50 @@ export interface RunTelemetry {
88
90
  pendingDecisions?: Promise<unknown>[];
89
91
  task: TaskTally;
90
92
  efficiency?: EfficiencyTally;
93
+ jevSavings?: JevSavings;
91
94
  }
92
95
  export declare function createEfficiencyTally(): EfficiencyTally;
93
- export declare function recordEfficiencyEvent(telemetry: RunTelemetry, type: string, data: Record<string, unknown>): void;
94
- export declare function createRunTelemetry(): RunTelemetry;
96
+ export declare function recordEfficiencyEvent(telemetry: RunTelemetry | undefined, type: string, data: Record<string, unknown>): void;
97
+ export interface TelemetryCaptureInput extends TelemetryPermissionInput {
98
+ lease?: TelemetryLease;
99
+ }
100
+ /** Latch start authority once; children must not enable capture after a later Yes/Auto. */
101
+ export declare function resolveTelemetryCapture(input?: TelemetryCaptureInput | false): TelemetryCaptureInput | false;
102
+ /** A typed inert sink preserves functional callers, but cannot collect or serialize anything. */
103
+ export declare function createRunTelemetry(input?: TelemetryCaptureInput | false): RunTelemetry;
104
+ /** Fresh necessary-choice read; callbacks from another process's old epoch are permanently inert. */
105
+ export declare function captureIsActive(value: unknown): boolean;
95
106
  export declare function hasRunTelemetry(value: unknown): value is RunTelemetry;
96
- export declare function recordModelUse(telemetry: RunTelemetry, input: {
107
+ export declare function captureLease(value: RunTelemetry | undefined): TelemetryLease | undefined;
108
+ /** Result getters drop revoked captures at every finalizer/spread/serialization boundary. */
109
+ export declare function bindRunTelemetry<T extends {
110
+ telemetry?: RunTelemetry;
111
+ }>(result: T, value: RunTelemetry): T;
112
+ export declare function recordModelUse(telemetry: RunTelemetry | undefined, input: {
97
113
  providerType?: string;
98
114
  baseUrl?: string;
99
115
  model?: string;
116
+ servedModel?: string;
117
+ authMode?: TelemetryAuthMode;
100
118
  role: 'agent' | 'orchestrator' | 'subagent' | 'jev' | 'other';
101
119
  usage: Partial<Usage>;
102
120
  pricing?: ModelPricing;
103
121
  }): void;
104
- export declare function recordToolUse(telemetry: RunTelemetry, name: string, failed: boolean): void;
105
- export declare function recordRunError(telemetry: RunTelemetry, code: unknown, count?: number): void;
122
+ export declare function recordToolUse(telemetry: RunTelemetry | undefined, name: string, failed: boolean): void;
123
+ /** Records nothing without an active capture: a run whose reporting is pending, declined or revoked still fails normally. */
124
+ export declare function recordRunError(telemetry: RunTelemetry | undefined, code: unknown, count?: number): void;
106
125
  /**
107
126
  * Records a thrown error once, however many handlers see it on its way up (the request path, then a compactor, the
108
127
  * agent loop or a graph). Returns the code it was recorded under, which later handlers reuse.
109
128
  */
110
- export declare function recordErrorOnce(telemetry: RunTelemetry, error: unknown, code: string): string;
129
+ export declare function recordErrorOnce(telemetry: RunTelemetry | undefined, error: unknown, code: string): string;
111
130
  /** The code an error was already recorded under, if any handler recorded it. */
112
131
  export declare function recordedErrorCode(error: unknown): string | undefined;
113
132
  /** The measured savings a run's efficiency tally holds, as sent in run.finished; undefined when nothing was tallied. */
114
133
  export declare function savingsFrom(telemetry: RunTelemetry): TelemetrySavings | undefined;
115
- export declare function recordAttempt(telemetry: RunTelemetry, retry: boolean): void;
116
- export declare function recordEdit(telemetry: RunTelemetry, filePath: string, created: boolean): void;
117
- export declare function recordTestCommand(telemetry: RunTelemetry): void;
118
- export declare function recordDecisionEvent(telemetry: RunTelemetry, type: string, data: Record<string, unknown>): void;
119
- export declare function recordToolFailure(telemetry: RunTelemetry, name: string): void;
120
- export declare function mergeRunTelemetry(into: RunTelemetry, from: RunTelemetry): RunTelemetry;
134
+ export declare function recordAttempt(telemetry: RunTelemetry | undefined, retry: boolean): void;
135
+ export declare function recordEdit(telemetry: RunTelemetry | undefined, filePath: string, created: boolean): void;
136
+ export declare function recordTestCommand(telemetry: RunTelemetry | undefined): void;
137
+ export declare function recordDecisionEvent(telemetry: RunTelemetry | undefined, type: string, data: Record<string, unknown>): void;
138
+ export declare function recordToolFailure(telemetry: RunTelemetry | undefined, name: string): void;
139
+ export declare function mergeRunTelemetry(into: RunTelemetry | undefined, from: RunTelemetry | undefined): RunTelemetry | undefined;
@@ -1,5 +1,9 @@
1
- import { TELEMETRY_ERROR_KINDS, bucketEndpoint, bucketErrorCode, bucketModel, bucketProviderType, bucketToolName, } from './schema.js';
1
+ import { emptyJevSavings, JEV_SAVINGS_FIELDS } from '../jev-savings.js';
2
+ import { configDirectory } from '../config.js';
3
+ import { currentTelemetryAdmission, trackTelemetryRevocation, telemetryLeaseSnapshot, telemetryLeaseIsCurrent, sameTelemetryLease } from './permission.js';
4
+ import { TELEMETRY_ERROR_KINDS, bucketErrorCode, bucketToolName, modelTupleKey, } from './schema.js';
2
5
  import { isDocumentationPath, isTestPath } from './classify.js';
6
+ import { modelTupleIdentity } from './aggregate.js';
3
7
  import { usageCostMicroUsd } from '../model-tiers.js';
4
8
  export function createEfficiencyTally() {
5
9
  return {
@@ -13,6 +17,8 @@ export function createEfficiencyTally() {
13
17
  }
14
18
  const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
15
19
  export function recordEfficiencyEvent(telemetry, type, data) {
20
+ if (!hasRunTelemetry(telemetry))
21
+ return;
16
22
  if (!type.startsWith('efficiency.'))
17
23
  return;
18
24
  const tally = telemetry.efficiency ??= createEfficiencyTally();
@@ -107,7 +113,7 @@ const UNAVAILABLE_REASONS = new Set([
107
113
  'provider_unavailable', 'provider_error', 'active_unsupported', 'timeout',
108
114
  'authentication_required', 'decision_service_unavailable', 'decision_input_too_large',
109
115
  ]);
110
- export function createRunTelemetry() {
116
+ function emptyCapture() {
111
117
  return {
112
118
  attempts: 0, retries: 0, toolCalls: 0, toolFailures: 0, tools: {}, models: [],
113
119
  jev: { requested: 0, completed: 0, applied: 0, fallback: 0, unavailable: 0 },
@@ -117,18 +123,77 @@ export function createRunTelemetry() {
117
123
  task: { documentation: 0, test: 0, otherEdits: 0, created: 0, testCommand: false, activity: false },
118
124
  };
119
125
  }
126
+ /** Latch start authority once; children must not enable capture after a later Yes/Auto. */
127
+ export function resolveTelemetryCapture(input) {
128
+ if (input === false)
129
+ return false;
130
+ if (input)
131
+ return input.lease && telemetryLeaseIsCurrent(input, input.lease) ? input : { home: input.home, signals: input.signals };
132
+ const privacy = { home: configDirectory() };
133
+ const lease = telemetryLeaseSnapshot(privacy);
134
+ return lease?.mode === 'out' ? { ...privacy, lease } : false;
135
+ }
136
+ const captures = new WeakMap();
137
+ const disabled = new WeakSet();
138
+ /** A typed inert sink preserves functional callers, but cannot collect or serialize anything. */
139
+ export function createRunTelemetry(input) {
140
+ const privacy = input || { home: configDirectory() };
141
+ const current = input === false ? undefined : telemetryLeaseSnapshot(privacy);
142
+ const lease = input ? input.lease : current?.mode === 'out' ? current : undefined;
143
+ const value = emptyCapture();
144
+ Object.defineProperty(value, 'toJSON', { value: () => hasRunTelemetry(value) ? { ...value } : undefined });
145
+ if (lease && sameTelemetryLease(lease, current)) {
146
+ const state = { input: privacy, lease, revoked: false, revoke() { state.revoked = true; Object.assign(value, emptyCapture()); } };
147
+ captures.set(value, state);
148
+ trackTelemetryRevocation(lease.home, state);
149
+ }
150
+ else
151
+ disabled.add(value);
152
+ return value;
153
+ }
154
+ /** Fresh necessary-choice read; callbacks from another process's old epoch are permanently inert. */
155
+ export function captureIsActive(value) {
156
+ if (!value || typeof value !== 'object' || disabled.has(value))
157
+ return false;
158
+ const state = captures.get(value);
159
+ if (state) {
160
+ if (state.revoked)
161
+ return false;
162
+ if (telemetryLeaseIsCurrent(state.input, state.lease))
163
+ return true;
164
+ state.revoke(); // release pending promises, tuples and counters
165
+ return false;
166
+ }
167
+ // Legacy plain captures remain readable ONLY in the unchanged outside branch.
168
+ return currentTelemetryAdmission()?.lease.mode !== 'consent' && telemetryLeaseSnapshot({ home: configDirectory() })?.mode === 'out';
169
+ }
120
170
  export function hasRunTelemetry(value) {
121
- return !!value && typeof value === 'object' && Array.isArray(value.models) && !!value.task;
171
+ return captureIsActive(value) && Array.isArray(value.models) && !!value.task;
172
+ }
173
+ export function captureLease(value) {
174
+ return hasRunTelemetry(value) ? captures.get(value)?.lease : undefined;
175
+ }
176
+ /** Result getters drop revoked captures at every finalizer/spread/serialization boundary. */
177
+ export function bindRunTelemetry(result, value) {
178
+ if (!hasRunTelemetry(value)) {
179
+ delete result.telemetry;
180
+ return result;
181
+ }
182
+ let capture = value;
183
+ Object.defineProperty(result, 'telemetry', { configurable: true, enumerable: true,
184
+ get: () => hasRunTelemetry(capture) ? capture : undefined,
185
+ set: (next) => { capture = next; } });
186
+ return result;
122
187
  }
123
188
  export function recordModelUse(telemetry, input) {
124
- const providerType = bucketProviderType(input.providerType);
125
- const endpoint = bucketEndpoint(input.baseUrl);
126
- const model = bucketModel(input.model);
127
- const key = `${providerType}\0${endpoint}\0${model}\0${input.role}`;
128
- let tuple = telemetry.models.find(candidate => `${candidate.providerType}\0${candidate.endpoint}\0${candidate.model}\0${candidate.role}` === key);
189
+ if (!hasRunTelemetry(telemetry))
190
+ return;
191
+ const identity = modelTupleIdentity(input);
192
+ const key = modelTupleKey(identity);
193
+ let tuple = telemetry.models.find(candidate => modelTupleKey(candidate) === key);
129
194
  if (!tuple) {
130
195
  tuple = {
131
- providerType, endpoint, model, role: input.role, requests: 0,
196
+ ...identity, requests: 0,
132
197
  reported: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, costVersions: new Set() },
133
198
  };
134
199
  telemetry.models.push(tuple);
@@ -159,6 +224,8 @@ export function recordModelUse(telemetry, input) {
159
224
  }
160
225
  }
161
226
  export function recordToolUse(telemetry, name, failed) {
227
+ if (!hasRunTelemetry(telemetry))
228
+ return;
162
229
  const bucket = bucketToolName(name);
163
230
  if (!bucket)
164
231
  return;
@@ -171,8 +238,9 @@ export function recordToolUse(telemetry, name, failed) {
171
238
  telemetry.toolFailures += 1;
172
239
  telemetry.task.activity = true;
173
240
  }
241
+ /** Records nothing without an active capture: a run whose reporting is pending, declined or revoked still fails normally. */
174
242
  export function recordRunError(telemetry, code, count = 1) {
175
- if (!Number.isSafeInteger(count) || count < 1)
243
+ if (!hasRunTelemetry(telemetry) || !Number.isSafeInteger(count) || count < 1)
176
244
  return;
177
245
  const errors = telemetry.errors ??= [];
178
246
  let bucket = bucketErrorCode(code);
@@ -210,29 +278,40 @@ export function recordedErrorCode(error) {
210
278
  /** The measured savings a run's efficiency tally holds, as sent in run.finished; undefined when nothing was tallied. */
211
279
  export function savingsFrom(telemetry) {
212
280
  const tally = telemetry.efficiency;
213
- if (!tally)
281
+ const jev = telemetry.jevSavings;
282
+ if (!tally && !jev)
214
283
  return undefined;
284
+ const counters = tally ?? createEfficiencyTally();
215
285
  return {
216
- toolResultsFiltered: tally.toolResults.filtered,
217
- toolResultOriginalChars: tally.toolResults.originalChars,
218
- toolResultKeptChars: tally.toolResults.keptChars,
219
- toolResultExpandedChars: tally.toolResults.expandedChars,
220
- schemaCharsBefore: tally.catalog.schemaCharsBefore,
221
- schemaCharsAfter: tally.catalog.schemaCharsAfter,
222
- contextOmittedChars: tally.context.omittedChars,
223
- contextDuplicates: tally.context.duplicates,
224
- preparedSteps: tally.prepared.steps,
225
- preparedExecuted: tally.prepared.executed,
226
- deterministicSteps: tally.prepared.deterministic,
227
- postflightSkipped: tally.postflight.skipped,
286
+ ...(jev === undefined ? {} : {
287
+ jevDirectInputTokens: jev.directInputTokens,
288
+ jevDirectOutputTokens: jev.directOutputTokens,
289
+ jevDownstreamInputTokens: jev.downstreamInputTokens,
290
+ }),
291
+ toolResultsFiltered: counters.toolResults.filtered,
292
+ toolResultOriginalChars: counters.toolResults.originalChars,
293
+ toolResultKeptChars: counters.toolResults.keptChars,
294
+ toolResultExpandedChars: counters.toolResults.expandedChars,
295
+ schemaCharsBefore: counters.catalog.schemaCharsBefore,
296
+ schemaCharsAfter: counters.catalog.schemaCharsAfter,
297
+ contextOmittedChars: counters.context.omittedChars,
298
+ contextDuplicates: counters.context.duplicates,
299
+ preparedSteps: counters.prepared.steps,
300
+ preparedExecuted: counters.prepared.executed,
301
+ deterministicSteps: counters.prepared.deterministic,
302
+ postflightSkipped: counters.postflight.skipped,
228
303
  };
229
304
  }
230
305
  export function recordAttempt(telemetry, retry) {
306
+ if (!hasRunTelemetry(telemetry))
307
+ return;
231
308
  telemetry.attempts += 1;
232
309
  if (retry)
233
310
  telemetry.retries += 1;
234
311
  }
235
312
  export function recordEdit(telemetry, filePath, created) {
313
+ if (!hasRunTelemetry(telemetry))
314
+ return;
236
315
  telemetry.task.activity = true;
237
316
  if (created)
238
317
  telemetry.task.created += 1;
@@ -244,10 +323,14 @@ export function recordEdit(telemetry, filePath, created) {
244
323
  telemetry.task.otherEdits += 1;
245
324
  }
246
325
  export function recordTestCommand(telemetry) {
326
+ if (!hasRunTelemetry(telemetry))
327
+ return;
247
328
  telemetry.task.activity = true;
248
329
  telemetry.task.testCommand = true;
249
330
  }
250
331
  export function recordDecisionEvent(telemetry, type, data) {
332
+ if (!hasRunTelemetry(telemetry))
333
+ return;
251
334
  const invocation = typeof data.invocationId === 'string' ? data.invocationId : '';
252
335
  const settle = (count) => {
253
336
  if (invocation === '')
@@ -293,6 +376,8 @@ export function recordDecisionEvent(telemetry, type, data) {
293
376
  }
294
377
  }
295
378
  export function recordToolFailure(telemetry, name) {
379
+ if (!hasRunTelemetry(telemetry))
380
+ return;
296
381
  const bucket = bucketToolName(name);
297
382
  if (!bucket)
298
383
  return;
@@ -301,9 +386,18 @@ export function recordToolFailure(telemetry, name) {
301
386
  telemetry.toolFailures += 1;
302
387
  }
303
388
  export function mergeRunTelemetry(into, from) {
389
+ if (!hasRunTelemetry(into) || !hasRunTelemetry(from))
390
+ return into;
391
+ const a = captures.get(into)?.lease, b = captures.get(from)?.lease;
392
+ if (((a && b) || a?.mode === 'consent' || b?.mode === 'consent') && !sameTelemetryLease(a, b))
393
+ return into;
304
394
  if (from.pendingDecisions?.length) {
305
395
  const before = { ...from.jev };
306
396
  (into.pendingDecisions ??= []).push(Promise.allSettled(from.pendingDecisions).then(() => {
397
+ if (!hasRunTelemetry(into) || !hasRunTelemetry(from))
398
+ return;
399
+ if ((a?.mode === 'consent' || b?.mode === 'consent') && !sameTelemetryLease(a, b))
400
+ return;
307
401
  for (const field of JEV_FIELDS) {
308
402
  const delta = from.jev[field] - before[field];
309
403
  if (delta !== 0)
@@ -321,8 +415,8 @@ export function mergeRunTelemetry(into, from) {
321
415
  entry.failures += counts.failures;
322
416
  }
323
417
  for (const source of from.models) {
324
- const key = `${source.providerType}\0${source.endpoint}\0${source.model}\0${source.role}`;
325
- let target = into.models.find(candidate => `${candidate.providerType}\0${candidate.endpoint}\0${candidate.model}\0${candidate.role}` === key);
418
+ const key = modelTupleKey(source);
419
+ let target = into.models.find(candidate => modelTupleKey(candidate) === key);
326
420
  if (!target) {
327
421
  target = { ...source, reported: { ...source.reported, costVersions: new Set(source.reported.costVersions) } };
328
422
  into.models.push(target);
@@ -348,6 +442,11 @@ export function mergeRunTelemetry(into, from) {
348
442
  into.jev[field] += from.jev[field];
349
443
  if (from.efficiency)
350
444
  mergeEfficiency(into.efficiency ??= createEfficiencyTally(), from.efficiency);
445
+ if (from.jevSavings) {
446
+ const totals = into.jevSavings ??= emptyJevSavings();
447
+ for (const field of JEV_SAVINGS_FIELDS)
448
+ totals[field] += from.jevSavings[field];
449
+ }
351
450
  into.task.documentation += from.task.documentation;
352
451
  into.task.test += from.task.test;
353
452
  into.task.otherEdits += from.task.otherEdits;
@@ -1,4 +1,5 @@
1
+ /** Consent-aware sinks; decision rounds additionally require per-request accounting. */
1
2
  export * from './capture-core.js';
2
3
  import { type RunTelemetry } from './capture-core.js';
3
- export declare function recordDecisionEvent(telemetry: RunTelemetry, type: string, data: Record<string, unknown>): void;
4
- export declare function recordEfficiencyEvent(telemetry: RunTelemetry, type: string, data: Record<string, unknown>): void;
4
+ export declare function recordDecisionEvent(telemetry: RunTelemetry | undefined, type: string, data: Record<string, unknown>): void;
5
+ export declare function recordEfficiencyEvent(telemetry: RunTelemetry | undefined, type: string, data: Record<string, unknown>): void;