@namzu/sdk 74.1.0 → 76.0.0

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 (251) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/dist/bridge/acp/server.d.ts +2 -0
  3. package/dist/bridge/acp/server.d.ts.map +1 -1
  4. package/dist/bridge/acp/server.js +13 -2
  5. package/dist/bridge/acp/server.js.map +1 -1
  6. package/dist/bridge/acp/update.d.ts.map +1 -1
  7. package/dist/bridge/acp/update.js +22 -2
  8. package/dist/bridge/acp/update.js.map +1 -1
  9. package/dist/connector/mcp/adapter.d.ts +1 -1
  10. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  11. package/dist/connector/mcp/adapter.js +3 -2
  12. package/dist/connector/mcp/adapter.js.map +1 -1
  13. package/dist/connector/mcp/client.d.ts +4 -25
  14. package/dist/connector/mcp/client.d.ts.map +1 -1
  15. package/dist/connector/mcp/client.js +32 -32
  16. package/dist/connector/mcp/client.js.map +1 -1
  17. package/dist/peers/record.d.ts +3 -3
  18. package/dist/provider/errors.d.ts.map +1 -1
  19. package/dist/provider/errors.js +13 -18
  20. package/dist/provider/errors.js.map +1 -1
  21. package/dist/provider/stream-request-timeout.d.ts +9 -0
  22. package/dist/provider/stream-request-timeout.d.ts.map +1 -0
  23. package/dist/provider/stream-request-timeout.js +34 -0
  24. package/dist/provider/stream-request-timeout.js.map +1 -0
  25. package/dist/public-runtime.d.ts +3 -2
  26. package/dist/public-runtime.d.ts.map +1 -1
  27. package/dist/public-runtime.js +2 -1
  28. package/dist/public-runtime.js.map +1 -1
  29. package/dist/public-tools.d.ts +1 -1
  30. package/dist/public-tools.d.ts.map +1 -1
  31. package/dist/public-tools.js +1 -1
  32. package/dist/public-tools.js.map +1 -1
  33. package/dist/runtime/query/executor.d.ts +3 -0
  34. package/dist/runtime/query/executor.d.ts.map +1 -1
  35. package/dist/runtime/query/executor.js +25 -4
  36. package/dist/runtime/query/executor.js.map +1 -1
  37. package/dist/runtime/query/file-evidence-replay.d.ts +1 -0
  38. package/dist/runtime/query/file-evidence-replay.d.ts.map +1 -1
  39. package/dist/runtime/query/file-evidence-replay.js +64 -21
  40. package/dist/runtime/query/file-evidence-replay.js.map +1 -1
  41. package/dist/runtime/query/file-evidence-seed.d.ts +7 -0
  42. package/dist/runtime/query/file-evidence-seed.d.ts.map +1 -1
  43. package/dist/runtime/query/file-evidence-seed.js +12 -1
  44. package/dist/runtime/query/file-evidence-seed.js.map +1 -1
  45. package/dist/runtime/query/index.d.ts +2 -0
  46. package/dist/runtime/query/index.d.ts.map +1 -1
  47. package/dist/runtime/query/index.js +5 -2
  48. package/dist/runtime/query/index.js.map +1 -1
  49. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  50. package/dist/runtime/query/path-escalation.js +4 -3
  51. package/dist/runtime/query/path-escalation.js.map +1 -1
  52. package/dist/runtime/query/tooling.d.ts +2 -0
  53. package/dist/runtime/query/tooling.d.ts.map +1 -1
  54. package/dist/runtime/query/tooling.js +1 -0
  55. package/dist/runtime/query/tooling.js.map +1 -1
  56. package/dist/sandbox/provider/local.d.ts.map +1 -1
  57. package/dist/sandbox/provider/local.js +45 -18
  58. package/dist/sandbox/provider/local.js.map +1 -1
  59. package/dist/schedules/cron.js +1 -1
  60. package/dist/schedules/cron.js.map +1 -1
  61. package/dist/schedules/describe.js +1 -1
  62. package/dist/schedules/describe.js.map +1 -1
  63. package/dist/schedules/next-fire.d.ts +2 -2
  64. package/dist/schedules/next-fire.d.ts.map +1 -1
  65. package/dist/schedules/next-fire.js +7 -4
  66. package/dist/schedules/next-fire.js.map +1 -1
  67. package/dist/schedules/spec.d.ts.map +1 -1
  68. package/dist/schedules/spec.js +23 -7
  69. package/dist/schedules/spec.js.map +1 -1
  70. package/dist/schedules/types.d.ts +2 -0
  71. package/dist/schedules/types.d.ts.map +1 -1
  72. package/dist/session/workspace/git-worktree.d.ts +18 -0
  73. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  74. package/dist/session/workspace/git-worktree.js +100 -1
  75. package/dist/session/workspace/git-worktree.js.map +1 -1
  76. package/dist/session/workspace/index.d.ts +1 -1
  77. package/dist/session/workspace/index.d.ts.map +1 -1
  78. package/dist/session/workspace/index.js +1 -1
  79. package/dist/session/workspace/index.js.map +1 -1
  80. package/dist/store/checkpoint/contract.d.ts.map +1 -1
  81. package/dist/store/checkpoint/contract.js +5 -2
  82. package/dist/store/checkpoint/contract.js.map +1 -1
  83. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  84. package/dist/store/session-index/sqlite.js +7 -3
  85. package/dist/store/session-index/sqlite.js.map +1 -1
  86. package/dist/store/session-log/core.d.ts.map +1 -1
  87. package/dist/store/session-log/core.js +118 -25
  88. package/dist/store/session-log/core.js.map +1 -1
  89. package/dist/store/session-log/disk.js +1 -1
  90. package/dist/store/session-log/disk.js.map +1 -1
  91. package/dist/tools/admit-facts.d.ts.map +1 -1
  92. package/dist/tools/admit-facts.js +19 -0
  93. package/dist/tools/admit-facts.js.map +1 -1
  94. package/dist/tools/builtins/bash.d.ts +1 -1
  95. package/dist/tools/builtins/bash.d.ts.map +1 -1
  96. package/dist/tools/builtins/bash.js +9 -7
  97. package/dist/tools/builtins/bash.js.map +1 -1
  98. package/dist/tools/builtins/browser.d.ts +2 -2
  99. package/dist/tools/builtins/browser.d.ts.map +1 -1
  100. package/dist/tools/builtins/browser.js +15 -3
  101. package/dist/tools/builtins/browser.js.map +1 -1
  102. package/dist/tools/builtins/code-analysis.d.ts.map +1 -1
  103. package/dist/tools/builtins/code-analysis.js +4 -1
  104. package/dist/tools/builtins/code-analysis.js.map +1 -1
  105. package/dist/tools/builtins/computer-use.d.ts +19 -3
  106. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  107. package/dist/tools/builtins/computer-use.js +150 -50
  108. package/dist/tools/builtins/computer-use.js.map +1 -1
  109. package/dist/tools/builtins/edit-apply.d.ts.map +1 -1
  110. package/dist/tools/builtins/edit-apply.js +24 -10
  111. package/dist/tools/builtins/edit-apply.js.map +1 -1
  112. package/dist/tools/builtins/edit.d.ts.map +1 -1
  113. package/dist/tools/builtins/edit.js +31 -15
  114. package/dist/tools/builtins/edit.js.map +1 -1
  115. package/dist/tools/builtins/file-text.d.ts +3 -0
  116. package/dist/tools/builtins/file-text.d.ts.map +1 -0
  117. package/dist/tools/builtins/file-text.js +14 -0
  118. package/dist/tools/builtins/file-text.js.map +1 -0
  119. package/dist/tools/builtins/glob.d.ts.map +1 -1
  120. package/dist/tools/builtins/glob.js +7 -2
  121. package/dist/tools/builtins/glob.js.map +1 -1
  122. package/dist/tools/builtins/grep.d.ts.map +1 -1
  123. package/dist/tools/builtins/grep.js +8 -5
  124. package/dist/tools/builtins/grep.js.map +1 -1
  125. package/dist/tools/builtins/ls.d.ts.map +1 -1
  126. package/dist/tools/builtins/ls.js +2 -1
  127. package/dist/tools/builtins/ls.js.map +1 -1
  128. package/dist/tools/builtins/notebook-edit.d.ts.map +1 -1
  129. package/dist/tools/builtins/notebook-edit.js +19 -10
  130. package/dist/tools/builtins/notebook-edit.js.map +1 -1
  131. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  132. package/dist/tools/builtins/read-file.js +48 -24
  133. package/dist/tools/builtins/read-file.js.map +1 -1
  134. package/dist/tools/builtins/read-regular-file.d.ts +5 -0
  135. package/dist/tools/builtins/read-regular-file.d.ts.map +1 -0
  136. package/dist/tools/builtins/read-regular-file.js +23 -0
  137. package/dist/tools/builtins/read-regular-file.js.map +1 -0
  138. package/dist/tools/builtins/search-support.d.ts +2 -0
  139. package/dist/tools/builtins/search-support.d.ts.map +1 -1
  140. package/dist/tools/builtins/search-support.js +14 -0
  141. package/dist/tools/builtins/search-support.js.map +1 -1
  142. package/dist/tools/builtins/stale-before-review.d.ts.map +1 -1
  143. package/dist/tools/builtins/stale-before-review.js +8 -5
  144. package/dist/tools/builtins/stale-before-review.js.map +1 -1
  145. package/dist/tools/builtins/write-file.d.ts.map +1 -1
  146. package/dist/tools/builtins/write-file.js +17 -13
  147. package/dist/tools/builtins/write-file.js.map +1 -1
  148. package/dist/tools/coordinator/agent.d.ts.map +1 -1
  149. package/dist/tools/coordinator/agent.js +6 -0
  150. package/dist/tools/coordinator/agent.js.map +1 -1
  151. package/dist/tools/coordinator/index.d.ts.map +1 -1
  152. package/dist/tools/coordinator/index.js +6 -0
  153. package/dist/tools/coordinator/index.js.map +1 -1
  154. package/dist/tools/coordinator/progress.d.ts +9 -0
  155. package/dist/tools/coordinator/progress.d.ts.map +1 -0
  156. package/dist/tools/coordinator/progress.js +30 -0
  157. package/dist/tools/coordinator/progress.js.map +1 -0
  158. package/dist/tools/paths.d.ts +9 -0
  159. package/dist/tools/paths.d.ts.map +1 -1
  160. package/dist/tools/paths.js +39 -9
  161. package/dist/tools/paths.js.map +1 -1
  162. package/dist/tools/posix-path.d.ts +2 -14
  163. package/dist/tools/posix-path.d.ts.map +1 -1
  164. package/dist/tools/posix-path.js +7 -0
  165. package/dist/tools/posix-path.js.map +1 -1
  166. package/dist/tools/shell-output-window.d.ts +12 -0
  167. package/dist/tools/shell-output-window.d.ts.map +1 -0
  168. package/dist/tools/shell-output-window.js +92 -0
  169. package/dist/tools/shell-output-window.js.map +1 -0
  170. package/dist/types/acp/index.d.ts +3 -0
  171. package/dist/types/acp/index.d.ts.map +1 -1
  172. package/dist/types/browser/index.d.ts +4 -0
  173. package/dist/types/browser/index.d.ts.map +1 -1
  174. package/dist/types/code-analysis/index.d.ts +1 -1
  175. package/dist/types/code-analysis/index.d.ts.map +1 -1
  176. package/dist/types/computer-use/index.d.ts +4 -0
  177. package/dist/types/computer-use/index.d.ts.map +1 -1
  178. package/dist/types/provider/errors.d.ts.map +1 -1
  179. package/dist/types/provider/errors.js +3 -5
  180. package/dist/types/provider/errors.js.map +1 -1
  181. package/dist/types/session/checkpoint.d.ts +13 -0
  182. package/dist/types/session/checkpoint.d.ts.map +1 -1
  183. package/dist/types/session/checkpoint.js +33 -0
  184. package/dist/types/session/checkpoint.js.map +1 -1
  185. package/dist/types/session/events.d.ts +3 -0
  186. package/dist/types/session/events.d.ts.map +1 -1
  187. package/dist/types/session/events.js.map +1 -1
  188. package/dist/types/tool/index.d.ts +17 -0
  189. package/dist/types/tool/index.d.ts.map +1 -1
  190. package/dist/types/tool/index.js.map +1 -1
  191. package/dist/types/tool/presentation.d.ts +8 -0
  192. package/dist/types/tool/presentation.d.ts.map +1 -1
  193. package/package.json +1 -1
  194. package/src/bridge/acp/server.ts +22 -8
  195. package/src/bridge/acp/update.ts +23 -2
  196. package/src/connector/mcp/adapter.ts +4 -3
  197. package/src/connector/mcp/client.ts +33 -32
  198. package/src/provider/errors.ts +12 -19
  199. package/src/provider/stream-request-timeout.ts +34 -0
  200. package/src/public-runtime.ts +3 -0
  201. package/src/public-tools.ts +1 -0
  202. package/src/runtime/query/executor.ts +41 -6
  203. package/src/runtime/query/file-evidence-replay.ts +73 -19
  204. package/src/runtime/query/file-evidence-seed.ts +16 -0
  205. package/src/runtime/query/index.ts +9 -1
  206. package/src/runtime/query/path-escalation.ts +4 -3
  207. package/src/runtime/query/tooling.ts +3 -0
  208. package/src/sandbox/provider/local.ts +53 -25
  209. package/src/schedules/cron.ts +1 -1
  210. package/src/schedules/describe.ts +1 -1
  211. package/src/schedules/next-fire.ts +7 -4
  212. package/src/schedules/spec.ts +36 -7
  213. package/src/schedules/types.ts +2 -0
  214. package/src/session/workspace/git-worktree.ts +115 -1
  215. package/src/session/workspace/index.ts +6 -1
  216. package/src/store/checkpoint/contract.ts +9 -2
  217. package/src/store/session-index/sqlite.ts +8 -4
  218. package/src/store/session-log/core.ts +130 -26
  219. package/src/store/session-log/disk.ts +1 -1
  220. package/src/tools/admit-facts.ts +20 -0
  221. package/src/tools/builtins/bash.ts +11 -12
  222. package/src/tools/builtins/browser.ts +16 -3
  223. package/src/tools/builtins/code-analysis.ts +6 -1
  224. package/src/tools/builtins/computer-use.ts +188 -44
  225. package/src/tools/builtins/edit-apply.ts +25 -10
  226. package/src/tools/builtins/edit.ts +31 -15
  227. package/src/tools/builtins/file-text.ts +14 -0
  228. package/src/tools/builtins/glob.ts +6 -1
  229. package/src/tools/builtins/grep.ts +7 -5
  230. package/src/tools/builtins/ls.ts +2 -1
  231. package/src/tools/builtins/notebook-edit.ts +18 -11
  232. package/src/tools/builtins/read-file.ts +52 -27
  233. package/src/tools/builtins/read-regular-file.ts +25 -0
  234. package/src/tools/builtins/search-support.ts +13 -0
  235. package/src/tools/builtins/stale-before-review.ts +8 -6
  236. package/src/tools/builtins/write-file.ts +18 -12
  237. package/src/tools/coordinator/agent.ts +6 -0
  238. package/src/tools/coordinator/index.ts +6 -0
  239. package/src/tools/coordinator/progress.ts +40 -0
  240. package/src/tools/paths.ts +49 -7
  241. package/src/tools/posix-path.ts +9 -0
  242. package/src/tools/shell-output-window.ts +97 -0
  243. package/src/types/acp/index.ts +3 -0
  244. package/src/types/browser/index.ts +2 -0
  245. package/src/types/code-analysis/index.ts +1 -1
  246. package/src/types/computer-use/index.ts +17 -0
  247. package/src/types/provider/errors.ts +3 -5
  248. package/src/types/session/checkpoint.ts +37 -0
  249. package/src/types/session/events.ts +3 -0
  250. package/src/types/tool/index.ts +12 -0
  251. package/src/types/tool/presentation.ts +12 -1
@@ -5,6 +5,7 @@ import {
5
5
  } from '../../session/log-hash.js'
6
6
  import type { SessionId, TurnId } from '../../types/ids/index.js'
7
7
  import type { Message } from '../../types/message/index.js'
8
+ import { persistedTokenUsage } from '../../types/session/checkpoint.js'
8
9
  import {
9
10
  type RecordPointer,
10
11
  SESSION_RECORD_MAX_BYTES,
@@ -440,8 +441,9 @@ export class SessionLogCore implements SessionLog {
440
441
  /** Records accepted into the chain that the medium has not taken yet, oldest first. */
441
442
  #pending: { readonly bytes: Buffer; readonly sync: boolean }[] = []
442
443
  #pendingBytes = 0
443
- /** Bytes the medium holds while records are pending. */
444
- #diskBytes = 0
444
+ /** The verified chain on the medium while the in-memory chain is ahead. */
445
+ #durableChain: SessionLogChain | undefined
446
+ #unrecordedDrops = 0
445
447
  #degradedCause: SessionLogDegradedCause | undefined
446
448
  #droppedRecords = 0
447
449
  #droppedNoticeSent = false
@@ -512,7 +514,7 @@ export class SessionLogCore implements SessionLog {
512
514
  */
513
515
  async #catchUp(): Promise<void> {
514
516
  // Records waiting for the disk are ahead of it; the lease keeps others out.
515
- if (this.#pending.length > 0) return
517
+ if (this.#durableChain !== undefined) return
516
518
  const size = await this.#medium.size()
517
519
  if (size === this.#synced + this.#torn && size >= this.#synced) return
518
520
  if (size < this.#synced) this.#reset()
@@ -807,7 +809,11 @@ export class SessionLogCore implements SessionLog {
807
809
  gen: lease.fence,
808
810
  }
809
811
  const { type, ...payload } = draft as { type: string } & Record<string, unknown>
810
- let candidate: Record<string, unknown> = { ...envelope, type, ...payload }
812
+ let candidate: Record<string, unknown> = {
813
+ ...envelope,
814
+ type,
815
+ ...persistedUsageOf(type, payload),
816
+ }
811
817
  candidate = await this.#spillIfLarge(candidate)
812
818
  const parsed = SessionRecordSchema.safeParse(candidate)
813
819
  if (!parsed.success) {
@@ -831,7 +837,11 @@ export class SessionLogCore implements SessionLog {
831
837
  }
832
838
  const bytes = Buffer.from(line, 'utf8')
833
839
  const sync = this.#sync === 'all' || (this.#sync === 'boundaries' && BOUNDARY_TYPES.has(type))
834
- await this.#persist(bytes, sync)
840
+ const recovered = await this.#persist(bytes, sync)
841
+ if (recovered !== undefined) {
842
+ this.#turns.apply(recovered.record)
843
+ return recovered
844
+ }
835
845
  const entry = this.#chain.accept(bytes, this.#synced)
836
846
  this.#turns.apply(entry.record)
837
847
  this.#synced += bytes.byteLength
@@ -856,15 +866,19 @@ export class SessionLogCore implements SessionLog {
856
866
  * buffer and goes out, in order, with the next record that can be written.
857
867
  * Any other error is thrown as before. Caller holds the mutex.
858
868
  */
859
- async #persist(bytes: Buffer, sync: boolean): Promise<void> {
860
- if (this.#pending.length === 0) {
869
+ async #persist(bytes: Buffer, sync: boolean): Promise<SessionLogEntry | undefined> {
870
+ if (this.#durableChain === undefined) {
861
871
  try {
862
872
  await this.#medium.append(bytes, this.#synced, sync)
863
- return
873
+ return undefined
864
874
  } catch (error) {
865
875
  const cause = sessionLogDegradedCause(error)
866
876
  if (cause === undefined) throw error
867
- this.#diskBytes = this.#synced
877
+ this.#durableChain = new SessionLogChain({
878
+ head: this.#chain.head,
879
+ sessionId: this.sessionId,
880
+ gen: this.#chain.gen,
881
+ })
868
882
  this.#degradedCause = cause
869
883
  this.#bufferRecord(bytes, sync)
870
884
  this.#notify({
@@ -873,12 +887,12 @@ export class SessionLogCore implements SessionLog {
873
887
  bufferedRecords: this.#pending.length,
874
888
  bufferedBytes: this.#pendingBytes,
875
889
  })
876
- return
890
+ return undefined
877
891
  }
878
892
  }
879
893
  const queued = this.#bufferRecord(bytes, sync)
880
894
  try {
881
- await this.#flushPending()
895
+ return await this.#flushPending()
882
896
  } catch (error) {
883
897
  // Only the volume refusing writes keeps the session going; anything else
884
898
  // fails this record, which must then not stay queued.
@@ -890,6 +904,7 @@ export class SessionLogCore implements SessionLog {
890
904
  }
891
905
  throw error
892
906
  }
907
+ return undefined
893
908
  }
894
909
  }
895
910
 
@@ -899,11 +914,14 @@ export class SessionLogCore implements SessionLog {
899
914
  this.#pendingBytes += bytes.byteLength
900
915
  let dropped = false
901
916
  // The newest record always stays, whatever the bound.
902
- while (this.#pendingBytes > this.#degradedBufferBytes && this.#pending.length > 1) {
903
- const oldest = this.#pending.shift()
917
+ // The first record is required even if the volume refused the session start.
918
+ const keepStart = this.#durableChain?.head === null ? 1 : 0
919
+ while (this.#pendingBytes > this.#degradedBufferBytes && this.#pending.length > keepStart + 1) {
920
+ const [oldest] = this.#pending.splice(keepStart, 1)
904
921
  if (oldest === undefined) break
905
922
  this.#pendingBytes -= oldest.bytes.byteLength
906
923
  this.#droppedRecords += 1
924
+ this.#unrecordedDrops += 1
907
925
  dropped = true
908
926
  }
909
927
  if (dropped && !this.#droppedNoticeSent && this.#degradedCause !== undefined) {
@@ -919,20 +937,56 @@ export class SessionLogCore implements SessionLog {
919
937
  return queued
920
938
  }
921
939
 
922
- /** Write the buffer in order. Throws the error that stopped it; clears the degraded mark when it empties. */
923
- async #flushPending(): Promise<void> {
924
- // A refused write may have left part of a record behind; cut it back.
940
+ /** Write the buffer in order, leaving a valid prefix even if a later write fails. */
941
+ async #flushPending(): Promise<SessionLogEntry | undefined> {
942
+ const chain = this.#durableChain
943
+ if (chain === undefined) return
925
944
  const size = await this.#medium.size()
926
- if (size > this.#diskBytes) await this.#medium.truncate(this.#diskBytes, size)
927
- while (this.#pending.length > 0) {
945
+ if (size > chain.end) await this.#medium.truncate(chain.end, size)
946
+ let last: SessionLogEntry | undefined
947
+ for (;;) {
928
948
  const next = this.#pending[0]
929
949
  if (next === undefined) break
930
- await this.#medium.append(next.bytes, this.#diskBytes, next.sync)
931
- this.#diskBytes += next.bytes.byteLength
950
+ // The pending bytes were already validated when the record was accepted.
951
+ const record = JSON.parse(next.bytes.toString('utf8')) as SessionRecord
952
+ if (this.#unrecordedDrops > 0 && chain.head !== null) {
953
+ const gap = {
954
+ v: SESSION_RECORD_SCHEMA_VERSION,
955
+ id: generateRecordId(),
956
+ sessionId: this.sessionId,
957
+ ts: record.ts,
958
+ gen: record.gen,
959
+ type: 'log_gap',
960
+ ignorable: true,
961
+ seq: chain.head.seq + 1,
962
+ prev: chain.head,
963
+ droppedRecords: this.#unrecordedDrops,
964
+ firstDroppedSeq: record.seq - this.#unrecordedDrops,
965
+ lastDroppedSeq: record.seq - 1,
966
+ }
967
+ const bytes = Buffer.from(`${JSON.stringify(gap)}\n`, 'utf8')
968
+ await this.#appendPendingLine(chain, bytes, this.#sync !== 'none')
969
+ this.#unrecordedDrops = 0
970
+ }
971
+ const head = chain.head
972
+ let bytes = next.bytes
973
+ if (record.seq !== (head?.seq ?? 0) + 1 || record.prev?.sha256 !== head?.sha256) {
974
+ // Skip links into the provisional chain are no longer valid.
975
+ const { prevText: _prevText, ...payload } = record
976
+ bytes = Buffer.from(
977
+ formatSessionLogLine({ ...payload, seq: (head?.seq ?? 0) + 1, prev: head }),
978
+ 'utf8',
979
+ )
980
+ }
981
+ last = await this.#appendPendingLine(chain, bytes, next.sync)
932
982
  this.#pendingBytes -= next.bytes.byteLength
933
- this.#pending.shift()
934
983
  this.#flushedWhileDegraded += 1
984
+ // Drop each durable record immediately so a retry starts after it.
985
+ this.#pending.shift()
935
986
  }
987
+ this.#chain = chain
988
+ this.#synced = chain.end
989
+ this.#durableChain = undefined
936
990
  const flushed = this.#flushedWhileDegraded
937
991
  this.#flushedWhileDegraded = 0
938
992
  const dropped = this.#droppedRecords
@@ -941,6 +995,19 @@ export class SessionLogCore implements SessionLog {
941
995
  this.#droppedNoticeSent = false
942
996
  this.#pendingBytes = 0
943
997
  this.#notify({ state: 'recovered', flushedRecords: flushed, droppedRecords: dropped })
998
+ return last
999
+ }
1000
+
1001
+ async #appendPendingLine(
1002
+ chain: SessionLogChain,
1003
+ bytes: Buffer,
1004
+ sync: boolean,
1005
+ ): Promise<SessionLogEntry> {
1006
+ const offset = chain.end
1007
+ await this.#medium.append(bytes, offset, sync)
1008
+ const entry = chain.accept(bytes, offset)
1009
+ if (this.#ledgerKey !== undefined) verifiedPrefixOf(this.#ledgerKey)?.append(entry)
1010
+ return entry
944
1011
  }
945
1012
 
946
1013
  /**
@@ -1037,10 +1104,10 @@ export class SessionLogCore implements SessionLog {
1037
1104
  }
1038
1105
  const content = candidate.content as Message & { toolCallId?: unknown }
1039
1106
  const key =
1040
- content.role === 'tool' && typeof content.toolCallId === 'string'
1041
- ? content.toolCallId
1042
- : type === 'message_replaced' || type === 'message_edited'
1043
- ? `record:${String(candidate.id)}`
1107
+ type === 'message_replaced' || type === 'message_edited'
1108
+ ? `record:${String(candidate.id)}`
1109
+ : content.role === 'tool' && typeof content.toolCallId === 'string'
1110
+ ? content.toolCallId
1044
1111
  : `message:${String(candidate.messageId)}`
1045
1112
  const ref = await this.#spillOrLose(key, 'message', JSON.stringify(content))
1046
1113
  const text =
@@ -1272,7 +1339,16 @@ export async function* walkSessionLog(
1272
1339
  }
1273
1340
 
1274
1341
  const splitter = new LineSplitter(start)
1275
- let anchorSeen = false
1342
+ // A resumed walk starts past its verified cursor.
1343
+ const cursor = chain.head
1344
+ const anchor = options.expectHead
1345
+ let anchorSeen =
1346
+ cursor !== null &&
1347
+ anchor !== undefined &&
1348
+ cursor.seq === anchor.seq &&
1349
+ cursor.offset === anchor.offset &&
1350
+ cursor.length === anchor.length &&
1351
+ cursor.sha256 === anchor.sha256
1276
1352
  let stopped = false
1277
1353
  outer: for await (const chunk of medium.stream(start)) {
1278
1354
  let lines: Generator<{ line: Uint8Array; offset: number }>
@@ -1343,3 +1419,31 @@ export async function* walkSessionLog(
1343
1419
  ...(brokeAt === undefined ? {} : { break: brokeAt }),
1344
1420
  }
1345
1421
  }
1422
+
1423
+ /**
1424
+ * Keep only the persisted usage keys in the usage of a settled turn and of an ended child
1425
+ * session (see {@link persistedTokenUsage}): a usage total carries summed fields those
1426
+ * shapes do not name, and every release reads them strictly. Other records' usage (a
1427
+ * completed message's own) has its own shape and is left as it is.
1428
+ */
1429
+ function persistedUsageOf(type: string, payload: Record<string, unknown>): Record<string, unknown> {
1430
+ const project = (value: unknown) =>
1431
+ value && typeof value === 'object' && !Array.isArray(value)
1432
+ ? persistedTokenUsage(value as Parameters<typeof persistedTokenUsage>[0])
1433
+ : value
1434
+ if (type === 'child_session_ended' && payload.usage !== undefined) {
1435
+ return { ...payload, usage: project(payload.usage) }
1436
+ }
1437
+ const settlement = payload.settlement
1438
+ if (
1439
+ (type === 'turn_completed' || type === 'turn_failed') &&
1440
+ settlement &&
1441
+ typeof settlement === 'object' &&
1442
+ !Array.isArray(settlement) &&
1443
+ (settlement as Record<string, unknown>).usage !== undefined
1444
+ ) {
1445
+ const settled = settlement as Record<string, unknown>
1446
+ return { ...payload, settlement: { ...settled, usage: project(settled.usage) } }
1447
+ }
1448
+ return payload
1449
+ }
@@ -120,7 +120,7 @@ export class DiskLogMedium implements LogMedium {
120
120
 
121
121
  async append(bytes: Uint8Array, expectedOffset: number, sync: boolean): Promise<void> {
122
122
  await mkdir(dirname(this.file), { recursive: true, mode: 0o700 })
123
- const handle = await open(this.file, 'a', 0o600)
123
+ const handle = await open(this.file, 'a+', 0o600)
124
124
  try {
125
125
  const before = (await handle.stat()).size
126
126
  if (before !== expectedOffset) {
@@ -1,4 +1,5 @@
1
1
  import type { ToolDiffHunk, ToolFacts, ToolFailureReason } from '../types/tool/presentation.js'
2
+ import { isEntityId } from '../utils/id.js'
2
3
 
3
4
  const FAILURE_REASONS: readonly ToolFailureReason[] = [
4
5
  'not_found',
@@ -130,6 +131,25 @@ function hunks(value: unknown): readonly ToolDiffHunk[] | undefined {
130
131
  export function admitToolFacts(value: unknown): ToolFacts | undefined {
131
132
  if (!isRecord(value)) return undefined
132
133
  switch (value.kind) {
134
+ case 'delegate': {
135
+ const id = value.childSessionId
136
+ const status = value.childStatus
137
+ return pick<ToolFacts>({
138
+ kind: 'delegate',
139
+ description: text(value.description)?.slice(0, 240),
140
+ childSessionId: isEntityId(id, 'session') ? id : undefined,
141
+ childStatus:
142
+ status === 'pending' ||
143
+ status === 'running' ||
144
+ status === 'completed' ||
145
+ status === 'failed' ||
146
+ status === 'canceled' ||
147
+ status === 'rejected' ||
148
+ status === 'input-required'
149
+ ? status
150
+ : undefined,
151
+ })
152
+ }
133
153
  case 'command':
134
154
  return pick<ToolFacts>({
135
155
  kind: 'command',
@@ -8,6 +8,7 @@ import { appendDirsToPath } from '../../plugin/bin-path.js'
8
8
  import { killTree } from '../../process/kill-tree.js'
9
9
  import { genericLabel } from '../../registry/tool/presentation.js'
10
10
  import { cancelCauseOf } from '../../types/session/cancel-cause.js'
11
+ import type { ToolProgressDetails } from '../../types/tool/index.js'
11
12
  import type { ToolFacts } from '../../types/tool/presentation.js'
12
13
  import { subscribeToAbort } from '../../utils/abort.js'
13
14
  import { readPositiveIntEnv } from '../../utils/env.js'
@@ -28,6 +29,7 @@ import { defineTool } from '../defineTool.js'
28
29
  import { scrubInheritedEnv, withheldEnvNoticeText } from '../env-scrub.js'
29
30
  import { withSafeGitConfig } from '../git-config-env.js'
30
31
  import { createHostOutputDecoder } from '../host-output.js'
32
+ import { ShellOutputWindow } from '../shell-output-window.js'
31
33
  import { looksBinary, windowText } from '../text-window.js'
32
34
  import {
33
35
  bashWorkingDirectoryForExecution,
@@ -260,25 +262,22 @@ function progressLine(value: string): string {
260
262
  }
261
263
 
262
264
  /**
263
- * One latest line per stream, independent of transport chunk boundaries.
265
+ * Recent output and the latest progress line, independent of transport chunk boundaries.
264
266
  * Reports stay synchronous: the executor owns coalescing and backpressure.
265
- * This projection adds neither an output log nor a queue of pending reports.
267
+ * Only the rolling window and the current partial lines are held.
266
268
  */
267
269
  function shellProgress(
268
- report?: (
269
- message: string,
270
- fraction?: number,
271
- details?: { readonly outputLines?: number },
272
- ) => void,
270
+ report?: (message: string, fraction?: number, details?: ToolProgressDetails) => void,
273
271
  ) {
274
272
  if (!report) return undefined
275
273
  const partial = { stdout: '', stderr: '' }
274
+ const window = new ShellOutputWindow()
276
275
  let lastMessage = ''
277
276
  // Lines of output so far, both streams: every line feed seen. Counted here, on
278
277
  // every chunk, because the reports below are coalesced and a viewer counting
279
278
  // the messages it received would undercount a fast command.
280
279
  let outputLines = 0
281
- let lastLines = 0
280
+
282
281
  return ({ stream, data }: { stream: 'stdout' | 'stderr'; data: string }): void => {
283
282
  let line = partial[stream]
284
283
  let latest = ''
@@ -294,11 +293,11 @@ function shellProgress(
294
293
  line = appendProgressTail(line, data, start, data.length)
295
294
  partial[stream] = line
296
295
  const message = progressLine(line) || latest
297
- if (!message || (message === lastMessage && outputLines === lastLines)) return
298
- lastMessage = message
299
- lastLines = outputLines
296
+ if (message) lastMessage = message
297
+ const output = window.append(stream, data)
298
+ if (!lastMessage) return
300
299
  try {
301
- report(message, undefined, { outputLines })
300
+ report(lastMessage, undefined, { outputLines, output })
302
301
  } catch {
303
302
  // A diagnostic observer cannot break the process output reader.
304
303
  }
@@ -725,7 +725,10 @@ function renderResult(host: BrowserHost, result: BrowserResult): ToolResult {
725
725
  else if (result.page && !result.screenshot) parts.push(formatBrowserPageHeader(result.page))
726
726
 
727
727
  const page = result.snapshot?.page ?? result.screenshot?.page ?? result.value?.page ?? result.page
728
- const data = page ? { page: { origin: headerOrigin(page), url: page.url, tab: page.tab } } : {}
728
+ const data = {
729
+ ...(page ? { page: { origin: headerOrigin(page), url: page.url, tab: page.tab } } : {}),
730
+ ...(result.paneFallback ? { paneFallback: result.paneFallback } : {}),
731
+ }
729
732
 
730
733
  if (result.screenshot) {
731
734
  const shot = result.screenshot
@@ -751,6 +754,14 @@ function renderResult(host: BrowserHost, result: BrowserResult): ToolResult {
751
754
  return { success: true, output: parts.join('\n') || 'Done.', data }
752
755
  }
753
756
 
757
+ function presentPaneFallback(_input: unknown, result: ToolResult) {
758
+ const fallback = (result.data as Pick<BrowserResult, 'paneFallback'> | undefined)?.paneFallback
759
+ if (fallback) {
760
+ return { kind: 'terminal' as const, output: result.output, paneFallback: fallback }
761
+ }
762
+ return undefined
763
+ }
764
+
754
765
  // ---------------------------------------------------------------------------
755
766
  // Host errors
756
767
  // ---------------------------------------------------------------------------
@@ -820,7 +831,7 @@ function hostErrorToResult(tool: string, error: BrowserHostError): ToolResult {
820
831
  )
821
832
  case 'browser_stale_ref':
822
833
  return refusal(
823
- `${tool}: element ${error.ref} is not on the page any more (it came from an older snapshot). Nothing was done. Take a new snapshot and use a ref from it.`,
834
+ `${tool}: element ${error.ref} no longer matches the older snapshot of this tab. Nothing was done. Take a new snapshot and use a ref from it.`,
824
835
  { code: error.code, ref: error.ref },
825
836
  )
826
837
  case 'browser_human_required': {
@@ -1053,7 +1064,7 @@ function actDescription(caps: BrowserCapabilities): string {
1053
1064
  return [
1054
1065
  "Changes the page in the web browser: click, type, fill_form, select, press, hover, upload, dialog (accept or dismiss a page alert, confirm or prompt; a prompt takes promptText, never a password or code). Act by ref from the latest snapshot of the browser tool. When an element has no ref (a menu that opens on hover, a control the snapshot leaves out), click and hover also take its visible text, or its role with its accessible name; they refuse and list the candidates when none or several match. A click or hover on a large container lands on the container's own text or its first control, not its middle.",
1055
1066
  'press takes a key; without ref it sends Escape, Enter, Tab, Shift+Tab, PageDown, PageUp, Home, End or Space to the focused element, and refuses when that is a password or code field. type can send real key presses (keys), keep the existing text (append) or clear first (clear).',
1056
- 'Every call must carry origin, copied from the snapshot header ("Page: <origin> — …"); if the page is no longer on that origin nothing is done. A stale ref is refused the same way: take a new snapshot.',
1067
+ 'Every call must carry origin, copied from the snapshot header ("Page: <origin> — …"); if the page is no longer on that origin nothing is done. A ref is refused if the tab or page changed, or if the ref no longer names the same role and accessible name. Take a new snapshot before trying again.',
1057
1068
  'Every result starts with "Effect:", what the action did to the page (lines that appeared or went, an address change, or "no visible change"). Read it before the next call: "no visible change" means nothing happened, so do not repeat the same call; look at the page or choose a different element. Set snapshot: true to get the whole page back after the action. Leave passwords and one-time codes to the person, because a model that holds a credential can be steered into leaking it; if the page needs a person, stop and tell the user.',
1058
1069
  'Example, filling two fields: {"action":"fill_form","origin":"https://example.com","fields":[{"ref":"e12","value":"<text>"},{"ref":"e14","value":"<text>"}]}.',
1059
1070
  ...unavailableLine(caps),
@@ -1197,6 +1208,7 @@ export function createBrowserTools(
1197
1208
  // A page is looked at to be acted on, and an action is read back by
1198
1209
  // looking: the two load in one search.
1199
1210
  loadsWith: [BROWSER_ACT_TOOL_NAME],
1211
+ presentResult: presentPaneFallback,
1200
1212
  presentCall: (input) => ({
1201
1213
  kind: 'generic',
1202
1214
  label: observeLabel(host, input),
@@ -1256,6 +1268,7 @@ export function createBrowserTools(
1256
1268
  concurrencySafe: false,
1257
1269
  pathArgument: 'path',
1258
1270
  loadsWith: [BROWSER_TOOL_NAME],
1271
+ presentResult: presentPaneFallback,
1259
1272
  presentCall: (input) => ({
1260
1273
  kind: 'generic',
1261
1274
  label: actLabel(host, input),
@@ -86,7 +86,12 @@ const findLiteralOp = z.object({
86
86
  .string()
87
87
  .optional()
88
88
  .describe('File or directory to search; defaults to the working directory.'),
89
- case_sensitive: z.boolean().optional().describe('Default true.'),
89
+ case_sensitive: z
90
+ .boolean()
91
+ .optional()
92
+ .describe(
93
+ 'Default true. False matches using Unicode simple case folding without locale tailoring.',
94
+ ),
90
95
  ...paging,
91
96
  })
92
97