maka-agent 0.2.0-dev.27.20260910 → 0.2.0-dev.28.20260911

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 (76) hide show
  1. package/LICENSE +106 -0
  2. package/dist/cli-core.js +7 -0
  3. package/dist/runtime-host-run-command.js +15 -7
  4. package/dist/session-import-command.js +69 -0
  5. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  6. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  7. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  8. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +9 -4
  11. package/node_modules/@maka/core/dist/diagnostic-log.js +18 -7
  12. package/node_modules/@maka/core/dist/text-sanitize.js +8 -2
  13. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +8 -8
  14. package/node_modules/@maka/runtime/dist/archive-read-tool.js +3 -1
  15. package/node_modules/@maka/runtime/dist/bots/bot-test.js +2 -1
  16. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +24 -20
  17. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +5 -3
  18. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +87 -29
  19. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +40 -36
  20. package/node_modules/@maka/runtime/dist/computer-use-tools.js +4 -1
  21. package/node_modules/@maka/runtime/dist/deep-research-tools.js +11 -5
  22. package/node_modules/@maka/runtime/dist/edit-replace.js +2 -2
  23. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +5 -6
  24. package/node_modules/@maka/runtime/dist/memory-extraction-evidence.js +7 -1
  25. package/node_modules/@maka/runtime/dist/memory-extraction.js +12 -7
  26. package/node_modules/@maka/runtime/dist/openai-responses-websocket.js +2 -5
  27. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +11 -2
  28. package/node_modules/@maka/runtime/dist/request-customization-fetch.js +14 -7
  29. package/node_modules/@maka/runtime/dist/session-export.js +1 -0
  30. package/node_modules/@maka/runtime/dist/session-import.js +100 -0
  31. package/node_modules/@maka/runtime/dist/session-manager.js +6 -1
  32. package/node_modules/@maka/runtime/dist/shell-run-manager.js +9 -6
  33. package/node_modules/@maka/runtime/dist/shell-run-tool-result.js +13 -6
  34. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +43 -10
  35. package/node_modules/@maka/runtime/dist/stream-graph-handoff.js +6 -1
  36. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +1 -4
  37. package/node_modules/@maka/runtime/dist/system-prompt/workspace-instructions.js +11 -6
  38. package/node_modules/@maka/runtime/dist/tavily-search.js +8 -2
  39. package/node_modules/@maka/runtime/dist/text-line-window.js +49 -0
  40. package/node_modules/@maka/runtime/dist/tool-output.js +35 -12
  41. package/node_modules/@maka/runtime/dist/unified-diff.js +40 -10
  42. package/node_modules/@maka/runtime/dist/web-fetch-tool.js +4 -2
  43. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +82 -33
  44. package/node_modules/@maka/runtime/dist/workspace-executor.js +2 -6
  45. package/node_modules/@maka/runtime/package.json +2 -1
  46. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +6 -6
  47. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +7 -4
  48. package/node_modules/@maka/runtime-host/dist/protocol/artifact.js +2 -2
  49. package/node_modules/@maka/runtime-host/dist/protocol/index.js +2 -1
  50. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +3 -2
  51. package/node_modules/@maka/runtime-host/dist/protocol/skill-catalog.js +2 -1
  52. package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +2 -0
  53. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +29 -4
  54. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +6 -1
  55. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +35 -4
  56. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +24 -8
  57. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +17 -8
  58. package/node_modules/@maka/runtime-host/dist/server/runtime-resource-projection.js +3 -9
  59. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +20 -21
  60. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +24 -2
  61. package/node_modules/@maka/runtime-host/dist/server/skill-catalog-coordinator.js +18 -2
  62. package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +4 -1
  63. package/node_modules/@maka/runtime-host/dist/transport/local-ipc-framing.js +4 -2
  64. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +9 -8
  65. package/node_modules/@maka/runtime-host/dist/transport/resumable-peer-stream.js +14 -9
  66. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +19 -4
  67. package/node_modules/@maka/storage/dist/context-value-mutation-gate.js +59 -0
  68. package/node_modules/@maka/storage/dist/session-bundle-policy.js +579 -7
  69. package/node_modules/@maka/storage/dist/session-message-projection.js +8 -4
  70. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +18 -4
  71. package/node_modules/@maka/storage/dist/stable-storage.js +2 -1
  72. package/node_modules/@modelcontextprotocol/client/dist/src-D_zzAWoS.mjs +22 -5
  73. package/node_modules/@modelcontextprotocol/client/dist/src-NAgB4Mp8.cjs +22 -5
  74. package/node_modules/zod/v4/core/memoizer.cjs +12 -16
  75. package/node_modules/zod/v4/core/memoizer.js +12 -16
  76. package/package.json +1 -1
@@ -1677,13 +1677,16 @@ function normalizeBackgroundTimeoutMs(value) {
1677
1677
  }
1678
1678
  return value;
1679
1679
  }
1680
- function splitPtyData(data) {
1681
- const codePoints = Array.from(data);
1682
- const chunks = [];
1683
- for (let offset = 0; offset < codePoints.length; offset += PTY_RAW_INPUT_CHUNK_CODE_POINTS) {
1684
- chunks.push(codePoints.slice(offset, offset + PTY_RAW_INPUT_CHUNK_CODE_POINTS).join(''));
1680
+ function* splitPtyData(data) {
1681
+ // Bound each published piece without materializing the entire callback as code points.
1682
+ let offset = 0;
1683
+ while (offset < data.length) {
1684
+ const start = offset;
1685
+ for (let count = 0; count < PTY_RAW_INPUT_CHUNK_CODE_POINTS && offset < data.length; count++) {
1686
+ offset += data.codePointAt(offset) > 0xffff ? 2 : 1;
1687
+ }
1688
+ yield data.slice(start, offset);
1685
1689
  }
1686
- return chunks;
1687
1690
  }
1688
1691
  function encodedPtyDataBytes(data) {
1689
1692
  return Buffer.byteLength(JSON.stringify(data), 'utf8');
@@ -212,16 +212,23 @@ function takeTailText(text, budget) {
212
212
  return { text: `${TRUNCATED_MARKER}\n${tail}`, truncated: true };
213
213
  }
214
214
  function sliceUtf8Tail(text, budget) {
215
- const characters = Array.from(text);
216
- let result = '';
215
+ const characters = [];
217
216
  let bytes = 0;
218
- for (let index = characters.length - 1; index >= 0; index -= 1) {
219
- const character = characters[index];
217
+ for (let end = text.length; end > 0;) {
218
+ let start = end - 1;
219
+ const last = text.charCodeAt(start);
220
+ if (last >= 0xdc00 && last <= 0xdfff && start > 0) {
221
+ const previous = text.charCodeAt(start - 1);
222
+ if (previous >= 0xd800 && previous <= 0xdbff)
223
+ start -= 1;
224
+ }
225
+ const character = text.slice(start, end);
220
226
  const size = Buffer.byteLength(character, 'utf8');
221
227
  if (bytes + size > budget)
222
228
  break;
223
- result = character + result;
229
+ characters.push(character);
224
230
  bytes += size;
231
+ end = start;
225
232
  }
226
- return result;
233
+ return characters.reverse().join('');
227
234
  }
@@ -286,17 +286,30 @@ export class AgentGraphCoordinator {
286
286
  /** Reconcile now and surface any host-level failure to explicit callers. */
287
287
  async reconcile(rootSessionId) {
288
288
  await this.#assertRootSupervisor(rootSessionId);
289
- const driver = await this.#driver(rootSessionId);
290
- driver.lastError = undefined;
291
- driver.paused = false;
292
- this.#requestDrive(driver);
293
- await this.waitForIdle(rootSessionId);
294
- if (driver.lastError !== undefined)
295
- throw driver.lastError;
296
- if (!driver.lastResult) {
297
- throw new Error(`Agent graph ${driver.graphId} produced no reconciliation result`);
289
+ let driver = await this.#driver(rootSessionId);
290
+ // A lookup started before handover can return after its driver retired.
291
+ while (driver.closed && !this.#closed)
292
+ driver = await this.#driver(rootSessionId);
293
+ driver.reconciliationReaders += 1;
294
+ try {
295
+ driver.lastError = undefined;
296
+ driver.paused = false;
297
+ this.#requestDrive(driver);
298
+ // An epoch handover must not redirect this caller to the next driver.
299
+ while (driver.task)
300
+ await driver.task;
301
+ if (driver.lastError !== undefined)
302
+ throw driver.lastError;
303
+ if (!driver.lastResult) {
304
+ throw new Error(`Agent graph ${driver.graphId} produced no reconciliation result`);
305
+ }
306
+ return driver.lastResult;
307
+ }
308
+ finally {
309
+ driver.reconciliationReaders -= 1;
310
+ if (driver.closed && driver.reconciliationReaders === 0)
311
+ driver.lastResult = undefined;
298
312
  }
299
- return driver.lastResult;
300
313
  }
301
314
  async waitForIdle(rootSessionId) {
302
315
  const driver = await this.#driver(rootSessionId);
@@ -1014,15 +1027,32 @@ export class AgentGraphCoordinator {
1014
1027
  const latest = await this.currentGraphEpoch(rootSessionId);
1015
1028
  if (latest.graphId !== current.graphId) {
1016
1029
  selected = latest;
1030
+ if (driver)
1031
+ void this.#retireDriver(driver);
1017
1032
  return;
1018
1033
  }
1019
1034
  if ((await this.#readSessionStateForGraph(rootSessionId, current.graphId)) !== 'terminal') {
1020
1035
  return;
1021
1036
  }
1022
1037
  selected = await this.advanceGraphEpoch(rootSessionId, current);
1038
+ if (driver)
1039
+ void this.#retireDriver(driver);
1023
1040
  });
1024
1041
  return selected;
1025
1042
  }
1043
+ async #retireDriver(driver) {
1044
+ // Tool closures can outlive their epoch. Fence them and let already
1045
+ // admitted operations finish before releasing their complete snapshots.
1046
+ // Cleanup belongs to the old epoch; its teardown I/O must not block the next.
1047
+ driver.closed = true;
1048
+ driver.requested = false;
1049
+ await Promise.allSettled([driver.task, driver.stopTask]);
1050
+ await this.#waitForClientProjectionUpdates(driver);
1051
+ if (driver.reconciliationReaders === 0)
1052
+ driver.lastResult = undefined;
1053
+ driver.runtimeFailureRunIds.clear();
1054
+ // Keep the lightweight driver for projection repair and close diagnostics.
1055
+ }
1026
1056
  async #readSessionStateForGraph(rootSessionId, graphId) {
1027
1057
  const snapshot = buildAgentGraphClientSnapshot(await this.#readClientModelInputForGraph(rootSessionId, graphId));
1028
1058
  if (snapshot.scheduleRevision === 0)
@@ -1094,6 +1124,7 @@ export class AgentGraphCoordinator {
1094
1124
  stopGeneration: 0,
1095
1125
  driveGeneration: 0,
1096
1126
  closed: false,
1127
+ reconciliationReaders: 0,
1097
1128
  clientProjectionDirty: false,
1098
1129
  runtimeFailureRunIds: new Set(),
1099
1130
  yieldWaiters: new Set(),
@@ -1125,6 +1156,8 @@ export class AgentGraphCoordinator {
1125
1156
  this.#requestDrive(driver);
1126
1157
  }
1127
1158
  #requestDrive(driver) {
1159
+ if (driver.closed || this.#closed)
1160
+ return;
1128
1161
  driver.requested = true;
1129
1162
  if (driver.task)
1130
1163
  return;
@@ -143,7 +143,12 @@ function truncateUtf8(text, maxBytes) {
143
143
  const ellipsisBytes = Buffer.byteLength(ellipsis, 'utf8');
144
144
  if (maxBytes < ellipsisBytes)
145
145
  return '';
146
- const codePoints = Array.from(text);
146
+ const codePoints = [];
147
+ for (const point of text) {
148
+ if (codePoints.length >= maxBytes)
149
+ break;
150
+ codePoints.push(point);
151
+ }
147
152
  let low = 0;
148
153
  let high = codePoints.length;
149
154
  let best = ellipsis;
@@ -151,10 +151,7 @@ async function checkedOpenAiCodexFetch(fetchFn, url, init, refreshOAuthAccessTok
151
151
  const response = await fetchFn(url, requestInit);
152
152
  if (response.ok)
153
153
  return response;
154
- const detail = await response
155
- .clone()
156
- .text()
157
- .catch(() => '');
154
+ const detail = await response.text().catch(() => '');
158
155
  if (response.status === 401 &&
159
156
  !authorizationReplayUsed &&
160
157
  refreshOAuthAccessToken &&
@@ -112,12 +112,12 @@ async function readWorkspaceInstructions(rootCandidate, scope) {
112
112
  if (seenDigests.has(digest))
113
113
  continue;
114
114
  seenDigests.add(digest);
115
- const chars = Array.from(cleaned).length;
115
+ const text = truncateCodepoints(cleaned, MAX_WORKSPACE_INSTRUCTION_FILE_CHARS);
116
116
  out.push({
117
117
  file,
118
118
  scope,
119
- text: truncateCodepoints(cleaned, MAX_WORKSPACE_INSTRUCTION_FILE_CHARS),
120
- truncated: chars > MAX_WORKSPACE_INSTRUCTION_FILE_CHARS,
119
+ text,
120
+ truncated: text.length < cleaned.length,
121
121
  });
122
122
  }
123
123
  catch {
@@ -130,8 +130,13 @@ function cleanPromptText(text) {
130
130
  return text.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '');
131
131
  }
132
132
  function truncateCodepoints(text, max) {
133
- const chars = Array.from(text);
134
- if (chars.length <= max)
133
+ if (text.length <= max)
135
134
  return text;
136
- return chars.slice(0, Math.max(0, max)).join('');
135
+ const chars = [];
136
+ for (const char of text) {
137
+ if (chars.length >= max)
138
+ return chars.join('');
139
+ chars.push(char);
140
+ }
141
+ return text;
137
142
  }
@@ -126,9 +126,9 @@ function mapTavilyRows(raw, limit) {
126
126
  continue;
127
127
  rows.push({
128
128
  provider: 'tavily',
129
- title: safeString(rawRow.title, location.url).slice(0, TAVILY_RESULT_TITLE_MAX_CHARS),
129
+ title: truncateResultText(safeString(rawRow.title, location.url), TAVILY_RESULT_TITLE_MAX_CHARS),
130
130
  url: location.url,
131
- snippet: safeString(rawRow.content).slice(0, TAVILY_RESULT_SNIPPET_MAX_CHARS),
131
+ snippet: truncateResultText(safeString(rawRow.content), TAVILY_RESULT_SNIPPET_MAX_CHARS),
132
132
  source: location.source,
133
133
  });
134
134
  if (rows.length >= limit)
@@ -166,6 +166,12 @@ async function readBoundedJson(response, maxBytes) {
166
166
  function safeString(value, fallback = '') {
167
167
  return typeof value === 'string' ? value : fallback;
168
168
  }
169
+ function truncateResultText(value, maxChars) {
170
+ if (value.length <= maxChars)
171
+ return value;
172
+ // Detach bounded results from large provider strings, preserving even unpaired UTF-16 surrogates.
173
+ return Buffer.from(value.slice(0, maxChars), 'utf16le').toString('utf16le');
174
+ }
169
175
  function normalizeResultLocation(value) {
170
176
  if (typeof value !== 'string' || value.length > TAVILY_RESULT_URL_MAX_CHARS)
171
177
  return null;
@@ -0,0 +1,49 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ // Match split('\n').slice(offset, end).join('\n'), without creating entries
20
+ // for lines outside the requested window. Empty and trailing lines count too.
21
+ // A missing or zero limit is unbounded: end is the total line count.
22
+ export function readTextLineWindow(content, offset, limit) {
23
+ if (offset === undefined && limit === undefined)
24
+ return content;
25
+ let lineCount = 1;
26
+ for (let cursor = content.indexOf('\n'); cursor !== -1; cursor = content.indexOf('\n', cursor + 1)) {
27
+ lineCount++;
28
+ }
29
+ const start = offset ?? 0;
30
+ const end = limit ? start + limit : lineCount;
31
+ const from = sliceIndex(start, lineCount);
32
+ const to = sliceIndex(end, lineCount);
33
+ if (from >= to)
34
+ return '';
35
+ const selected = [];
36
+ let cursor = 0;
37
+ for (let line = 0; line < to; line++) {
38
+ const newline = content.indexOf('\n', cursor);
39
+ const lineEnd = newline === -1 ? content.length : newline;
40
+ if (line >= from)
41
+ selected.push(content.slice(cursor, lineEnd));
42
+ cursor = lineEnd + 1;
43
+ }
44
+ return selected.join('\n');
45
+ }
46
+ function sliceIndex(value, length) {
47
+ const integer = Math.trunc(value) || 0;
48
+ return integer < 0 ? Math.max(length + integer, 0) : Math.min(integer, length);
49
+ }
@@ -47,9 +47,17 @@ function utf8Len(text) {
47
47
  * multi-byte sequence at the boundary with U+FFFD, which we strip.
48
48
  */
49
49
  function sliceLineByBytes(line, maxBytes, keep) {
50
- const buf = Buffer.from(line, 'utf8');
51
- if (buf.length <= maxBytes)
50
+ if (utf8Len(line) <= maxBytes)
52
51
  return line;
52
+ // One UTF-16 unit needs at least one UTF-8 byte. The extra unit keeps a
53
+ // surrogate pair crossing the window boundary outside the retained bytes.
54
+ // Preserve Buffer.subarray's original behavior for unusual numeric budgets.
55
+ const window = Number.isInteger(maxBytes) && maxBytes >= 0
56
+ ? keep === 'head'
57
+ ? line.slice(0, maxBytes + 1)
58
+ : line.slice(-(maxBytes + 1))
59
+ : line;
60
+ const buf = Buffer.from(window, 'utf8');
53
61
  const slice = keep === 'head' ? buf.subarray(0, maxBytes) : buf.subarray(buf.length - maxBytes);
54
62
  const decoded = slice.toString('utf8');
55
63
  return keep === 'head' ? decoded.replace(/�+$/, '') : decoded.replace(/^�+/, '');
@@ -68,33 +76,45 @@ export function truncateToolOutput(text, options = {}) {
68
76
  // A single trailing newline terminates the last line; it is not an extra
69
77
  // empty line, so it must not count against the line budget.
70
78
  const body = text.endsWith('\n') ? text.slice(0, -1) : text;
71
- const lines = body.split('\n');
72
- if (lines.length <= maxLines && totalBytes <= maxBytes) {
79
+ let lineCount = 1;
80
+ for (let index = body.indexOf('\n'); index !== -1; index = body.indexOf('\n', index + 1)) {
81
+ lineCount++;
82
+ }
83
+ if (lineCount <= maxLines && totalBytes <= maxBytes) {
73
84
  return { content: text, truncated: false, removed: 0, unit: 'lines' };
74
85
  }
75
86
  const out = [];
76
87
  let bytes = 0;
77
88
  let hitBytes = false;
78
89
  if (direction === 'head') {
79
- for (let i = 0; i < lines.length && i < maxLines; i++) {
80
- const size = utf8Len(lines[i]) + (i > 0 ? 1 : 0);
90
+ let start = 0;
91
+ for (let i = 0; i < lineCount && i < maxLines; i++) {
92
+ const newline = body.indexOf('\n', start);
93
+ const end = newline === -1 ? body.length : newline;
94
+ const line = body.slice(start, end);
95
+ const size = utf8Len(line) + (i > 0 ? 1 : 0);
81
96
  if (bytes + size > maxBytes) {
82
97
  hitBytes = true;
83
98
  break;
84
99
  }
85
- out.push(lines[i]);
100
+ out.push(line);
86
101
  bytes += size;
102
+ start = end + 1;
87
103
  }
88
104
  }
89
105
  else {
90
- for (let i = lines.length - 1; i >= 0 && out.length < maxLines; i--) {
91
- const size = utf8Len(lines[i]) + (out.length > 0 ? 1 : 0);
106
+ let end = body.length;
107
+ for (let i = lineCount - 1; i >= 0 && out.length < maxLines; i--) {
108
+ const start = end > 0 ? body.lastIndexOf('\n', end - 1) + 1 : 0;
109
+ const line = body.slice(start, end);
110
+ const size = utf8Len(line) + (out.length > 0 ? 1 : 0);
92
111
  if (bytes + size > maxBytes) {
93
112
  hitBytes = true;
94
113
  break;
95
114
  }
96
- out.unshift(lines[i]);
115
+ out.unshift(line);
97
116
  bytes += size;
117
+ end = start - 1;
98
118
  }
99
119
  }
100
120
  // The boundary line alone exceeds the byte budget. Rather than show only a
@@ -102,7 +122,10 @@ export function truncateToolOutput(text, options = {}) {
102
122
  // JSON/stack trace), keep a byte-safe slice of that line.
103
123
  let preview;
104
124
  if (out.length === 0) {
105
- const line = direction === 'head' ? lines[0] : lines[lines.length - 1];
125
+ const firstNewline = body.indexOf('\n');
126
+ const line = direction === 'head'
127
+ ? body.slice(0, firstNewline === -1 ? body.length : firstNewline)
128
+ : body.slice(body.lastIndexOf('\n') + 1);
106
129
  preview = sliceLineByBytes(line, maxBytes, direction);
107
130
  bytes = utf8Len(preview);
108
131
  hitBytes = true;
@@ -110,7 +133,7 @@ export function truncateToolOutput(text, options = {}) {
110
133
  else {
111
134
  preview = out.join('\n');
112
135
  }
113
- const removed = hitBytes ? Math.max(0, totalBytes - bytes) : lines.length - out.length;
136
+ const removed = hitBytes ? Math.max(0, totalBytes - bytes) : lineCount - out.length;
114
137
  if (removed <= 0) {
115
138
  // Nothing was actually dropped — e.g. content fits but a lone trailing
116
139
  // newline pushed totalBytes one over the byte budget. Don't emit a
@@ -58,19 +58,21 @@ export function createUnifiedDiff(path, oldContent, newContent) {
58
58
  export function createEditUnifiedDiff(path, oldContent, newContent, match) {
59
59
  if (oldContent.includes('\0') || newContent.includes('\0'))
60
60
  return undefined;
61
- const oldLines = splitLines(oldContent);
62
- const newLines = splitLines(newContent);
61
+ const oldLineCount = countLines(oldContent);
62
+ const newLineCount = countLines(newContent);
63
63
  const startIndex = match.startLine - 1;
64
64
  const oldEndIndex = match.endLine - 1;
65
- if (startIndex < 0 || oldEndIndex < startIndex || oldEndIndex >= oldLines.length) {
65
+ if (startIndex < 0 || oldEndIndex < startIndex || oldEndIndex >= oldLineCount) {
66
66
  return undefined;
67
67
  }
68
68
  const windowStart = Math.max(0, startIndex - CONTEXT_LINES);
69
69
  const oldAfterStart = oldEndIndex + 1;
70
- const newAfterStart = oldAfterStart + newLines.length - oldLines.length;
71
- const oldWindow = oldLines.slice(windowStart, Math.min(oldLines.length, oldAfterStart + CONTEXT_LINES));
72
- const newWindow = newLines.slice(windowStart, Math.min(newLines.length, Math.max(windowStart, newAfterStart) + CONTEXT_LINES));
73
- if (isDiffWindowTooLarge(oldWindow) || isDiffWindowTooLarge(newWindow))
70
+ const newAfterStart = oldAfterStart + newLineCount - oldLineCount;
71
+ const oldWindow = readDiffWindow(oldContent, windowStart, Math.min(oldLineCount, oldAfterStart + CONTEXT_LINES));
72
+ if (!oldWindow)
73
+ return undefined;
74
+ const newWindow = readDiffWindow(newContent, windowStart, Math.min(newLineCount, Math.max(windowStart, newAfterStart) + CONTEXT_LINES));
75
+ if (!newWindow)
74
76
  return undefined;
75
77
  const ops = diffLines(oldWindow, newWindow);
76
78
  if (ops.every((op) => op.kind === 'keep'))
@@ -85,9 +87,6 @@ export function createEditUnifiedDiff(path, oldContent, newContent, match) {
85
87
  function isUndiffable(content) {
86
88
  return content.includes('\0') || Buffer.byteLength(content, 'utf8') > MAX_DIFF_SOURCE_BYTES;
87
89
  }
88
- function isDiffWindowTooLarge(lines) {
89
- return lines.length > MAX_DIFF_SOURCE_LINES || isUndiffable(lines.join('\n'));
90
- }
91
90
  function splitLines(content) {
92
91
  const lines = content.split('\n');
93
92
  // A trailing newline terminates the last line rather than starting an empty
@@ -96,6 +95,37 @@ function splitLines(content) {
96
95
  lines.pop();
97
96
  return lines;
98
97
  }
98
+ function countLines(content) {
99
+ let count = content.length > 0 && !content.endsWith('\n') ? 1 : 0;
100
+ for (let index = content.indexOf('\n'); index !== -1; index = content.indexOf('\n', index + 1)) {
101
+ count += 1;
102
+ }
103
+ return count;
104
+ }
105
+ /** Collect only the requested lines, failing before an oversized window is materialized. */
106
+ function readDiffWindow(content, startLine, endLine) {
107
+ // Preserve Array.slice's fractional/NaN index normalization.
108
+ const from = Math.trunc(startLine) || 0;
109
+ const until = Math.trunc(endLine) || 0;
110
+ const lines = [];
111
+ let bytes = 0;
112
+ let offset = 0;
113
+ for (let lineIndex = 0; offset < content.length && lineIndex < until; lineIndex += 1) {
114
+ const newline = content.indexOf('\n', offset);
115
+ const end = newline === -1 ? content.length : newline;
116
+ if (lineIndex >= from) {
117
+ if (lines.length === MAX_DIFF_SOURCE_LINES)
118
+ return undefined;
119
+ const line = content.slice(offset, end);
120
+ bytes += Buffer.byteLength(line, 'utf8') + (lines.length > 0 ? 1 : 0);
121
+ if (bytes > MAX_DIFF_SOURCE_BYTES)
122
+ return undefined;
123
+ lines.push(line);
124
+ }
125
+ offset = end + 1;
126
+ }
127
+ return lines;
128
+ }
99
129
  /** Line-level edit script via LCS dynamic programming, bounded by the caps above. */
100
130
  function diffLines(oldLines, newLines) {
101
131
  const n = oldLines.length;
@@ -56,8 +56,10 @@ function truncateWebFetchOutput(content) {
56
56
  if (Buffer.byteLength(content, 'utf8') <= WEB_FETCH_MODEL_OUTPUT_MAX_BYTES)
57
57
  return content;
58
58
  const markerBytes = Buffer.byteLength(WEB_FETCH_TRUNCATION_MARKER, 'utf8');
59
- const kept = Buffer.from(content, 'utf8')
60
- .subarray(0, WEB_FETCH_MODEL_OUTPUT_MAX_BYTES - markerBytes)
59
+ const contentBytes = WEB_FETCH_MODEL_OUTPUT_MAX_BYTES - markerBytes;
60
+ // The extra UTF-16 unit keeps a split surrogate outside the retained bytes.
61
+ const kept = Buffer.from(content.slice(0, contentBytes + 1), 'utf8')
62
+ .subarray(0, contentBytes)
61
63
  .toString('utf8')
62
64
  .replace(/�+$/, '');
63
65
  return kept + WEB_FETCH_TRUNCATION_MARKER;
@@ -830,8 +830,8 @@ function computeEditedSource(source, oldString, newString, where) {
830
830
  function finish(content, span, replacement, matchedVia) {
831
831
  const index = content.indexOf(span);
832
832
  const before = content.slice(0, index);
833
- const startLine = before.split("\n").length;
834
- const spanLineCount = span.split("\n").length - (span.endsWith("\n") ? 1 : 0);
833
+ const startLine = countOccurrences(before, "\n") + 1;
834
+ const spanLineCount = countOccurrences(span, "\n") + 1 - (span.endsWith("\n") ? 1 : 0);
835
835
  const endLine = startLine + Math.max(spanLineCount, 1) - 1;
836
836
  const next = before + replacement + content.slice(index + span.length);
837
837
  return { content: next, matchedVia, startLine, endLine };
@@ -941,6 +941,33 @@ function computeEditedSource(source, oldString, newString, where) {
941
941
  }
942
942
  }
943
943
 
944
+ // src/text-line-window.ts
945
+ function readTextLineWindow(content, offset, limit) {
946
+ if (offset === void 0 && limit === void 0) return content;
947
+ let lineCount = 1;
948
+ for (let cursor2 = content.indexOf("\n"); cursor2 !== -1; cursor2 = content.indexOf("\n", cursor2 + 1)) {
949
+ lineCount++;
950
+ }
951
+ const start = offset ?? 0;
952
+ const end = limit ? start + limit : lineCount;
953
+ const from = sliceIndex(start, lineCount);
954
+ const to = sliceIndex(end, lineCount);
955
+ if (from >= to) return "";
956
+ const selected = [];
957
+ let cursor = 0;
958
+ for (let line = 0; line < to; line++) {
959
+ const newline = content.indexOf("\n", cursor);
960
+ const lineEnd = newline === -1 ? content.length : newline;
961
+ if (line >= from) selected.push(content.slice(cursor, lineEnd));
962
+ cursor = lineEnd + 1;
963
+ }
964
+ return selected.join("\n");
965
+ }
966
+ function sliceIndex(value, length) {
967
+ const integer2 = Math.trunc(value) || 0;
968
+ return integer2 < 0 ? Math.max(length + integer2, 0) : Math.min(integer2, length);
969
+ }
970
+
944
971
  // src/unified-diff.ts
945
972
  var MAX_DIFF_SOURCE_LINES = 800;
946
973
  var MAX_DIFF_SOURCE_BYTES = 32 * 1024;
@@ -960,25 +987,28 @@ function createUnifiedDiff(path2, oldContent, newContent) {
960
987
  }
961
988
  function createEditUnifiedDiff(path2, oldContent, newContent, match) {
962
989
  if (oldContent.includes("\0") || newContent.includes("\0")) return void 0;
963
- const oldLines = splitLines(oldContent);
964
- const newLines = splitLines(newContent);
990
+ const oldLineCount = countLines(oldContent);
991
+ const newLineCount = countLines(newContent);
965
992
  const startIndex = match.startLine - 1;
966
993
  const oldEndIndex = match.endLine - 1;
967
- if (startIndex < 0 || oldEndIndex < startIndex || oldEndIndex >= oldLines.length) {
994
+ if (startIndex < 0 || oldEndIndex < startIndex || oldEndIndex >= oldLineCount) {
968
995
  return void 0;
969
996
  }
970
997
  const windowStart = Math.max(0, startIndex - CONTEXT_LINES);
971
998
  const oldAfterStart = oldEndIndex + 1;
972
- const newAfterStart = oldAfterStart + newLines.length - oldLines.length;
973
- const oldWindow = oldLines.slice(
999
+ const newAfterStart = oldAfterStart + newLineCount - oldLineCount;
1000
+ const oldWindow = readDiffWindow(
1001
+ oldContent,
974
1002
  windowStart,
975
- Math.min(oldLines.length, oldAfterStart + CONTEXT_LINES)
1003
+ Math.min(oldLineCount, oldAfterStart + CONTEXT_LINES)
976
1004
  );
977
- const newWindow = newLines.slice(
1005
+ if (!oldWindow) return void 0;
1006
+ const newWindow = readDiffWindow(
1007
+ newContent,
978
1008
  windowStart,
979
- Math.min(newLines.length, Math.max(windowStart, newAfterStart) + CONTEXT_LINES)
1009
+ Math.min(newLineCount, Math.max(windowStart, newAfterStart) + CONTEXT_LINES)
980
1010
  );
981
- if (isDiffWindowTooLarge(oldWindow) || isDiffWindowTooLarge(newWindow)) return void 0;
1011
+ if (!newWindow) return void 0;
982
1012
  const ops = diffLines(oldWindow, newWindow);
983
1013
  if (ops.every((op) => op.kind === "keep")) return void 0;
984
1014
  const diff = [
@@ -991,14 +1021,38 @@ function createEditUnifiedDiff(path2, oldContent, newContent, match) {
991
1021
  function isUndiffable(content) {
992
1022
  return content.includes("\0") || Buffer.byteLength(content, "utf8") > MAX_DIFF_SOURCE_BYTES;
993
1023
  }
994
- function isDiffWindowTooLarge(lines) {
995
- return lines.length > MAX_DIFF_SOURCE_LINES || isUndiffable(lines.join("\n"));
996
- }
997
1024
  function splitLines(content) {
998
1025
  const lines = content.split("\n");
999
1026
  if (lines.at(-1) === "") lines.pop();
1000
1027
  return lines;
1001
1028
  }
1029
+ function countLines(content) {
1030
+ let count = content.length > 0 && !content.endsWith("\n") ? 1 : 0;
1031
+ for (let index = content.indexOf("\n"); index !== -1; index = content.indexOf("\n", index + 1)) {
1032
+ count += 1;
1033
+ }
1034
+ return count;
1035
+ }
1036
+ function readDiffWindow(content, startLine, endLine) {
1037
+ const from = Math.trunc(startLine) || 0;
1038
+ const until = Math.trunc(endLine) || 0;
1039
+ const lines = [];
1040
+ let bytes = 0;
1041
+ let offset = 0;
1042
+ for (let lineIndex = 0; offset < content.length && lineIndex < until; lineIndex += 1) {
1043
+ const newline = content.indexOf("\n", offset);
1044
+ const end = newline === -1 ? content.length : newline;
1045
+ if (lineIndex >= from) {
1046
+ if (lines.length === MAX_DIFF_SOURCE_LINES) return void 0;
1047
+ const line = content.slice(offset, end);
1048
+ bytes += Buffer.byteLength(line, "utf8") + (lines.length > 0 ? 1 : 0);
1049
+ if (bytes > MAX_DIFF_SOURCE_BYTES) return void 0;
1050
+ lines.push(line);
1051
+ }
1052
+ offset = end + 1;
1053
+ }
1054
+ return lines;
1055
+ }
1002
1056
  function diffLines(oldLines, newLines) {
1003
1057
  const n = oldLines.length;
1004
1058
  const m = newLines.length;
@@ -6747,8 +6801,6 @@ var memo = {
6747
6801
  attach(inst) {
6748
6802
  var _a3;
6749
6803
  let isRecursiveInst;
6750
- let lastCtx;
6751
- let lastBucket;
6752
6804
  (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
6753
6805
  inst._zod.deferred.push(() => {
6754
6806
  const base = inst._zod.parse;
@@ -6770,14 +6822,7 @@ var memo = {
6770
6822
  state = { buckets: /* @__PURE__ */ new Map(), backEdges: void 0 };
6771
6823
  ctx[STATE] = state;
6772
6824
  }
6773
- let bucket;
6774
- if (lastCtx === ctx) {
6775
- bucket = lastBucket;
6776
- } else {
6777
- bucket = bucketFor(state, inst);
6778
- lastCtx = ctx;
6779
- lastBucket = bucket;
6780
- }
6825
+ const bucket = bucketFor(state, inst);
6781
6826
  const hit = bucket.get(input2);
6782
6827
  if (hit) {
6783
6828
  payload.value = hit.value;
@@ -6791,11 +6836,17 @@ var memo = {
6791
6836
  }
6792
6837
  return payload;
6793
6838
  }
6839
+ const previousHandoff = handoff;
6794
6840
  handoff = bucket;
6795
6841
  const depth = open2.length;
6796
- const result = base(payload, ctx);
6797
- handoff = void 0;
6798
- const entry = open2.length > depth ? open2.pop() : void 0;
6842
+ let result;
6843
+ let entry;
6844
+ try {
6845
+ result = base(payload, ctx);
6846
+ } finally {
6847
+ handoff = previousHandoff;
6848
+ entry = open2.length > depth ? open2.pop() : void 0;
6849
+ }
6799
6850
  if (result instanceof Promise) {
6800
6851
  return result.then((r) => {
6801
6852
  if (entry)
@@ -20815,12 +20866,10 @@ async function executeFilesystemOperation(operation, operationBoundary, dependen
20815
20866
  }
20816
20867
  }
20817
20868
  const content = await fs3.readFile(path2, "utf8");
20818
- if (operation.offset === void 0 && operation.limit === void 0)
20819
- return { kind: "read", content };
20820
- const lines = content.split("\n");
20821
- const start = operation.offset ?? 0;
20822
- const end = operation.limit ? start + operation.limit : lines.length;
20823
- return { kind: "read", content: lines.slice(start, end).join("\n") };
20869
+ return {
20870
+ kind: "read",
20871
+ content: readTextLineWindow(content, operation.offset, operation.limit)
20872
+ };
20824
20873
  }
20825
20874
  case "write": {
20826
20875
  const path2 = await resolveWritableAllowed(