@andorra-labs/code 0.1.17 → 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 (313) 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 +441 -53
  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/errors.js +3 -0
  11. package/dist/src/andorra/hosted.d.ts +8 -0
  12. package/dist/src/andorra/hosted.js +22 -3
  13. package/dist/src/andorra/streams.d.ts +49 -0
  14. package/dist/src/andorra/streams.js +98 -0
  15. package/dist/src/antigravity-acp.d.ts +28 -0
  16. package/dist/src/antigravity-acp.js +150 -0
  17. package/dist/src/antigravity-terminal.d.ts +2 -0
  18. package/dist/src/antigravity-terminal.js +214 -0
  19. package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
  20. package/dist/src/app-server/adaptive-routing-settings.js +69 -0
  21. package/dist/src/app-server/artifact.d.ts +14 -0
  22. package/dist/src/app-server/artifact.js +46 -0
  23. package/dist/src/app-server/legal-protocol.d.ts +33 -0
  24. package/dist/src/app-server/legal-protocol.js +16 -0
  25. package/dist/src/app-server/protocol.d.ts +34 -3
  26. package/dist/src/app-server/protocol.js +3 -1
  27. package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
  28. package/dist/src/app-server/telemetry-protocol.js +2 -0
  29. package/dist/src/app-server/telemetry.d.ts +38 -0
  30. package/dist/src/app-server/telemetry.js +163 -0
  31. package/dist/src/app-server/workspace.d.ts +21 -0
  32. package/dist/src/app-server/workspace.js +192 -10
  33. package/dist/src/app-server.d.ts +82 -26
  34. package/dist/src/app-server.js +1573 -417
  35. package/dist/src/attachments.d.ts +10 -0
  36. package/dist/src/attachments.js +102 -7
  37. package/dist/src/auth/AuthManager.d.ts +11 -2
  38. package/dist/src/auth/AuthManager.js +56 -13
  39. package/dist/src/auth/index.d.ts +5 -1
  40. package/dist/src/auth/index.js +8 -1
  41. package/dist/src/auth/lifecycle.d.ts +13 -0
  42. package/dist/src/auth/lifecycle.js +109 -0
  43. package/dist/src/auth/store.d.ts +1 -0
  44. package/dist/src/auth/store.js +12 -0
  45. package/dist/src/auth/types.d.ts +12 -0
  46. package/dist/src/automation-runner.js +2 -0
  47. package/dist/src/automation-service.js +7 -2
  48. package/dist/src/automation-tool.js +2 -1
  49. package/dist/src/benchmark-scores.d.ts +88 -0
  50. package/dist/src/benchmark-scores.js +302 -0
  51. package/dist/src/bridge/command.js +16 -1
  52. package/dist/src/bridge/control.d.ts +3 -1
  53. package/dist/src/bridge/control.js +9 -3
  54. package/dist/src/bridge/engines.d.ts +2 -0
  55. package/dist/src/bridge/engines.js +9 -0
  56. package/dist/src/bridge/github.d.ts +108 -0
  57. package/dist/src/bridge/github.js +378 -0
  58. package/dist/src/bridge/host-ops.d.ts +3 -3
  59. package/dist/src/bridge/host-ops.js +14 -2
  60. package/dist/src/bridge/host.d.ts +2 -0
  61. package/dist/src/bridge/host.js +70 -16
  62. package/dist/src/bridge/protocol.d.ts +1 -0
  63. package/dist/src/bridge/protocol.js +1 -0
  64. package/dist/src/browser-panel-tool.d.ts +12 -0
  65. package/dist/src/browser-panel-tool.js +30 -3
  66. package/dist/src/browser-runner.js +53 -62
  67. package/dist/src/browser-server.js +10 -4
  68. package/dist/src/browser-session.d.ts +14 -0
  69. package/dist/src/browser-session.js +57 -12
  70. package/dist/src/browser-view.d.ts +40 -1
  71. package/dist/src/browser-view.js +163 -9
  72. package/dist/src/browser-window-style.d.ts +27 -0
  73. package/dist/src/browser-window-style.js +244 -0
  74. package/dist/src/bug-report-attachments.d.ts +48 -0
  75. package/dist/src/bug-report-attachments.js +327 -0
  76. package/dist/src/bug-report.d.ts +23 -3
  77. package/dist/src/bug-report.js +72 -9
  78. package/dist/src/claude-provider.d.ts +1 -0
  79. package/dist/src/claude-provider.js +77 -36
  80. package/dist/src/cli.d.ts +1 -3
  81. package/dist/src/cli.js +245 -62
  82. package/dist/src/codex-provider.d.ts +1 -0
  83. package/dist/src/codex-provider.js +44 -8
  84. package/dist/src/coding-tools.d.ts +1 -0
  85. package/dist/src/coding-tools.js +28 -7
  86. package/dist/src/command-screens.d.ts +1 -1
  87. package/dist/src/command-screens.js +2 -2
  88. package/dist/src/commands.d.ts +9 -2
  89. package/dist/src/commands.js +69 -64
  90. package/dist/src/completion.js +13 -7
  91. package/dist/src/config.d.ts +14 -3
  92. package/dist/src/config.js +57 -17
  93. package/dist/src/context-budget.d.ts +11 -2
  94. package/dist/src/context-budget.js +38 -4
  95. package/dist/src/context-compaction.d.ts +10 -8
  96. package/dist/src/context-compaction.js +23 -24
  97. package/dist/src/deadline.js +1 -1
  98. package/dist/src/decision/DecisionEngine.d.ts +2 -0
  99. package/dist/src/decision/DecisionManager.d.ts +16 -0
  100. package/dist/src/decision/DecisionManager.js +75 -2
  101. package/dist/src/decision/applyTaskKind.d.ts +8 -0
  102. package/dist/src/decision/applyTaskKind.js +53 -0
  103. package/dist/src/decision/applyToolMenu.js +6 -2
  104. package/dist/src/decision/hostedPolicy.js +6 -3
  105. package/dist/src/decision/optimizationPolicy.d.ts +10 -0
  106. package/dist/src/decision/optimizationPolicy.js +23 -3
  107. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +4 -1
  108. package/dist/src/decision/providers/AndorraDecisionProvider.js +29 -7
  109. package/dist/src/decision/providers/index.js +1 -1
  110. package/dist/src/decision/taskKind.d.ts +52 -0
  111. package/dist/src/decision/taskKind.js +76 -0
  112. package/dist/src/decision/toolFamilies.js +1 -1
  113. package/dist/src/decision/types.d.ts +3 -1
  114. package/dist/src/default-graph.js +1 -1
  115. package/dist/src/efficiency.d.ts +80 -1
  116. package/dist/src/efficiency.js +119 -4
  117. package/dist/src/effort-routing.d.ts +27 -0
  118. package/dist/src/effort-routing.js +34 -0
  119. package/dist/src/evidence.d.ts +110 -0
  120. package/dist/src/evidence.js +195 -0
  121. package/dist/src/extensions.d.ts +2 -0
  122. package/dist/src/extensions.js +30 -20
  123. package/dist/src/github-app/agent-writes.d.ts +1 -1
  124. package/dist/src/github-app/agent-writes.js +1 -1
  125. package/dist/src/github-app/client.d.ts +19 -0
  126. package/dist/src/github-app/client.js +21 -1
  127. package/dist/src/github-app/event-source.d.ts +0 -5
  128. package/dist/src/github-app/event-source.js +1 -31
  129. package/dist/src/github-app/metrics.d.ts +2 -5
  130. package/dist/src/github-app/metrics.js +2 -14
  131. package/dist/src/github-app/review-loop.d.ts +5 -5
  132. package/dist/src/github-app/review-loop.js +1 -1
  133. package/dist/src/github-app/review-node.d.ts +2 -2
  134. package/dist/src/github-app/triggers.d.ts +3 -3
  135. package/dist/src/github-names.d.ts +7 -0
  136. package/dist/src/github-names.js +7 -0
  137. package/dist/src/glob-search.d.ts +1 -0
  138. package/dist/src/glob-search.js +3 -0
  139. package/dist/src/google-provider.d.ts +5 -28
  140. package/dist/src/google-provider.js +6 -141
  141. package/dist/src/graph-editor-session.d.ts +1 -0
  142. package/dist/src/graph-editor-session.js +2 -0
  143. package/dist/src/graph-health.js +3 -1
  144. package/dist/src/graph-preview.d.ts +2 -0
  145. package/dist/src/graph-preview.js +1 -0
  146. package/dist/src/graph-runner.js +20 -14
  147. package/dist/src/graph-selection.d.ts +3 -1
  148. package/dist/src/graph-selection.js +2 -2
  149. package/dist/src/graph-server.d.ts +8 -1
  150. package/dist/src/graph-server.js +49 -12
  151. package/dist/src/graph-sync.d.ts +2 -1
  152. package/dist/src/graph-sync.js +13 -0
  153. package/dist/src/graph-ui/app.js +49 -8
  154. package/dist/src/graph-ui/index.html +1 -1
  155. package/dist/src/graphs.d.ts +23 -1
  156. package/dist/src/graphs.js +58 -7
  157. package/dist/src/grok-provider.js +17 -14
  158. package/dist/src/hardened-runtime.js +39 -25
  159. package/dist/src/jev-savings.d.ts +4 -0
  160. package/dist/src/jev-savings.js +13 -0
  161. package/dist/src/legal/client.d.ts +25 -0
  162. package/dist/src/legal/client.js +47 -0
  163. package/dist/src/legal/command.d.ts +13 -0
  164. package/dist/src/legal/command.js +98 -0
  165. package/dist/src/legal/documents.d.ts +2 -0
  166. package/dist/src/legal/documents.js +14 -0
  167. package/dist/src/legal/gate.d.ts +13 -0
  168. package/dist/src/legal/gate.js +96 -0
  169. package/dist/src/legal/manifest.d.ts +21 -0
  170. package/dist/src/legal/manifest.js +23 -0
  171. package/dist/src/legal/receipt.d.ts +13 -0
  172. package/dist/src/legal/receipt.js +137 -0
  173. package/dist/src/legal/release.d.ts +27 -0
  174. package/dist/src/legal/release.js +28 -0
  175. package/dist/src/managed-sign-in.d.ts +0 -1
  176. package/dist/src/managed-sign-in.js +0 -13
  177. package/dist/src/membership.d.ts +27 -1
  178. package/dist/src/membership.js +139 -7
  179. package/dist/src/model-health-cache.js +1 -1
  180. package/dist/src/model-metadata.js +3 -7
  181. package/dist/src/model-override.d.ts +2 -1
  182. package/dist/src/model-override.js +9 -0
  183. package/dist/src/model-pool.d.ts +99 -0
  184. package/dist/src/model-pool.js +136 -0
  185. package/dist/src/model-relay/local.js +5 -0
  186. package/dist/src/model-relay/remote.d.ts +2 -0
  187. package/dist/src/model-relay/remote.js +4 -0
  188. package/dist/src/model-tiers.d.ts +16 -1
  189. package/dist/src/model-tiers.js +31 -7
  190. package/dist/src/opencode-cli-provider.js +59 -56
  191. package/dist/src/opencode-provider.js +16 -13
  192. package/dist/src/permissions.d.ts +5 -0
  193. package/dist/src/permissions.js +7 -0
  194. package/dist/src/plan-pass.js +2 -1
  195. package/dist/src/pool-scores.d.ts +45 -0
  196. package/dist/src/pool-scores.js +40 -0
  197. package/dist/src/provider-connection.js +3 -17
  198. package/dist/src/provider-engine.d.ts +13 -1
  199. package/dist/src/provider-engine.js +116 -12
  200. package/dist/src/provider-request-error.d.ts +8 -0
  201. package/dist/src/provider-request-error.js +12 -0
  202. package/dist/src/provider-settings.d.ts +1 -1
  203. package/dist/src/provider-settings.js +36 -18
  204. package/dist/src/provider-turn-deadline.d.ts +39 -0
  205. package/dist/src/provider-turn-deadline.js +139 -0
  206. package/dist/src/providers.d.ts +8 -9
  207. package/dist/src/providers.js +211 -150
  208. package/dist/src/pull-request-merge.d.ts +1 -8
  209. package/dist/src/pull-request-merge.js +0 -4
  210. package/dist/src/pull-requests.d.ts +83 -57
  211. package/dist/src/pull-requests.js +266 -225
  212. package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
  213. package/dist/src/qa/runtime/ProcessManager.js +9 -3
  214. package/dist/src/react-runtime.js +245 -71
  215. package/dist/src/reasoning-probe-cloud.d.ts +10 -0
  216. package/dist/src/reasoning-probe-cloud.js +209 -0
  217. package/dist/src/remote/engine-pool.d.ts +3 -0
  218. package/dist/src/remote/engine-pool.js +88 -21
  219. package/dist/src/remote/recovery.d.ts +6 -0
  220. package/dist/src/remote/recovery.js +37 -0
  221. package/dist/src/run-records.d.ts +13 -3
  222. package/dist/src/run-records.js +59 -34
  223. package/dist/src/runtime.d.ts +47 -2
  224. package/dist/src/runtime.js +33 -7
  225. package/dist/src/session-summary.d.ts +8 -0
  226. package/dist/src/session-summary.js +34 -0
  227. package/dist/src/sessions.d.ts +32 -0
  228. package/dist/src/sessions.js +65 -3
  229. package/dist/src/shell.js +6 -0
  230. package/dist/src/side-panel.js +36 -2
  231. package/dist/src/sign-in-detection.d.ts +1 -1
  232. package/dist/src/sign-in-detection.js +4 -10
  233. package/dist/src/sign-in-offer.js +1 -1
  234. package/dist/src/skill-commands.js +1 -1
  235. package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
  236. package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
  237. package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
  238. package/dist/src/skills/bundled/provenance.json +3 -3
  239. package/dist/src/subagent-run.js +50 -50
  240. package/dist/src/subscription-usage.d.ts +50 -0
  241. package/dist/src/subscription-usage.js +92 -0
  242. package/dist/src/task-checkout.d.ts +157 -0
  243. package/dist/src/task-checkout.js +628 -0
  244. package/dist/src/telemetry/access.d.ts +18 -0
  245. package/dist/src/telemetry/access.js +43 -0
  246. package/dist/src/telemetry/aggregate.d.ts +18 -2
  247. package/dist/src/telemetry/aggregate.js +22 -9
  248. package/dist/src/telemetry/capture-core.d.ts +33 -14
  249. package/dist/src/telemetry/capture-core.js +124 -25
  250. package/dist/src/telemetry/capture.d.ts +3 -2
  251. package/dist/src/telemetry/capture.js +21 -1
  252. package/dist/src/telemetry/decision-capture.js +4 -0
  253. package/dist/src/telemetry/emitter.d.ts +6 -7
  254. package/dist/src/telemetry/emitter.js +124 -29
  255. package/dist/src/telemetry/gate.d.ts +41 -2
  256. package/dist/src/telemetry/gate.js +89 -4
  257. package/dist/src/telemetry/home.d.ts +1 -0
  258. package/dist/src/telemetry/home.js +20 -0
  259. package/dist/src/telemetry/identity.d.ts +6 -3
  260. package/dist/src/telemetry/identity.js +19 -6
  261. package/dist/src/telemetry/lifecycle.d.ts +8 -0
  262. package/dist/src/telemetry/lifecycle.js +76 -0
  263. package/dist/src/telemetry/outbox.d.ts +13 -8
  264. package/dist/src/telemetry/outbox.js +68 -12
  265. package/dist/src/telemetry/permission-command.d.ts +38 -0
  266. package/dist/src/telemetry/permission-command.js +208 -0
  267. package/dist/src/telemetry/permission.d.ts +168 -0
  268. package/dist/src/telemetry/permission.js +662 -0
  269. package/dist/src/telemetry/record-installation.d.ts +1 -0
  270. package/dist/src/telemetry/record-installation.js +9 -0
  271. package/dist/src/telemetry/region-data.d.ts +12 -0
  272. package/dist/src/telemetry/region-data.js +1314 -0
  273. package/dist/src/telemetry/region.d.ts +34 -0
  274. package/dist/src/telemetry/region.js +87 -0
  275. package/dist/src/telemetry/run-privacy.d.ts +11 -0
  276. package/dist/src/telemetry/run-privacy.js +165 -0
  277. package/dist/src/telemetry/schema.d.ts +27 -6
  278. package/dist/src/telemetry/schema.js +109 -14
  279. package/dist/src/telemetry/state.d.ts +11 -7
  280. package/dist/src/telemetry/state.js +39 -6
  281. package/dist/src/telemetry/surface.d.ts +20 -3
  282. package/dist/src/telemetry/surface.js +71 -15
  283. package/dist/src/telemetry/uploader.d.ts +6 -11
  284. package/dist/src/telemetry/uploader.js +72 -46
  285. package/dist/src/telemetry/uploads.d.ts +5 -1
  286. package/dist/src/telemetry/uploads.js +25 -6
  287. package/dist/src/telemetry/version.d.ts +5 -0
  288. package/dist/src/telemetry/version.js +34 -0
  289. package/dist/src/telemetry/workspace.d.ts +4 -1
  290. package/dist/src/telemetry/workspace.js +18 -3
  291. package/dist/src/terminal-ui.d.ts +3 -0
  292. package/dist/src/terminal-ui.js +48 -6
  293. package/dist/src/test-edit-guard.d.ts +30 -0
  294. package/dist/src/test-edit-guard.js +167 -2
  295. package/dist/src/thinking-level-detect.d.ts +13 -0
  296. package/dist/src/thinking-level-detect.js +52 -0
  297. package/dist/src/thinking-levels.d.ts +30 -0
  298. package/dist/src/thinking-levels.js +131 -0
  299. package/dist/src/timers.d.ts +3 -0
  300. package/dist/src/todos.d.ts +2 -1
  301. package/dist/src/todos.js +24 -4
  302. package/dist/src/tool-argument-coercion.d.ts +7 -0
  303. package/dist/src/tool-argument-coercion.js +49 -0
  304. package/dist/src/tool-catalog.d.ts +2 -2
  305. package/dist/src/tool-catalog.js +1 -1
  306. package/dist/src/tools.js +67 -22
  307. package/dist/src/transcript.js +3 -2
  308. package/dist/src/types.d.ts +48 -1
  309. package/dist/src/update.js +4 -0
  310. package/dist/src/usage-analytics.d.ts +7 -0
  311. package/dist/src/usage-analytics.js +85 -13
  312. package/dist/telemetry-consent-v1 +1 -0
  313. package/package.json +97 -96
@@ -6,6 +6,9 @@ import { configDirectory } from './config.js';
6
6
  import { writeSessionSnapshot } from './sessions.js';
7
7
  import { ToolFailureTracker } from './tool-failure-tracker.js';
8
8
  import { stopReasonPhrase } from './runtime.js';
9
+ import { withTelemetryAdmission, currentTelemetryAdmission, telemetryLeaseSnapshot } from './telemetry/permission.js';
10
+ import { functionalRunRecord, admittedRunRecord, withRunRecordProjection, withRunFileLock } from './telemetry/run-privacy.js';
11
+ export { scrubRuns, functionalRunRecord } from './telemetry/run-privacy.js';
9
12
  export function runRecordsDirectory(directory = configDirectory()) {
10
13
  return join(directory, 'runs');
11
14
  }
@@ -48,12 +51,23 @@ export async function removeOpenRunRecord(directory, runId) {
48
51
  if (removed)
49
52
  await clearOpenRunClaim(directory, runId);
50
53
  }
51
- export async function writeOpenRunRecord(directory, record) {
54
+ async function writeOpenRunRecordAdmitted(directory, record) {
52
55
  await mkdir(runRecordsDirectory(directory), { recursive: true, mode: 0o700 });
53
56
  await writeOpenRunClaim(directory, { runId: record.id, sessionId: record.sessionId, pid: record.pid });
54
57
  await writeSessionSnapshot(runRecordPath(directory, record.id, 'json'), JSON.stringify(record, null, 2) + '\n');
55
58
  await writeStudioRunSummary(directory, record).catch(() => { });
56
59
  }
60
+ /** Public persistence boundary; blocked/stale writers can save only functional data. */
61
+ export async function writeOpenRunRecord(directory, record, access) {
62
+ await withRunFileLock(directory, runRecordPath(directory, record.id, 'json'), () => withRunRecordProjection(directory, record, projected => writeOpenRunRecordAdmitted(directory, projected), access));
63
+ }
64
+ /** Phase C finalizers must use this instead of raw writeFile/writeSessionSnapshot. */
65
+ export async function writeFinalRunRecord(directory, record, access) {
66
+ await withRunFileLock(directory, runRecordPath(directory, record.id, 'json'), () => withRunRecordProjection(directory, record, async (projected) => {
67
+ await mkdir(runRecordsDirectory(directory), { recursive: true, mode: 0o700 });
68
+ await writeSessionSnapshot(runRecordPath(directory, record.id, 'json'), JSON.stringify(projected, null, 2) + '\n');
69
+ }, access));
70
+ }
57
71
  export function isPidAlive(pid) {
58
72
  if (!Number.isSafeInteger(pid) || pid < 1)
59
73
  return false;
@@ -133,7 +147,8 @@ async function scanFiles(paths, pick, concurrency = 32) {
133
147
  }
134
148
  export async function reconcileInterruptedRuns(directory, onlyRunIds, options) {
135
149
  const recovery = { runs: [], markers: 0, live: [], interrupted: [] };
136
- const swept = await markOpenRunsInterrupted(directory, onlyRunIds, options?.skipOwnProcess === true, options?.includePending === true);
150
+ const sweep = () => markOpenRunsInterrupted(directory, onlyRunIds, options?.skipOwnProcess === true, options?.includePending === true);
151
+ const swept = await sweep(); // functional recovery must never wait for analytics/network admission
137
152
  recovery.runs = swept.ids;
138
153
  recovery.live = swept.live;
139
154
  recovery.interrupted = swept.records;
@@ -159,6 +174,10 @@ async function claimedByThisProcess(directory, runId) {
159
174
  }
160
175
  }
161
176
  async function markOpenRunsInterrupted(directory, onlyRunIds, skipOwnProcess = false, includePending = false) {
177
+ const project = (value) => {
178
+ const lease = telemetryLeaseSnapshot({ home: directory });
179
+ return lease ? admittedRunRecord(value, lease) : functionalRunRecord(value);
180
+ };
162
181
  const runs = runRecordsDirectory(directory);
163
182
  let names;
164
183
  try {
@@ -181,7 +200,7 @@ async function markOpenRunsInterrupted(directory, onlyRunIds, skipOwnProcess = f
181
200
  continue;
182
201
  let value;
183
202
  try {
184
- value = JSON.parse(text);
203
+ value = project(JSON.parse(text));
185
204
  }
186
205
  catch {
187
206
  continue;
@@ -220,28 +239,23 @@ async function markOpenRunsInterrupted(directory, onlyRunIds, skipOwnProcess = f
220
239
  await release();
221
240
  await rm(lockDirectory, { recursive: true, force: true }).catch(() => { });
222
241
  };
223
- let current;
224
- try {
225
- current = JSON.parse(await readFile(path, 'utf8'));
226
- }
227
- catch {
228
- await unlock();
229
- continue;
230
- }
231
- if (!current || typeof current !== 'object' || current.status !== 'running') {
232
- await unlock();
233
- continue;
234
- }
235
- const measured = plainObject(current.usage) ? undefined : await journalRunUsage(directory, runId);
236
- const interrupted = { ...current, status: 'interrupted', telemetryPending: true, reason: 'the engine stopped while this run was active', endedAt: new Date().toISOString(), ...(measured === undefined ? {} : { usage: measured }) };
242
+ let interrupted;
237
243
  try {
238
- await writeSessionSnapshot(path, JSON.stringify(interrupted, null, 2) + '\n');
239
- }
240
- catch {
241
- await unlock();
242
- continue;
244
+ interrupted = await withRunFileLock(directory, path, async () => {
245
+ const current = project(JSON.parse(await readFile(path, 'utf8')));
246
+ if (!current || typeof current !== 'object' || current.status !== 'running')
247
+ return undefined;
248
+ // Privacy cleanup and functional recovery serialize on this file, even while reporting is off.
249
+ const measured = plainObject(current.usage) ? undefined : await journalRunUsage(directory, runId);
250
+ const updated = { ...current, status: 'interrupted', ...(current.telemetry ? { telemetryPending: true } : {}), reason: 'the engine stopped while this run was active', endedAt: new Date().toISOString(), ...(measured === undefined ? {} : { usage: measured }) };
251
+ await writeSessionSnapshot(path, JSON.stringify(updated, null, 2) + '\n');
252
+ return updated;
253
+ });
243
254
  }
255
+ catch { /* A failed functional rewrite is retried by a later recovery. */ }
244
256
  await unlock();
257
+ if (!interrupted)
258
+ continue;
245
259
  const crash = await rememberCrashedClaim(directory, {
246
260
  runId, sessionId: value.sessionId, claimedAt: value.startedAt,
247
261
  });
@@ -742,7 +756,7 @@ function foldRecordUsage(session, usage) {
742
756
  }
743
757
  async function readRunRecord(directory, runId) {
744
758
  try {
745
- return JSON.parse(await readFile(runRecordPath(directory, runId, 'json'), 'utf8'));
759
+ return functionalRunRecord(JSON.parse(await readFile(runRecordPath(directory, runId, 'json'), 'utf8')));
746
760
  }
747
761
  catch {
748
762
  return undefined;
@@ -1084,9 +1098,11 @@ function runCheckpointPath(directory, runId, nodeId) {
1084
1098
  }
1085
1099
  return `${runRecordPath(directory, runId, 'checkpoint')}.${slug}-${(hash >>> 0).toString(36)}`;
1086
1100
  }
1087
- export async function writeRunCheckpoint(directory, runId, checkpoint) {
1088
- await mkdir(runRecordsDirectory(directory), { recursive: true, mode: 0o700 });
1089
- await writeSessionSnapshot(runCheckpointPath(directory, runId, checkpoint.nodeId), JSON.stringify(checkpoint) + '\n');
1101
+ export async function writeRunCheckpoint(directory, runId, checkpoint, access) {
1102
+ await withRunFileLock(directory, runCheckpointPath(directory, runId, checkpoint.nodeId), () => withRunRecordProjection(directory, checkpoint, async (projected) => {
1103
+ await mkdir(runRecordsDirectory(directory), { recursive: true, mode: 0o700 });
1104
+ await writeSessionSnapshot(runCheckpointPath(directory, runId, checkpoint.nodeId), JSON.stringify(projected) + '\n');
1105
+ }, access, true));
1090
1106
  }
1091
1107
  export async function readRunCheckpoint(directory, runId, nodeId) {
1092
1108
  let raw;
@@ -1134,7 +1150,8 @@ function reviveFailures(state) {
1134
1150
  const CHECKPOINT_MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool']);
1135
1151
  function parseRunCheckpoint(raw) {
1136
1152
  try {
1137
- const value = JSON.parse(raw);
1153
+ const parsed = JSON.parse(raw);
1154
+ const value = parsed && functionalRunRecord(parsed, true);
1138
1155
  if (!value || typeof value.nodeId !== 'string' || !Array.isArray(value.messages)
1139
1156
  || typeof value.state !== 'object' || value.state === null
1140
1157
  || typeof value.state.directionRevision !== 'number'
@@ -1374,16 +1391,24 @@ export async function acquireSessionMutationLock(directory, sessionId, options =
1374
1391
  finish();
1375
1392
  };
1376
1393
  }
1377
- export async function clearInterruptedTelemetry(directory, runIds) {
1394
+ async function clearInterruptedTelemetryAdmitted(directory, runIds) {
1378
1395
  for (const runId of runIds) {
1379
1396
  const path = runRecordPath(directory, runId, 'json');
1380
1397
  try {
1381
- const value = JSON.parse(await readFile(path, 'utf8'));
1382
- if (value.status !== 'interrupted' || value.telemetryPending !== true)
1383
- continue;
1384
- delete value.telemetryPending;
1385
- await writeSessionSnapshot(path, JSON.stringify(value, null, 2) + '\n');
1398
+ await withRunFileLock(directory, path, async () => {
1399
+ const admission = currentTelemetryAdmission();
1400
+ if (!admission)
1401
+ return;
1402
+ const value = admittedRunRecord(JSON.parse(await readFile(path, 'utf8')), admission.lease);
1403
+ if (value.status !== 'interrupted' || value.telemetryPending !== true)
1404
+ return;
1405
+ delete value.telemetryPending;
1406
+ await writeSessionSnapshot(path, JSON.stringify(value, null, 2) + '\n');
1407
+ });
1386
1408
  }
1387
- catch { }
1409
+ catch { /* A record that cannot be rewritten is reported again next time; the id is stable. */ }
1388
1410
  }
1389
1411
  }
1412
+ export async function clearInterruptedTelemetry(directory, runIds, access) {
1413
+ await withTelemetryAdmission({ home: directory, signals: access?.signals }, () => clearInterruptedTelemetryAdmitted(directory, runIds), access?.lease);
1414
+ }
@@ -8,6 +8,8 @@ import type { Message, ModelAdapter, RuntimeEvent, Tool, ToolContext, Usage } fr
8
8
  import { type Limits } from './limits.js';
9
9
  import type { DecisionManager } from './decision/DecisionManager.js';
10
10
  import type { DecisionBatch } from './decision/types.js';
11
+ import type { TaskKind } from './decision/taskKind.js';
12
+ import type { JevOutputBaseline } from './context-budget.js';
11
13
  export declare const DEFAULT_GRAPH: Readonly<{
12
14
  id: "default";
13
15
  name: "Andorra Agent";
@@ -35,6 +37,9 @@ export interface Completion {
35
37
  output?: Record<string, unknown>;
36
38
  artifacts?: ArtifactRef[];
37
39
  remaining?: string[];
40
+ /** The requested outcomes the agent listed, and the evidence the runtime resolved for them (phase 3). */
41
+ outcomes?: import('./evidence.js').RequestedOutcome[];
42
+ evidence?: import('./evidence.js').EvidenceItem[];
38
43
  status?: 'running' | 'cancelled' | 'interrupted' | 'infrastructure_error' | 'exhausted' | 'needs_clarification';
39
44
  }
40
45
  export interface InvocationBudget {
@@ -115,6 +120,11 @@ export interface AgentContinuationState {
115
120
  export declare function timerReminderText(prompt: string): string;
116
121
  type RetainedWake = 'timer' | 'auto-fix' | 'fix-checks' | 'mention' | 'andorra-review';
117
122
  export declare function wakeMessageText(wake: RetainedWake | undefined, message: string): string;
123
+ /**
124
+ * A past turn's completion as the model is given it again: the outcomes it listed and the evidence the runtime
125
+ * resolved stay out, since they repeat command output (untrusted text) and grow every later request.
126
+ */
127
+ export declare function turnModelCompletion(completion: Completion): Omit<Completion, 'outcomes' | 'evidence'>;
118
128
  export declare function turnModelTask(turn: {
119
129
  task: string;
120
130
  note?: string;
@@ -130,6 +140,8 @@ export declare function turnModelTask(turn: {
130
140
  }[];
131
141
  }): string;
132
142
  export interface RunOptions {
143
+ /** Product capture start authority. false/absent in protected mode stays off for the whole run. */
144
+ telemetry?: import('./telemetry/capture.js').TelemetryCaptureInput | false;
133
145
  goalCompletionVerification?: import('./goal-completion-verification.js').GoalCompletionVerificationOptions;
134
146
  decisionManager?: DecisionManager;
135
147
  decisionHints?: DecisionBatch;
@@ -137,14 +149,25 @@ export interface RunOptions {
137
149
  efficiency?: import('./efficiency.js').EfficiencyConfig;
138
150
  attachments?: ResolvedAttachments;
139
151
  recoverTools?: Tool[];
140
- getLiveModel?: (nodeId: string | undefined, provider: string, model: string, signal: AbortSignal) => Promise<(ResolvedGraphModel & {
152
+ /** Schemas Jev removed and prompt text it added to enable the routing. */
153
+ jevToolRouting?: {
154
+ omittedTools: readonly Tool[];
155
+ promptAdditions: readonly string[];
156
+ };
157
+ jevOutputBaseline?: JevOutputBaseline;
158
+ /** `sessionModel` marks a live model that is the run's own selection, as opposed to one node's override. */
159
+ getLiveModel?: (nodeId: string | undefined, provider: string, model: string, signal: AbortSignal, appliedRevision?: number, hints?: DecisionBatch) => Promise<(ResolvedGraphModel & {
141
160
  provider: string;
161
+ sessionModel?: boolean;
162
+ selectionRevision?: number;
142
163
  }) | undefined>;
143
164
  task: string;
144
165
  model: string;
145
166
  provider: string;
146
167
  adapter: ModelAdapter;
147
168
  tools: Tool[];
169
+ /** Automatically retrieved reference text, separate from the task and confirmed user requirements. */
170
+ optionalContext?: Partial<Record<NonNullable<Message['optionalContext']>, string>>;
148
171
  contextWindow?: number;
149
172
  context: ToolContext;
150
173
  limits?: Partial<Limits>;
@@ -173,6 +196,13 @@ export interface RunOptions {
173
196
  todoList?: boolean;
174
197
  completionPolicy?: CompletionPolicy;
175
198
  canonicalTask?: string;
199
+ /** The hosted classifier's reading of this run's first message; see src/decision/taskKind.ts. */
200
+ taskKind?: {
201
+ kind: TaskKind;
202
+ confidence: number;
203
+ expectsChange: boolean;
204
+ note?: string;
205
+ };
176
206
  completionGuard?: (completion: Completion) => string | undefined;
177
207
  finalAnswerOutcomes?: readonly string[];
178
208
  sessionGoal?: string;
@@ -226,6 +256,8 @@ export interface ResolvedGraphModel {
226
256
  contextWindow?: number;
227
257
  providerType?: string;
228
258
  baseUrl?: string;
259
+ /** The thinking level this model's requests carry, when one applies. */
260
+ reasoningEffort?: string;
229
261
  }
230
262
  export interface GraphRunOptions extends RunOptions {
231
263
  installedSkillClaims?: (name: string) => boolean;
@@ -245,14 +277,27 @@ export interface GraphRunOptions extends RunOptions {
245
277
  id: string;
246
278
  model?: string;
247
279
  models?: readonly string[];
280
+ type?: string;
248
281
  }[];
282
+ /** Reads the account's Andorra stream limit for the `currentAndorraStreams` tool; the router is asked when absent. */
283
+ andorraHostedCheck?: (signal?: AbortSignal) => Promise<import('./andorra/hosted.js').HostedCheck>;
284
+ /** Subscription usage by provider id, for pool routing. Absent, failing or silent on a provider: no known limit. */
285
+ quotaReadings?: (signal: AbortSignal) => Promise<import('./model-pool.js').QuotaReadings | undefined>;
249
286
  workspaceFacts?: import('./workspace-facts.js').WorkspaceFacts;
250
287
  skillInvocationInstruction?: string;
251
288
  suspendMemoryBudget?: () => () => void;
252
289
  modifierIteration?: number;
253
290
  previousIterationCompletion?: Completion;
254
291
  concurrencyBudget?: number;
255
- resolveModel?: (id: string, model: string | undefined, signal: AbortSignal) => Promise<ResolvedGraphModel>;
292
+ /** `reasoningEffort`, when given, is the thinking level the returned model must run at in place of any saved one. */
293
+ resolveModel?: (id: string, model: string | undefined, signal: AbortSignal, reasoningEffort?: import('./providers.js').ReasoningEffort) => Promise<ResolvedGraphModel>;
294
+ /** The run's own thinking level is Auto: a node on the session model with no level of its own lets Jev pick one. */
295
+ sessionEffortAuto?: boolean;
296
+ /**
297
+ * A model's enabled thinking levels, lowest first; with `forAuto`, the ones Auto may pick among. Absent: every level
298
+ * of a provider type that takes one, and low, medium and high for Auto.
299
+ */
300
+ thinkingLevels?: (provider: string, model: string, forAuto: boolean) => import('./providers.js').ReasoningEffort[];
256
301
  resolveProvider?: (id: string) => ResolvedGraphModel;
257
302
  memory?: import('./memory/MemoryManager.js').MemoryManager;
258
303
  commandMemory?: import('./memory/LocalToolMemory.js').LocalToolMemory;
@@ -1,6 +1,6 @@
1
1
  import { attachmentReferenceBlock } from './attachments.js';
2
2
  import { advertiseAvailableTools } from './tool-availability.js';
3
- import { createRunTelemetry, recordErrorOnce, recordModelUse, recordRunError } from './telemetry/capture.js';
3
+ import { bindRunTelemetry, createRunTelemetry, resolveTelemetryCapture, recordErrorOnce, recordModelUse, recordRunError } from './telemetry/capture.js';
4
4
  import { runFailureCode } from './providers.js';
5
5
  import { pricingFor } from './model-tiers.js';
6
6
  import { bucketEndpoint } from './telemetry/schema.js';
@@ -30,6 +30,14 @@ export function wakeMessageText(wake, message) {
30
30
  return `Delivered by Andorra review (not a message from the user): ${message}`;
31
31
  return wake === 'timer' ? timerReminderText(message) : message;
32
32
  }
33
+ /**
34
+ * A past turn's completion as the model is given it again: the outcomes it listed and the evidence the runtime
35
+ * resolved stay out, since they repeat command output (untrusted text) and grow every later request.
36
+ */
37
+ export function turnModelCompletion(completion) {
38
+ const { outcomes: _outcomes, evidence: _evidence, ...given } = completion;
39
+ return given;
40
+ }
33
41
  export function turnModelTask(turn) {
34
42
  const woken = (message) => wakeMessageText(turn.wake ?? 'timer', message);
35
43
  const said = turn.direction === undefined
@@ -48,6 +56,11 @@ export function turnModelTask(turn) {
48
56
  return turn.attachments?.length ? `${withSteers}\n\n${attachmentReferenceBlock(turn.attachments, { imagesIncluded: false })}` : withSteers;
49
57
  }
50
58
  export async function generateWithUsage(options, result, request) {
59
+ const captureInput = resolveTelemetryCapture(options.telemetry);
60
+ const ensureCapture = () => {
61
+ if (!result.telemetry && captureInput)
62
+ bindRunTelemetry(result, createRunTelemetry(captureInput));
63
+ };
51
64
  let recordedRequests = 0;
52
65
  const localModel = bucketEndpoint(options.telemetryIdentity?.baseUrl) === 'local';
53
66
  const origin = request.context?.invocationId || localModel ? {
@@ -74,7 +87,8 @@ export async function generateWithUsage(options, result, request) {
74
87
  };
75
88
  // Every model request of the run goes through here (agent turns, compaction summaries, auxiliary calls), so this is
76
89
  // where an error the provider recovered from is recorded: before the retry or resend, never only on failure.
77
- const recordError = (code) => { recordRunError(result.telemetry ??= createRunTelemetry(), code ?? 'provider_error'); };
90
+ const recordError = (code) => { ensureCapture(); if (result.telemetry)
91
+ recordRunError(result.telemetry, code ?? 'provider_error'); };
78
92
  const response = await options.adapter.generate({ ...request, onRequest: () => {
79
93
  recordedRequests++;
80
94
  add({ inputTokens: 0, outputTokens: 0, requests: 1 });
@@ -82,22 +96,34 @@ export async function generateWithUsage(options, result, request) {
82
96
  onRecoveredError: code => { recordError(code); request.onRecoveredError?.(code); } }).catch(error => {
83
97
  // The failed request is recorded here, before a caller recovers from it (a verifier's failed verdict, a distiller's
84
98
  // fallback, a compaction or image retry). Handlers further up reuse this record instead of counting it again.
85
- if (!request.signal.aborted)
86
- recordErrorOnce(result.telemetry ??= createRunTelemetry(), error, runFailureCode(error));
99
+ if (!request.signal.aborted) {
100
+ ensureCapture();
101
+ if (result.telemetry)
102
+ recordErrorOnce(result.telemetry, error, runFailureCode(error));
103
+ }
87
104
  if (recordedRequests > 0) {
88
- result.telemetry ??= createRunTelemetry();
105
+ ensureCapture();
89
106
  recordModelUse(result.telemetry, { ...identity, usage: { requests: recordedRequests } });
90
107
  }
91
108
  add({ inputTokens: 0, outputTokens: 0, requests: 0 }, true);
92
109
  throw error;
93
110
  });
111
+ options.jevOutputBaseline?.observe(request.context?.providerId ?? options.provider, request.model, response.usage);
94
112
  add({ inputTokens: response.usage?.inputTokens ?? 0, outputTokens: response.usage?.outputTokens ?? 0,
95
113
  ...(response.usage?.cacheRead === undefined ? {} : { cacheRead: response.usage.cacheRead }),
96
114
  ...(response.usage?.cacheWrite === undefined ? {} : { cacheWrite: response.usage.cacheWrite }),
97
115
  ...(response.usage?.decodeMs === undefined ? {} : { decodeMs: response.usage.decodeMs }),
98
116
  requests: Math.max(0, (response.usage?.requests ?? 1) - recordedRequests) }, true);
99
- result.telemetry ??= createRunTelemetry();
100
- recordModelUse(result.telemetry, { ...identity, usage: response.usage ?? {},
117
+ ensureCapture();
118
+ const attributed = response.servedModel !== undefined || response.authMode !== undefined;
119
+ const requests = Math.max(recordedRequests, response.usage?.requests ?? 1);
120
+ const priorRequests = attributed ? Math.max(0, requests - 1) : 0;
121
+ if (priorRequests)
122
+ recordModelUse(result.telemetry, { ...identity, usage: { requests: priorRequests } });
123
+ const reportedUsage = response.reportedUsage ?? response.usage;
124
+ // The adapters that attach attribution parse usage from the final accepted response, independently of retries.
125
+ recordModelUse(result.telemetry, { ...identity, servedModel: response.servedModel, authMode: response.authMode,
126
+ usage: { ...reportedUsage, requests: attributed ? 1 : requests },
101
127
  ...(options.efficiency?.adaptiveRouting?.pricing ? { pricing: pricingFor(options.efficiency.adaptiveRouting, request.context?.providerId ?? '', request.model) } : {}) });
102
128
  return response;
103
129
  }
@@ -5,4 +5,12 @@ export declare const titleRequestSupported: (provider: Pick<ProviderConfig, "typ
5
5
  export declare const SESSION_SUMMARY_TIMEOUT_MS = 120000;
6
6
  export declare const MAX_SESSION_TITLE_CHARS = 80;
7
7
  export declare function summarizeSessionPrompt(prompt: string, adapter: ModelAdapter, model: string, signal?: AbortSignal): Promise<string>;
8
+ /** The most words a branch name keeps: a task summed up in a few words, not a whole sentence. */
9
+ export declare const MAX_BRANCH_WORDS = 6;
10
+ /**
11
+ * A branch name the model offered, made a safe slug: lower case, at most 6 words, hyphen-chained
12
+ * (`fix-login-redirect-loop`). Nothing usable yields an empty string, so the caller keeps the name it started under.
13
+ */
14
+ export declare function branchFromSummary(text: string): string;
15
+ export declare function summarizeTaskBranch(prompt: string, adapter: ModelAdapter, model: string, signal?: AbortSignal): Promise<string>;
8
16
  export declare function titleFromSummary(text: string): string;
@@ -19,6 +19,40 @@ export async function summarizeSessionPrompt(prompt, adapter, model, signal) {
19
19
  });
20
20
  return titleFromSummary(redactSecrets(response.text));
21
21
  }
22
+ /** The most words a branch name keeps: a task summed up in a few words, not a whole sentence. */
23
+ export const MAX_BRANCH_WORDS = 6;
24
+ const MAX_BRANCH_NAME_CHARS = 40;
25
+ /**
26
+ * A branch name the model offered, made a safe slug: lower case, at most 6 words, hyphen-chained
27
+ * (`fix-login-redirect-loop`). Nothing usable yields an empty string, so the caller keeps the name it started under.
28
+ */
29
+ export function branchFromSummary(text) {
30
+ const firstLine = stripVTControlCharacters(text)
31
+ .replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
32
+ .split('\n').map(line => line.trim()).find(Boolean) ?? '';
33
+ // A model that echoes its own label ("Branch name: fix the loop") keeps the label's words out of the name.
34
+ const bare = firstLine
35
+ .replace(/^[\s>#*_]+/g, '')
36
+ .replace(/^(?:branch name|branch|name)\s*(?:[::]\s*|[\u2014\u2013]\s*|-\s+)[\s*_]*/i, '');
37
+ const words = bare.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
38
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').replace(/-+$/, '')
39
+ .split('-').filter(Boolean).slice(0, MAX_BRANCH_WORDS);
40
+ return words.join('-').slice(0, MAX_BRANCH_NAME_CHARS).replace(/-+$/, '');
41
+ }
42
+ export async function summarizeTaskBranch(prompt, adapter, model, signal) {
43
+ const clean = stripVTControlCharacters(prompt).trim();
44
+ if (!clean)
45
+ return '';
46
+ const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(SESSION_SUMMARY_TIMEOUT_MS)]) : AbortSignal.timeout(SESSION_SUMMARY_TIMEOUT_MS);
47
+ const response = await adapter.generate({
48
+ model, signal: bounded, tools: [], maxTokens: 512,
49
+ messages: [
50
+ { role: 'system', content: 'You name coding sessions. Answer with a Git branch name only: 5 to 6 lowercase words that sum up what the task does, chained together with hyphens (fix-login-redirect-loop). Lowercase, words joined by hyphens, no spaces, no slashes, no underscores, no other punctuation, no preamble, no quotes. Never include a password, API key, token, or other credential.' },
51
+ { role: 'user', content: `A coding task starts with this prompt. Give it its branch name.\n\n${redactSecrets(clean).slice(0, MAX_PROMPT_CHARS)}` },
52
+ ],
53
+ });
54
+ return branchFromSummary(redactSecrets(response.text));
55
+ }
22
56
  export function titleFromSummary(text) {
23
57
  const firstLine = stripVTControlCharacters(text)
24
58
  .replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
@@ -1,7 +1,12 @@
1
1
  import type { ConversationTurn } from './commands.js';
2
2
  import { type SessionGoal } from './session-goal.js';
3
+ import { type SessionCheckout } from './task-checkout.js';
3
4
  import type { Usage } from './types.js';
5
+ /** The most a session's `placeholder` may hold (`validSavedSession`); a prompt-derived name must fit it, too. */
6
+ export declare const MAX_SESSION_NAME_CHARS = 64;
4
7
  export declare const sessionName: (prompt: string) => string;
8
+ /** A random 8-character name (`a92x9dwe`): what a hidden subagent run still starts under. */
9
+ export declare const randomSessionName: () => string;
5
10
  export interface SavedWidget {
6
11
  id: string;
7
12
  name: string;
@@ -23,6 +28,8 @@ export interface SavedSession {
23
28
  usage: Usage;
24
29
  contextHistory?: ConversationTurn[];
25
30
  parentId?: string;
31
+ /** Rail-only link to the chat that proposed this fresh session; never a source of inherited context or usage. */
32
+ handoffParentId?: string;
26
33
  trajectoryId?: string;
27
34
  inheritedUsage?: Usage;
28
35
  ancestors?: string[];
@@ -39,15 +46,40 @@ export interface SavedSession {
39
46
  /** Pinned by the user to the top of its project in the rail. Archiving clears it, and auto-archive leaves a pinned session alone. */
40
47
  pinned?: boolean;
41
48
  renamed?: boolean;
49
+ /** The name the task started under — its prompt's first words — so a delayed title knows the name a real title may replace. */
50
+ placeholder?: string;
42
51
  goal?: SessionGoal;
43
52
  jevEnabled?: boolean;
44
53
  /** Set on a session another part of Andorra started for itself, such as a review run; such a session is kept out of every list. */
45
54
  origin?: SessionOrigin;
55
+ /** Where the task works: its own worktree, or the project folder. Absent on tasks from before it was recorded. */
56
+ checkout?: SessionCheckout;
57
+ /**
58
+ * The newest completed turn waiting for the lead's review in Needs you, and when they marked it reviewed. Set when a
59
+ * turn completes; a turn that fails or is interrupted clears it, and the next completed turn replaces it.
60
+ */
61
+ review?: SessionReview;
62
+ }
63
+ /** `headline`: the first line of the turn's summary, for the line under the task in Needs you. */
64
+ /** `unverified`: requested outcomes the turn did not observe (not checked, or only agent-reported), for the ledger's line. */
65
+ export interface SessionReview {
66
+ runId: string;
67
+ finishedAt: string;
68
+ reviewedAt?: string;
69
+ headline?: string;
70
+ unverified?: string[];
46
71
  }
47
72
  export type SessionOrigin = 'andorra-review';
48
73
  /** A session the review loop's reviewer saved: it stays on disk and opens by id, but no task list, search or stats shows it. */
49
74
  export declare const hiddenSession: (session: Pick<SavedSession, "origin">) => boolean;
50
75
  export declare const MAX_LINEAGE_ENTRIES = 64;
76
+ /**
77
+ * The review a session carries after a turn is saved: a completed newest turn waits for review (keeping the mark of one
78
+ * already reviewed), and any other ending clears it.
79
+ */
80
+ export declare function reviewAfterTurn(history: SavedSession['history'], previous: SessionReview | undefined, finishedAt: string): SessionReview | undefined;
81
+ /** The first sentence-bearing line of a summary, without Markdown marks, at most 200 characters. */
82
+ export declare function reviewHeadline(summary: unknown): string | undefined;
51
83
  export declare function canExtendLineage(ancestors: string[] | undefined): boolean;
52
84
  export declare function lineageThrough(ancestors: string[] | undefined, id: string): string[];
53
85
  export declare function lineagePoints(parent: {
@@ -5,8 +5,12 @@ import { join, resolve } from 'node:path';
5
5
  import { stripVTControlCharacters } from 'node:util';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import { validSessionGoal } from './session-goal.js';
8
+ import { randomTaskName, validCheckout } from './task-checkout.js';
9
+ import { unverified } from './evidence.js';
8
10
  import { decodeDoubleEscapedSummary, stripEchoedEnvelope } from './completion.js';
9
11
  import { redactSecrets } from './secret-redaction.js';
12
+ /** The most a session's `placeholder` may hold (`validSavedSession`); a prompt-derived name must fit it, too. */
13
+ export const MAX_SESSION_NAME_CHARS = 64;
10
14
  export const sessionName = (prompt) => {
11
15
  const clean = redactSecrets(stripVTControlCharacters(prompt))
12
16
  .replace(/https?:\/\/\S+/gi, ' ')
@@ -18,11 +22,56 @@ export const sessionName = (prompt) => {
18
22
  .replace(/^(?:hi|hello|hey)[!,.: ]+/i, '');
19
23
  const words = focused.match(/[\p{L}\p{N}][\p{L}\p{N}'-]*/gu) ?? [];
20
24
  const useful = words.filter(word => !/^(please|can|could|you|would|the|a|an|my|me|to|i|want|need|inside)$/i.test(word));
21
- return [...(useful.length ? useful : words).slice(0, 5), 'coding', 'task', 'session'].slice(0, Math.max(3, Math.min(5, useful.length || words.length))).map(word => word.slice(0, 32)).join(' ');
25
+ const name = [...(useful.length ? useful : words).slice(0, 5), 'coding', 'task', 'session'].slice(0, Math.max(3, Math.min(5, useful.length || words.length))).map(word => word.slice(0, 32)).join(' ');
26
+ return name.length <= MAX_SESSION_NAME_CHARS ? name : name.slice(0, MAX_SESSION_NAME_CHARS).trim();
22
27
  };
28
+ /** A random 8-character name (`a92x9dwe`): what a hidden subagent run still starts under. */
29
+ export const randomSessionName = () => randomTaskName();
23
30
  /** A session the review loop's reviewer saved: it stays on disk and opens by id, but no task list, search or stats shows it. */
24
31
  export const hiddenSession = (session) => session.origin !== undefined;
25
32
  export const MAX_LINEAGE_ENTRIES = 64;
33
+ function validReview(value) {
34
+ if (value === null || typeof value !== 'object')
35
+ return false;
36
+ const entry = value;
37
+ return typeof entry.runId === 'string' && entry.runId.length > 0 && entry.runId.length <= 128
38
+ && typeof entry.finishedAt === 'string' && Number.isFinite(Date.parse(entry.finishedAt))
39
+ && (entry.reviewedAt === undefined || (typeof entry.reviewedAt === 'string' && Number.isFinite(Date.parse(entry.reviewedAt))))
40
+ && (entry.headline === undefined || (typeof entry.headline === 'string' && entry.headline.length <= 400))
41
+ && (entry.unverified === undefined || (Array.isArray(entry.unverified) && entry.unverified.length <= 20 && entry.unverified.every(item => typeof item === 'string' && item.length <= 400)));
42
+ }
43
+ /**
44
+ * The review a session carries after a turn is saved: a completed newest turn waits for review (keeping the mark of one
45
+ * already reviewed), and any other ending clears it.
46
+ */
47
+ export function reviewAfterTurn(history, previous, finishedAt) {
48
+ const last = history[history.length - 1];
49
+ if (last === undefined || typeof last.runId !== 'string' || !last.runId)
50
+ return previous;
51
+ if ((last.completion?.status ?? 'succeeded') !== 'succeeded')
52
+ return undefined;
53
+ if (previous?.runId === last.runId)
54
+ return previous;
55
+ const headline = reviewHeadline(stripEchoedEnvelope(decodeDoubleEscapedSummary(last.completion?.summary ?? ''), last.completion?.outcome));
56
+ const open = unverified(last.completion?.evidence).slice(0, 20).map(item => item.slice(0, 300));
57
+ return { runId: last.runId, finishedAt, ...(headline ? { headline } : {}), ...(open.length ? { unverified: open } : {}) };
58
+ }
59
+ /** The first sentence-bearing line of a summary, without Markdown marks, at most 200 characters. */
60
+ export function reviewHeadline(summary) {
61
+ if (typeof summary !== 'string')
62
+ return undefined;
63
+ const lines = summary.split('\n').map(text => text.trim()).filter(Boolean);
64
+ // A heading such as "## Summary" names the section; the line under it says what happened.
65
+ const chosen = lines.find(text => !/^#{1,6}\s/.test(text)) ?? lines[0];
66
+ if (chosen === undefined)
67
+ return undefined;
68
+ // Only paired marks are Markdown: snake_case names and globs keep their underscores and asterisks.
69
+ const line = chosen.replace(/^(?:#{1,6}\s+|[-*+]\s+|\d+\.\s+|>\s*)/, '')
70
+ .replace(/`([^`]+)`/g, '$1').replace(/\*\*([^*]+)\*\*/g, '$1').replace(/(^|[\s(])__([^_]+)__(?=[\s).,;:!?]|$)/g, '$1$2').trim();
71
+ if (!line)
72
+ return undefined;
73
+ return line.length > 200 ? `${line.slice(0, 199).trimEnd()}…` : line;
74
+ }
26
75
  export function canExtendLineage(ancestors) {
27
76
  return (ancestors?.length ?? 0) < MAX_LINEAGE_ENTRIES;
28
77
  }
@@ -33,8 +82,9 @@ export function lineagePoints(parent, parentUsage, parentTurns) {
33
82
  return [...(parent.lineage ?? []), { usage: parentUsage, turns: parentTurns }].slice(-MAX_LINEAGE_ENTRIES);
34
83
  }
35
84
  export function savedSessionFields(session) {
36
- const { version, id, name, workspace, updatedAt, history, usage, contextHistory, parentId, inheritedUsage, inheritedTurns, ancestors, lineage, projectId, trajectoryId, widgets, context, archived, autoArchived, pinned, renamed, goal, jevEnabled, origin } = session;
85
+ const { version, id, name, workspace, updatedAt, history, usage, contextHistory, parentId, handoffParentId, inheritedUsage, inheritedTurns, ancestors, lineage, projectId, trajectoryId, widgets, context, archived, autoArchived, pinned, renamed, placeholder, goal, jevEnabled, origin, checkout, review } = session;
37
86
  return { version, id, name, workspace, updatedAt, history, usage, contextHistory, parentId, projectId, widgets,
87
+ ...(handoffParentId === undefined ? {} : { handoffParentId }),
38
88
  ...(context === undefined ? {} : { context }),
39
89
  ...(inheritedUsage === undefined ? {} : { inheritedUsage }),
40
90
  ...(inheritedTurns === undefined ? {} : { inheritedTurns }),
@@ -44,9 +94,12 @@ export function savedSessionFields(session) {
44
94
  ...(archived === undefined ? {} : { archived }), ...(autoArchived === undefined ? {} : { autoArchived }),
45
95
  ...(pinned === undefined ? {} : { pinned }),
46
96
  ...(renamed === undefined ? {} : { renamed }),
97
+ ...(placeholder === undefined ? {} : { placeholder }),
47
98
  ...(goal === undefined ? {} : { goal }),
48
99
  ...(jevEnabled === undefined ? {} : { jevEnabled }),
49
- ...(origin === undefined ? {} : { origin }) };
100
+ ...(origin === undefined ? {} : { origin }),
101
+ ...(checkout === undefined ? {} : { checkout }),
102
+ ...(review === undefined ? {} : { review }) };
50
103
  }
51
104
  export const primaryDigest = (session) => createHash('sha256').update(JSON.stringify(savedSessionFields(session))).digest('hex');
52
105
  async function readRunUsage(path) {
@@ -85,6 +138,11 @@ export function carryRailOwnedFields(record, stored) {
85
138
  record.pinned = stored.pinned;
86
139
  else
87
140
  delete record.pinned;
141
+ // Needs you's review mark is the app's to set: a writer that loaded an older copy keeps the stored one.
142
+ if (stored.review !== undefined)
143
+ record.review = stored.review;
144
+ else
145
+ delete record.review;
88
146
  }
89
147
  export function displayHistory(history) {
90
148
  return history.map(turn => {
@@ -159,12 +217,15 @@ export function validSavedSession(value) {
159
217
  return session.version === 1 && typeof session.id === 'string' && validId(session.id) && typeof session.name === 'string' && typeof session.workspace === 'string' && Number.isFinite(Date.parse(session.updatedAt)) &&
160
218
  validHistory(session.history) && (session.contextHistory === undefined || validHistory(session.contextHistory)) &&
161
219
  (session.parentId === undefined || typeof session.parentId === 'string') &&
220
+ (session.handoffParentId === undefined || (typeof session.handoffParentId === 'string' && validId(session.handoffParentId) && session.handoffParentId !== session.id)) &&
162
221
  (session.ancestors === undefined || (Array.isArray(session.ancestors) && session.ancestors.length <= MAX_LINEAGE_ENTRIES
163
222
  && session.ancestors.every((entry) => typeof entry === 'string' && validId(entry)))) &&
164
223
  (session.inheritedTurns === undefined || (Number.isSafeInteger(session.inheritedTurns)
165
224
  && session.inheritedTurns >= 0 && session.inheritedTurns <= session.history.length)) &&
166
225
  (session.lineage === undefined || validLineage(session.lineage, session.usage, session.history.length, { usage: session.inheritedUsage, turns: session.inheritedTurns })) &&
167
226
  (session.projectId === undefined || typeof session.projectId === 'string') &&
227
+ (session.checkout === undefined || validCheckout(session.checkout)) &&
228
+ (session.review === undefined || validReview(session.review)) &&
168
229
  (session.trajectoryId === undefined || (typeof session.trajectoryId === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(session.trajectoryId))) &&
169
230
  (session.widgets === undefined || Array.isArray(session.widgets) && session.widgets.every(widget => !!widget && typeof widget === 'object' && typeof widget.id === 'string' && typeof widget.name === 'string'
170
231
  && typeof widget.description === 'string' && typeof widget.value === 'string')) &&
@@ -176,6 +237,7 @@ export function validSavedSession(value) {
176
237
  (session.autoArchived === undefined || typeof session.autoArchived === 'boolean') &&
177
238
  (session.pinned === undefined || typeof session.pinned === 'boolean') &&
178
239
  (session.renamed === undefined || typeof session.renamed === 'boolean') &&
240
+ (session.placeholder === undefined || typeof session.placeholder === 'string' && session.placeholder.length <= MAX_SESSION_NAME_CHARS) &&
179
241
  (session.goal === undefined || validSessionGoal(session.goal)) &&
180
242
  (session.jevEnabled === undefined || typeof session.jevEnabled === 'boolean') &&
181
243
  (session.origin === undefined || session.origin === 'andorra-review') &&
package/dist/src/shell.js CHANGED
@@ -255,6 +255,12 @@ export function shellBaseEnv(marker, options = {}) {
255
255
  for (const [key, value] of Object.entries(process.env))
256
256
  if (allowed.has(key.toLowerCase()))
257
257
  env[key] = key.toLowerCase() === 'codex_home' && value ? path.resolve(value) : value;
258
+ // Shell commands find the same node that NativeExec runs. It goes last, so a node the user installed still wins.
259
+ const nodeDirectory = path.dirname(process.execPath);
260
+ const pathKey = Object.keys(env).find(key => key.toLowerCase() === 'path') ?? 'PATH';
261
+ const pathEntries = (env[pathKey] ?? '').split(path.delimiter).filter(Boolean);
262
+ if (!pathEntries.includes(nodeDirectory))
263
+ env[pathKey] = [...pathEntries, nodeDirectory].join(path.delimiter);
258
264
  if (marker !== undefined)
259
265
  env.ANDORRACODE_RUN_ID = marker;
260
266
  // While commits with the wrong git identity are held, every command gets the push hold (git-identity-hold.ts).