@namzu/sdk 62.6.1 → 62.7.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 (291) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +5 -0
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/agents/examples/SupervisorAgent.d.ts.map +1 -1
  6. package/dist/agents/examples/SupervisorAgent.js +1 -0
  7. package/dist/agents/examples/SupervisorAgent.js.map +1 -1
  8. package/dist/agents/explore.d.ts.map +1 -1
  9. package/dist/agents/explore.js +2 -1
  10. package/dist/agents/explore.js.map +1 -1
  11. package/dist/compaction/index.d.ts +1 -1
  12. package/dist/compaction/index.d.ts.map +1 -1
  13. package/dist/compaction/index.js +1 -1
  14. package/dist/compaction/index.js.map +1 -1
  15. package/dist/compaction/model-summary.js +2 -2
  16. package/dist/compaction/model-summary.js.map +1 -1
  17. package/dist/compaction/summary.d.ts +16 -1
  18. package/dist/compaction/summary.d.ts.map +1 -1
  19. package/dist/compaction/summary.js +25 -2
  20. package/dist/compaction/summary.js.map +1 -1
  21. package/dist/config/runtime.d.ts +8 -0
  22. package/dist/config/runtime.d.ts.map +1 -1
  23. package/dist/config/runtime.js +15 -0
  24. package/dist/config/runtime.js.map +1 -1
  25. package/dist/execution/workflow/runtime.d.ts.map +1 -1
  26. package/dist/execution/workflow/runtime.js +3 -0
  27. package/dist/execution/workflow/runtime.js.map +1 -1
  28. package/dist/execution/workflow/types.d.ts +8 -0
  29. package/dist/execution/workflow/types.d.ts.map +1 -1
  30. package/dist/manager/agent/child-session.d.ts +12 -0
  31. package/dist/manager/agent/child-session.d.ts.map +1 -1
  32. package/dist/manager/agent/child-session.js +29 -0
  33. package/dist/manager/agent/child-session.js.map +1 -1
  34. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  35. package/dist/manager/agent/lifecycle.js +8 -0
  36. package/dist/manager/agent/lifecycle.js.map +1 -1
  37. package/dist/manager/session/turn-recorder.d.ts +13 -2
  38. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  39. package/dist/manager/session/turn-recorder.js +57 -3
  40. package/dist/manager/session/turn-recorder.js.map +1 -1
  41. package/dist/prompt/coding-agent-doctrine.d.ts +3 -3
  42. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  43. package/dist/prompt/coding-agent-doctrine.js +5 -3
  44. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  45. package/dist/provider/fallback.d.ts.map +1 -1
  46. package/dist/provider/fallback.js +5 -1
  47. package/dist/provider/fallback.js.map +1 -1
  48. package/dist/provider/retry.d.ts +25 -0
  49. package/dist/provider/retry.d.ts.map +1 -1
  50. package/dist/provider/retry.js +28 -0
  51. package/dist/provider/retry.js.map +1 -1
  52. package/dist/public-runtime.d.ts +3 -3
  53. package/dist/public-runtime.d.ts.map +1 -1
  54. package/dist/public-runtime.js +3 -3
  55. package/dist/public-runtime.js.map +1 -1
  56. package/dist/public-tools.d.ts +4 -2
  57. package/dist/public-tools.d.ts.map +1 -1
  58. package/dist/public-tools.js +5 -2
  59. package/dist/public-tools.js.map +1 -1
  60. package/dist/runtime/query/auto-review/classifier.d.ts +7 -1
  61. package/dist/runtime/query/auto-review/classifier.d.ts.map +1 -1
  62. package/dist/runtime/query/auto-review/classifier.js +8 -4
  63. package/dist/runtime/query/auto-review/classifier.js.map +1 -1
  64. package/dist/runtime/query/auto-review/prompt.d.ts.map +1 -1
  65. package/dist/runtime/query/auto-review/prompt.js +2 -0
  66. package/dist/runtime/query/auto-review/prompt.js.map +1 -1
  67. package/dist/runtime/query/auto-review/script-evidence.d.ts +93 -0
  68. package/dist/runtime/query/auto-review/script-evidence.d.ts.map +1 -0
  69. package/dist/runtime/query/auto-review/script-evidence.js +566 -0
  70. package/dist/runtime/query/auto-review/script-evidence.js.map +1 -0
  71. package/dist/runtime/query/checkpoint.d.ts +13 -0
  72. package/dist/runtime/query/checkpoint.d.ts.map +1 -1
  73. package/dist/runtime/query/checkpoint.js +37 -0
  74. package/dist/runtime/query/checkpoint.js.map +1 -1
  75. package/dist/runtime/query/executor.d.ts +38 -1
  76. package/dist/runtime/query/executor.d.ts.map +1 -1
  77. package/dist/runtime/query/executor.js +130 -11
  78. package/dist/runtime/query/executor.js.map +1 -1
  79. package/dist/runtime/query/finalize-turn.d.ts +7 -1
  80. package/dist/runtime/query/finalize-turn.d.ts.map +1 -1
  81. package/dist/runtime/query/finalize-turn.js +2 -0
  82. package/dist/runtime/query/finalize-turn.js.map +1 -1
  83. package/dist/runtime/query/index.d.ts +8 -0
  84. package/dist/runtime/query/index.d.ts.map +1 -1
  85. package/dist/runtime/query/index.js +7 -0
  86. package/dist/runtime/query/index.js.map +1 -1
  87. package/dist/runtime/query/iteration/index.d.ts +32 -1
  88. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  89. package/dist/runtime/query/iteration/index.js +158 -10
  90. package/dist/runtime/query/iteration/index.js.map +1 -1
  91. package/dist/runtime/query/iteration/phases/compaction.d.ts +12 -0
  92. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  93. package/dist/runtime/query/iteration/phases/compaction.js +48 -1
  94. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  95. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  96. package/dist/runtime/query/iteration/phases/context.js +5 -0
  97. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  98. package/dist/runtime/query/iteration/stream-turn.js +3 -3
  99. package/dist/runtime/query/iteration/stream-turn.js.map +1 -1
  100. package/dist/runtime/query/prelude-lease.d.ts.map +1 -1
  101. package/dist/runtime/query/prelude-lease.js +22 -0
  102. package/dist/runtime/query/prelude-lease.js.map +1 -1
  103. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  104. package/dist/runtime/query/prepare-turn.js +13 -4
  105. package/dist/runtime/query/prepare-turn.js.map +1 -1
  106. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  107. package/dist/runtime/query/review-policy.js +29 -0
  108. package/dist/runtime/query/review-policy.js.map +1 -1
  109. package/dist/runtime/query/tooling.d.ts +2 -0
  110. package/dist/runtime/query/tooling.d.ts.map +1 -1
  111. package/dist/runtime/query/tooling.js +1 -0
  112. package/dist/runtime/query/tooling.js.map +1 -1
  113. package/dist/runtime/query/turn/completion-audit.d.ts +27 -1
  114. package/dist/runtime/query/turn/completion-audit.d.ts.map +1 -1
  115. package/dist/runtime/query/turn/completion-audit.js +71 -6
  116. package/dist/runtime/query/turn/completion-audit.js.map +1 -1
  117. package/dist/runtime/query/turn/outcome-ledger.d.ts +113 -0
  118. package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -0
  119. package/dist/runtime/query/turn/outcome-ledger.js +578 -0
  120. package/dist/runtime/query/turn/outcome-ledger.js.map +1 -0
  121. package/dist/sandbox/glob-segment.d.ts +8 -1
  122. package/dist/sandbox/glob-segment.d.ts.map +1 -1
  123. package/dist/sandbox/glob-segment.js +28 -9
  124. package/dist/sandbox/glob-segment.js.map +1 -1
  125. package/dist/store/session-log/index.d.ts +1 -0
  126. package/dist/store/session-log/index.d.ts.map +1 -1
  127. package/dist/store/session-log/index.js +1 -0
  128. package/dist/store/session-log/index.js.map +1 -1
  129. package/dist/store/session-log/turn-outcome.d.ts +37 -0
  130. package/dist/store/session-log/turn-outcome.d.ts.map +1 -0
  131. package/dist/store/session-log/turn-outcome.js +77 -0
  132. package/dist/store/session-log/turn-outcome.js.map +1 -0
  133. package/dist/tools/builtins/bash.js +1 -1
  134. package/dist/tools/builtins/bash.js.map +1 -1
  135. package/dist/tools/builtins/edit-apply.d.ts.map +1 -1
  136. package/dist/tools/builtins/edit-apply.js +24 -3
  137. package/dist/tools/builtins/edit-apply.js.map +1 -1
  138. package/dist/tools/builtins/edit.d.ts +31 -17
  139. package/dist/tools/builtins/edit.d.ts.map +1 -1
  140. package/dist/tools/builtins/edit.js +92 -27
  141. package/dist/tools/builtins/edit.js.map +1 -1
  142. package/dist/tools/builtins/glob.js +1 -1
  143. package/dist/tools/builtins/glob.js.map +1 -1
  144. package/dist/tools/builtins/grep.js +1 -1
  145. package/dist/tools/builtins/grep.js.map +1 -1
  146. package/dist/tools/builtins/notebook-guard.d.ts +19 -0
  147. package/dist/tools/builtins/notebook-guard.d.ts.map +1 -0
  148. package/dist/tools/builtins/notebook-guard.js +75 -0
  149. package/dist/tools/builtins/notebook-guard.js.map +1 -0
  150. package/dist/tools/builtins/read-render.d.ts.map +1 -1
  151. package/dist/tools/builtins/read-render.js +8 -2
  152. package/dist/tools/builtins/read-render.js.map +1 -1
  153. package/dist/tools/builtins/write-file.d.ts.map +1 -1
  154. package/dist/tools/builtins/write-file.js +14 -1
  155. package/dist/tools/builtins/write-file.js.map +1 -1
  156. package/dist/tools/coordinator/agent.d.ts.map +1 -1
  157. package/dist/tools/coordinator/agent.js +25 -6
  158. package/dist/tools/coordinator/agent.js.map +1 -1
  159. package/dist/tools/coordinator/index.d.ts.map +1 -1
  160. package/dist/tools/coordinator/index.js +6 -1
  161. package/dist/tools/coordinator/index.js.map +1 -1
  162. package/dist/tools/coordinator/outcome-record.d.ts +22 -0
  163. package/dist/tools/coordinator/outcome-record.d.ts.map +1 -0
  164. package/dist/tools/coordinator/outcome-record.js +91 -0
  165. package/dist/tools/coordinator/outcome-record.js.map +1 -0
  166. package/dist/tools/defineTool.d.ts +2 -0
  167. package/dist/tools/defineTool.d.ts.map +1 -1
  168. package/dist/tools/defineTool.js +1 -0
  169. package/dist/tools/defineTool.js.map +1 -1
  170. package/dist/tools/file-read-tracker.d.ts +23 -2
  171. package/dist/tools/file-read-tracker.d.ts.map +1 -1
  172. package/dist/tools/file-read-tracker.js +37 -2
  173. package/dist/tools/file-read-tracker.js.map +1 -1
  174. package/dist/tools/untrusted-envelope.d.ts +6 -0
  175. package/dist/tools/untrusted-envelope.d.ts.map +1 -1
  176. package/dist/tools/untrusted-envelope.js +22 -1
  177. package/dist/tools/untrusted-envelope.js.map +1 -1
  178. package/dist/toolsets/manager.d.ts.map +1 -1
  179. package/dist/toolsets/manager.js +3 -4
  180. package/dist/toolsets/manager.js.map +1 -1
  181. package/dist/toolsets/validation-issues.d.ts +27 -0
  182. package/dist/toolsets/validation-issues.d.ts.map +1 -0
  183. package/dist/toolsets/validation-issues.js +83 -0
  184. package/dist/toolsets/validation-issues.js.map +1 -0
  185. package/dist/turn/memory-recall.d.ts +13 -0
  186. package/dist/turn/memory-recall.d.ts.map +1 -1
  187. package/dist/turn/memory-recall.js +18 -0
  188. package/dist/turn/memory-recall.js.map +1 -1
  189. package/dist/types/agent/base.d.ts +19 -0
  190. package/dist/types/agent/base.d.ts.map +1 -1
  191. package/dist/types/agent/query.d.ts +2 -0
  192. package/dist/types/agent/query.d.ts.map +1 -1
  193. package/dist/types/common/index.d.ts +17 -0
  194. package/dist/types/common/index.d.ts.map +1 -1
  195. package/dist/types/common/index.js +8 -1
  196. package/dist/types/common/index.js.map +1 -1
  197. package/dist/types/hitl/index.d.ts +22 -0
  198. package/dist/types/hitl/index.d.ts.map +1 -1
  199. package/dist/types/hitl/index.js.map +1 -1
  200. package/dist/types/session/config.d.ts +20 -0
  201. package/dist/types/session/config.d.ts.map +1 -1
  202. package/dist/types/session/events.d.ts +3 -3
  203. package/dist/types/session/events.d.ts.map +1 -1
  204. package/dist/types/session/index.d.ts +1 -0
  205. package/dist/types/session/index.d.ts.map +1 -1
  206. package/dist/types/session/index.js +1 -0
  207. package/dist/types/session/index.js.map +1 -1
  208. package/dist/types/session/outcome.d.ts +95 -0
  209. package/dist/types/session/outcome.d.ts.map +1 -0
  210. package/dist/types/session/outcome.js +45 -0
  211. package/dist/types/session/outcome.js.map +1 -0
  212. package/dist/types/session/prepare-step.d.ts +2 -0
  213. package/dist/types/session/prepare-step.d.ts.map +1 -1
  214. package/dist/types/session/records.d.ts +167 -2
  215. package/dist/types/session/records.d.ts.map +1 -1
  216. package/dist/types/session/records.js +42 -0
  217. package/dist/types/session/records.js.map +1 -1
  218. package/dist/types/session/turn.d.ts +18 -0
  219. package/dist/types/session/turn.d.ts.map +1 -1
  220. package/dist/types/session/turn.js.map +1 -1
  221. package/dist/types/tool/index.d.ts +30 -0
  222. package/dist/types/tool/index.d.ts.map +1 -1
  223. package/dist/types/tool/index.js.map +1 -1
  224. package/package.json +1 -1
  225. package/src/agents/QueryAgent.ts +5 -0
  226. package/src/agents/examples/SupervisorAgent.ts +1 -0
  227. package/src/agents/explore.ts +2 -1
  228. package/src/compaction/index.ts +1 -0
  229. package/src/compaction/model-summary.ts +2 -2
  230. package/src/compaction/summary.ts +30 -2
  231. package/src/config/runtime.ts +15 -0
  232. package/src/execution/workflow/runtime.ts +4 -0
  233. package/src/execution/workflow/types.ts +9 -0
  234. package/src/manager/agent/child-session.ts +36 -0
  235. package/src/manager/agent/lifecycle.ts +9 -0
  236. package/src/manager/session/turn-recorder.ts +62 -3
  237. package/src/pricing/rates.source.json +1 -1
  238. package/src/prompt/coding-agent-doctrine.ts +5 -3
  239. package/src/provider/fallback.ts +6 -1
  240. package/src/provider/retry.ts +51 -0
  241. package/src/public-runtime.ts +10 -1
  242. package/src/public-tools.ts +6 -1
  243. package/src/runtime/query/auto-review/classifier.ts +21 -5
  244. package/src/runtime/query/auto-review/prompt.ts +2 -0
  245. package/src/runtime/query/auto-review/script-evidence.ts +618 -0
  246. package/src/runtime/query/checkpoint.ts +53 -1
  247. package/src/runtime/query/executor.ts +159 -19
  248. package/src/runtime/query/finalize-turn.ts +8 -1
  249. package/src/runtime/query/index.ts +19 -0
  250. package/src/runtime/query/iteration/index.ts +167 -14
  251. package/src/runtime/query/iteration/phases/compaction.ts +53 -3
  252. package/src/runtime/query/iteration/phases/context.ts +6 -0
  253. package/src/runtime/query/iteration/stream-turn.ts +3 -3
  254. package/src/runtime/query/prelude-lease.ts +19 -0
  255. package/src/runtime/query/prepare-turn.ts +13 -4
  256. package/src/runtime/query/review-policy.ts +33 -0
  257. package/src/runtime/query/tooling.ts +3 -0
  258. package/src/runtime/query/turn/completion-audit.ts +76 -5
  259. package/src/runtime/query/turn/outcome-ledger.ts +633 -0
  260. package/src/sandbox/glob-segment.ts +48 -24
  261. package/src/store/session-log/index.ts +7 -0
  262. package/src/store/session-log/turn-outcome.ts +84 -0
  263. package/src/tools/builtins/bash.ts +1 -1
  264. package/src/tools/builtins/edit-apply.ts +26 -4
  265. package/src/tools/builtins/edit.ts +106 -41
  266. package/src/tools/builtins/glob.ts +1 -1
  267. package/src/tools/builtins/grep.ts +1 -1
  268. package/src/tools/builtins/notebook-guard.ts +76 -0
  269. package/src/tools/builtins/read-render.ts +12 -2
  270. package/src/tools/builtins/write-file.ts +12 -1
  271. package/src/tools/coordinator/agent.ts +31 -7
  272. package/src/tools/coordinator/index.ts +6 -1
  273. package/src/tools/coordinator/outcome-record.ts +93 -0
  274. package/src/tools/defineTool.ts +3 -0
  275. package/src/tools/file-read-tracker.ts +51 -2
  276. package/src/tools/untrusted-envelope.ts +23 -1
  277. package/src/toolsets/manager.ts +6 -10
  278. package/src/toolsets/validation-issues.ts +97 -0
  279. package/src/turn/memory-recall.ts +28 -0
  280. package/src/types/agent/base.ts +20 -0
  281. package/src/types/agent/query.ts +2 -0
  282. package/src/types/common/index.ts +25 -1
  283. package/src/types/hitl/index.ts +27 -0
  284. package/src/types/session/config.ts +20 -0
  285. package/src/types/session/events.ts +3 -3
  286. package/src/types/session/index.ts +1 -0
  287. package/src/types/session/outcome.ts +139 -0
  288. package/src/types/session/prepare-step.ts +2 -0
  289. package/src/types/session/records.ts +67 -1
  290. package/src/types/session/turn.ts +19 -0
  291. package/src/types/tool/index.ts +30 -0
@@ -7,22 +7,24 @@
7
7
  */
8
8
 
9
9
  // Written for the `u` flag, which every compiled expression carries.
10
- const POSIX_CLASSES: Record<string, string> = {
11
- alnum: '\\p{L}\\p{Nl}\\p{Nd}',
12
- alpha: '\\p{L}\\p{Nl}',
13
- ascii: '\\x00-\\x7f',
14
- blank: '\\p{Zs}\\t',
15
- cntrl: '\\p{Cc}',
16
- digit: '\\p{Nd}',
17
- graph: '\\x21-\\x7e',
18
- lower: '\\p{Ll}',
19
- print: '\\x20-\\x7e',
20
- punct: '\\p{P}\\p{S}',
21
- space: '\\s',
22
- upper: '\\p{Lu}',
23
- word: '\\p{L}\\p{Nl}\\p{Nd}_',
24
- xdigit: '0-9a-fA-F',
25
- }
10
+ const POSIX_CLASSES: ReadonlyMap<string, string> = new Map(
11
+ Object.entries({
12
+ alnum: '\\p{L}\\p{Nl}\\p{Nd}',
13
+ alpha: '\\p{L}\\p{Nl}',
14
+ ascii: '\\x00-\\x7f',
15
+ blank: '\\p{Zs}\\t',
16
+ cntrl: '\\p{Cc}',
17
+ digit: '\\p{Nd}',
18
+ graph: '\\x21-\\x7e',
19
+ lower: '\\p{Ll}',
20
+ print: '\\x20-\\x7e',
21
+ punct: '\\p{P}\\p{S}',
22
+ space: '\\s',
23
+ upper: '\\p{Lu}',
24
+ word: '\\p{L}\\p{Nl}\\p{Nd}_',
25
+ xdigit: '0-9a-fA-F',
26
+ }),
27
+ )
26
28
 
27
29
  export interface CompiledSegment {
28
30
  /** Set when the segment has no magic: the exact name it matches. */
@@ -31,6 +33,23 @@ export interface CompiledSegment {
31
33
  source: string
32
34
  }
33
35
 
36
+ /**
37
+ * The longest segment, in UTF-16 code units, that `compileSegment` accepts. A
38
+ * file name is at most 255 bytes on the file systems Namzu runs on, so a
39
+ * pattern for one name beyond four times that is never legitimate, while
40
+ * compiling a segment costs time in proportion to the square of its length.
41
+ */
42
+ export const MAX_GLOB_SEGMENT_LENGTH = 1024
43
+
44
+ /** How much of an over-long pattern an error message shows, in code points. */
45
+ const PREVIEW_LENGTH = 60
46
+
47
+ /** The first `PREVIEW_LENGTH` code points of `text`, never cutting a surrogate pair. */
48
+ const preview = (text: string) =>
49
+ Array.from(text.slice(0, PREVIEW_LENGTH * 2))
50
+ .slice(0, PREVIEW_LENGTH)
51
+ .join('')
52
+
34
53
  /**
35
54
  * Raised for a segment that repeats a group (`*( )` or `+( )`) which could match
36
55
  * the same text more than one way. Such a group backtracks exponentially on a
@@ -38,14 +57,17 @@ export interface CompiledSegment {
38
57
  */
39
58
  export class GlobTooComplexError extends Error {
40
59
  readonly segment: string
41
- constructor(segment: string, reason: 'ambiguous' | 'stretch' = 'ambiguous') {
60
+ constructor(segment: string, reason: 'ambiguous' | 'stretch' | 'length' = 'ambiguous') {
42
61
  super(
43
- reason === 'stretch'
44
- ? `The pattern '${segment}' has more than three wildcards that can stretch; split it across folders or use fewer *.`
45
- : `The pattern '${segment}' repeats a group that can match the same text more than one way; use ** or {a,b} instead.`,
62
+ reason === 'length'
63
+ ? `The pattern '${preview(segment)}...' is too long (${segment.length} characters; at most ${MAX_GLOB_SEGMENT_LENGTH} between slashes); shorten it or split it across folders.`
64
+ : reason === 'stretch'
65
+ ? `The pattern '${segment}' has more than three wildcards that can stretch; split it across folders or use fewer *.`
66
+ : `The pattern '${segment}' repeats a group that can match the same text more than one way; use ** or {a,b} instead.`,
46
67
  )
47
68
  this.name = 'GlobTooComplexError'
48
- this.segment = segment
69
+ // An over-long pattern is not kept whole: the error may be logged.
70
+ this.segment = reason === 'length' ? preview(segment) : segment
49
71
  }
50
72
  }
51
73
 
@@ -85,7 +107,7 @@ function classEnd(text: string, start: number): number {
85
107
  if (ch === '\\') index += 1
86
108
  else if (ch === '[' && text[index + 1] === ':') {
87
109
  const end = text.indexOf(':]', index + 2)
88
- if (end > 0 && POSIX_CLASSES[text.slice(index + 2, end)]) index = end + 1
110
+ if (end > 0 && POSIX_CLASSES.has(text.slice(index + 2, end))) index = end + 1
89
111
  } else if (ch === ']') return index
90
112
  }
91
113
  return -1
@@ -134,8 +156,9 @@ function classSource(body: string): string {
134
156
  if (ch === '[' && body[index + 1] === ':') {
135
157
  const end = body.indexOf(':]', index + 2)
136
158
  const name = end > 0 ? body.slice(index + 2, end) : ''
137
- if (POSIX_CLASSES[name]) {
138
- out += POSIX_CLASSES[name]
159
+ const members = POSIX_CLASSES.get(name)
160
+ if (members !== undefined) {
161
+ out += members
139
162
  index = end + 1
140
163
  continue
141
164
  }
@@ -268,6 +291,7 @@ function isOneGroup(text: string): boolean {
268
291
  * segment that itself begins with a literal `.` can.
269
292
  */
270
293
  export function compileSegment(segment: string, dot: boolean): CompiledSegment {
294
+ if (segment.length > MAX_GLOB_SEGMENT_LENGTH) throw new GlobTooComplexError(segment, 'length')
271
295
  const guard = dot ? '' : '(?!\\.)'
272
296
  let parsed: Parsed
273
297
  try {
@@ -61,6 +61,13 @@ export {
61
61
  withMessageId,
62
62
  } from './fold.js'
63
63
  export { type TornTailRepair, repairRecordDraft } from './heal.js'
64
+ export {
65
+ foldChildOutcomes,
66
+ foldTurnOutcomes,
67
+ parseTurnOutcome,
68
+ readOutcomeProgress,
69
+ readTurnOutcome,
70
+ } from './turn-outcome.js'
64
71
  export {
65
72
  type ReleaseHeldSessionLeasesOptions,
66
73
  type ReleaseHeldSessionLeasesResult,
@@ -0,0 +1,84 @@
1
+ import type { CheckpointId, SessionId, TurnId } from '../../types/ids/index.js'
2
+ import { type TurnOutcome, TurnOutcomeSchema } from '../../types/session/outcome.js'
3
+ import type { SessionRecord } from '../../types/session/records.js'
4
+ import type { SessionLog } from './core.js'
5
+
6
+ /**
7
+ * Reading the turn's outcome record back out of the session log.
8
+ *
9
+ * It lives in three records of its own (`turn_outcome_recorded`,
10
+ * `child_outcome_recorded`, `outcome_progress_written`), each flagged
11
+ * `ignorable`, and never in a field of an older record: a release that
12
+ * validates `turn_completed`, `child_session_ended` or the checkpoint strictly
13
+ * reads a log that has them and loses only the outcome. The fold of messages
14
+ * does not look at them. A body that does not parse as a `TurnOutcome` reads
15
+ * as no outcome, never as a guess.
16
+ */
17
+
18
+ /** `value` as a {@link TurnOutcome}, or `undefined` when it is not one. */
19
+ export function parseTurnOutcome(value: unknown): TurnOutcome | undefined {
20
+ const parsed = TurnOutcomeSchema.safeParse(value)
21
+ return parsed.success ? parsed.data : undefined
22
+ }
23
+
24
+ /**
25
+ * The outcome of each turn that recorded one, from records in log order. A
26
+ * turn that recorded none is absent, so a caller never reads `unchanged` into
27
+ * a turn nobody measured.
28
+ */
29
+ export function foldTurnOutcomes(records: Iterable<SessionRecord>): Map<TurnId, TurnOutcome> {
30
+ const outcomes = new Map<TurnId, TurnOutcome>()
31
+ for (const record of records) {
32
+ if (record.type !== 'turn_outcome_recorded') continue
33
+ const outcome = parseTurnOutcome(record.outcome)
34
+ if (outcome) outcomes.set(record.turnId, outcome)
35
+ else outcomes.delete(record.turnId)
36
+ }
37
+ return outcomes
38
+ }
39
+
40
+ /** The outcome `turnId` recorded, or `undefined`. */
41
+ export async function readTurnOutcome(
42
+ log: SessionLog,
43
+ turnId: TurnId,
44
+ ): Promise<TurnOutcome | undefined> {
45
+ let found: TurnOutcome | undefined
46
+ for await (const { record } of log.read({ mode: 'tolerant' })) {
47
+ if (record.type !== 'turn_outcome_recorded' || record.turnId !== turnId) continue
48
+ found = parseTurnOutcome(record.outcome)
49
+ }
50
+ return found
51
+ }
52
+
53
+ /**
54
+ * The outcome a child's settled turn recorded in the parent's log, by child
55
+ * session id. A child with no record is absent.
56
+ */
57
+ export function foldChildOutcomes(records: Iterable<SessionRecord>): Map<SessionId, TurnOutcome> {
58
+ const outcomes = new Map<SessionId, TurnOutcome>()
59
+ for (const record of records) {
60
+ if (record.type !== 'child_outcome_recorded') continue
61
+ const outcome = parseTurnOutcome(record.outcome)
62
+ if (outcome) outcomes.set(record.childSessionId, outcome)
63
+ else outcomes.delete(record.childSessionId)
64
+ }
65
+ return outcomes
66
+ }
67
+
68
+ /**
69
+ * What the outcome record had gathered when `checkpointId` was written, or
70
+ * `undefined` when no progress record names it (a checkpoint written before
71
+ * the record existed, or by a release that does not write it).
72
+ */
73
+ export async function readOutcomeProgress(
74
+ log: SessionLog,
75
+ checkpointId: CheckpointId,
76
+ ): Promise<Readonly<Record<string, unknown>> | undefined> {
77
+ let found: Readonly<Record<string, unknown>> | undefined
78
+ for await (const { record } of log.read({ mode: 'tolerant' })) {
79
+ if (record.type === 'outcome_progress_written' && record.checkpointId === checkpointId) {
80
+ found = record.progress
81
+ }
82
+ }
83
+ return found
84
+ }
@@ -537,7 +537,7 @@ export const SANDBOX_ESCAPE_NOT_APPROVED =
537
537
  'dangerously_disable_sandbox was not approved for this call, so the command did not run. Leaving the sandbox needs the user to confirm it each time, and this turn either cannot ask or does not allow it. Run the command inside the sandbox, or tell the user what it needs and let them run it.'
538
538
 
539
539
  const BASH_DESCRIPTION =
540
- 'Executes a command line using the execution shell disclosed in the system context and returns stdout/stderr output. The working directory persists between calls, but shell state does not. Command timeout is configurable. The `command` parameter is required, so every call carries one. Long file content goes through `write`, not a heredoc, so it cannot hit the output token limit mid-stream.'
540
+ 'Executes a command line using the execution shell disclosed in the system context and returns stdout/stderr output. The working directory persists between calls, but shell state does not. Command timeout is configurable. Read and search with `read`, `grep` and `glob`, not shell loops: a file read through the shell earns no read credit, so its next edit is refused once. Run a check on its own, not piped: its output is already trimmed, and a pipe hides the exit status.'
541
541
 
542
542
  const BashToolBase = defineTool({
543
543
  name: 'bash',
@@ -40,7 +40,7 @@ export type NormalizedEditInput =
40
40
  export function normalizeEditInput(
41
41
  input: EditInput,
42
42
  ): { success: true; operations: NormalizedEditInput[] } | { success: false; error: string } {
43
- if (input.edits !== undefined) {
43
+ if (input.edits !== undefined && input.edits.length > 0) {
44
44
  return {
45
45
  success: true,
46
46
  operations: input.edits.map((edit) => ({
@@ -197,11 +197,15 @@ function applyOne(
197
197
  if (!content.includes(oldString)) {
198
198
  const resolved = resolveOldString(content, oldString)
199
199
  if (resolved === null) {
200
+ const near = nearLine(content, oldString)
200
201
  return {
201
202
  success: false,
202
203
  reason: 'text_not_found',
203
- error:
204
- 'old_string/oldStr not found in file. Make sure the string matches exactly, including whitespace and indentation.',
204
+ error: `old_string/oldStr not found in file. Make sure the string matches exactly, including whitespace and indentation. ${
205
+ near === undefined
206
+ ? 'Read the lines you mean to change again and copy them as they are.'
207
+ : `A line that matches its first line apart from spacing is at line ${near}; read around it again and copy it as it is.`
208
+ }`,
205
209
  }
206
210
  }
207
211
  newString = reconcileNewString(oldString, resolved, newString)
@@ -235,7 +239,7 @@ function applyOne(
235
239
  return {
236
240
  success: false,
237
241
  reason: 'not_unique',
238
- error: `old_string/oldStr is not unique — found at lines ${lineNumber} and ${secondLine}. Provide more surrounding context to make it unique, or use replace_all: true.`,
242
+ error: `old_string/oldStr is not unique — found at lines ${lineNumber} and ${secondLine}. Provide more surrounding context to make it unique, or use replace_all: true. Read around those lines again to choose context that is only in one of them.`,
239
243
  }
240
244
  }
241
245
 
@@ -247,6 +251,24 @@ function applyOne(
247
251
  }
248
252
  }
249
253
 
254
+ const NEAR_LINE_MIN_CHARS = 8
255
+
256
+ /** The line of `content` that matches the first non-blank line of `needle` apart from spacing, 1-based. */
257
+ function nearLine(content: string, needle: string): number | undefined {
258
+ const squash = (text: string) => text.replace(/\s+/g, ' ').trim()
259
+ const first = needle
260
+ .split('\n')
261
+ .map(squash)
262
+ .find((line) => line !== '')
263
+ // A bare brace or paren is on many lines; naming the first one would point at the wrong place.
264
+ if (first === undefined || first.length < NEAR_LINE_MIN_CHARS) return undefined
265
+ const lines = content.split('\n')
266
+ for (let i = 0; i < lines.length; i++) {
267
+ if (squash(lines[i] ?? '') === first) return i + 1
268
+ }
269
+ return undefined
270
+ }
271
+
250
272
  function applyLineInsert(
251
273
  content: string,
252
274
  input: Extract<NormalizedEditInput, { operation: 'insert' }>,
@@ -22,8 +22,91 @@ import {
22
22
  import { withFileMutationLock } from './file-mutation-lock.js'
23
23
  import { jsonStringEscapes } from './json-string-hint.js'
24
24
  import { lineDiff } from './line-diff.js'
25
+ import { notebookRefusal } from './notebook-guard.js'
25
26
  import { staleBeforeReview } from './stale-before-review.js'
26
27
 
28
+ type RawEditInput = {
29
+ path: string
30
+ old_string?: string
31
+ oldStr?: string
32
+ new_string?: string
33
+ newStr?: string
34
+ insertLine?: number | string
35
+ replace_all?: boolean
36
+ edits?: { old_string: string; new_string: string; replace_all?: boolean }[]
37
+ }
38
+
39
+ const ONE_SHAPE_EACH =
40
+ 'Single edit: {"path":"file.md","old_string":"exact unique text","new_string":"replacement text"}\nSeveral edits: {"path":"file.md","edits":[{"old_string":"a","new_string":"b"},{"old_string":"c","new_string":"d"}]}'
41
+
42
+ const hasTopLevelEdit = (value: RawEditInput): boolean =>
43
+ value.old_string !== undefined ||
44
+ value.oldStr !== undefined ||
45
+ value.new_string !== undefined ||
46
+ value.newStr !== undefined ||
47
+ value.insertLine !== undefined
48
+
49
+ /**
50
+ * A top-level edit that is exactly the one entry of a one-entry batch: the same
51
+ * call said twice, not two intentions. Anything else (a different text, a
52
+ * longer list, an insertion) is a real conflict and stays refused.
53
+ */
54
+ function restatesTheBatch(value: RawEditInput): boolean {
55
+ const entries = value.edits
56
+ if (entries === undefined || entries.length !== 1 || value.insertLine !== undefined) return false
57
+ const [entry] = entries
58
+ return (
59
+ entry !== undefined &&
60
+ (value.old_string ?? value.oldStr) === entry.old_string &&
61
+ (value.new_string ?? value.newStr) === entry.new_string &&
62
+ (value.replace_all ?? false) === (entry.replace_all ?? false)
63
+ )
64
+ }
65
+
66
+ /**
67
+ * Which of the two shapes this call is, and what to say when it is neither.
68
+ *
69
+ * An empty `edits` beside a top-level edit, and a one-entry `edits` that restates
70
+ * the top-level edit, are the single edit: the intent is not in doubt and nothing
71
+ * is dropped. A batch beside a DIFFERENT top-level edit stays refused, because
72
+ * any precedence would silently drop an edit somebody believes was made.
73
+ */
74
+ function checkEditShape(value: RawEditInput): string | undefined {
75
+ const batch = value.edits !== undefined && value.edits.length > 0
76
+ const top = hasTopLevelEdit(value)
77
+ if (value.edits !== undefined && !batch && !top) {
78
+ return `\`edits\` is an empty list, so there is nothing to change. Send exactly one of these, and leave out the field you are not using:\n${ONE_SHAPE_EACH}`
79
+ }
80
+ if (batch && top && !restatesTheBatch(value)) {
81
+ return `This call has both an \`edits\` list and a different top-level edit, and only one can be applied. Send exactly one of these, and leave out the field you are not using:\n${ONE_SHAPE_EACH}`
82
+ }
83
+ if (batch) return undefined
84
+ if (typeof value.new_string !== 'string' && typeof value.newStr !== 'string') {
85
+ return 'Either new_string or newStr is required.'
86
+ }
87
+ if (
88
+ value.insertLine === undefined &&
89
+ typeof value.old_string !== 'string' &&
90
+ typeof value.oldStr !== 'string'
91
+ ) {
92
+ return 'Either old_string/oldStr or insertLine is required.'
93
+ }
94
+ return undefined
95
+ }
96
+
97
+ /**
98
+ * The input every later stage sees: one shape, with the redundant half gone. The
99
+ * review card, the classifier, the dry run and the apply step all read this, so
100
+ * none of them meets `edits: []` or a restated edit.
101
+ */
102
+ function canonicalEditInput(value: RawEditInput): RawEditInput {
103
+ if (value.edits === undefined) return value
104
+ const { edits, ...rest } = value
105
+ if (edits.length === 0) return rest
106
+ const { old_string, oldStr, new_string, newStr, insertLine, ...kept } = rest
107
+ return { ...kept, edits }
108
+ }
109
+
27
110
  /**
28
111
  * Two schemas, on purpose.
29
112
  *
@@ -106,48 +189,23 @@ const inputSchema = z
106
189
  })
107
190
  .strict(),
108
191
  )
109
- .min(1)
192
+ // No `.min(1)`: a model that fills every optional field of a flat object
193
+ // sends `edits: []` next to a single top-level edit, and that is the
194
+ // single edit, not an error. An empty list with nothing beside it is
195
+ // refused by `checkEditShape` below, in a sentence that says what to send.
110
196
  .optional()
111
197
  .describe(
112
- 'Several replacements in one file, applied in order and committed together. Nothing is written unless every one applies.',
198
+ 'Several replacements in one file, applied in order and committed together. Nothing is written unless every one applies. Leave out when sending a single old_string/new_string.',
113
199
  ),
114
200
  })
115
201
  .strict()
116
- .refine(
117
- (value) =>
118
- value.edits !== undefined ||
119
- typeof value.new_string === 'string' ||
120
- typeof value.newStr === 'string',
121
- { message: 'Either new_string or newStr is required.' },
122
- )
123
- .refine(
124
- (value) =>
125
- value.edits !== undefined ||
126
- value.insertLine !== undefined ||
127
- typeof value.old_string === 'string' ||
128
- typeof value.oldStr === 'string',
129
- { message: 'Either old_string/oldStr or insertLine is required.' },
130
- )
131
- // Refused rather than resolved. A call carrying both an `edits` list and a
132
- // top-level replacement is two different intentions in one object, and any
133
- // precedence this code picked would be a guess about which the model meant
134
- // — silently dropping the other. There is no reading of that which is safe:
135
- // the dropped half is an edit somebody believes was made.
136
- .refine(
137
- (value) =>
138
- value.edits === undefined ||
139
- (value.old_string === undefined &&
140
- value.oldStr === undefined &&
141
- value.new_string === undefined &&
142
- value.newStr === undefined &&
143
- value.insertLine === undefined),
144
- {
145
- message:
146
- 'Use either `edits` or a single top-level edit, not both. Move the top-level old_string/new_string into the edits list.',
147
- },
148
- )
202
+ .superRefine((value, ctx) => {
203
+ const problem = checkEditShape(value)
204
+ if (problem) ctx.addIssue({ code: 'custom', message: problem })
205
+ })
206
+ .transform(canonicalEditInput)
149
207
 
150
- export type EditInput = z.infer<typeof inputSchema>
208
+ export type EditInput = z.output<typeof inputSchema>
151
209
 
152
210
  /**
153
211
  * What an `edit` call WOULD produce for a file body, without touching any file.
@@ -184,7 +242,10 @@ export function dryRunEdit(
184
242
  }
185
243
  }
186
244
  const result = applyEdit(content, normalized.operations)
187
- return result.success ? { success: true, content: result.content } : result
245
+ if (!result.success) return result
246
+ const notebook = notebookRefusal(parsed.data.path, result.content, content)
247
+ if (notebook) return { success: false, error: notebook }
248
+ return { success: true, content: result.content }
188
249
  }
189
250
 
190
251
  /**
@@ -205,7 +266,7 @@ const modelInputSchema: Record<string, unknown> = {
205
266
  old_string: {
206
267
  type: 'string',
207
268
  description:
208
- 'Exact unique text from the file, without read-tool line-number prefixes. Must not be empty.',
269
+ 'For a single change: exact unique text from the file, without read-tool line-number prefixes. Must not be empty. Do not send together with edits.',
209
270
  },
210
271
  new_string: {
211
272
  type: 'string',
@@ -282,7 +343,7 @@ const modelInputSchema: Record<string, unknown> = {
282
343
  additionalProperties: false,
283
344
  },
284
345
  description:
285
- 'Several replacements in one file, applied in order and committed together. Nothing is written unless every one applies. Use this instead of several edit calls when the changes only make sense together.',
346
+ 'For SEVERAL changes to one file: a non-empty list, applied in order and committed together. Nothing is written unless every one applies. Leave this field out entirely when you send old_string/new_string; never send an empty list.',
286
347
  },
287
348
  },
288
349
  // `old_string` is deliberately NOT required, and this is the fix.
@@ -437,7 +498,7 @@ function refusedEdit(result: EditApplyFailure, path: string) {
437
498
  export const EditTool = defineTool({
438
499
  name: 'edit',
439
500
  description:
440
- 'Makes targeted edits to a file using exact string find-and-replace or line insertion. To change an existing file, use `edit`: `write` overwrites the whole body and discards earlier work on partial failure, while `edit` keeps the rest of the file byte-for-byte intact and is recoverable: if a single edit fails (old_string/oldStr ambiguous, broader restructuring needed), follow up with another `edit` instead of re-emitting the entire file via `write`. The old_string/oldStr must be unique in the file unless replace_all is true. For insertions, pass insertLine plus new_string/newStr; use insertLine: "end" to extend a file at the end. Keep new_string/newStr under 12000 characters, because a longer payload can be cut off mid-call and fail; use repeated bounded edits for long sections. Preserves file formatting and indentation. To make several changes to one file that only make sense together, send them as `edits`: a list of {old_string, new_string} applied in order and committed as one write — if any of them does not apply, nothing is written and the reply names which one, so the file is never left half-changed.',
501
+ 'Makes targeted edits to a file using exact string find-and-replace or line insertion. To change an existing file, use `edit`: `write` overwrites the whole body and discards earlier work on partial failure, while `edit` keeps the rest of the file byte-for-byte intact and is recoverable: if a single edit fails (old_string/oldStr ambiguous, broader restructuring needed), follow up with another `edit` instead of re-emitting the entire file via `write`. The old_string/oldStr must be unique in the file unless replace_all is true. For insertions, pass insertLine plus new_string/newStr; use insertLine: "end" to extend a file at the end. Keep new_string/newStr under 12000 characters, because a longer payload can be cut off mid-call and fail; use repeated bounded edits for long sections. Preserves file formatting and indentation. To make several changes to one file that only make sense together, send them as `edits` (and then no top-level old_string/new_string; for a single change leave `edits` out): a list of {old_string, new_string} applied in order and committed as one write — if any of them does not apply, nothing is written and the reply names which one, so the file is never left half-changed. An edit that would leave a `.ipynb` file as invalid notebook JSON is refused and the file is unchanged.',
441
502
  inputSchema,
442
503
  modelInputSchema,
443
504
  enforceModelInput: true,
@@ -458,7 +519,7 @@ export const EditTool = defineTool({
458
519
  refuseBeforeReview: (input: EditInput, context) => staleBeforeReview(context, input.path, 'edit'),
459
520
  // The classifier judges which file changes and in what way, in a line.
460
521
  classifierInput: (input: EditInput) => {
461
- if (input.edits !== undefined) {
522
+ if (input.edits !== undefined && input.edits.length > 0) {
462
523
  const shown = input.edits.slice(0, 5).map((e) => describeChange(e.old_string, e.new_string))
463
524
  const more =
464
525
  input.edits.length > shown.length ? `; ${input.edits.length - shown.length} more` : ''
@@ -570,6 +631,8 @@ export const EditTool = defineTool({
570
631
  if (!admitted.success) return admitted
571
632
  const result = admitted.result
572
633
  if (!result.success) return refusedEdit(result, parsed.data.path)
634
+ const notebook = notebookRefusal(parsed.data.path, result.content, content)
635
+ if (notebook) return { success: false as const, output: '', error: notebook }
573
636
 
574
637
  await context.sandbox.writeFile(parsed.data.path, result.content)
575
638
  recordEditedContent(context, parsed.data.path, result.content)
@@ -593,6 +656,8 @@ export const EditTool = defineTool({
593
656
  if (!admitted.success) return admitted
594
657
  const result = admitted.result
595
658
  if (!result.success) return refusedEdit(result, hostPath)
659
+ const notebook = notebookRefusal(hostPath, result.content, content)
660
+ if (notebook) return { success: false as const, output: '', error: notebook }
596
661
 
597
662
  // Temp file, fsync, rename — a reader sees the old body or the new
598
663
  // one, never a half-written one. A plain `writeFile` that fails
@@ -68,7 +68,7 @@ function relativePattern(pattern: string, root: string, sandboxed: boolean): str
68
68
  export const GlobTool = defineTool({
69
69
  name: 'glob',
70
70
  description:
71
- 'Finds regular files by glob pattern in a bounded search. "*" searches one directory; use "**" explicitly for recursive discovery. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Returns at most 500 paths and says when a result is limited or a search stopped early. Does not follow symlinks.',
71
+ 'Finds regular files by glob pattern in a bounded search. "*" searches one directory; use "**" explicitly for recursive discovery. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Returns at most 500 paths and says when a result is limited or a search stopped early. Does not follow symlinks. To search inside files, use grep.',
72
72
  inputSchema,
73
73
  category: 'filesystem',
74
74
  // Declared so a path outside the turn's roots can be reviewed before the
@@ -211,7 +211,7 @@ function isBinaryContent(buffer: Buffer): boolean {
211
211
  export const GrepTool = defineTool({
212
212
  name: 'grep',
213
213
  description:
214
- 'Searches file contents using a regular expression. By default returns the paths of matching files, newest first; output_mode "content" returns matching lines with file paths, line numbers and optional context lines, and "count" returns the number of matching lines per file. Set multiline for a pattern that spans lines and type (js, py, rust, ...) to search one kind of file. In content mode, before_context and after_context override symmetric context_lines; only_matching returns matched substrings without context. Results are paged: head_limit (default 250, 0 for none) and offset. A line over 500 characters is replaced by a notice. Searches hidden files unless include_hidden is false. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Says when a result is limited or a search stopped early. Skips binary files, files over 5 MB, and symlinks. Choose the narrowest relevant directory.',
214
+ 'Searches file contents using a regular expression. By default returns the paths of matching files, newest first; output_mode "content" returns matching lines with file paths, line numbers and optional context lines, and "count" returns the number of matching lines per file. Set multiline for a pattern that spans lines and type (js, py, rust, ...) to search one kind of file. In content mode, before_context and after_context override symmetric context_lines; only_matching returns matched substrings without context. Results are paged: head_limit (default 250, 0 for none) and offset. A line over 500 characters is replaced by a notice. Searches hidden files unless include_hidden is false. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Says when a result is limited or a search stopped early. Skips binary files, files over 5 MB, and symlinks. Choose the narrowest relevant directory. To find files by name, use glob.',
215
215
  inputSchema,
216
216
  category: 'analysis',
217
217
  // Declared so a path outside the turn's roots can be reviewed before the
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A notebook is JSON with a fixed shape. `edit` and `write` treat every file
3
+ * as text, so a model can leave an `.ipynb` that no notebook program opens.
4
+ * This check runs on the body about to be written, never on the file on disk,
5
+ * so a refusal leaves the file untouched.
6
+ */
7
+
8
+ const CELL_TYPES = new Set(['code', 'markdown', 'raw'])
9
+
10
+ export function isNotebookPath(path: string): boolean {
11
+ return path.toLowerCase().endsWith('.ipynb')
12
+ }
13
+
14
+ function isRecord(value: unknown): value is Record<string, unknown> {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
16
+ }
17
+
18
+ function shapeProblem(parsed: unknown): string | undefined {
19
+ if (!isRecord(parsed)) return 'the top level must be a JSON object'
20
+ if (typeof parsed.nbformat !== 'number') return 'it needs a numeric "nbformat"'
21
+ if (!isRecord(parsed.metadata)) return 'it needs a "metadata" object'
22
+ // Formats before 4 keep their cells inside "worksheets" and name a code cell's text "input".
23
+ // Those files are valid and still open, so only the envelope is checked for them.
24
+ if (parsed.nbformat < 4) {
25
+ return Array.isArray(parsed.worksheets) ? undefined : 'it needs a "worksheets" list'
26
+ }
27
+ if (!Array.isArray(parsed.cells)) return 'it needs a "cells" list'
28
+ for (const [index, cell] of parsed.cells.entries()) {
29
+ if (!isRecord(cell)) return `cell ${index} must be an object`
30
+ if (typeof cell.cell_type !== 'string' || !CELL_TYPES.has(cell.cell_type)) {
31
+ return `cell ${index} needs a "cell_type" of code, markdown or raw`
32
+ }
33
+ const source = cell.source
34
+ const sourceOk =
35
+ typeof source === 'string' ||
36
+ (Array.isArray(source) && source.every((line) => typeof line === 'string'))
37
+ if (!sourceOk) return `cell ${index} needs a "source" that is a string or a list of strings`
38
+ }
39
+ return undefined
40
+ }
41
+
42
+ /** Why a notebook body would not open, or `undefined` when it would. */
43
+ function bodyProblem(content: string): string | undefined {
44
+ let parsed: unknown
45
+ try {
46
+ parsed = JSON.parse(content)
47
+ } catch (error) {
48
+ const reason = error instanceof Error ? error.message : String(error)
49
+ return `it is not valid JSON (${reason})`
50
+ }
51
+ return shapeProblem(parsed)
52
+ }
53
+
54
+ /**
55
+ * Returns a plain refusal for a notebook body that would no longer open, or
56
+ * `undefined` when the body is fine or the path is not a notebook.
57
+ *
58
+ * `before` is the file's current body, when the caller has it. A notebook that
59
+ * was already broken cannot be mended one string at a time, because every
60
+ * partial repair still leaves a file that does not open; without saying so the
61
+ * refusal would tell the model to keep a structure the file never had, and it
62
+ * would try the same edit again.
63
+ */
64
+ export function notebookRefusal(
65
+ path: string,
66
+ content: string,
67
+ before?: string,
68
+ ): string | undefined {
69
+ if (!isNotebookPath(path)) return undefined
70
+ const problem = bodyProblem(content)
71
+ if (problem === undefined) return undefined
72
+ if (before !== undefined && bodyProblem(before) !== undefined) {
73
+ return `Not written: ${path} is a notebook that already does not open, and after this change it still would not because ${problem}. Repair it in one change that leaves a whole valid notebook, or replace the file with a write of the corrected notebook. The file is unchanged.`
74
+ }
75
+ return `Not written: ${path} is a notebook, and after this change it would no longer open because ${problem}. Change only text inside a cell and keep the notebook's structure (its cells, nbformat and metadata, with the surrounding quotes, commas and brackets), then try again. The file is unchanged.`
76
+ }
@@ -80,8 +80,12 @@ export function renderNumberedRead(content: string, input: ReadWindowRequest): R
80
80
  }
81
81
  const selected = lines.slice(start, Math.min(end, lineCount))
82
82
  const numbered = selected.map((line, i) => `${start + i + 1}\t${line}`).join('\n')
83
+ // Only a cut the cap imposed is the model's to be warned about: a window it
84
+ // asked for is what it got.
85
+ const asked = (input.readRange?.length ?? 0) >= 2 || Boolean(input.limit)
86
+ const capCut = !asked
83
87
  return {
84
- output: numbered + partialViewNotice(start, selected.length, lineCount),
88
+ output: numbered + partialViewNotice(start, selected.length, lineCount, capCut),
85
89
  totalLines: lineCount,
86
90
  returnedLines: selected.length,
87
91
  partial: selected.length < lineCount,
@@ -97,9 +101,15 @@ export function renderNumberedRead(content: string, input: ReadWindowRequest): R
97
101
  * most expensive silent failure a read tool can have. The notice names the
98
102
  * exact next call rather than describing it.
99
103
  */
100
- function partialViewNotice(start: number, returned: number, total: number): string {
104
+ function partialViewNotice(
105
+ start: number,
106
+ returned: number,
107
+ total: number,
108
+ capCut: boolean,
109
+ ): string {
101
110
  if (returned >= total) return ''
102
111
  const shownTo = start + returned
112
+ if (!capCut) return `\n\n[Lines ${start + 1}-${shownTo} of ${total}, as asked.]`
103
113
  return [
104
114
  '',
105
115
  '',