@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5

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 (275) hide show
  1. package/README.md +146 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge.base.d.ts +13 -1
  7. package/dist/bridge/bridge.service.d.ts +155 -4
  8. package/dist/bridge/bridge.service.js +1805 -155
  9. package/dist/bridge/bridge.types.d.ts +68 -1
  10. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  11. package/dist/bridge/dispatch-result-outbox.js +87 -0
  12. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  13. package/dist/bridge/dispatch-result-worker.js +122 -0
  14. package/dist/bridge/internals.d.ts +2 -0
  15. package/dist/bridge/internals.js +1 -0
  16. package/dist/bridge/local-yield-flag.d.ts +6 -0
  17. package/dist/bridge/local-yield-flag.js +34 -0
  18. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  19. package/dist/bridge/readiness-result-outbox.js +54 -0
  20. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  21. package/dist/bridge/readiness-result-worker.js +121 -0
  22. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +110 -0
  24. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  25. package/dist/bridge/test-postgres-capability.js +120 -0
  26. package/dist/cleanup/cleanup.service.d.ts +10 -0
  27. package/dist/cleanup/cleanup.service.js +128 -104
  28. package/dist/cleanup/cleanup.types.d.ts +4 -0
  29. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  30. package/dist/cleanup/forge-owned-paths.js +53 -0
  31. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  32. package/dist/cleanup/host-runtime-ledger.js +109 -0
  33. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  34. package/dist/cleanup/managed-branch-sweep.js +111 -0
  35. package/dist/cli/cli.help.js +22 -4
  36. package/dist/cli/cli.service.d.ts +30 -6
  37. package/dist/cli/cli.service.js +216 -31
  38. package/dist/cli/local-config.d.ts +5 -0
  39. package/dist/cli/local-config.js +30 -4
  40. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  41. package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
  42. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  43. package/dist/runtime/attempt-database-broker.js +390 -0
  44. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  45. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  46. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  47. package/dist/runtime/attempt-path-operation.js +94 -0
  48. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  49. package/dist/runtime/attempt-private-directory.js +54 -0
  50. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  51. package/dist/runtime/attempt-process-supervisor.js +144 -23
  52. package/dist/runtime/canonical-source-file.d.ts +3 -0
  53. package/dist/runtime/canonical-source-file.js +54 -0
  54. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  55. package/dist/runtime/docker-engine-probe.js +333 -0
  56. package/dist/runtime/generated-output-reset.d.ts +10 -0
  57. package/dist/runtime/generated-output-reset.js +62 -8
  58. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  59. package/dist/runtime/host-database-capability-boundary.js +63 -0
  60. package/dist/runtime/host-diagnostics.d.ts +11 -0
  61. package/dist/runtime/host-diagnostics.js +192 -0
  62. package/dist/runtime/host-execution-root.d.ts +4 -0
  63. package/dist/runtime/host-execution-root.js +39 -0
  64. package/dist/runtime/host-facts.d.ts +36 -0
  65. package/dist/runtime/host-facts.js +95 -0
  66. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  67. package/dist/runtime/host-listener-inspector.js +121 -60
  68. package/dist/runtime/host-load-admission.d.ts +67 -0
  69. package/dist/runtime/host-load-admission.js +99 -0
  70. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  71. package/dist/runtime/host-load-child-environment.js +76 -0
  72. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  73. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  74. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  75. package/dist/runtime/host-load-governor-config.js +83 -0
  76. package/dist/runtime/host-load-governor.d.ts +184 -0
  77. package/dist/runtime/host-load-governor.js +632 -0
  78. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  79. package/dist/runtime/host-load-ledger-lock.js +185 -0
  80. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  81. package/dist/runtime/host-load-runtime-settings.js +78 -0
  82. package/dist/runtime/host-load-sampler.d.ts +149 -0
  83. package/dist/runtime/host-load-sampler.js +291 -0
  84. package/dist/runtime/host-load-step-class.d.ts +70 -0
  85. package/dist/runtime/host-load-step-class.js +161 -0
  86. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  87. package/dist/runtime/host-load-step-reaper.js +95 -0
  88. package/dist/runtime/host-load-step-run.d.ts +73 -0
  89. package/dist/runtime/host-load-step-run.js +102 -0
  90. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  91. package/dist/runtime/host-load-test-slot.js +81 -0
  92. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  93. package/dist/runtime/host-load-token-ledger.js +453 -0
  94. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  95. package/dist/runtime/host-load-windows-cpu.js +85 -0
  96. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  97. package/dist/runtime/host-pressure-stall.js +168 -0
  98. package/dist/runtime/host-runtime-contract.d.ts +16 -1
  99. package/dist/runtime/host-runtime-contract.js +174 -56
  100. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  101. package/dist/runtime/host-runtime-lease.js +1464 -121
  102. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  103. package/dist/runtime/host-runtime-promotion.js +107 -12
  104. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  105. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  106. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  107. package/dist/runtime/host-runtime-requirements.js +117 -0
  108. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  109. package/dist/runtime/managed-command-teardown.js +607 -0
  110. package/dist/runtime/memory-capacity.d.ts +70 -0
  111. package/dist/runtime/memory-capacity.js +123 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  113. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  114. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  115. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  116. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  117. package/dist/runtime/pinned-directory-process.js +61 -0
  118. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  119. package/dist/runtime/pinned-source-directory.js +94 -0
  120. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  121. package/dist/runtime/playwright-browser-cache.js +227 -0
  122. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  123. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  124. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  125. package/dist/runtime/prepared-runtime-identity.js +218 -0
  126. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  127. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  128. package/dist/runtime/runner-settings.d.ts +100 -0
  129. package/dist/runtime/runner-settings.js +214 -0
  130. package/dist/runtime/runtime-isolation-lease.js +4 -1
  131. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  132. package/dist/runtime/workspace-resource-estimator.js +174 -0
  133. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  134. package/dist/sandbox/host-capacity-broker.js +334 -0
  135. package/dist/sandbox/preflight.d.ts +31 -1
  136. package/dist/sandbox/preflight.js +237 -51
  137. package/dist/sandbox/repository-lock.d.ts +2 -1
  138. package/dist/sandbox/repository-lock.js +19 -9
  139. package/dist/sandbox/runtime.d.ts +16 -2
  140. package/dist/sandbox/runtime.js +182 -109
  141. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  142. package/dist/sandbox/sandbox-cgroups.js +42 -0
  143. package/dist/sandbox/sandbox.types.d.ts +7 -0
  144. package/dist/sandbox/workspace.service.js +2 -0
  145. package/dist/session/architect-waits.d.ts +2 -0
  146. package/dist/session/architect-waits.js +138 -0
  147. package/dist/session/managed-attempt-tools.d.ts +44 -1
  148. package/dist/session/managed-attempt-tools.js +816 -46
  149. package/dist/session/managed-build-coordinator.d.ts +5 -0
  150. package/dist/session/managed-build-coordinator.js +109 -0
  151. package/dist/session/managed-build-receipt.d.ts +21 -0
  152. package/dist/session/managed-build-receipt.js +337 -0
  153. package/dist/session/managed-command-host-load.d.ts +47 -0
  154. package/dist/session/managed-command-host-load.js +83 -0
  155. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  156. package/dist/session/managed-verification-timeouts.js +17 -0
  157. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  158. package/dist/session/mcp-argument-coercion.js +121 -0
  159. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  160. package/dist/session/phase-completion.artifacts.js +319 -44
  161. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  162. package/dist/session/phase-completion.command-validation.js +77 -0
  163. package/dist/session/phase-completion.d.ts +15 -1
  164. package/dist/session/phase-completion.helpers.d.ts +5 -0
  165. package/dist/session/phase-completion.helpers.js +43 -19
  166. package/dist/session/phase-completion.js +18 -3
  167. package/dist/session/phase-completion.prompts.js +22 -18
  168. package/dist/session/phase-completion.runtime.d.ts +6 -2
  169. package/dist/session/phase-completion.runtime.js +191 -47
  170. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  171. package/dist/session/phase-completion.schema-parts.js +188 -0
  172. package/dist/session/phase-completion.schemas.d.ts +3 -3
  173. package/dist/session/phase-completion.schemas.js +250 -226
  174. package/dist/session/phase-completion.validation.d.ts +3 -3
  175. package/dist/session/phase-completion.validation.js +135 -89
  176. package/dist/session/pre-publication-host-load.d.ts +27 -0
  177. package/dist/session/pre-publication-host-load.js +111 -0
  178. package/dist/session/pre-publication-pass.d.ts +61 -0
  179. package/dist/session/pre-publication-pass.js +148 -0
  180. package/dist/session/pre-publication-process.d.ts +23 -0
  181. package/dist/session/pre-publication-process.js +109 -0
  182. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  183. package/dist/session/pre-publication-skipped-tests.js +109 -0
  184. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  185. package/dist/session/pre-publication-step-execution.js +49 -0
  186. package/dist/session/pre-publication-validation.d.ts +87 -0
  187. package/dist/session/pre-publication-validation.js +668 -0
  188. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  189. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  190. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  191. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  192. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  193. package/dist/session/provider-cli/claude-background-work.js +180 -0
  194. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  195. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  196. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  197. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  198. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  199. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  200. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  201. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  202. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  203. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  204. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  205. package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
  206. package/dist/session/provider-cli/provider-cli.process.js +583 -210
  207. package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
  208. package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
  209. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  210. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  211. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  212. package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
  213. package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
  214. package/dist/session/provider-cli/provider-cli.service.js +819 -84
  215. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  216. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  217. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  218. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  219. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  220. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  221. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  222. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  223. package/dist/session/provider-cli/provider-output-state.js +376 -17
  224. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  225. package/dist/session/provider-cli/provider-usage.js +28 -5
  226. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  227. package/dist/session/publishable-worktree-changes.js +193 -0
  228. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  229. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  230. package/dist/session/session-redaction.js +434 -9
  231. package/dist/session/session.base.d.ts +9 -1
  232. package/dist/session/session.service.d.ts +9 -2
  233. package/dist/session/session.service.js +264 -27
  234. package/dist/session/session.types.d.ts +150 -2
  235. package/dist/session/session.types.js +599 -7
  236. package/dist/session/unreferenced-exports.d.ts +12 -0
  237. package/dist/session/unreferenced-exports.js +59 -0
  238. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  239. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  240. package/dist/shared/format/format-bytes.d.ts +1 -0
  241. package/dist/shared/format/format-bytes.js +9 -0
  242. package/dist/shared/git/git.js +2 -1
  243. package/dist/shared/path/path.d.ts +1 -0
  244. package/dist/shared/path/path.js +18 -0
  245. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  246. package/dist/shared/process/dotnet-toolchain.js +307 -0
  247. package/dist/shared/process/host-process-recovery.js +3 -2
  248. package/dist/shared/process/host-process-supervisor.d.ts +3 -0
  249. package/dist/shared/process/host-process-supervisor.js +61 -12
  250. package/dist/shared/process/process-tree.d.ts +52 -0
  251. package/dist/shared/process/process-tree.js +144 -0
  252. package/dist/shared/process/process.d.ts +69 -0
  253. package/dist/shared/process/process.js +223 -16
  254. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  255. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  256. package/dist/shared/process/windows-launch.d.ts +18 -0
  257. package/dist/shared/process/windows-launch.js +68 -0
  258. package/dist/shared/provider-capabilities.d.ts +3 -0
  259. package/dist/shared/provider-capabilities.js +84 -0
  260. package/dist/shared/redaction/redaction.d.ts +1 -0
  261. package/dist/shared/redaction/redaction.js +39 -3
  262. package/dist/shared/time/monotonic.d.ts +1 -0
  263. package/dist/shared/time/monotonic.js +8 -0
  264. package/dist/version.d.ts +1 -1
  265. package/dist/version.js +1 -1
  266. package/dist/worktree/dependency-warmer.d.ts +66 -9
  267. package/dist/worktree/dependency-warmer.js +609 -24
  268. package/dist/worktree/index.d.ts +1 -1
  269. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  270. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  271. package/dist/worktree/worktree.service.d.ts +17 -1
  272. package/dist/worktree/worktree.service.js +293 -21
  273. package/dist/worktree/worktree.types.d.ts +14 -1
  274. package/package.json +8 -6
  275. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -2,6 +2,12 @@ import { addUsage, emptyUsage, readUsageNumber } from "./provider-usage.js";
2
2
  export function messageFromError(error) {
3
3
  return error instanceof Error ? error.message : String(error);
4
4
  }
5
+ /** Keeps the end of `value`, where a process's failure detail is, within `maximumLength`. */
6
+ export function clipTail(value, maximumLength) {
7
+ if (value.length <= maximumLength)
8
+ return value;
9
+ return `...${value.slice(-(maximumLength - 3))}`;
10
+ }
5
11
  export function clip(value, maxLength) {
6
12
  if (maxLength <= 0) {
7
13
  return "";
@@ -16,9 +22,14 @@ export function clip(value, maxLength) {
16
22
  return `${value.slice(0, maxLength - ellipsis.length)}${ellipsis}`;
17
23
  }
18
24
  export function createProviderOutputState(provider) {
19
- return provider.trim().toLowerCase() === "cursor"
20
- ? new CursorStreamJsonState()
21
- : new CodexJsonState();
25
+ const normalized = provider.trim().toLowerCase();
26
+ if (normalized === "cursor") {
27
+ return new CursorStreamJsonState();
28
+ }
29
+ if (normalized === "claude") {
30
+ return new ClaudeStreamJsonState();
31
+ }
32
+ return new CodexJsonState();
22
33
  }
23
34
  class CursorStreamJsonState {
24
35
  sessionId = null;
@@ -29,12 +40,18 @@ class CursorStreamJsonState {
29
40
  get sessionLabel() {
30
41
  return this.sessionId ? `session ${this.sessionId}` : null;
31
42
  }
43
+ get providerThreadId() {
44
+ return this.sessionId;
45
+ }
32
46
  get usage() {
33
47
  return this.accumulatedUsage;
34
48
  }
35
49
  get hasActiveToolCall() {
36
50
  return this.activeToolCallCount > 0;
37
51
  }
52
+ resetActiveToolCalls() {
53
+ this.activeToolCallCount = 0;
54
+ }
38
55
  consume(line) {
39
56
  const event = parseJsonLine(line);
40
57
  if (!event) {
@@ -49,7 +66,8 @@ class CursorStreamJsonState {
49
66
  role: "runner",
50
67
  kind: "checkpoint",
51
68
  content: `Cursor session started: ${this.sessionId}.`,
52
- eventType: "provider_thread_started"
69
+ eventType: "provider_thread_started",
70
+ data: JSON.stringify({ threadId: this.sessionId })
53
71
  }];
54
72
  }
55
73
  }
@@ -116,13 +134,19 @@ class CursorStreamJsonState {
116
134
  if (Object.keys(usage).length === 0 && durationMs === 0) {
117
135
  return;
118
136
  }
137
+ const uncachedInputTokens = readUsageNumber(usage, "inputTokens");
138
+ const cacheReadTokens = readUsageNumber(usage, "cacheReadTokens");
139
+ const cacheCreationTokens = readUsageNumber(usage, "cacheWriteTokens");
119
140
  this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
120
- inputTokens: readUsageNumber(usage, "inputTokens"),
141
+ inputTokens: uncachedInputTokens + cacheReadTokens + cacheCreationTokens,
142
+ uncachedInputTokens,
121
143
  outputTokens: readUsageNumber(usage, "outputTokens"),
122
- cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
123
- cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
144
+ cacheReadTokens,
145
+ cacheCreationTokens,
124
146
  providerDurationMs: durationMs > 0 ? durationMs : null,
125
- source: "provider_reported"
147
+ source: "provider_reported",
148
+ inputTokenSemantics: "excludes_cache_tokens",
149
+ rawUsage: [{ provider: "cursor", usage }]
126
150
  });
127
151
  }
128
152
  }
@@ -225,6 +249,295 @@ export function parseJsonLine(line) {
225
249
  ? parsed
226
250
  : null;
227
251
  }
252
+ const claudeFileEditTools = new Set(["edit", "multiedit", "write", "notebookedit"]);
253
+ /**
254
+ * Parses `claude -p --output-format stream-json --verbose` output. Each line is one of:
255
+ * `system/init`, `assistant` (text + tool_use blocks), `user` (tool_result blocks), or the
256
+ * terminal `result` event that carries the aggregated usage for the whole run.
257
+ */
258
+ class ClaudeStreamJsonState {
259
+ sessionId = null;
260
+ finalMessage = null;
261
+ emittedSession = false;
262
+ accumulatedUsage = null;
263
+ activeToolUses = new Map();
264
+ get sessionLabel() {
265
+ return this.sessionId ? `session ${this.sessionId}` : null;
266
+ }
267
+ get providerThreadId() {
268
+ return this.sessionId;
269
+ }
270
+ get usage() {
271
+ return this.accumulatedUsage;
272
+ }
273
+ get hasActiveToolCall() {
274
+ return this.activeToolUses.size > 0;
275
+ }
276
+ resetActiveToolCalls() {
277
+ this.activeToolUses.clear();
278
+ }
279
+ consume(line) {
280
+ const event = parseJsonLine(line);
281
+ if (!event) {
282
+ return [];
283
+ }
284
+ const type = stringField(event, "type");
285
+ if (type === "system" && stringField(event, "subtype") === "init") {
286
+ return this.consumeInit(event);
287
+ }
288
+ if (type === "assistant") {
289
+ return this.consumeAssistant(event);
290
+ }
291
+ if (type === "user") {
292
+ return this.consumeToolResults(event);
293
+ }
294
+ if (type === "result") {
295
+ return this.consumeResult(event, line);
296
+ }
297
+ if (type === "error") {
298
+ return [providerCliError(line)];
299
+ }
300
+ return [];
301
+ }
302
+ consumeInit(event) {
303
+ const events = [];
304
+ this.sessionId = stringField(event, "session_id") ?? this.sessionId;
305
+ if (this.sessionId && !this.emittedSession) {
306
+ this.emittedSession = true;
307
+ events.push({
308
+ role: "runner",
309
+ kind: "checkpoint",
310
+ content: `Claude session started: ${this.sessionId}.`,
311
+ eventType: "provider_thread_started"
312
+ });
313
+ }
314
+ const servers = Array.isArray(event.mcp_servers) ? event.mcp_servers : [];
315
+ for (const entry of servers) {
316
+ if (!entry || typeof entry !== "object") {
317
+ continue;
318
+ }
319
+ const server = entry;
320
+ const name = stringField(server, "name");
321
+ const status = stringField(server, "status");
322
+ if (name && status && status !== "connected") {
323
+ events.push({
324
+ role: "runner",
325
+ kind: "checkpoint",
326
+ content: `Claude MCP server ${name} is ${status}.`,
327
+ eventType: "provider_mcp_server_status",
328
+ data: JSON.stringify({ server_name: name, status })
329
+ });
330
+ }
331
+ }
332
+ return events;
333
+ }
334
+ consumeAssistant(event) {
335
+ const events = [];
336
+ const text = assistantMessageText(event);
337
+ if (text) {
338
+ this.finalMessage = text;
339
+ events.push({
340
+ role: "assistant",
341
+ kind: "message",
342
+ content: clip(text, 4000),
343
+ eventType: "provider_message"
344
+ });
345
+ }
346
+ for (const block of messageContentBlocks(event)) {
347
+ if (stringField(block, "type") !== "tool_use") {
348
+ continue;
349
+ }
350
+ const id = stringField(block, "id");
351
+ const name = stringField(block, "name");
352
+ if (!id || !name) {
353
+ continue;
354
+ }
355
+ const toolUse = { name, input: objectField(block, "input") };
356
+ this.activeToolUses.set(id, toolUse);
357
+ events.push(...formatClaudeToolUseStarted(toolUse));
358
+ }
359
+ return events;
360
+ }
361
+ consumeToolResults(event) {
362
+ const events = [];
363
+ for (const block of messageContentBlocks(event)) {
364
+ if (stringField(block, "type") !== "tool_result") {
365
+ continue;
366
+ }
367
+ const id = stringField(block, "tool_use_id");
368
+ const toolUse = id ? this.activeToolUses.get(id) : undefined;
369
+ if (!id || !toolUse) {
370
+ continue;
371
+ }
372
+ this.activeToolUses.delete(id);
373
+ events.push(...formatClaudeToolUseCompleted(toolUse, block.is_error === true, toolResultText(block)));
374
+ }
375
+ return events;
376
+ }
377
+ consumeResult(event, line) {
378
+ this.activeToolUses.clear();
379
+ this.accumulateUsage(event);
380
+ const result = stringField(event, "result");
381
+ const subtype = stringField(event, "subtype") ?? "";
382
+ const failed = event.is_error === true || subtype.startsWith("error");
383
+ if (!failed) {
384
+ if (result) {
385
+ this.finalMessage = result;
386
+ }
387
+ return [{
388
+ role: "runner",
389
+ kind: "checkpoint",
390
+ content: "Claude turn completed.",
391
+ eventType: "provider_turn_completed"
392
+ }];
393
+ }
394
+ return [providerCliError(line)];
395
+ }
396
+ accumulateUsage(event) {
397
+ const usage = objectField(event, "usage");
398
+ const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
399
+ if (Object.keys(usage).length === 0 && durationMs === 0) {
400
+ return;
401
+ }
402
+ // Anthropic's input_tokens excludes cache reads and writes; normalize to a cache-inclusive total.
403
+ const uncachedInputTokens = readUsageNumber(usage, "input_tokens");
404
+ const cacheReadTokens = readUsageNumber(usage, "cache_read_input_tokens");
405
+ const cacheCreationTokens = readUsageNumber(usage, "cache_creation_input_tokens");
406
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
407
+ inputTokens: uncachedInputTokens + cacheReadTokens + cacheCreationTokens,
408
+ uncachedInputTokens,
409
+ outputTokens: readUsageNumber(usage, "output_tokens"),
410
+ cacheReadTokens,
411
+ cacheCreationTokens,
412
+ providerDurationMs: durationMs > 0 ? durationMs : null,
413
+ source: "provider_reported",
414
+ inputTokenSemantics: "excludes_cache_tokens",
415
+ rawUsage: [{ provider: "claude", usage }]
416
+ });
417
+ }
418
+ }
419
+ function providerCliError(line) {
420
+ return {
421
+ role: "runner",
422
+ kind: "error",
423
+ content: clip(line.trim(), 1000),
424
+ eventType: "provider_cli_error"
425
+ };
426
+ }
427
+ function messageContentBlocks(event) {
428
+ const content = objectField(event, "message").content;
429
+ if (!Array.isArray(content)) {
430
+ return [];
431
+ }
432
+ return content.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
433
+ }
434
+ function toolResultText(block) {
435
+ const content = block.content;
436
+ if (typeof content === "string") {
437
+ return content.trim() || null;
438
+ }
439
+ if (!Array.isArray(content)) {
440
+ return null;
441
+ }
442
+ const text = content
443
+ .map((entry) => entry && typeof entry === "object" ? stringField(entry, "text") : null)
444
+ .filter((part) => Boolean(part))
445
+ .join("\n")
446
+ .trim();
447
+ return text || null;
448
+ }
449
+ /**
450
+ * Claude Code exposes MCP tools as `mcp__<server>__<tool>` and replaces characters outside
451
+ * `[A-Za-z0-9_-]` with `_`, so `forge.complete_qa` arrives as `mcp__forge__forge_complete_qa`.
452
+ */
453
+ export function parseClaudeMcpToolName(name) {
454
+ const match = /^mcp__(.+?)__(.+)$/u.exec(name);
455
+ if (!match) {
456
+ return null;
457
+ }
458
+ const server = match[1] ?? "";
459
+ const rawTool = match[2] ?? "";
460
+ const tool = server === "forge" && rawTool.startsWith("forge_") ? `forge.${rawTool.slice("forge_".length)}` : rawTool;
461
+ return server && tool ? { server, tool } : null;
462
+ }
463
+ function claudeMcpEvents(toolUse, phase, errorText) {
464
+ const mcp = parseClaudeMcpToolName(toolUse.name);
465
+ if (!mcp) {
466
+ return null;
467
+ }
468
+ const item = {
469
+ type: "mcp_tool_call",
470
+ server: mcp.server,
471
+ tool: mcp.tool,
472
+ status: phase
473
+ };
474
+ if (phase === "failed") {
475
+ item.error = errorText ? clip(errorText, 600) : "MCP tool call failed.";
476
+ }
477
+ return formatCodexMcpToolCallEvents(phase === "started" ? "item.started" : "item.completed", { item });
478
+ }
479
+ function formatClaudeToolUseStarted(toolUse) {
480
+ const mcp = claudeMcpEvents(toolUse, "started", null);
481
+ if (mcp) {
482
+ return mcp;
483
+ }
484
+ const normalized = toolUse.name.toLowerCase();
485
+ const filePath = stringField(toolUse.input, "file_path") ?? stringField(toolUse.input, "notebook_path") ?? stringField(toolUse.input, "path");
486
+ let content;
487
+ if (normalized === "bash") {
488
+ const command = stringField(toolUse.input, "command");
489
+ content = command ? `Shell command started: ${clip(command, 500)}` : "Shell command started.";
490
+ }
491
+ else if (normalized === "read" && filePath) {
492
+ content = `Reading ${filePath}`;
493
+ }
494
+ else if (claudeFileEditTools.has(normalized) && filePath) {
495
+ content = `Writing ${filePath}`;
496
+ }
497
+ else {
498
+ content = `Tool call started: ${toolUse.name}`;
499
+ }
500
+ return [{
501
+ role: "worker",
502
+ kind: "checkpoint",
503
+ content,
504
+ eventType: normalized === "bash" ? "provider_command" : "provider_tool_call"
505
+ }];
506
+ }
507
+ function formatClaudeToolUseCompleted(toolUse, isError, resultText) {
508
+ const mcp = claudeMcpEvents(toolUse, isError ? "failed" : "completed", resultText);
509
+ if (mcp) {
510
+ return mcp;
511
+ }
512
+ const normalized = toolUse.name.toLowerCase();
513
+ const filePath = stringField(toolUse.input, "file_path") ?? stringField(toolUse.input, "notebook_path") ?? stringField(toolUse.input, "path");
514
+ if (claudeFileEditTools.has(normalized) && filePath && !isError) {
515
+ return [{
516
+ role: "worker",
517
+ kind: "file_edit",
518
+ content: `Wrote ${filePath}`,
519
+ eventType: "provider_file_edit"
520
+ }];
521
+ }
522
+ const status = isError ? "failed" : "completed";
523
+ let content;
524
+ if (normalized === "bash") {
525
+ const command = stringField(toolUse.input, "command");
526
+ content = command ? `Shell command ${status}: ${clip(command, 500)}` : `Shell command ${status}.`;
527
+ }
528
+ else if (normalized === "read" && filePath) {
529
+ content = isError ? `Read failed: ${filePath}` : `Read ${filePath}`;
530
+ }
531
+ else {
532
+ content = `Tool call ${status}: ${toolUse.name}`;
533
+ }
534
+ return [{
535
+ role: "worker",
536
+ kind: "checkpoint",
537
+ content,
538
+ eventType: normalized === "bash" ? "provider_command" : "provider_tool_call"
539
+ }];
540
+ }
228
541
  class CodexJsonState {
229
542
  threadId = null;
230
543
  finalMessage = null;
@@ -234,12 +547,18 @@ class CodexJsonState {
234
547
  get sessionLabel() {
235
548
  return this.threadId ? `thread ${this.threadId}` : null;
236
549
  }
550
+ get providerThreadId() {
551
+ return this.threadId;
552
+ }
237
553
  get usage() {
238
554
  return this.accumulatedUsage;
239
555
  }
240
556
  get hasActiveToolCall() {
241
557
  return this.activeToolCallCount > 0;
242
558
  }
559
+ resetActiveToolCalls() {
560
+ this.activeToolCallCount = 0;
561
+ }
243
562
  consume(line) {
244
563
  const event = parseJsonLine(line);
245
564
  if (!event) {
@@ -255,7 +574,8 @@ class CodexJsonState {
255
574
  role: "runner",
256
575
  kind: "checkpoint",
257
576
  content: `Codex thread started: ${this.threadId}.`,
258
- eventType: "provider_thread_started"
577
+ eventType: "provider_thread_started",
578
+ data: JSON.stringify({ threadId: this.threadId })
259
579
  }];
260
580
  }
261
581
  }
@@ -332,12 +652,17 @@ class CodexJsonState {
332
652
  if (Object.keys(usage).length === 0) {
333
653
  return;
334
654
  }
655
+ const inputTokens = readUsageNumber(usage, "input_tokens");
656
+ const cacheReadTokens = readUsageNumber(usage, "cached_input_tokens");
335
657
  this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
336
- inputTokens: readUsageNumber(usage, "input_tokens"),
658
+ inputTokens,
659
+ uncachedInputTokens: Math.max(0, inputTokens - cacheReadTokens),
337
660
  outputTokens: readUsageNumber(usage, "output_tokens"),
338
- cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
661
+ cacheReadTokens,
339
662
  reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
340
- source: "provider_reported"
663
+ source: "provider_reported",
664
+ inputTokenSemantics: "includes_cached_input",
665
+ rawUsage: [{ provider: "codex", usage }]
341
666
  });
342
667
  }
343
668
  }
@@ -425,11 +750,45 @@ function mcpErrorSummary(item) {
425
750
  if (direct) {
426
751
  return clip(direct, 600);
427
752
  }
428
- const error = objectField(item, "error");
429
- return stringField(error, "message")
430
- ?? stringField(error, "summary")
431
- ?? stringField(objectField(item, "result"), "error")
432
- ?? null;
753
+ const messages = uniqueErrorMessages([
754
+ item.error,
755
+ item.result,
756
+ item.content,
757
+ ]);
758
+ return messages.length > 0 ? clip(messages.join(" Caused by: "), 600) : null;
759
+ }
760
+ function uniqueErrorMessages(values) {
761
+ const messages = [];
762
+ const seenMessages = new Set();
763
+ const seenObjects = new Set();
764
+ const visit = (value, depth) => {
765
+ if (depth > 8 || value === null || value === undefined)
766
+ return;
767
+ if (typeof value === "string") {
768
+ const message = value.trim();
769
+ if (message.length > 0 && !seenMessages.has(message)) {
770
+ seenMessages.add(message);
771
+ messages.push(message);
772
+ }
773
+ return;
774
+ }
775
+ if (typeof value !== "object" || seenObjects.has(value))
776
+ return;
777
+ seenObjects.add(value);
778
+ if (Array.isArray(value)) {
779
+ for (const entry of value)
780
+ visit(entry, depth + 1);
781
+ return;
782
+ }
783
+ const record = value;
784
+ for (const key of ["message", "summary", "error", "cause", "data", "details", "result", "content"]) {
785
+ if (key in record)
786
+ visit(record[key], depth + 1);
787
+ }
788
+ };
789
+ for (const value of values)
790
+ visit(value, 0);
791
+ return messages;
433
792
  }
434
793
  function safeProviderMcpData(item, serverName, toolName, status) {
435
794
  const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
@@ -1,17 +1,25 @@
1
1
  import type { RunOnceDispatchPacket, RunnerDispatchEvent } from "../session.types.js";
2
2
  export type UsageSource = "provider_reported" | "cli_reported" | "estimated" | "unknown";
3
+ export type InputTokenSemantics = "includes_cached_input" | "excludes_cache_tokens" | "unknown";
4
+ export declare const PROVIDER_USAGE_SCHEMA_VERSION = 1;
3
5
  /**
4
6
  * Normalized, provider-agnostic token usage accumulated for a dispatch. Cost is never computed
5
- * here; the API recomputes cost from these tokens x model rates (ADR-0006).
7
+ * here; the API recomputes cost from these tokens x model rates (legacy
8
+ * ADR-0006, .forge-designer/decisions/legacy/0006-cost-capture.md).
6
9
  */
7
10
  export interface ProviderUsage {
11
+ /** Normalized total input. Cached input is a subset, never an additive peer. */
8
12
  readonly inputTokens: number;
13
+ readonly uncachedInputTokens: number | null;
9
14
  readonly outputTokens: number;
10
15
  readonly cacheReadTokens: number;
11
16
  readonly cacheCreationTokens: number;
12
17
  readonly reasoningOutputTokens: number;
13
18
  readonly providerDurationMs: number | null;
14
19
  readonly source: UsageSource;
20
+ readonly inputTokenSemantics: InputTokenSemantics;
21
+ /** Exact provider usage objects retained for audit/re-normalization. */
22
+ readonly rawUsage: readonly Record<string, unknown>[];
15
23
  }
16
24
  export declare function emptyUsage(source?: UsageSource): ProviderUsage;
17
25
  export declare function addUsage(base: ProviderUsage, next: Partial<ProviderUsage>): ProviderUsage;
@@ -1,27 +1,38 @@
1
+ export const PROVIDER_USAGE_SCHEMA_VERSION = 1;
1
2
  export function emptyUsage(source = "unknown") {
2
3
  return {
3
4
  inputTokens: 0,
5
+ uncachedInputTokens: 0,
4
6
  outputTokens: 0,
5
7
  cacheReadTokens: 0,
6
8
  cacheCreationTokens: 0,
7
9
  reasoningOutputTokens: 0,
8
10
  providerDurationMs: null,
9
- source
11
+ source,
12
+ inputTokenSemantics: "unknown",
13
+ rawUsage: []
10
14
  };
11
15
  }
12
16
  export function addUsage(base, next) {
17
+ const nextUncached = next.uncachedInputTokens;
18
+ const uncachedInputTokens = base.uncachedInputTokens === null || nextUncached === null
19
+ ? null
20
+ : base.uncachedInputTokens + nonNegative(nextUncached);
13
21
  return {
14
22
  inputTokens: base.inputTokens + nonNegative(next.inputTokens),
23
+ uncachedInputTokens,
15
24
  outputTokens: base.outputTokens + nonNegative(next.outputTokens),
16
25
  cacheReadTokens: base.cacheReadTokens + nonNegative(next.cacheReadTokens),
17
26
  cacheCreationTokens: base.cacheCreationTokens + nonNegative(next.cacheCreationTokens),
18
27
  reasoningOutputTokens: base.reasoningOutputTokens + nonNegative(next.reasoningOutputTokens),
19
28
  providerDurationMs: next.providerDurationMs ?? base.providerDurationMs,
20
- source: next.source ?? base.source
29
+ source: next.source ?? base.source,
30
+ inputTokenSemantics: mergeSemantics(base.inputTokenSemantics, next.inputTokenSemantics),
31
+ rawUsage: [...base.rawUsage, ...(next.rawUsage ?? [])]
21
32
  };
22
33
  }
23
34
  export function totalTokens(usage) {
24
- return usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheCreationTokens;
35
+ return usage.inputTokens + usage.outputTokens;
25
36
  }
26
37
  export function hasUsage(usage) {
27
38
  return usage !== null && totalTokens(usage) > 0;
@@ -37,20 +48,26 @@ export function buildProviderUsageEvent(dispatch, usage) {
37
48
  lane: dispatch.execution.lane,
38
49
  phase: dispatch.cycleRun.phase,
39
50
  attempt: dispatch.cycleRun.attempt,
51
+ usage_schema_version: PROVIDER_USAGE_SCHEMA_VERSION,
52
+ input_token_semantics: usage.inputTokenSemantics,
40
53
  input_tokens: usage.inputTokens,
54
+ uncached_input_tokens: usage.uncachedInputTokens,
41
55
  output_tokens: usage.outputTokens,
42
56
  cache_read_tokens: usage.cacheReadTokens,
43
57
  cache_creation_tokens: usage.cacheCreationTokens,
44
58
  reasoning_output_tokens: usage.reasoningOutputTokens,
45
59
  metered: dispatch.execution.authKind === "api_key",
46
60
  usage_source: usage.source,
47
- provider_duration_ms: usage.providerDurationMs
61
+ provider_duration_ms: usage.providerDurationMs,
62
+ normalized_total_tokens: totalTokens(usage),
63
+ normalized_total_formula: "total_input + output; cached_input is a subset of total_input",
64
+ raw_usage: usage.rawUsage
48
65
  };
49
66
  const total = totalTokens(usage);
50
67
  return {
51
68
  role: "runner",
52
69
  kind: "checkpoint",
53
- content: `Provider usage: ${total} tokens (${usage.inputTokens} in / ${usage.outputTokens} out) for ${dispatch.execution.model}.`,
70
+ content: `Provider usage: ${total} tokens (${usage.inputTokens} total in, including ${usage.cacheReadTokens} cached / ${usage.outputTokens} out) for ${dispatch.execution.model}.`,
54
71
  eventType: "provider_usage",
55
72
  data: JSON.stringify(data)
56
73
  };
@@ -62,3 +79,9 @@ export function readUsageNumber(source, key) {
62
79
  function nonNegative(value) {
63
80
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
64
81
  }
82
+ function mergeSemantics(base, next) {
83
+ if (!next || next === "unknown") {
84
+ return base;
85
+ }
86
+ return base === "unknown" || base === next ? next : "unknown";
87
+ }
@@ -0,0 +1,54 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ import { type ProcessRunner } from "../shared/process/process.js";
3
+ export interface PublishableWorktreeChangeSet {
4
+ /** Paths staged for publication, as `git diff --cached --name-only` reports them. */
5
+ readonly publishable: readonly string[];
6
+ /** Worktree changes Forge treats as runtime output and leaves unstaged. */
7
+ readonly excluded: readonly string[];
8
+ }
9
+ /**
10
+ * Decides whether a staged change is Forge runtime output rather than an author edit.
11
+ *
12
+ * `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
13
+ * other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
14
+ * that covers injected managed commands, hooks and skills. The injector never overwrites a
15
+ * tracked `.forge/` file and restores one that matches the managed body, so a tracked
16
+ * `.forge/` file that differs from HEAD is an author edit and must be published.
17
+ */
18
+ export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
19
+ /** `.local/`, `.forge/work-items/` and `.forge/stories/`: never published, even during a merge. */
20
+ export declare function isRuntimeOnlyPath(relativePath: string): boolean;
21
+ /**
22
+ * Stages every publishable worktree change in the real index and returns both sets.
23
+ *
24
+ * During an in-progress merge it first refuses unresolved conflicts, and afterwards
25
+ * restores merge-owned paths that the exclusion unstaged back to HEAD (the story side),
26
+ * such as `.forge/` files the target branch added (#491). Runtime-only paths are never
27
+ * restored.
28
+ */
29
+ export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
30
+ /**
31
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
32
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
33
+ * `worktreePath` is not the root of a git worktree.
34
+ */
35
+ export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
36
+ /** Compares claimed `changed_files` paths with the publishable diff. */
37
+ export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
38
+ readonly missing: readonly string[];
39
+ readonly unexpected: readonly string[];
40
+ };
41
+ export declare function normalizeChangedFilePath(value: string): string;
42
+ /**
43
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
44
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
45
+ * in the same turn instead of failing at publication.
46
+ */
47
+ export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
48
+ /**
49
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
50
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
51
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
52
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
53
+ */
54
+ export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;