@sixb/agent 0.2.3 → 0.2.4

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 (80) hide show
  1. package/README.md +2 -2
  2. package/dist/artifacts/publish-tool.d.ts +26 -44
  3. package/dist/artifacts/publish-tool.d.ts.map +1 -1
  4. package/dist/ask-tool.d.ts +62 -0
  5. package/dist/ask-tool.d.ts.map +1 -0
  6. package/dist/attachments.d.ts +1 -1
  7. package/dist/attachments.d.ts.map +1 -1
  8. package/dist/background-commands.d.ts +3 -3
  9. package/dist/background-commands.d.ts.map +1 -1
  10. package/dist/background-notices.d.ts.map +1 -1
  11. package/dist/child-files.d.ts +1 -1
  12. package/dist/child-questions.d.ts +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1380 -596
  16. package/dist/index.js.map +30 -26
  17. package/dist/run-agent-turn.d.ts.map +1 -1
  18. package/dist/run-conversation-turn.d.ts.map +1 -1
  19. package/dist/run-environment.d.ts +4 -1
  20. package/dist/run-environment.d.ts.map +1 -1
  21. package/dist/run-subagent.d.ts +1 -1
  22. package/dist/subagent-tools.d.ts +20 -1
  23. package/dist/subagent-tools.d.ts.map +1 -1
  24. package/dist/tools/background.d.ts +50 -18
  25. package/dist/tools/background.d.ts.map +1 -1
  26. package/dist/tools/bash.d.ts +1 -0
  27. package/dist/tools/bash.d.ts.map +1 -1
  28. package/dist/tools/edit-text.d.ts +22 -0
  29. package/dist/tools/edit-text.d.ts.map +1 -0
  30. package/dist/tools/edit.d.ts +54 -0
  31. package/dist/tools/edit.d.ts.map +1 -0
  32. package/dist/tools/file-writes.d.ts +52 -0
  33. package/dist/tools/file-writes.d.ts.map +1 -0
  34. package/dist/tools/model-spec.d.ts.map +1 -1
  35. package/dist/tools/read.d.ts +16 -3
  36. package/dist/tools/read.d.ts.map +1 -1
  37. package/dist/tools/view-file.d.ts +20 -23
  38. package/dist/tools/view-file.d.ts.map +1 -1
  39. package/dist/tools/web-fetch/tool.d.ts +1 -0
  40. package/dist/tools/web-fetch/tool.d.ts.map +1 -1
  41. package/dist/tools/web-search.d.ts +1 -0
  42. package/dist/tools/web-search.d.ts.map +1 -1
  43. package/dist/tools/write.d.ts +36 -0
  44. package/dist/tools/write.d.ts.map +1 -0
  45. package/package.json +4 -4
  46. package/src/agent-prompt.ts +9 -9
  47. package/src/artifacts/publish-tool.ts +76 -94
  48. package/src/ask-tool.ts +223 -0
  49. package/src/attachments.ts +7 -6
  50. package/src/background-commands.ts +5 -5
  51. package/src/background-notices.ts +5 -12
  52. package/src/child-files.ts +1 -1
  53. package/src/child-questions.ts +1 -1
  54. package/src/context-compaction.ts +4 -1
  55. package/src/index.ts +1 -1
  56. package/src/run-agent-turn.ts +14 -4
  57. package/src/run-child.ts +1 -1
  58. package/src/run-conversation-turn.ts +4 -1
  59. package/src/run-environment.ts +36 -21
  60. package/src/run-subagent.ts +3 -3
  61. package/src/skills/sixb-artifacts/SKILL.md +7 -7
  62. package/src/skills/sixb-artifacts/canvas.md +2 -2
  63. package/src/skills/sixb-artifacts/page.md +2 -2
  64. package/src/skills/sixb-artifacts/slides.md +2 -2
  65. package/src/subagent-tools.ts +115 -81
  66. package/src/tools/background.ts +227 -67
  67. package/src/tools/bash.ts +2 -1
  68. package/src/tools/edit-text.ts +241 -0
  69. package/src/tools/edit.ts +166 -0
  70. package/src/tools/file-writes.ts +270 -0
  71. package/src/tools/model-spec.ts +9 -13
  72. package/src/tools/read.ts +75 -9
  73. package/src/tools/tool-outputs.ts +2 -2
  74. package/src/tools/view-file.ts +78 -80
  75. package/src/tools/web-fetch/tool.ts +2 -1
  76. package/src/tools/web-search.ts +1 -0
  77. package/src/tools/write.ts +95 -0
  78. package/dist/ask-parent-tool.d.ts +0 -36
  79. package/dist/ask-parent-tool.d.ts.map +0 -1
  80. package/src/ask-parent-tool.ts +0 -100
@@ -1,125 +1,285 @@
1
- import { AgentToolPublicError } from "@sixb/core"
2
- import type { JsonObject, JsonValue, ModelTool } from "@sixb/core/models"
1
+ import { AgentToolPublicError, type AgentToolResult } from "@sixb/core"
2
+ import { isAgentToolResult } from "@sixb/core/internal/agents"
3
+ import { assertJsonValue, type JsonObject, type JsonValue, type ModelTool } from "@sixb/core/models"
3
4
  import type { BackgroundCommandOutput, BackgroundCommands } from "../background-commands"
4
5
  import { agentToolErrorText } from "../model-adapters"
5
6
  import type { AgentSandboxHandle } from "../sandbox-handle"
7
+ import type { WaitForSubagentsOutput } from "../subagent-tools"
6
8
 
7
- /** The longest `bash_output` waits for a command to end. */
9
+ /** The longest `wait` waits for a command to end. */
8
10
  const MAX_WAIT_MS = 600_000
9
11
 
10
- export const BASH_OUTPUT_TOOL_SPEC = {
11
- name: "bash_output",
12
- description:
13
- "A background command's status (running, exited with its code, or stopped) and its output since your last read: the newest 20,000 bytes, the rest in its file. wait blocks until it ends, at most that many ms. You are told when one ends: do not poll.",
12
+ /** How many ids one `wait` takes. */
13
+ const MAX_WAIT_IDS = 16
14
+
15
+ /** Before `wait` and `stop`, a background command's tools: earlier threads hold calls to them. */
16
+ export const LEGACY_BACKGROUND_TOOLS = ["bash_output", "bash_stop"] as const
17
+
18
+ /** Before `wait`, the Agent's wait for its children: earlier threads hold calls to it. */
19
+ export const LEGACY_WAIT_AGENT_TOOL = "wait_agent"
20
+
21
+ export const WAIT_TOOL_SPEC = {
22
+ name: "wait",
23
+ strict: true,
24
+ description: [
25
+ "Wait for work you started: background commands, by the id bash returned, and child agents, by their key.",
26
+ "A command returns its status (running, exited with its code, or stopped) and its output since your last read: the newest 20,000 bytes, the rest in its file. To see a running command's output without waiting, read its file.",
27
+ "A child returns its final text or failure, and the files it wrote to out/, each with its path in your sandbox.",
28
+ "It returns once all have ended, or as soon as a child asks you a question, or once timeoutMs passes for commands. You are told when a command ends: do not poll.",
29
+ ].join("\n"),
14
30
  inputSchema: {
15
31
  type: "object",
16
32
  properties: {
17
- id: { type: "string", description: "The id bash returned, like bg_3f9a1c." },
18
- wait: {
33
+ ids: {
34
+ type: "array",
35
+ minItems: 1,
36
+ maxItems: MAX_WAIT_IDS,
37
+ uniqueItems: true,
38
+ items: { type: "string", minLength: 1 },
39
+ description: "Background command ids, like bg_3f9a1c, and child agents' keys.",
40
+ },
41
+ timeoutMs: {
19
42
  type: "number",
20
- description: "Milliseconds to wait for its end, up to 600000.",
43
+ description: `The longest to wait for commands to end, up to ${MAX_WAIT_MS}; 0 returns their status at once. Default: ${MAX_WAIT_MS}.`,
21
44
  },
22
45
  },
23
- required: ["id"],
46
+ required: ["ids"],
24
47
  additionalProperties: false,
25
48
  } satisfies JsonObject,
26
49
  } as const
27
50
 
28
- export const BASH_STOP_TOOL_SPEC = {
29
- name: "bash_stop",
51
+ export const STOP_TOOL_SPEC = {
52
+ name: "stop",
53
+ strict: true,
30
54
  description:
31
- "Stop a background command and all it started: SIGTERM, then SIGKILL after 3 s. Returns its final status and output since your last read.",
55
+ "Stop work you started: a background command and all it started (SIGTERM, then SIGKILL after 3 s), or a child agent of this turn. Returns what wait would: how it ended, and its output or answer so far.",
32
56
  inputSchema: {
33
57
  type: "object",
34
58
  properties: {
35
- id: { type: "string", description: "The id bash returned, like bg_3f9a1c." },
59
+ id: {
60
+ type: "string",
61
+ minLength: 1,
62
+ description: "A background command's id, like bg_3f9a1c, or a child agent's key.",
63
+ },
36
64
  },
37
65
  required: ["id"],
38
66
  additionalProperties: false,
39
67
  } satisfies JsonObject,
40
68
  } as const
41
69
 
42
- interface BashOutputToolInput {
43
- readonly id: string
44
- readonly wait?: number
70
+ /**
71
+ * The Agent's children, as `wait` and `stop` reach them: an id that names no background command
72
+ * names one of them, by its key or its run id.
73
+ */
74
+ export interface WaitableChildren {
75
+ wait(ids: readonly string[], signal: AbortSignal): Promise<WaitForSubagentsOutput>
76
+ stop(id: string, signal: AbortSignal): Promise<WaitForSubagentsOutput>
77
+ }
78
+
79
+ /** What `wait` and `stop` return: the commands named, and the children's results. */
80
+ export interface WaitOutput extends Partial<Omit<WaitForSubagentsOutput, "files">> {
81
+ readonly commands?: readonly BackgroundCommandOutput[]
45
82
  }
46
83
 
47
- interface BashStopToolInput {
84
+ interface WaitToolInput {
85
+ readonly ids: readonly string[]
86
+ readonly timeoutMs?: number
87
+ }
88
+
89
+ interface StopToolInput {
48
90
  readonly id: string
49
91
  }
50
92
 
51
- /** `bash_output`: a background command's status and new output, after waiting when asked. */
52
- export function createBashOutputTool(
93
+ /** `wait`: until the commands and children named end, a child asks, or the timeout passes. */
94
+ export function createWaitTool(
53
95
  resolveSandbox: () => Promise<AgentSandboxHandle>,
54
- commands: BackgroundCommands
55
- ): ModelTool<BashOutputToolInput> {
96
+ commands: BackgroundCommands,
97
+ children?: WaitableChildren
98
+ ): ModelTool<WaitToolInput> {
56
99
  return {
57
- ...BASH_OUTPUT_TOOL_SPEC,
100
+ ...WAIT_TOOL_SPEC,
58
101
  parseInput: (value) => {
59
- const input = parseInput(BASH_OUTPUT_TOOL_SPEC.name, value, ["id", "wait"])
60
- if (input.wait !== undefined && (typeof input.wait !== "number" || input.wait < 0)) {
61
- throw publicError(BASH_OUTPUT_TOOL_SPEC.name, "wait must be a number of milliseconds.")
102
+ const input = parseObject(WAIT_TOOL_SPEC.name, value, ["ids", "timeoutMs"])
103
+ const ids = input.ids
104
+ if (
105
+ !Array.isArray(ids) ||
106
+ ids.length < 1 ||
107
+ ids.length > MAX_WAIT_IDS ||
108
+ !ids.every((id) => typeof id === "string" && id.trim().length > 0)
109
+ ) {
110
+ throw publicError(
111
+ WAIT_TOOL_SPEC.name,
112
+ `ids must list 1 to ${MAX_WAIT_IDS} background command ids or child agents' keys.`
113
+ )
114
+ }
115
+ const timeoutMs = input.timeoutMs
116
+ if (timeoutMs !== undefined && (typeof timeoutMs !== "number" || timeoutMs < 0)) {
117
+ throw publicError(WAIT_TOOL_SPEC.name, "timeoutMs must be a number of milliseconds.")
62
118
  }
63
119
  return {
64
- id: input.id as string,
65
- ...(input.wait === undefined ? {} : { wait: Math.min(input.wait as number, MAX_WAIT_MS) }),
120
+ ids: [...new Set(ids.map((id: string) => id.trim()))],
121
+ ...(timeoutMs === undefined ? {} : { timeoutMs: Math.min(timeoutMs, MAX_WAIT_MS) }),
66
122
  }
67
123
  },
68
124
  async execute(input, { signal }): Promise<JsonValue> {
69
- commands.get(input.id)
70
- if (input.wait) await commands.wait(input.id, input.wait, signal)
71
-
72
- const output: BackgroundCommandOutput = await commands.read(
73
- input.id,
74
- await resolveSandbox(),
75
- signal
76
- )
77
- return output as unknown as JsonValue
125
+ const commandIds = input.ids.filter((id) => commands.has(id))
126
+ const childIds = input.ids.filter((id) => !commands.has(id))
127
+ if (childIds.length > 0 && !children) throw unknownCommand(WAIT_TOOL_SPEC.name, childIds)
128
+ const timeoutMs = input.timeoutMs ?? MAX_WAIT_MS
129
+
130
+ // The children decide when a wait for them returns, at their end or a question: then the
131
+ // commands are read as they are. Commands that end first wait for the children.
132
+ const settled = new AbortController()
133
+ const stopWaiting = () => settled.abort()
134
+ signal.addEventListener("abort", stopWaiting, { once: true })
135
+ try {
136
+ const commandsEnded = Promise.all(
137
+ commandIds.map((id) => commands.wait(id, timeoutMs, settled.signal))
138
+ ).catch((error: unknown) => {
139
+ if (!settled.signal.aborted || signal.aborted) throw error
140
+ })
141
+ const childrenWaited =
142
+ children && childIds.length > 0
143
+ ? children.wait(childIds, signal).finally(stopWaiting)
144
+ : undefined
145
+ // Awaited together: the turn's stop rejects both, and one wait for both handles each.
146
+ const [waited] = await Promise.all([childrenWaited, commandsEnded])
147
+ signal.throwIfAborted()
148
+ return await output(
149
+ await readCommands(commandIds, commands, resolveSandbox, signal),
150
+ waited
151
+ )
152
+ } finally {
153
+ signal.removeEventListener("abort", stopWaiting)
154
+ }
78
155
  },
156
+ toModelOutput: textOfResult,
79
157
  errorText: agentToolErrorText,
80
158
  }
81
159
  }
82
160
 
83
- /** `bash_stop`: stop a background command, then report how it ended and its last output. */
84
- export function createBashStopTool(
161
+ /** `stop`: stop a command or a child, then report how it ended and its output or answer so far. */
162
+ export function createStopTool(
85
163
  resolveSandbox: () => Promise<AgentSandboxHandle>,
86
- commands: BackgroundCommands
87
- ): ModelTool<BashStopToolInput> {
164
+ commands: BackgroundCommands,
165
+ children?: WaitableChildren
166
+ ): ModelTool<StopToolInput> {
88
167
  return {
89
- ...BASH_STOP_TOOL_SPEC,
90
- parseInput: (value) => ({
91
- id: parseInput(BASH_STOP_TOOL_SPEC.name, value, ["id"]).id as string,
92
- }),
168
+ ...STOP_TOOL_SPEC,
169
+ parseInput: (value) => {
170
+ const input = parseObject(STOP_TOOL_SPEC.name, value, ["id"])
171
+ if (typeof input.id !== "string" || !input.id.trim()) {
172
+ throw publicError(
173
+ STOP_TOOL_SPEC.name,
174
+ "id must be a background command's id, such as bg_3f9a1c, or a child agent's key."
175
+ )
176
+ }
177
+ return { id: input.id.trim() }
178
+ },
93
179
  async execute(input, { signal }): Promise<JsonValue> {
94
- await commands.stop(input.id)
95
-
96
- const output: BackgroundCommandOutput = await commands.read(
97
- input.id,
98
- await resolveSandbox(),
99
- signal
100
- )
101
- return output as unknown as JsonValue
180
+ if (commands.has(input.id)) {
181
+ await commands.stop(input.id)
182
+ return output(await readCommands([input.id], commands, resolveSandbox, signal), undefined)
183
+ }
184
+ if (!children) throw unknownCommand(STOP_TOOL_SPEC.name, [input.id])
185
+ return output([], await children.stop(input.id, signal))
102
186
  },
187
+ toModelOutput: textOfResult,
103
188
  errorText: agentToolErrorText,
104
189
  }
105
190
  }
106
191
 
107
- function parseInput(
108
- tool: string,
109
- value: unknown,
110
- keys: readonly string[]
111
- ): Record<string, unknown> & { readonly id: string } {
112
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
113
- throw publicError(tool, "input must be an object.")
192
+ /**
193
+ * The background commands a tool's result reports, as each read it: `bash` and the tools before
194
+ * `wait` report one, `wait` and `stop` those they name.
195
+ */
196
+ export function reportedCommands(toolName: string, output: unknown): readonly unknown[] {
197
+ if (toolName === "bash" || (LEGACY_BACKGROUND_TOOLS as readonly string[]).includes(toolName)) {
198
+ return [output]
114
199
  }
115
- const input = value as Record<string, unknown>
116
- for (const key of Object.keys(input)) {
117
- if (!keys.includes(key)) throw publicError(tool, `input contains unknown property '${key}'.`)
200
+ if (toolName !== WAIT_TOOL_SPEC.name && toolName !== STOP_TOOL_SPEC.name) return []
201
+ const value = resultValue(output)
202
+ return isRecord(value) && Array.isArray(value.commands) ? value.commands : []
203
+ }
204
+
205
+ async function readCommands(
206
+ ids: readonly string[],
207
+ commands: BackgroundCommands,
208
+ resolveSandbox: () => Promise<AgentSandboxHandle>,
209
+ signal: AbortSignal
210
+ ): Promise<readonly BackgroundCommandOutput[]> {
211
+ if (ids.length === 0) return []
212
+ const sandbox = await resolveSandbox()
213
+ return Promise.all(ids.map((id) => commands.read(id, sandbox, signal)))
214
+ }
215
+
216
+ /**
217
+ * The commands alone are a plain result. With children it is a rich one, so the files they wrote
218
+ * reach later turns through `$SIXB_ATTACHMENTS` and the work trace.
219
+ */
220
+ async function output(
221
+ read: readonly BackgroundCommandOutput[],
222
+ waited: WaitForSubagentsOutput | undefined
223
+ ): Promise<JsonValue> {
224
+ const commandsPart = read.length > 0 ? { commands: read } : {}
225
+ if (!waited) {
226
+ const result: WaitOutput = commandsPart
227
+ assertJsonValue(result)
228
+ return result
118
229
  }
119
- if (typeof input.id !== "string" || !input.id) {
120
- throw publicError(tool, "id must be a background command's id, such as bg_3f9a1c.")
230
+ const { files, ...answer } = waited
231
+ const result: AgentToolResult = {
232
+ kind: "agentToolResult",
233
+ content: [
234
+ { type: "text", text: JSON.stringify({ ...commandsPart, ...answer } satisfies WaitOutput) },
235
+ ...files.map(({ fileRef }) => ({ type: "file" as const, fileRef })),
236
+ ],
121
237
  }
122
- return input as Record<string, unknown> & { readonly id: string }
238
+ assertJsonValue(result)
239
+ return result
240
+ }
241
+
242
+ /** The answer lists each file's path this turn; the Agent reads the ones it needs. */
243
+ function textOfResult(output: JsonValue) {
244
+ return isAgentToolResult(output)
245
+ ? {
246
+ type: "text" as const,
247
+ value: output.content
248
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
249
+ .join("\n"),
250
+ }
251
+ : { type: "json" as const, value: output }
252
+ }
253
+
254
+ /** A result's value: a rich one's first text, parsed. */
255
+ function resultValue(output: unknown): unknown {
256
+ if (!isAgentToolResult(output)) return output
257
+ const text = output.content.find((part) => part.type === "text")
258
+ if (text?.type !== "text") return undefined
259
+ try {
260
+ return JSON.parse(text.text)
261
+ } catch {
262
+ return undefined
263
+ }
264
+ }
265
+
266
+ function unknownCommand(tool: string, ids: readonly string[]): AgentToolPublicError {
267
+ return publicError(
268
+ tool,
269
+ `has no background command ${ids.map((id) => `'${id}'`).join(", ")}: pass the id bash returned, such as bg_3f9a1c.`
270
+ )
271
+ }
272
+
273
+ function parseObject(tool: string, value: unknown, keys: readonly string[]) {
274
+ if (!isRecord(value)) throw publicError(tool, "input must be an object.")
275
+ for (const key of Object.keys(value)) {
276
+ if (!keys.includes(key)) throw publicError(tool, `input contains unknown property '${key}'.`)
277
+ }
278
+ return value
279
+ }
280
+
281
+ function isRecord(value: unknown): value is Record<string, unknown> {
282
+ return typeof value === "object" && value !== null && !Array.isArray(value)
123
283
  }
124
284
 
125
285
  function publicError(tool: string, message: string): AgentToolPublicError {
package/src/tools/bash.ts CHANGED
@@ -11,6 +11,7 @@ const DEFAULT_MAX_OUTPUT_CHARS = 20_000
11
11
 
12
12
  export const BASH_TOOL_SPEC = {
13
13
  name: "bash",
14
+ strict: true,
14
15
  description:
15
16
  `Run a Bash command in the agent run sandbox. A command is stopped after ${durationText(DEFAULT_COMMAND_TIMEOUT_MS)} ` +
16
17
  `(${DEFAULT_COMMAND_TIMEOUT_MS} ms); pass timeoutMs to give it up to ${durationText(MAX_COMMAND_TIMEOUT_MS)} ` +
@@ -33,7 +34,7 @@ export const BASH_TOOL_SPEC = {
33
34
  run_in_background: {
34
35
  type: "boolean",
35
36
  description:
36
- "Run it in the background, returning at once with its id and output file: for servers, watchers, long builds. You are told when it ends; read it with bash_output, stop it with bash_stop. No timeout. It ends with the run, a pause for approval too, and its file with it; in the user's folder on their computer it runs until it exits, is stopped, or sixb quits.",
37
+ "Run it in the background, returning at once with its id and output file: for servers, watchers, long builds. You are told when it ends; wait for it with wait, stop it with stop, or read its file. No timeout. It ends with the run, a pause for approval too, and its file with it; in the user's folder on their computer it runs until it exits, is stopped, or sixb quits.",
37
38
  },
38
39
  },
39
40
  required: ["command"],
@@ -0,0 +1,241 @@
1
+ /**
2
+ * The text half of `edit`: find `old` in a file, replace it, and describe the change as a unified
3
+ * diff, or say where to look when it does not match. No sandbox here, so it is tested on strings.
4
+ */
5
+
6
+ const DIFF_CONTEXT_LINES = 2
7
+ const MAX_DIFF_CHARACTERS = 4_000
8
+ const MAX_LISTED_MATCHES = 10
9
+
10
+ export type EditTextResult =
11
+ | {
12
+ readonly ok: true
13
+ readonly text: string
14
+ readonly replaced: number
15
+ readonly diff: string
16
+ /** Lines the change adds and removes, all of them: the diff may be cut. */
17
+ readonly added: number
18
+ readonly removed: number
19
+ }
20
+ | { readonly ok: false; readonly reason: string }
21
+
22
+ export function editText(
23
+ text: string,
24
+ input: { readonly old: string; readonly new: string; readonly all: boolean }
25
+ ): EditTextResult {
26
+ let { old, new: replacement } = input
27
+ let starts = occurrences(text, old)
28
+ // A model writes "\n" for a file that ends its lines with "\r\n": match it the file's way.
29
+ if (starts.length === 0 && text.includes("\r\n") && !old.includes("\r")) {
30
+ const crlf = (value: string) => value.replace(/\n/g, "\r\n")
31
+ const found = occurrences(text, crlf(old))
32
+ if (found.length > 0) {
33
+ old = crlf(old)
34
+ replacement = crlf(replacement)
35
+ starts = found
36
+ }
37
+ }
38
+
39
+ if (starts.length === 0) return { ok: false, reason: missReason(text, input.old) }
40
+ if (starts.length > 1 && !input.all) {
41
+ const lineOf = lineIndex(text)
42
+ const lines = starts.slice(0, MAX_LISTED_MATCHES).map((start) => lineOf(start))
43
+ const more = starts.length > MAX_LISTED_MATCHES ? ", …" : ""
44
+ return {
45
+ ok: false,
46
+ reason: `old_string matches ${starts.length} times (lines ${lines.join(", ")}${more}). Add surrounding lines to make it unique, or pass replace_all: true.`,
47
+ }
48
+ }
49
+
50
+ let result = ""
51
+ let cursor = 0
52
+ for (const start of starts) {
53
+ result += text.slice(cursor, start) + replacement
54
+ cursor = start + old.length
55
+ }
56
+ result += text.slice(cursor)
57
+ return {
58
+ ok: true,
59
+ text: result,
60
+ replaced: starts.length,
61
+ ...unifiedDiff(text, result, starts, old.length, replacement.length),
62
+ }
63
+ }
64
+
65
+ /** Where `needle` starts in `text`, without overlaps, left to right. */
66
+ function occurrences(text: string, needle: string): number[] {
67
+ const starts: number[] = []
68
+ for (let index = text.indexOf(needle); index !== -1; ) {
69
+ starts.push(index)
70
+ index = text.indexOf(needle, index + needle.length)
71
+ }
72
+ return starts
73
+ }
74
+
75
+ /** A lookup of the 1-based line an offset of `text` falls on, by binary search. */
76
+ function lineIndex(text: string): (offset: number) => number {
77
+ const newlines: number[] = []
78
+ for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) {
79
+ newlines.push(index)
80
+ }
81
+ return (offset) => {
82
+ let low = 0
83
+ let high = newlines.length
84
+ while (low < high) {
85
+ const middle = (low + high) >> 1
86
+ if ((newlines[middle] ?? 0) < offset) low = middle + 1
87
+ else high = middle
88
+ }
89
+ return low + 1
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Why nothing matched, with where to look: the same lines with other spacing, or the line the
95
+ * first line of `old` is on. Most misses are indentation or a stale copy of the file.
96
+ */
97
+ function missReason(text: string, old: string): string {
98
+ const fileLines = text.split(/\r?\n/)
99
+ const wanted = old.split(/\r?\n/)
100
+ while (wanted.length > 1 && wanted.at(-1)?.trim() === "") wanted.pop()
101
+ const squash = (line: string) => line.trim().replace(/\s+/g, " ")
102
+ const target = wanted.map(squash)
103
+
104
+ for (let start = 0; start + target.length <= fileLines.length; start += 1) {
105
+ if (target.every((line, offset) => squash(fileLines[start + offset] ?? "") === line)) {
106
+ const range =
107
+ target.length === 1 ? `line ${start + 1}` : `lines ${start + 1}-${start + target.length}`
108
+ return `old_string matches nothing exactly. The same text with other whitespace is at ${range}: copy it as the file has it.`
109
+ }
110
+ }
111
+
112
+ const first = target.find((line) => line !== "")
113
+ if (first) {
114
+ const at = fileLines.findIndex((line) => squash(line) === first)
115
+ if (at !== -1) {
116
+ return `old_string matches nothing. Its first line is at line ${at + 1}, but what follows differs: read the file there again.`
117
+ }
118
+ }
119
+ return "old_string matches nothing in the file. Read the file again and copy the text exactly."
120
+ }
121
+
122
+ interface ChangedRange {
123
+ /** 0-based, end exclusive, in the old and the new text's lines. */
124
+ readonly oldStart: number
125
+ readonly oldEnd: number
126
+ readonly newStart: number
127
+ readonly newEnd: number
128
+ }
129
+
130
+ /** A text's lines, its final newline ending the last rather than starting an empty one. */
131
+ function textLines(text: string): readonly string[] {
132
+ return (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n")
133
+ }
134
+
135
+ /**
136
+ * The replacements as unified-diff hunks, nearby ones merged, cut past a few thousand characters,
137
+ * and the lines they add and remove, counted before the cut.
138
+ */
139
+ function unifiedDiff(
140
+ before: string,
141
+ after: string,
142
+ starts: readonly number[],
143
+ oldLength: number,
144
+ newLength: number
145
+ ): { readonly diff: string; readonly added: number; readonly removed: number } {
146
+ // A file's final newline ends its last line: it starts no empty one.
147
+ const oldLines = textLines(before)
148
+ const newLines = textLines(after)
149
+ const oldLineOf = lineIndex(before)
150
+ const newLineOf = lineIndex(after)
151
+ const ranges: ChangedRange[] = []
152
+ let shift = 0
153
+ for (const start of starts) {
154
+ // Every line the replacement touches, then the lines both sides still share trimmed off: a
155
+ // match ending in "\n" reaches the next line, which the new text may leave as it was.
156
+ let oldStart = oldLineOf(start) - 1
157
+ let oldEnd = oldLineOf(start + oldLength)
158
+ let newStart = newLineOf(start + shift) - 1
159
+ let newEnd = newLineOf(start + shift + newLength)
160
+ // A match ending with the final newline reaches no line past the last.
161
+ oldEnd = Math.min(oldEnd, oldLines.length)
162
+ newEnd = Math.min(newEnd, newLines.length)
163
+ while (
164
+ oldEnd > oldStart &&
165
+ newEnd > newStart &&
166
+ oldLines[oldEnd - 1] === newLines[newEnd - 1]
167
+ ) {
168
+ oldEnd -= 1
169
+ newEnd -= 1
170
+ }
171
+ while (oldStart < oldEnd && newStart < newEnd && oldLines[oldStart] === newLines[newStart]) {
172
+ oldStart += 1
173
+ newStart += 1
174
+ }
175
+
176
+ // Two matches on one line change it once: their ranges merge, so the line shows once.
177
+ const previous = ranges.at(-1)
178
+ if (previous && (oldStart < previous.oldEnd || newStart < previous.newEnd)) {
179
+ ranges[ranges.length - 1] = {
180
+ oldStart: Math.min(previous.oldStart, oldStart),
181
+ oldEnd: Math.max(previous.oldEnd, oldEnd),
182
+ newStart: Math.min(previous.newStart, newStart),
183
+ newEnd: Math.max(previous.newEnd, newEnd),
184
+ }
185
+ } else {
186
+ ranges.push({ oldStart, oldEnd, newStart, newEnd })
187
+ }
188
+ shift += newLength - oldLength
189
+ }
190
+
191
+ // Counted before the diff is cut, so they hold the whole change.
192
+ let added = 0
193
+ let removed = 0
194
+ for (const range of ranges) {
195
+ removed += range.oldEnd - range.oldStart
196
+ added += range.newEnd - range.newStart
197
+ }
198
+
199
+ const hunks: ChangedRange[][] = []
200
+ for (const range of ranges) {
201
+ const last = hunks.at(-1)
202
+ const previous = last?.at(-1)
203
+ if (last && previous && range.oldStart - previous.oldEnd <= DIFF_CONTEXT_LINES * 2) {
204
+ last.push(range)
205
+ } else {
206
+ hunks.push([range])
207
+ }
208
+ }
209
+
210
+ let diff = ""
211
+ for (const [index, group] of hunks.entries()) {
212
+ const first = group[0]!
213
+ const last = group.at(-1)!
214
+ const oldFrom = Math.max(0, first.oldStart - DIFF_CONTEXT_LINES)
215
+ const oldTo = Math.min(oldLines.length, last.oldEnd + DIFF_CONTEXT_LINES)
216
+ const newFrom = first.newStart - (first.oldStart - oldFrom)
217
+ const newTo = last.newEnd + (oldTo - last.oldEnd)
218
+
219
+ const body: string[] = []
220
+ let oldCursor = oldFrom
221
+ for (const range of group) {
222
+ for (; oldCursor < range.oldStart; oldCursor += 1) body.push(` ${oldLines[oldCursor]}`)
223
+ for (let line = range.oldStart; line < range.oldEnd; line += 1) {
224
+ body.push(`-${oldLines[line]}`)
225
+ }
226
+ for (let line = range.newStart; line < range.newEnd; line += 1) {
227
+ body.push(`+${newLines[line]}`)
228
+ }
229
+ oldCursor = range.oldEnd
230
+ }
231
+ for (; oldCursor < oldTo; oldCursor += 1) body.push(` ${oldLines[oldCursor]}`)
232
+
233
+ const hunk = `@@ -${oldFrom + 1},${oldTo - oldFrom} +${newFrom + 1},${newTo - newFrom} @@\n${body.join("\n")}\n`
234
+ if (diff.length + hunk.length > MAX_DIFF_CHARACTERS) {
235
+ const left = hunks.length - index
236
+ return { diff: `${diff}… ${left} more ${left === 1 ? "hunk" : "hunks"}\n`, added, removed }
237
+ }
238
+ diff += hunk
239
+ }
240
+ return { diff, added, removed }
241
+ }