aegiscode 7.0.14 → 7.0.16

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 (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
package/src/devrun.js CHANGED
@@ -1,189 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * /run support: sniff the project's dev command and run it in a captured
10
- * sub-shell. Output streams to the transcript as it happens; the session loop
11
- * can stop the process (Esc) via the returned job handle.
12
- *
13
- * Ported from the upstream engine reference (ESM → CommonJS).
14
- */
15
-
16
- const { spawn } = require('node:child_process');
17
- const fs = require('node:fs');
18
- const path = require('node:path');
19
-
20
- // The one shared module that knows which OS this is (plan Phase 30.1), staged
21
- // into `cli/vendor/client/` for the published layout — same resolver every
22
- // other shared client module goes through, so this file never re-derives
23
- // `process.platform` on its own (that duplication is F4's complaint).
24
- const { resolveClientModule } = require('./shared.js');
25
- const sharedPlatform = require(resolveClientModule('platform.js'));
26
-
27
- const MAX_STREAM_LINES = 40;
28
-
29
- /** Detect the most likely dev command for a project, or null. */
30
- function detectDevCommand(cwd = process.cwd()) {
31
- const pkg = path.join(cwd, 'package.json');
32
- if (fs.existsSync(pkg)) {
33
- try {
34
- const scripts = JSON.parse(fs.readFileSync(pkg, 'utf8')).scripts || {};
35
- for (const name of ['dev', 'start', 'watch', 'serve']) {
36
- if (typeof scripts[name] === 'string' && scripts[name].trim()) return `npm run ${name}`;
37
- }
38
- } catch {}
39
- return 'npm start';
40
- }
41
- if (fs.existsSync(path.join(cwd, 'go.mod'))) return 'go run .';
42
- if (fs.existsSync(path.join(cwd, 'Cargo.toml'))) return 'cargo run';
43
- if (fs.existsSync(path.join(cwd, 'Makefile'))) return 'make';
44
- if (fs.existsSync(path.join(cwd, 'pyproject.toml'))) return 'python -m <module>'; // honest: user picks
45
- return null;
46
- }
47
-
48
- /**
49
- * Run a shell command, streaming stdout/stderr lines to onLine. Returns a job:
50
- * { stop(), done: Promise<{ code, stopped }> }
51
- * The child — and, via platform.killTree(), its descendants — is killed when
52
- * stop() is called or `signal` aborts.
53
- *
54
- * Options:
55
- * onLine (line) => void stream sink
56
- * signal AbortSignal abort => stop
57
- * cwd string
58
- * onError (err, result) => void where a FAILED kill is reported
59
- * platform implementation or name the test seam: pass an object with
60
- * `killTree` to stub the kill, or an
61
- * OS name ('win32' | 'linux' | …) to
62
- * drive the real module's win32 path
63
- * from a non-Windows host
64
- * killOptions seams forwarded to killTree ({ platform, kill, run, signal,
65
- * detached, timeout })
66
- */
67
- function runDevServer(command, { onLine, signal, cwd, onError, platform: platformImpl, killOptions } = {}) {
68
- // detached: the child leads its own process group on posix, which is what
69
- // lets killTree() take the whole tree out with kill(-pid) instead of leaking
70
- // grandchildren. On win32 there is no group to signal — killTree() uses
71
- // `taskkill /T` to walk the parent/child tree instead.
72
- const child = spawn(command, { shell: true, cwd: cwd || process.cwd(), env: process.env, detached: true });
73
- let buffer = '';
74
- let stopped = false;
75
- let code = null;
76
- let nLines = 0;
77
- // Settle-once guard shared by every completion path. The job's `done` MUST
78
- // resolve: the session loop's streamJob guard — which swallows every key
79
- // while a /run job is live — is only cleared by job.done settling. If
80
- // 'close' never fires (a detached grandchild escaped the group kill and
81
- // still holds the stdout pipe), 'exit' + the stop fallback cover it.
82
- let doneResolved = false;
83
- let resolveDone = null;
84
-
85
- const deliver = (chunk) => {
86
- buffer += chunk;
87
- let idx;
88
- while ((idx = buffer.indexOf('\n')) >= 0) {
89
- const line = buffer.slice(0, idx).replace(/\r$/, '').trimEnd();
90
- buffer = buffer.slice(idx + 1);
91
- if (line && nLines++ < MAX_STREAM_LINES && onLine) onLine(line);
92
- }
93
- };
94
- child.stdout && child.stdout.on('data', deliver);
95
- child.stderr && child.stderr.on('data', deliver);
96
- if (buffer.trim() && onLine) onLine(buffer.trim()); // trailing partial line
97
-
98
- // ---------------------------------------------------------------------
99
- // Stopping the server (plan Phase 30.2, defect F3).
100
- //
101
- // This used to be a bare negative-pid signal to the process group, wrapped in
102
- // an empty `try {} catch {}`.
103
- //
104
- // A negative pid is a POSIX *process-group* kill. On win32 that call throws,
105
- // and the empty catch ate the throw, so the dev server and every child it
106
- // had spawned were silently orphaned with no error anywhere: not in the
107
- // transcript, not on stderr. The swallow was as much the bug as the signal
108
- // (the same defect class the engine fixed in its Phase 21c, src/proc.js).
109
- //
110
- // The stop now goes through platform.killTree() (the shared module, plan
111
- // 30.1): posix keeps the detached-group kill, win32 runs
112
- // `taskkill /PID <pid> /T /F`, and the result is `{ ok, error }` rather than
113
- // a throw — so a failure can be *reported*. It is: onError if the caller
114
- // gave one, otherwise the transcript the user is already reading, otherwise
115
- // stderr. Never dropped.
116
- // ---------------------------------------------------------------------
117
- const killApi =
118
- platformImpl && typeof platformImpl === 'object' && typeof platformImpl.killTree === 'function'
119
- ? platformImpl
120
- : sharedPlatform;
121
- const killSeams = { ...(killOptions || {}) };
122
- if (typeof platformImpl === 'string' && !killSeams.platform) killSeams.platform = platformImpl;
123
-
124
- const reportKillFailure = (err) => {
125
- if (typeof onError === 'function') {
126
- onError(err);
127
- return;
128
- }
129
- const text = `[run] could not stop the dev server (pid ${child.pid}): ${err && err.message} — it may still be running`;
130
- if (typeof onLine === 'function') onLine(text);
131
- else console.error(text);
132
- };
133
-
134
- let killError = null;
135
- const killGroup = () => {
136
- const res = killApi.killTree(child, killSeams);
137
- if (res && res.ok) return res;
138
- killError = (res && res.error) || new Error('killTree failed without an error result');
139
- reportKillFailure(killError);
140
- return res;
141
- };
142
- const onAbort = () => { stopped = true; killGroup(); };
143
- if (signal) signal.addEventListener('abort', onAbort, { once: true });
144
-
145
- const settle = (patch) => {
146
- if (doneResolved) return;
147
- doneResolved = true;
148
- if (signal) signal.removeEventListener('abort', onAbort);
149
- resolveDone(patch);
150
- };
151
-
152
- const done = new Promise((resolve) => { resolveDone = resolve; });
153
- child.on('error', () => settle({ code: code ?? 1, stopped }));
154
- child.on('close', (c) => {
155
- code = c;
156
- settle({ code, stopped });
157
- });
158
- // 'close' waits for the stdio pipes; a grandchild that escaped the group
159
- // keeps the write end open and 'close' never fires. Settle shortly after
160
- // the shell itself exits, whatever the pipes do.
161
- child.on('exit', () => setTimeout(() => settle({ code: code ?? 0, stopped }), 1000));
162
-
163
- return {
164
- // The spawned pid — the one stop() actually kills, and the value a caller
165
- // (or a test, on a host that is not the OS under test) needs to reason
166
- // about the kill after the fact.
167
- pid: child.pid,
168
- stop: () => {
169
- stopped = true;
170
- const res = killGroup();
171
- // Pipe-holding survivors can still delay 'close' — force the job to
172
- // settle so the session loop's streamJob guard can't swallow keys.
173
- setTimeout(() => settle({ code: code ?? null, stopped: true }), 5000);
174
- return res;
175
- },
176
- // The last kill failure, if any — the caller can report it after the fact
177
- // instead of only through the onError callback.
178
- get killError() {
179
- return killError;
180
- },
181
- done,
182
- };
183
- }
184
-
185
- module.exports = {
186
- MAX_STREAM_LINES,
187
- detectDevCommand,
188
- runDevServer,
189
- };
3
+ "use strict";const{spawn:spawn}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),{resolveClientModule:resolveClientModule}=require("./shared.js"),sharedPlatform=require(resolveClientModule("platform.js")),MAX_STREAM_LINES=40;function detectDevCommand(e=process.cwd()){const t=path.join(e,"package.json");if(fs.existsSync(t)){try{const e=JSON.parse(fs.readFileSync(t,"utf8")).scripts||{};for(const t of["dev","start","watch","serve"])if("string"==typeof e[t]&&e[t].trim())return`npm run ${t}`}catch{}return"npm start"}return fs.existsSync(path.join(e,"go.mod"))?"go run .":fs.existsSync(path.join(e,"Cargo.toml"))?"cargo run":fs.existsSync(path.join(e,"Makefile"))?"make":fs.existsSync(path.join(e,"pyproject.toml"))?"python -m <module>":null}function runDevServer(e,{onLine:t,signal:r,cwd:o,onError:n,platform:s,killOptions:i}={}){const l=spawn(e,{shell:!0,cwd:o||process.cwd(),env:process.env,detached:!0});let c="",d=!1,p=null,a=0,u=!1,f=null;const m=e=>{let r;for(c+=e;(r=c.indexOf("\n"))>=0;){const e=c.slice(0,r).replace(/\r$/,"").trimEnd();c=c.slice(r+1),e&&a++<40&&t&&t(e)}};l.stdout&&l.stdout.on("data",m),l.stderr&&l.stderr.on("data",m),c.trim()&&t&&t(c.trim());const v=s&&"object"==typeof s&&"function"==typeof s.killTree?s:sharedPlatform,h={...i||{}};"string"!=typeof s||h.platform||(h.platform=s);let y=null;const S=()=>{const e=v.killTree(l,h);return e&&e.ok||(y=e&&e.error||new Error("killTree failed without an error result"),(e=>{if("function"==typeof n)return void n(e);const r=`[run] could not stop the dev server (pid ${l.pid}): ${e&&e.message} — it may still be running`;"function"==typeof t?t(r):console.error(r)})(y)),e},g=()=>{d=!0,S()};r&&r.addEventListener("abort",g,{once:!0});const w=e=>{u||(u=!0,r&&r.removeEventListener("abort",g),f(e))},j=new Promise((e=>{f=e}));return l.on("error",(()=>w({code:p??1,stopped:d}))),l.on("close",(e=>{p=e,w({code:p,stopped:d})})),l.on("exit",(()=>setTimeout((()=>w({code:p??0,stopped:d})),1e3))),{pid:l.pid,stop:()=>{d=!0;const e=S();return setTimeout((()=>w({code:p??null,stopped:!0})),5e3),e},get killError(){return y},done:j}}module.exports={MAX_STREAM_LINES:40,detectDevCommand:detectDevCommand,runDevServer:runDevServer};
package/src/diff.js CHANGED
@@ -1,335 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Line-level diff for the transcript's edit blocks.
10
- *
11
- * An `editFile`/`writeFile` call used to render as a single gray row
12
- * (" ⎿ $ {\"file_path\":\"src/hello.js\",...}"): you could see that a file
13
- * changed and never *what* changed — the one thing a coding session is
14
- * actually about. This module turns the tool call's arguments into a real
15
- * unified-style diff, which diffview.js paints as a colored block.
16
- *
17
- * Where the two sides come from:
18
- * editFile — args.old_string → args.new_string. No I/O at all.
19
- * writeFile — the file as it was on disk *before* the call ran, against
20
- * args.content. app.js builds the preview when the tool's
21
- * `phase: 'run'` event arrives, which is strictly before the
22
- * executor writes, so the read is the pre-edit state.
23
- *
24
- * Pure: strings in, plain row objects out — no spans, no colors, no globals,
25
- * no `process.stdout` — so the whole thing is unit-testable with no TTY. The
26
- * ANSI painting lives in diffview.js, exactly the split render.js already
27
- * keeps between structure and paint.
28
- *
29
- * Ported from the upstream engine reference; the engine's tool names are
30
- * `Edit`/`Write`/`MultiEdit`, this host's are `editFile`/`writeFile`, so
31
- * `editPreview` accepts both spellings. `MultiEdit` has no counterpart here
32
- * and is kept only so a newer engine frame cannot silently render nothing.
33
- */
34
-
35
- const fs = require('node:fs');
36
- const path = require('node:path');
37
-
38
- // Budgets. The preview is built synchronously inside the tool event, on the
39
- // render path, so a 200 MB writeFile must not stall the CLI — the read is
40
- // capped and the LCS table is bounded so a pathological pair of long files
41
- // cannot allocate hundreds of megabytes. Past a budget the middle collapses to
42
- // "remove everything, add everything", which is honest about being incomplete
43
- // (`truncated: true` on the preview, `… N unchanged lines` in the block).
44
- const DIFF_LIMITS = {
45
- fileBytes: 256 * 1024, // bytes read from disk for writeFile
46
- lcsCells: 250000, // n*m cap for the LCS table (~1 MB of Int32)
47
- rows: 400, // diff rows kept per preview
48
- context: 3, // unchanged lines kept around each change
49
- };
50
-
51
- /**
52
- * Split text into display lines. A trailing newline is a terminator, not an
53
- * empty last line — otherwise every normal file diff ends in a phantom
54
- * "- " / "+ " pair. CRLF is normalized so a Windows checkout doesn't render as
55
- * "every line changed".
56
- */
57
- function splitLines(text) {
58
- const s = String(text == null ? '' : text).replace(/\r\n?/g, '\n');
59
- if (s === '') return [];
60
- const lines = s.split('\n');
61
- if (lines.length && lines[lines.length - 1] === '') lines.pop();
62
- return lines;
63
- }
64
-
65
- /**
66
- * Unified-style diff of two strings.
67
- *
68
- * @returns {{rows: Array<{sign: string, text: string, no: number|null,
69
- * marker?: boolean, note?: string}>, adds: number, dels: number,
70
- * truncated: boolean}} `rows` carries context rows around each change run
71
- * (DIFF_LIMITS.context lines), collapsed runs of unchanged lines as `marker`
72
- * rows, and every changed line with a `no` for the gutter (old number on
73
- * '-', new number otherwise).
74
- */
75
- function lineDiff(oldText, newText) {
76
- const a = splitLines(oldText);
77
- const b = splitLines(newText);
78
- let pre = 0;
79
- while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
80
- let post = 0;
81
- while (post < a.length - pre && post < b.length - pre && a[a.length - 1 - post] === b[b.length - 1 - post]) post++;
82
-
83
- const midA = a.slice(pre, a.length - post);
84
- const midB = b.slice(pre, b.length - post);
85
- const ops = lcsOps(midA, midB);
86
- const truncated = ops === null;
87
- const body = ops || [
88
- ...midA.map((text) => ({ sign: '-', text })),
89
- ...midB.map((text) => ({ sign: '+', text })),
90
- ];
91
-
92
- // Nothing changed: say so with no rows at all. The prefix/suffix trim ate the
93
- // whole file (pre === a.length, post === 0), so the context arithmetic below
94
- // would otherwise paint "… 46 unchanged lines" plus three orphans over an
95
- // identical pair — a marker claiming an omission that never happened.
96
- if (!body.some((op) => op.sign !== ' ')) return { rows: [], adds: 0, dels: 0, truncated };
97
-
98
- const ctx = DIFF_LIMITS.context;
99
-
100
- const rows = [];
101
- let oldNo = 1;
102
- let newNo = 1;
103
- // Leading context: keep *all* of it when it fits, otherwise the last `ctx`
104
- // lines plus a marker for the ones actually dropped. The engine's original
105
- // condition (`ctxBeforeStart < pre`) fires whenever the change is preceded by
106
- // any line at all, so an ordinary three-line edit grew a bogus
107
- // "… 1 unchanged line" marker and a change deep in a file reported `ctx` as
108
- // the number hidden rather than the real count. A marker means "something was
109
- // omitted", so it may only appear when something was.
110
- const leadStart = pre > ctx ? pre - ctx : 0;
111
- const hiddenLead = leadStart;
112
- if (hiddenLead > 0) {
113
- rows.push({ sign: ' ', text: '', marker: true, note: `… ${hiddenLead} unchanged line${hiddenLead === 1 ? '' : 's'}` });
114
- }
115
- for (let i = leadStart; i < pre; i++) {
116
- rows.push({ sign: ' ', text: a[i], no: newNo });
117
- newNo++;
118
- oldNo++;
119
- }
120
- for (const op of body) {
121
- if (op.sign === ' ') {
122
- rows.push({ sign: ' ', text: op.text, no: newNo });
123
- newNo++;
124
- oldNo++;
125
- } else if (op.sign === '-') {
126
- rows.push({ sign: '-', text: op.text, no: oldNo });
127
- oldNo++;
128
- } else {
129
- rows.push({ sign: '+', text: op.text, no: newNo });
130
- newNo++;
131
- }
132
- }
133
- // Suffix context: the first `ctx` lines of the untouched tail, then a marker
134
- // for whatever unchanged tail is left over. Both the index into `b` and the
135
- // gutter number come from `b`'s tail, not `a`'s: the engine read
136
- // `b[a.length - post + i]`, which is the wrong line — and the wrong numbering
137
- // — for every edit that changes the line count.
138
- const tailStart = b.length - post;
139
- const tailCount = Math.min(post, ctx);
140
- newNo = tailStart + 1;
141
- for (let i = 0; i < tailCount; i++) {
142
- rows.push({ sign: ' ', text: b[tailStart + i], no: newNo });
143
- newNo++;
144
- oldNo++;
145
- }
146
- if (post > ctx) {
147
- const n = post - ctx;
148
- rows.push({ sign: ' ', text: '', marker: true, note: `… ${n} unchanged line${n === 1 ? '' : 's'}` });
149
- }
150
-
151
- const adds = rows.filter((r) => r.sign === '+').length;
152
- const dels = rows.filter((r) => r.sign === '-').length;
153
- let out = rows;
154
- let cut = false;
155
- if (out.length > DIFF_LIMITS.rows) {
156
- out = out.slice(0, DIFF_LIMITS.rows);
157
- out.push({ sign: ' ', text: '', marker: true, note: `… ${rows.length - DIFF_LIMITS.rows} more diff lines` });
158
- cut = true;
159
- }
160
- return { rows: out, adds, dels, truncated: truncated || cut };
161
- }
162
-
163
- /**
164
- * Longest-common-subsequence walk over two line arrays.
165
- * @returns {Array<{sign: string, text: string}>|null} ops, or null when the
166
- * table would exceed DIFF_LIMITS.lcsCells (the caller then treats the middle
167
- * as a full replacement).
168
- */
169
- function lcsOps(a, b) {
170
- const n = a.length;
171
- const m = b.length;
172
- if (!n || !m) {
173
- return [
174
- ...a.map((text) => ({ sign: '-', text })),
175
- ...b.map((text) => ({ sign: '+', text })),
176
- ];
177
- }
178
- if (n * m > DIFF_LIMITS.lcsCells) return null;
179
- const w = m + 1;
180
- const dp = new Int32Array((n + 1) * w); // dp[i*w+j] = |LCS(a[i:], b[j:])|
181
- for (let i = n - 1; i >= 0; i--) {
182
- for (let j = m - 1; j >= 0; j--) {
183
- dp[i * w + j] = a[i] === b[j]
184
- ? dp[(i + 1) * w + (j + 1)] + 1
185
- : Math.max(dp[(i + 1) * w + j], dp[i * w + (j + 1)]);
186
- }
187
- }
188
- const ops = [];
189
- let i = 0;
190
- let j = 0;
191
- while (i < n && j < m) {
192
- if (a[i] === b[j]) { ops.push({ sign: ' ', text: a[i] }); i++; j++; }
193
- else if (dp[(i + 1) * w + j] >= dp[i * w + (j + 1)]) { ops.push({ sign: '-', text: a[i] }); i++; }
194
- else { ops.push({ sign: '+', text: b[j] }); j++; }
195
- }
196
- while (i < n) ops.push({ sign: '-', text: a[i++] });
197
- while (j < m) ops.push({ sign: '+', text: b[j++] });
198
- return ops;
199
- }
200
-
201
- /** Capped read for the pre-edit state. Never throws; missing/unreadable → null. */
202
- function readCapped(file, opts = {}) {
203
- const bytes = opts.bytes == null ? DIFF_LIMITS.fileBytes : opts.bytes;
204
- try {
205
- const st = fs.statSync(file);
206
- if (!st.isFile()) return { text: null, missing: true };
207
- const text = fs.readFileSync(file, 'utf8');
208
- if (st.size > bytes) return { text: text.slice(0, bytes), missing: false, truncated: true };
209
- return { text, missing: false };
210
- } catch {
211
- return { text: null, missing: true };
212
- }
213
- }
214
-
215
- /** Path as the user thinks of it: relative to the session cwd when it is inside it. */
216
- function shortPath(file, cwd) {
217
- const f = String(file || '');
218
- if (!cwd) return f;
219
- const rel = path.relative(cwd, f);
220
- if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return rel;
221
- const parts = f.split(path.sep).filter(Boolean);
222
- const base = f.startsWith(path.sep) ? path.sep : '';
223
- return parts.length > 2 ? base + '…' + path.sep + parts.slice(-2).join(path.sep) : f;
224
- }
225
-
226
- /**
227
- * Build the diff preview for a tool call, or null when the call isn't an edit
228
- * or its arguments don't carry enough to diff (a partial stream, a malformed
229
- * call). Never throws — a preview is decoration, not the tool result, so a bad
230
- * argument object must not be able to break a turn.
231
- *
232
- * @param {string} name Tool name — this host's `editFile`/`writeFile`, or the
233
- * engine's `Edit`/`Write`/`MultiEdit` (a vendored frame can carry either).
234
- * @param {object|string} args Tool arguments as parsed from the stream.
235
- * @param {{cwd?: string, readFile?: Function}} [opts] `readFile` is injectable
236
- * so tests never touch disk.
237
- */
238
- function editPreview(name, args, opts = {}) {
239
- try {
240
- const cwd = opts.cwd == null ? process.cwd() : opts.cwd;
241
- const readFile = opts.readFile || readCapped;
242
- if (!args || typeof args !== 'object') return null;
243
- const file = typeof args.file_path === 'string' ? args.file_path
244
- : typeof args.path === 'string' ? args.path : null;
245
- if (!file) return null;
246
- const base = { file, short: shortPath(file, cwd) };
247
-
248
- if (name === 'Edit' || name === 'editFile') {
249
- if (typeof args.old_string !== 'string' || typeof args.new_string !== 'string') return null;
250
- return Object.assign(
251
- { kind: 'Update' },
252
- base,
253
- lineDiff(args.old_string, args.new_string),
254
- { replaceAll: !!args.replace_all },
255
- );
256
- }
257
-
258
- if (name === 'Write' || name === 'writeFile') {
259
- if (typeof args.content !== 'string') return null;
260
- const prev = readFile(file) || { text: null, missing: true };
261
- const d = lineDiff(prev.text == null ? '' : prev.text, args.content);
262
- return Object.assign(
263
- { kind: prev.missing ? 'Create' : 'Write' },
264
- base,
265
- d,
266
- { truncated: d.truncated || !!prev.truncated },
267
- );
268
- }
269
-
270
- if (name === 'MultiEdit') {
271
- const edits = (Array.isArray(args.edits) ? args.edits : []).filter(
272
- (e) => e && typeof e.old_string === 'string' && typeof e.new_string === 'string',
273
- );
274
- if (!edits.length) return null;
275
- const prev = readFile(file) || { text: null, missing: true };
276
- if (typeof prev.text === 'string') {
277
- let cur = prev.text;
278
- let misses = 0;
279
- for (const e of edits) {
280
- if (cur.indexOf(e.old_string) === -1) { misses++; continue; }
281
- cur = e.replace_all
282
- ? cur.split(e.old_string).join(e.new_string)
283
- : cur.replace(e.old_string, e.new_string);
284
- }
285
- const d = lineDiff(prev.text, cur);
286
- return Object.assign(
287
- { kind: 'Update' },
288
- base,
289
- d,
290
- { misses, replaceAll: edits.some((e) => e.replace_all) },
291
- );
292
- }
293
- // No base on disk: stack each edit's own diff rather than inventing one.
294
- let rows = [];
295
- let adds = 0;
296
- let dels = 0;
297
- let truncated = false;
298
- edits.forEach((e, i) => {
299
- const d = lineDiff(e.old_string, e.new_string);
300
- if (i) rows.push({ sign: ' ', text: '', marker: true, note: `… edit ${i + 1} of ${edits.length}` });
301
- rows = rows.concat(d.rows);
302
- adds += d.adds;
303
- dels += d.dels;
304
- truncated = truncated || d.truncated;
305
- });
306
- return Object.assign(
307
- { kind: 'Update' },
308
- base,
309
- { rows, adds, dels, truncated, stacked: edits.length },
310
- );
311
- }
312
-
313
- return null;
314
- } catch {
315
- return null; // decoration must never break a turn
316
- }
317
- }
318
-
319
- /** Human count line in the reference's wording: "Added 3 lines, removed 1 line". */
320
- function changeSummary(preview) {
321
- const parts = [];
322
- if (preview.adds) parts.push(`Added ${preview.adds} line${preview.adds === 1 ? '' : 's'}`);
323
- if (preview.dels) parts.push(`removed ${preview.dels} line${preview.dels === 1 ? '' : 's'}`);
324
- return parts.length ? parts.join(', ') : 'no line changes';
325
- }
326
-
327
- module.exports = {
328
- DIFF_LIMITS,
329
- splitLines,
330
- lineDiff,
331
- readCapped,
332
- shortPath,
333
- changeSummary,
334
- editPreview,
335
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),DIFF_LIMITS={fileBytes:262144,lcsCells:25e4,rows:400,context:3};function splitLines(t){const e=String(null==t?"":t).replace(/\r\n?/g,"\n");if(""===e)return[];const n=e.split("\n");return n.length&&""===n[n.length-1]&&n.pop(),n}function lineDiff(t,e){const n=splitLines(t),s=splitLines(e);let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let r=0;for(;r<n.length-i&&r<s.length-i&&n[n.length-1-r]===s[s.length-1-r];)r++;const l=n.slice(i,n.length-r),o=s.slice(i,s.length-r),a=lcsOps(l,o),c=null===a,g=a||[...l.map((t=>({sign:"-",text:t}))),...o.map((t=>({sign:"+",text:t})))];if(!g.some((t=>" "!==t.sign)))return{rows:[],adds:0,dels:0,truncated:c};const u=DIFF_LIMITS.context,p=[];let f=1,d=1;const h=i>u?i-u:0,x=h;x>0&&p.push({sign:" ",text:"",marker:!0,note:`… ${x} unchanged line${1===x?"":"s"}`});for(let t=h;t<i;t++)p.push({sign:" ",text:n[t],no:d}),d++,f++;for(const t of g)" "===t.sign?(p.push({sign:" ",text:t.text,no:d}),d++,f++):"-"===t.sign?(p.push({sign:"-",text:t.text,no:f}),f++):(p.push({sign:"+",text:t.text,no:d}),d++);const m=s.length-r,I=Math.min(r,u);d=m+1;for(let t=0;t<I;t++)p.push({sign:" ",text:s[m+t],no:d}),d++,f++;if(r>u){const t=r-u;p.push({sign:" ",text:"",marker:!0,note:`… ${t} unchanged line${1===t?"":"s"}`})}const _=p.filter((t=>"+"===t.sign)).length,y=p.filter((t=>"-"===t.sign)).length;let F=p,w=!1;return F.length>DIFF_LIMITS.rows&&(F=F.slice(0,DIFF_LIMITS.rows),F.push({sign:" ",text:"",marker:!0,note:`… ${p.length-DIFF_LIMITS.rows} more diff lines`}),w=!0),{rows:F,adds:_,dels:y,truncated:c||w}}function lcsOps(t,e){const n=t.length,s=e.length;if(!n||!s)return[...t.map((t=>({sign:"-",text:t}))),...e.map((t=>({sign:"+",text:t})))];if(n*s>DIFF_LIMITS.lcsCells)return null;const i=s+1,r=new Int32Array((n+1)*i);for(let l=n-1;l>=0;l--)for(let n=s-1;n>=0;n--)r[l*i+n]=t[l]===e[n]?r[(l+1)*i+(n+1)]+1:Math.max(r[(l+1)*i+n],r[l*i+(n+1)]);const l=[];let o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(l.push({sign:" ",text:t[o]}),o++,a++):r[(o+1)*i+a]>=r[o*i+(a+1)]?(l.push({sign:"-",text:t[o]}),o++):(l.push({sign:"+",text:e[a]}),a++);for(;o<n;)l.push({sign:"-",text:t[o++]});for(;a<s;)l.push({sign:"+",text:e[a++]});return l}function readCapped(t,e={}){const n=null==e.bytes?DIFF_LIMITS.fileBytes:e.bytes;try{const e=fs.statSync(t);if(!e.isFile())return{text:null,missing:!0};const s=fs.readFileSync(t,"utf8");return e.size>n?{text:s.slice(0,n),missing:!1,truncated:!0}:{text:s,missing:!1}}catch{return{text:null,missing:!0}}}function shortPath(t,e){const n=String(t||"");if(!e)return n;const s=path.relative(e,n);if(s&&!s.startsWith("..")&&!path.isAbsolute(s))return s;const i=n.split(path.sep).filter(Boolean),r=n.startsWith(path.sep)?path.sep:"";return i.length>2?r+"…"+path.sep+i.slice(-2).join(path.sep):n}function editPreview(t,e,n={}){try{const s=null==n.cwd?process.cwd():n.cwd,i=n.readFile||readCapped;if(!e||"object"!=typeof e)return null;const r="string"==typeof e.file_path?e.file_path:"string"==typeof e.path?e.path:null;if(!r)return null;const l={file:r,short:shortPath(r,s)};if("Edit"===t||"editFile"===t)return"string"!=typeof e.old_string||"string"!=typeof e.new_string?null:Object.assign({kind:"Update"},l,lineDiff(e.old_string,e.new_string),{replaceAll:!!e.replace_all});if("Write"===t||"writeFile"===t){if("string"!=typeof e.content)return null;const t=i(r)||{text:null,missing:!0},n=lineDiff(null==t.text?"":t.text,e.content);return Object.assign({kind:t.missing?"Create":"Write"},l,n,{truncated:n.truncated||!!t.truncated})}if("MultiEdit"===t){const t=(Array.isArray(e.edits)?e.edits:[]).filter((t=>t&&"string"==typeof t.old_string&&"string"==typeof t.new_string));if(!t.length)return null;const n=i(r)||{text:null,missing:!0};if("string"==typeof n.text){let e=n.text,s=0;for(const n of t)-1!==e.indexOf(n.old_string)?e=n.replace_all?e.split(n.old_string).join(n.new_string):e.replace(n.old_string,n.new_string):s++;const i=lineDiff(n.text,e);return Object.assign({kind:"Update"},l,i,{misses:s,replaceAll:t.some((t=>t.replace_all))})}let s=[],o=0,a=0,c=!1;return t.forEach(((e,n)=>{const i=lineDiff(e.old_string,e.new_string);n&&s.push({sign:" ",text:"",marker:!0,note:`… edit ${n+1} of ${t.length}`}),s=s.concat(i.rows),o+=i.adds,a+=i.dels,c=c||i.truncated})),Object.assign({kind:"Update"},l,{rows:s,adds:o,dels:a,truncated:c,stacked:t.length})}return null}catch{return null}}function changeSummary(t){const e=[];return t.adds&&e.push(`Added ${t.adds} line${1===t.adds?"":"s"}`),t.dels&&e.push(`removed ${t.dels} line${1===t.dels?"":"s"}`),e.length?e.join(", "):"no line changes"}module.exports={DIFF_LIMITS:DIFF_LIMITS,splitLines:splitLines,lineDiff:lineDiff,readCapped:readCapped,shortPath:shortPath,changeSummary:changeSummary,editPreview:editPreview};