@kolisachint/hoocode-agent 0.5.48 → 0.5.50

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 (33) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/core/session-identity.d.ts +10 -0
  3. package/dist/core/session-identity.d.ts.map +1 -1
  4. package/dist/core/session-identity.js +48 -0
  5. package/dist/core/session-identity.js.map +1 -1
  6. package/dist/core/slash-commands.d.ts.map +1 -1
  7. package/dist/core/slash-commands.js +1 -1
  8. package/dist/core/slash-commands.js.map +1 -1
  9. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  10. package/dist/core/tools/edit-diff.js +326 -101
  11. package/dist/core/tools/edit-diff.js.map +1 -1
  12. package/dist/core/tools/read-dedup.d.ts +14 -1
  13. package/dist/core/tools/read-dedup.d.ts.map +1 -1
  14. package/dist/core/tools/read-dedup.js +53 -1
  15. package/dist/core/tools/read-dedup.js.map +1 -1
  16. package/dist/core/tools/read.d.ts.map +1 -1
  17. package/dist/core/tools/read.js +17 -5
  18. package/dist/core/tools/read.js.map +1 -1
  19. package/dist/extensions/core/permission-gate.d.ts.map +1 -1
  20. package/dist/extensions/core/permission-gate.js +23 -5
  21. package/dist/extensions/core/permission-gate.js.map +1 -1
  22. package/dist/modes/interactive/command-executor.d.ts +9 -3
  23. package/dist/modes/interactive/command-executor.d.ts.map +1 -1
  24. package/dist/modes/interactive/command-executor.js +16 -8
  25. package/dist/modes/interactive/command-executor.js.map +1 -1
  26. package/dist/modes/interactive/components/session-color-selector.d.ts.map +1 -1
  27. package/dist/modes/interactive/components/session-color-selector.js +5 -2
  28. package/dist/modes/interactive/components/session-color-selector.js.map +1 -1
  29. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  30. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  31. package/examples/extensions/sandbox/package.json +1 -1
  32. package/examples/extensions/with-deps/package.json +1 -1
  33. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.50] - 2026-09-03
4
+
5
+ ## [0.5.49] - 2026-09-03
6
+
7
+ ### Added
8
+
9
+ - `/color` takes colour names, not just slot numbers: `/color green`,
10
+ `/color blue`, `/color magenta`, and the first letter of each on its own —
11
+ `/color g`, `/color b`, `/color y`, `/color r`.
12
+
13
+ The six slots are palette positions rather than fixed hues, but across the
14
+ built-in themes each position keeps a recognisable family, so the names
15
+ describe it: cyan, purple, yellow, magenta, green, blue. Spellings that sit
16
+ between slots resolve to the nearest one instead of being rejected — `red`
17
+ and `pink` reach magenta, `orange` and `amber` reach yellow — and the
18
+ confirmation names the slot it landed on, so `/color red` answering with
19
+ "magenta" is how you learn the palette has no red of its own. The numbers
20
+ still work, and the picker now labels each swatch with its name.
21
+
3
22
  ## [0.5.48] - 2026-09-03
4
23
 
5
24
  ## [0.5.47] - 2026-08-31
@@ -22,4 +22,14 @@ export declare function sessionSlugFor(sessionId: string): string;
22
22
  export declare function sessionColorSlotFor(sessionId: string): number;
23
23
  /** Whether `slot` is one a session can actually be assigned. */
24
24
  export declare function isSessionColorSlot(slot: number): boolean;
25
+ /** The canonical slot names, in slot order. For usage lines and pickers. */
26
+ export declare const SESSION_COLOR_NAME_LIST: readonly string[];
27
+ /** What to call `slot` when reporting it back, or undefined if it is not a slot. */
28
+ export declare function sessionColorName(slot: number): string | undefined;
29
+ /**
30
+ * The slot an argument to `/color` asks for: a number (`4`), a name
31
+ * (`magenta`), or an initial (`m`). Case and surrounding space do not matter.
32
+ * Undefined when it names no slot at all.
33
+ */
34
+ export declare function parseSessionColorSlot(input: string): number | undefined;
25
35
  //# sourceMappingURL=session-identity.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-identity.d.ts","sourceRoot":"","sources":["../../src/core/session-identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,IAAI,CAAC;AA8GrC,4FAA4F;AAC5F,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAIxD;AAED,iFAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE7D;AAED,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAExD","sourcesContent":["/**\n * A session's visual identity: the name it carries before anyone names it, and\n * the palette slot its chip is filled with.\n *\n * Both are pure functions of the session id, which means they need no storage of\n * their own: the id is already in the session header, so a resumed session comes\n * back wearing the same slug and the same colour, and a fork — which mints a new\n * id — gets its own identity instead of quietly wearing its parent's. What *is*\n * stored is an override: `/name` and `/color` write to the session's\n * `session_info` entry, and those win over everything here (see\n * SessionManager.getDisplayName / getSessionColorSlot).\n *\n * This module is deliberately theme-free. It deals in slot *numbers*; mapping a\n * slot onto a colour token is the theme's job, so `core/` never has to reach into\n * a mode's rendering code.\n */\n\n/** Number of colour slots a session can land in. Matches the theme's identity palette. */\nexport const SESSION_COLOR_SLOTS = 6;\n\n/**\n * The slug vocabulary. Chosen for the terminal, not for poetry: every word is\n * short (so a two-word slug stays well inside the chip's 20-column cap), lower\n * case, unambiguous when read at a glance from across a desk, and free of the\n * near-homographs that make two sessions hard to tell apart (no \"lake\"/\"lane\").\n * 32 × 32 gives 1024 combinations, which is far more than the number of sessions\n * anyone has open at once — the point is recognition, not uniqueness.\n */\nconst ADJECTIVES = [\n\t\"amber\",\n\t\"ash\",\n\t\"azure\",\n\t\"brisk\",\n\t\"bronze\",\n\t\"calm\",\n\t\"clay\",\n\t\"coral\",\n\t\"crisp\",\n\t\"dusk\",\n\t\"ember\",\n\t\"fern\",\n\t\"flint\",\n\t\"frost\",\n\t\"gold\",\n\t\"ivory\",\n\t\"jade\",\n\t\"lunar\",\n\t\"mellow\",\n\t\"mint\",\n\t\"olive\",\n\t\"onyx\",\n\t\"plum\",\n\t\"quiet\",\n\t\"rust\",\n\t\"sable\",\n\t\"sage\",\n\t\"slate\",\n\t\"solar\",\n\t\"swift\",\n\t\"teal\",\n\t\"velvet\",\n] as const;\n\nconst NOUNS = [\n\t\"anchor\",\n\t\"arbor\",\n\t\"basin\",\n\t\"beacon\",\n\t\"birch\",\n\t\"canyon\",\n\t\"cedar\",\n\t\"cinder\",\n\t\"cove\",\n\t\"delta\",\n\t\"drift\",\n\t\"ferry\",\n\t\"forge\",\n\t\"harbor\",\n\t\"hollow\",\n\t\"lantern\",\n\t\"meadow\",\n\t\"mesa\",\n\t\"orchard\",\n\t\"pier\",\n\t\"prairie\",\n\t\"quarry\",\n\t\"ridge\",\n\t\"summit\",\n\t\"thicket\",\n\t\"tide\",\n\t\"trellis\",\n\t\"vale\",\n\t\"willow\",\n\t\"windmill\",\n\t\"yarrow\",\n\t\"zenith\",\n] as const;\n\n/**\n * djb2 over the whole string. The same hash the agent palette uses — tiny,\n * stable across runs and machines, and good spread for identifier-like input.\n *\n * Hashing the *whole* id matters here. Session ids are uuidv7, which is\n * time-ordered: two sessions started in the same minute share their leading\n * characters, so a hash over a prefix would drop them into the same slug and the\n * same colour — exactly the sessions a person most needs to tell apart.\n */\nfunction djb2(value: string): number {\n\tlet hash = 5381;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = ((hash << 5) + hash + value.charCodeAt(i)) >>> 0;\n\t}\n\treturn hash;\n}\n\n/**\n * A second hash over the same string, seeded differently (sdbm). The slug needs\n * two independent indices; running djb2 twice would tie the noun to the\n * adjective and collapse the vocabulary from 1024 pairs to 32.\n */\nfunction sdbm(value: string): number {\n\tlet hash = 0;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = (value.charCodeAt(i) + (hash << 6) + (hash << 16) - hash) >>> 0;\n\t}\n\treturn hash;\n}\n\n/** The auto-assigned name for a session: a memorable two-word slug, e.g. `amber-harbor`. */\nexport function sessionSlugFor(sessionId: string): string {\n\tconst adjective = ADJECTIVES[djb2(sessionId) % ADJECTIVES.length];\n\tconst noun = NOUNS[sdbm(sessionId) % NOUNS.length];\n\treturn `${adjective}-${noun}`;\n}\n\n/** The auto-assigned colour slot for a session, in `1…SESSION_COLOR_SLOTS`. */\nexport function sessionColorSlotFor(sessionId: string): number {\n\treturn (djb2(sessionId) % SESSION_COLOR_SLOTS) + 1;\n}\n\n/** Whether `slot` is one a session can actually be assigned. */\nexport function isSessionColorSlot(slot: number): boolean {\n\treturn Number.isInteger(slot) && slot >= 1 && slot <= SESSION_COLOR_SLOTS;\n}\n"]}
1
+ {"version":3,"file":"session-identity.d.ts","sourceRoot":"","sources":["../../src/core/session-identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,IAAI,CAAC;AA8GrC,4FAA4F;AAC5F,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAIxD;AAED,iFAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE7D;AAED,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAExD;AAiCD,4EAA4E;AAC5E,eAAO,MAAM,uBAAuB,EAAE,SAAS,MAAM,EAAmD,CAAC;AAEzG,oFAAoF;AACpF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEjE;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CASvE","sourcesContent":["/**\n * A session's visual identity: the name it carries before anyone names it, and\n * the palette slot its chip is filled with.\n *\n * Both are pure functions of the session id, which means they need no storage of\n * their own: the id is already in the session header, so a resumed session comes\n * back wearing the same slug and the same colour, and a fork — which mints a new\n * id — gets its own identity instead of quietly wearing its parent's. What *is*\n * stored is an override: `/name` and `/color` write to the session's\n * `session_info` entry, and those win over everything here (see\n * SessionManager.getDisplayName / getSessionColorSlot).\n *\n * This module is deliberately theme-free. It deals in slot *numbers*; mapping a\n * slot onto a colour token is the theme's job, so `core/` never has to reach into\n * a mode's rendering code.\n */\n\n/** Number of colour slots a session can land in. Matches the theme's identity palette. */\nexport const SESSION_COLOR_SLOTS = 6;\n\n/**\n * The slug vocabulary. Chosen for the terminal, not for poetry: every word is\n * short (so a two-word slug stays well inside the chip's 20-column cap), lower\n * case, unambiguous when read at a glance from across a desk, and free of the\n * near-homographs that make two sessions hard to tell apart (no \"lake\"/\"lane\").\n * 32 × 32 gives 1024 combinations, which is far more than the number of sessions\n * anyone has open at once — the point is recognition, not uniqueness.\n */\nconst ADJECTIVES = [\n\t\"amber\",\n\t\"ash\",\n\t\"azure\",\n\t\"brisk\",\n\t\"bronze\",\n\t\"calm\",\n\t\"clay\",\n\t\"coral\",\n\t\"crisp\",\n\t\"dusk\",\n\t\"ember\",\n\t\"fern\",\n\t\"flint\",\n\t\"frost\",\n\t\"gold\",\n\t\"ivory\",\n\t\"jade\",\n\t\"lunar\",\n\t\"mellow\",\n\t\"mint\",\n\t\"olive\",\n\t\"onyx\",\n\t\"plum\",\n\t\"quiet\",\n\t\"rust\",\n\t\"sable\",\n\t\"sage\",\n\t\"slate\",\n\t\"solar\",\n\t\"swift\",\n\t\"teal\",\n\t\"velvet\",\n] as const;\n\nconst NOUNS = [\n\t\"anchor\",\n\t\"arbor\",\n\t\"basin\",\n\t\"beacon\",\n\t\"birch\",\n\t\"canyon\",\n\t\"cedar\",\n\t\"cinder\",\n\t\"cove\",\n\t\"delta\",\n\t\"drift\",\n\t\"ferry\",\n\t\"forge\",\n\t\"harbor\",\n\t\"hollow\",\n\t\"lantern\",\n\t\"meadow\",\n\t\"mesa\",\n\t\"orchard\",\n\t\"pier\",\n\t\"prairie\",\n\t\"quarry\",\n\t\"ridge\",\n\t\"summit\",\n\t\"thicket\",\n\t\"tide\",\n\t\"trellis\",\n\t\"vale\",\n\t\"willow\",\n\t\"windmill\",\n\t\"yarrow\",\n\t\"zenith\",\n] as const;\n\n/**\n * djb2 over the whole string. The same hash the agent palette uses — tiny,\n * stable across runs and machines, and good spread for identifier-like input.\n *\n * Hashing the *whole* id matters here. Session ids are uuidv7, which is\n * time-ordered: two sessions started in the same minute share their leading\n * characters, so a hash over a prefix would drop them into the same slug and the\n * same colour — exactly the sessions a person most needs to tell apart.\n */\nfunction djb2(value: string): number {\n\tlet hash = 5381;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = ((hash << 5) + hash + value.charCodeAt(i)) >>> 0;\n\t}\n\treturn hash;\n}\n\n/**\n * A second hash over the same string, seeded differently (sdbm). The slug needs\n * two independent indices; running djb2 twice would tie the noun to the\n * adjective and collapse the vocabulary from 1024 pairs to 32.\n */\nfunction sdbm(value: string): number {\n\tlet hash = 0;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = (value.charCodeAt(i) + (hash << 6) + (hash << 16) - hash) >>> 0;\n\t}\n\treturn hash;\n}\n\n/** The auto-assigned name for a session: a memorable two-word slug, e.g. `amber-harbor`. */\nexport function sessionSlugFor(sessionId: string): string {\n\tconst adjective = ADJECTIVES[djb2(sessionId) % ADJECTIVES.length];\n\tconst noun = NOUNS[sdbm(sessionId) % NOUNS.length];\n\treturn `${adjective}-${noun}`;\n}\n\n/** The auto-assigned colour slot for a session, in `1…SESSION_COLOR_SLOTS`. */\nexport function sessionColorSlotFor(sessionId: string): number {\n\treturn (djb2(sessionId) % SESSION_COLOR_SLOTS) + 1;\n}\n\n/** Whether `slot` is one a session can actually be assigned. */\nexport function isSessionColorSlot(slot: number): boolean {\n\treturn Number.isInteger(slot) && slot >= 1 && slot <= SESSION_COLOR_SLOTS;\n}\n\n/**\n * The name each slot answers to, and the other spellings that reach it.\n *\n * A slot is a palette position, not a fixed hue — every theme fills\n * `agent1…agent6` with its own colours — but across the built-in themes each\n * position keeps a recognisable family, and that is what these names describe:\n * slot 3 is the warm yellow/amber one wherever you are, slot 6 the blue. That\n * is enough for the thing names are for, which is typing `/color green`\n * instead of remembering that green is the fifth swatch.\n *\n * The aliases are deliberately generous, because a name only helps if the\n * obvious spelling of it works. Each name's initial stands for it, and the\n * hues that sit between slots (`orange`, `red`) resolve to the nearest slot\n * rather than being rejected — the palette has six entries, not a full colour\n * wheel, and refusing `/color red` because the swatch is officially magenta\n * would be pedantry. A theme whose palette drifts from these names is still\n * addressable by number, which is why the numbers never go away.\n */\nconst SESSION_COLOR_NAMES: ReadonlyArray<{\n\treadonly slot: number;\n\treadonly name: string;\n\treadonly aliases: readonly string[];\n}> = [\n\t{ slot: 1, name: \"cyan\", aliases: [\"c\", \"teal\", \"aqua\"] },\n\t{ slot: 2, name: \"purple\", aliases: [\"p\", \"violet\"] },\n\t{ slot: 3, name: \"yellow\", aliases: [\"y\", \"amber\", \"gold\", \"orange\", \"o\"] },\n\t{ slot: 4, name: \"magenta\", aliases: [\"m\", \"pink\", \"rose\", \"red\", \"r\"] },\n\t{ slot: 5, name: \"green\", aliases: [\"g\"] },\n\t{ slot: 6, name: \"blue\", aliases: [\"b\"] },\n];\n\n/** The canonical slot names, in slot order. For usage lines and pickers. */\nexport const SESSION_COLOR_NAME_LIST: readonly string[] = SESSION_COLOR_NAMES.map((entry) => entry.name);\n\n/** What to call `slot` when reporting it back, or undefined if it is not a slot. */\nexport function sessionColorName(slot: number): string | undefined {\n\treturn SESSION_COLOR_NAMES.find((entry) => entry.slot === slot)?.name;\n}\n\n/**\n * The slot an argument to `/color` asks for: a number (`4`), a name\n * (`magenta`), or an initial (`m`). Case and surrounding space do not matter.\n * Undefined when it names no slot at all.\n */\nexport function parseSessionColorSlot(input: string): number | undefined {\n\tconst normalized = input.trim().toLowerCase();\n\tif (!normalized) return undefined;\n\tif (/^\\d+$/.test(normalized)) {\n\t\tconst slot = Number(normalized);\n\t\treturn isSessionColorSlot(slot) ? slot : undefined;\n\t}\n\tconst match = SESSION_COLOR_NAMES.find((entry) => entry.name === normalized || entry.aliases.includes(normalized));\n\treturn match?.slot;\n}\n"]}
@@ -134,4 +134,52 @@ export function sessionColorSlotFor(sessionId) {
134
134
  export function isSessionColorSlot(slot) {
135
135
  return Number.isInteger(slot) && slot >= 1 && slot <= SESSION_COLOR_SLOTS;
136
136
  }
137
+ /**
138
+ * The name each slot answers to, and the other spellings that reach it.
139
+ *
140
+ * A slot is a palette position, not a fixed hue — every theme fills
141
+ * `agent1…agent6` with its own colours — but across the built-in themes each
142
+ * position keeps a recognisable family, and that is what these names describe:
143
+ * slot 3 is the warm yellow/amber one wherever you are, slot 6 the blue. That
144
+ * is enough for the thing names are for, which is typing `/color green`
145
+ * instead of remembering that green is the fifth swatch.
146
+ *
147
+ * The aliases are deliberately generous, because a name only helps if the
148
+ * obvious spelling of it works. Each name's initial stands for it, and the
149
+ * hues that sit between slots (`orange`, `red`) resolve to the nearest slot
150
+ * rather than being rejected — the palette has six entries, not a full colour
151
+ * wheel, and refusing `/color red` because the swatch is officially magenta
152
+ * would be pedantry. A theme whose palette drifts from these names is still
153
+ * addressable by number, which is why the numbers never go away.
154
+ */
155
+ const SESSION_COLOR_NAMES = [
156
+ { slot: 1, name: "cyan", aliases: ["c", "teal", "aqua"] },
157
+ { slot: 2, name: "purple", aliases: ["p", "violet"] },
158
+ { slot: 3, name: "yellow", aliases: ["y", "amber", "gold", "orange", "o"] },
159
+ { slot: 4, name: "magenta", aliases: ["m", "pink", "rose", "red", "r"] },
160
+ { slot: 5, name: "green", aliases: ["g"] },
161
+ { slot: 6, name: "blue", aliases: ["b"] },
162
+ ];
163
+ /** The canonical slot names, in slot order. For usage lines and pickers. */
164
+ export const SESSION_COLOR_NAME_LIST = SESSION_COLOR_NAMES.map((entry) => entry.name);
165
+ /** What to call `slot` when reporting it back, or undefined if it is not a slot. */
166
+ export function sessionColorName(slot) {
167
+ return SESSION_COLOR_NAMES.find((entry) => entry.slot === slot)?.name;
168
+ }
169
+ /**
170
+ * The slot an argument to `/color` asks for: a number (`4`), a name
171
+ * (`magenta`), or an initial (`m`). Case and surrounding space do not matter.
172
+ * Undefined when it names no slot at all.
173
+ */
174
+ export function parseSessionColorSlot(input) {
175
+ const normalized = input.trim().toLowerCase();
176
+ if (!normalized)
177
+ return undefined;
178
+ if (/^\d+$/.test(normalized)) {
179
+ const slot = Number(normalized);
180
+ return isSessionColorSlot(slot) ? slot : undefined;
181
+ }
182
+ const match = SESSION_COLOR_NAMES.find((entry) => entry.name === normalized || entry.aliases.includes(normalized));
183
+ return match?.slot;
184
+ }
137
185
  //# sourceMappingURL=session-identity.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-identity.js","sourceRoot":"","sources":["../../src/core/session-identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,0FAA0F;AAC1F,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,UAAU,GAAG;IAClB,OAAO;IACP,KAAK;IACL,OAAO;IACP,OAAO;IACP,QAAQ;IACR,MAAM;IACN,MAAM;IACN,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,QAAQ;IACR,MAAM;IACN,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,OAAO;IACP,MAAM;IACN,QAAQ;CACC,CAAC;AAEX,MAAM,KAAK,GAAG;IACb,QAAQ;IACR,OAAO;IACP,OAAO;IACP,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,MAAM;IACN,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,MAAM;IACN,SAAS;IACT,MAAM;IACN,SAAS;IACT,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,SAAS;IACT,MAAM;IACN,SAAS;IACT,MAAM;IACN,QAAQ;IACR,UAAU;IACV,QAAQ;IACR,QAAQ;CACC,CAAC;AAEX;;;;;;;;GAQG;AACH,SAAS,IAAI,CAAC,KAAa,EAAU;IACpC,IAAI,IAAI,GAAG,IAAI,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,IAAI,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ;AAED;;;;GAIG;AACH,SAAS,IAAI,CAAC,KAAa,EAAU;IACpC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,IAAI,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ;AAED,4FAA4F;AAC5F,MAAM,UAAU,cAAc,CAAC,SAAiB,EAAU;IACzD,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;IAClE,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IACnD,OAAO,GAAG,SAAS,IAAI,IAAI,EAAE,CAAC;AAAA,CAC9B;AAED,iFAA+E;AAC/E,MAAM,UAAU,mBAAmB,CAAC,SAAiB,EAAU;IAC9D,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAAA,CACnD;AAED,gEAAgE;AAChE,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAW;IACzD,OAAO,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,mBAAmB,CAAC;AAAA,CAC1E","sourcesContent":["/**\n * A session's visual identity: the name it carries before anyone names it, and\n * the palette slot its chip is filled with.\n *\n * Both are pure functions of the session id, which means they need no storage of\n * their own: the id is already in the session header, so a resumed session comes\n * back wearing the same slug and the same colour, and a fork — which mints a new\n * id — gets its own identity instead of quietly wearing its parent's. What *is*\n * stored is an override: `/name` and `/color` write to the session's\n * `session_info` entry, and those win over everything here (see\n * SessionManager.getDisplayName / getSessionColorSlot).\n *\n * This module is deliberately theme-free. It deals in slot *numbers*; mapping a\n * slot onto a colour token is the theme's job, so `core/` never has to reach into\n * a mode's rendering code.\n */\n\n/** Number of colour slots a session can land in. Matches the theme's identity palette. */\nexport const SESSION_COLOR_SLOTS = 6;\n\n/**\n * The slug vocabulary. Chosen for the terminal, not for poetry: every word is\n * short (so a two-word slug stays well inside the chip's 20-column cap), lower\n * case, unambiguous when read at a glance from across a desk, and free of the\n * near-homographs that make two sessions hard to tell apart (no \"lake\"/\"lane\").\n * 32 × 32 gives 1024 combinations, which is far more than the number of sessions\n * anyone has open at once — the point is recognition, not uniqueness.\n */\nconst ADJECTIVES = [\n\t\"amber\",\n\t\"ash\",\n\t\"azure\",\n\t\"brisk\",\n\t\"bronze\",\n\t\"calm\",\n\t\"clay\",\n\t\"coral\",\n\t\"crisp\",\n\t\"dusk\",\n\t\"ember\",\n\t\"fern\",\n\t\"flint\",\n\t\"frost\",\n\t\"gold\",\n\t\"ivory\",\n\t\"jade\",\n\t\"lunar\",\n\t\"mellow\",\n\t\"mint\",\n\t\"olive\",\n\t\"onyx\",\n\t\"plum\",\n\t\"quiet\",\n\t\"rust\",\n\t\"sable\",\n\t\"sage\",\n\t\"slate\",\n\t\"solar\",\n\t\"swift\",\n\t\"teal\",\n\t\"velvet\",\n] as const;\n\nconst NOUNS = [\n\t\"anchor\",\n\t\"arbor\",\n\t\"basin\",\n\t\"beacon\",\n\t\"birch\",\n\t\"canyon\",\n\t\"cedar\",\n\t\"cinder\",\n\t\"cove\",\n\t\"delta\",\n\t\"drift\",\n\t\"ferry\",\n\t\"forge\",\n\t\"harbor\",\n\t\"hollow\",\n\t\"lantern\",\n\t\"meadow\",\n\t\"mesa\",\n\t\"orchard\",\n\t\"pier\",\n\t\"prairie\",\n\t\"quarry\",\n\t\"ridge\",\n\t\"summit\",\n\t\"thicket\",\n\t\"tide\",\n\t\"trellis\",\n\t\"vale\",\n\t\"willow\",\n\t\"windmill\",\n\t\"yarrow\",\n\t\"zenith\",\n] as const;\n\n/**\n * djb2 over the whole string. The same hash the agent palette uses — tiny,\n * stable across runs and machines, and good spread for identifier-like input.\n *\n * Hashing the *whole* id matters here. Session ids are uuidv7, which is\n * time-ordered: two sessions started in the same minute share their leading\n * characters, so a hash over a prefix would drop them into the same slug and the\n * same colour — exactly the sessions a person most needs to tell apart.\n */\nfunction djb2(value: string): number {\n\tlet hash = 5381;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = ((hash << 5) + hash + value.charCodeAt(i)) >>> 0;\n\t}\n\treturn hash;\n}\n\n/**\n * A second hash over the same string, seeded differently (sdbm). The slug needs\n * two independent indices; running djb2 twice would tie the noun to the\n * adjective and collapse the vocabulary from 1024 pairs to 32.\n */\nfunction sdbm(value: string): number {\n\tlet hash = 0;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = (value.charCodeAt(i) + (hash << 6) + (hash << 16) - hash) >>> 0;\n\t}\n\treturn hash;\n}\n\n/** The auto-assigned name for a session: a memorable two-word slug, e.g. `amber-harbor`. */\nexport function sessionSlugFor(sessionId: string): string {\n\tconst adjective = ADJECTIVES[djb2(sessionId) % ADJECTIVES.length];\n\tconst noun = NOUNS[sdbm(sessionId) % NOUNS.length];\n\treturn `${adjective}-${noun}`;\n}\n\n/** The auto-assigned colour slot for a session, in `1…SESSION_COLOR_SLOTS`. */\nexport function sessionColorSlotFor(sessionId: string): number {\n\treturn (djb2(sessionId) % SESSION_COLOR_SLOTS) + 1;\n}\n\n/** Whether `slot` is one a session can actually be assigned. */\nexport function isSessionColorSlot(slot: number): boolean {\n\treturn Number.isInteger(slot) && slot >= 1 && slot <= SESSION_COLOR_SLOTS;\n}\n"]}
1
+ {"version":3,"file":"session-identity.js","sourceRoot":"","sources":["../../src/core/session-identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,0FAA0F;AAC1F,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,UAAU,GAAG;IAClB,OAAO;IACP,KAAK;IACL,OAAO;IACP,OAAO;IACP,QAAQ;IACR,MAAM;IACN,MAAM;IACN,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,QAAQ;IACR,MAAM;IACN,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,OAAO;IACP,MAAM;IACN,QAAQ;CACC,CAAC;AAEX,MAAM,KAAK,GAAG;IACb,QAAQ;IACR,OAAO;IACP,OAAO;IACP,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,MAAM;IACN,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,MAAM;IACN,SAAS;IACT,MAAM;IACN,SAAS;IACT,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,SAAS;IACT,MAAM;IACN,SAAS;IACT,MAAM;IACN,QAAQ;IACR,UAAU;IACV,QAAQ;IACR,QAAQ;CACC,CAAC;AAEX;;;;;;;;GAQG;AACH,SAAS,IAAI,CAAC,KAAa,EAAU;IACpC,IAAI,IAAI,GAAG,IAAI,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,IAAI,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ;AAED;;;;GAIG;AACH,SAAS,IAAI,CAAC,KAAa,EAAU;IACpC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,IAAI,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ;AAED,4FAA4F;AAC5F,MAAM,UAAU,cAAc,CAAC,SAAiB,EAAU;IACzD,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;IAClE,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IACnD,OAAO,GAAG,SAAS,IAAI,IAAI,EAAE,CAAC;AAAA,CAC9B;AAED,iFAA+E;AAC/E,MAAM,UAAU,mBAAmB,CAAC,SAAiB,EAAU;IAC9D,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAAA,CACnD;AAED,gEAAgE;AAChE,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAW;IACzD,OAAO,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,mBAAmB,CAAC;AAAA,CAC1E;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,mBAAmB,GAIpB;IACJ,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE;IACzD,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE;IACrD,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,CAAC,EAAE;IAC3E,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE;IACxE,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,EAAE;IAC1C,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,EAAE;CACzC,CAAC;AAEF,4EAA4E;AAC5E,MAAM,CAAC,MAAM,uBAAuB,GAAsB,mBAAmB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAEzG,oFAAoF;AACpF,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAsB;IAClE,OAAO,mBAAmB,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,IAAI,CAAC;AAAA,CACtE;AAED;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CAAC,KAAa,EAAsB;IACxE,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC9C,IAAI,CAAC,UAAU;QAAE,OAAO,SAAS,CAAC;IAClC,IAAI,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;QAChC,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACpD,CAAC;IACD,MAAM,KAAK,GAAG,mBAAmB,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC;IACnH,OAAO,KAAK,EAAE,IAAI,CAAC;AAAA,CACnB","sourcesContent":["/**\n * A session's visual identity: the name it carries before anyone names it, and\n * the palette slot its chip is filled with.\n *\n * Both are pure functions of the session id, which means they need no storage of\n * their own: the id is already in the session header, so a resumed session comes\n * back wearing the same slug and the same colour, and a fork — which mints a new\n * id — gets its own identity instead of quietly wearing its parent's. What *is*\n * stored is an override: `/name` and `/color` write to the session's\n * `session_info` entry, and those win over everything here (see\n * SessionManager.getDisplayName / getSessionColorSlot).\n *\n * This module is deliberately theme-free. It deals in slot *numbers*; mapping a\n * slot onto a colour token is the theme's job, so `core/` never has to reach into\n * a mode's rendering code.\n */\n\n/** Number of colour slots a session can land in. Matches the theme's identity palette. */\nexport const SESSION_COLOR_SLOTS = 6;\n\n/**\n * The slug vocabulary. Chosen for the terminal, not for poetry: every word is\n * short (so a two-word slug stays well inside the chip's 20-column cap), lower\n * case, unambiguous when read at a glance from across a desk, and free of the\n * near-homographs that make two sessions hard to tell apart (no \"lake\"/\"lane\").\n * 32 × 32 gives 1024 combinations, which is far more than the number of sessions\n * anyone has open at once — the point is recognition, not uniqueness.\n */\nconst ADJECTIVES = [\n\t\"amber\",\n\t\"ash\",\n\t\"azure\",\n\t\"brisk\",\n\t\"bronze\",\n\t\"calm\",\n\t\"clay\",\n\t\"coral\",\n\t\"crisp\",\n\t\"dusk\",\n\t\"ember\",\n\t\"fern\",\n\t\"flint\",\n\t\"frost\",\n\t\"gold\",\n\t\"ivory\",\n\t\"jade\",\n\t\"lunar\",\n\t\"mellow\",\n\t\"mint\",\n\t\"olive\",\n\t\"onyx\",\n\t\"plum\",\n\t\"quiet\",\n\t\"rust\",\n\t\"sable\",\n\t\"sage\",\n\t\"slate\",\n\t\"solar\",\n\t\"swift\",\n\t\"teal\",\n\t\"velvet\",\n] as const;\n\nconst NOUNS = [\n\t\"anchor\",\n\t\"arbor\",\n\t\"basin\",\n\t\"beacon\",\n\t\"birch\",\n\t\"canyon\",\n\t\"cedar\",\n\t\"cinder\",\n\t\"cove\",\n\t\"delta\",\n\t\"drift\",\n\t\"ferry\",\n\t\"forge\",\n\t\"harbor\",\n\t\"hollow\",\n\t\"lantern\",\n\t\"meadow\",\n\t\"mesa\",\n\t\"orchard\",\n\t\"pier\",\n\t\"prairie\",\n\t\"quarry\",\n\t\"ridge\",\n\t\"summit\",\n\t\"thicket\",\n\t\"tide\",\n\t\"trellis\",\n\t\"vale\",\n\t\"willow\",\n\t\"windmill\",\n\t\"yarrow\",\n\t\"zenith\",\n] as const;\n\n/**\n * djb2 over the whole string. The same hash the agent palette uses — tiny,\n * stable across runs and machines, and good spread for identifier-like input.\n *\n * Hashing the *whole* id matters here. Session ids are uuidv7, which is\n * time-ordered: two sessions started in the same minute share their leading\n * characters, so a hash over a prefix would drop them into the same slug and the\n * same colour — exactly the sessions a person most needs to tell apart.\n */\nfunction djb2(value: string): number {\n\tlet hash = 5381;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = ((hash << 5) + hash + value.charCodeAt(i)) >>> 0;\n\t}\n\treturn hash;\n}\n\n/**\n * A second hash over the same string, seeded differently (sdbm). The slug needs\n * two independent indices; running djb2 twice would tie the noun to the\n * adjective and collapse the vocabulary from 1024 pairs to 32.\n */\nfunction sdbm(value: string): number {\n\tlet hash = 0;\n\tfor (let i = 0; i < value.length; i++) {\n\t\thash = (value.charCodeAt(i) + (hash << 6) + (hash << 16) - hash) >>> 0;\n\t}\n\treturn hash;\n}\n\n/** The auto-assigned name for a session: a memorable two-word slug, e.g. `amber-harbor`. */\nexport function sessionSlugFor(sessionId: string): string {\n\tconst adjective = ADJECTIVES[djb2(sessionId) % ADJECTIVES.length];\n\tconst noun = NOUNS[sdbm(sessionId) % NOUNS.length];\n\treturn `${adjective}-${noun}`;\n}\n\n/** The auto-assigned colour slot for a session, in `1…SESSION_COLOR_SLOTS`. */\nexport function sessionColorSlotFor(sessionId: string): number {\n\treturn (djb2(sessionId) % SESSION_COLOR_SLOTS) + 1;\n}\n\n/** Whether `slot` is one a session can actually be assigned. */\nexport function isSessionColorSlot(slot: number): boolean {\n\treturn Number.isInteger(slot) && slot >= 1 && slot <= SESSION_COLOR_SLOTS;\n}\n\n/**\n * The name each slot answers to, and the other spellings that reach it.\n *\n * A slot is a palette position, not a fixed hue — every theme fills\n * `agent1…agent6` with its own colours — but across the built-in themes each\n * position keeps a recognisable family, and that is what these names describe:\n * slot 3 is the warm yellow/amber one wherever you are, slot 6 the blue. That\n * is enough for the thing names are for, which is typing `/color green`\n * instead of remembering that green is the fifth swatch.\n *\n * The aliases are deliberately generous, because a name only helps if the\n * obvious spelling of it works. Each name's initial stands for it, and the\n * hues that sit between slots (`orange`, `red`) resolve to the nearest slot\n * rather than being rejected — the palette has six entries, not a full colour\n * wheel, and refusing `/color red` because the swatch is officially magenta\n * would be pedantry. A theme whose palette drifts from these names is still\n * addressable by number, which is why the numbers never go away.\n */\nconst SESSION_COLOR_NAMES: ReadonlyArray<{\n\treadonly slot: number;\n\treadonly name: string;\n\treadonly aliases: readonly string[];\n}> = [\n\t{ slot: 1, name: \"cyan\", aliases: [\"c\", \"teal\", \"aqua\"] },\n\t{ slot: 2, name: \"purple\", aliases: [\"p\", \"violet\"] },\n\t{ slot: 3, name: \"yellow\", aliases: [\"y\", \"amber\", \"gold\", \"orange\", \"o\"] },\n\t{ slot: 4, name: \"magenta\", aliases: [\"m\", \"pink\", \"rose\", \"red\", \"r\"] },\n\t{ slot: 5, name: \"green\", aliases: [\"g\"] },\n\t{ slot: 6, name: \"blue\", aliases: [\"b\"] },\n];\n\n/** The canonical slot names, in slot order. For usage lines and pickers. */\nexport const SESSION_COLOR_NAME_LIST: readonly string[] = SESSION_COLOR_NAMES.map((entry) => entry.name);\n\n/** What to call `slot` when reporting it back, or undefined if it is not a slot. */\nexport function sessionColorName(slot: number): string | undefined {\n\treturn SESSION_COLOR_NAMES.find((entry) => entry.slot === slot)?.name;\n}\n\n/**\n * The slot an argument to `/color` asks for: a number (`4`), a name\n * (`magenta`), or an initial (`m`). Case and surrounding space do not matter.\n * Undefined when it names no slot at all.\n */\nexport function parseSessionColorSlot(input: string): number | undefined {\n\tconst normalized = input.trim().toLowerCase();\n\tif (!normalized) return undefined;\n\tif (/^\\d+$/.test(normalized)) {\n\t\tconst slot = Number(normalized);\n\t\treturn isSessionColorSlot(slot) ? slot : undefined;\n\t}\n\tconst match = SESSION_COLOR_NAMES.find((entry) => entry.name === normalized || entry.aliases.includes(normalized));\n\treturn match?.slot;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CA4BrE,CAAC","sourcesContent":["import { APP_NAME } from \"../config.js\";\nimport type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for model cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"color\", description: \"Set the session chip color (1-6)\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{\n\t\tname: \"cd\",\n\t\tdescription: \"Change working directory: /cd <path> (bare = home, - = previous). Starts a session there.\",\n\t},\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n\t{ name: \"subagent\", description: \"Spawn a subagent directly: /subagent <mode> <task>\" },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CA4BrE,CAAC","sourcesContent":["import { APP_NAME } from \"../config.js\";\nimport type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for model cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"color\", description: \"Set the session chip color: /color <1-6|name> (bare = pick one)\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{\n\t\tname: \"cd\",\n\t\tdescription: \"Change working directory: /cd <path> (bare = home, - = previous). Starts a session there.\",\n\t},\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n\t{ name: \"subagent\", description: \"Spawn a subagent directly: /subagent <mode> <task>\" },\n];\n"]}
@@ -8,7 +8,7 @@ export const BUILTIN_SLASH_COMMANDS = [
8
8
  { name: "share", description: "Share session as a secret GitHub gist" },
9
9
  { name: "copy", description: "Copy last agent message to clipboard" },
10
10
  { name: "name", description: "Set session display name" },
11
- { name: "color", description: "Set the session chip color (1-6)" },
11
+ { name: "color", description: "Set the session chip color: /color <1-6|name> (bare = pick one)" },
12
12
  { name: "session", description: "Show session info and stats" },
13
13
  { name: "changelog", description: "Show changelog entries" },
14
14
  { name: "hotkeys", description: "Show all keyboard shortcuts" },
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAiBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE;IAClE,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACjF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,+CAA+C,EAAE;IAChF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uCAAuC,EAAE;IACvE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACrE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,0BAA0B,EAAE;IACzD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE;IAClE,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB,EAAE;IAC5D,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,gDAAgD,EAAE;IAC/E,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uDAAuD,EAAE;IACvF,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,mCAAmC,EAAE;IACnE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gCAAgC,EAAE;IACjE,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D;QACC,IAAI,EAAE,IAAI;QACV,WAAW,EAAE,2FAA2F;KACxG;IACD,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,6DAA6D,EAAE;IAC9F,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;IACjD,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oDAAoD,EAAE;CACvF,CAAC","sourcesContent":["import { APP_NAME } from \"../config.js\";\nimport type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for model cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"color\", description: \"Set the session chip color (1-6)\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{\n\t\tname: \"cd\",\n\t\tdescription: \"Change working directory: /cd <path> (bare = home, - = previous). Starts a session there.\",\n\t},\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n\t{ name: \"subagent\", description: \"Spawn a subagent directly: /subagent <mode> <task>\" },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAiBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE;IAClE,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACjF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,+CAA+C,EAAE;IAChF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uCAAuC,EAAE;IACvE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACrE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,0BAA0B,EAAE;IACzD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,iEAAiE,EAAE;IACjG,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB,EAAE;IAC5D,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,gDAAgD,EAAE;IAC/E,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uDAAuD,EAAE;IACvF,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,mCAAmC,EAAE;IACnE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gCAAgC,EAAE;IACjE,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D;QACC,IAAI,EAAE,IAAI;QACV,WAAW,EAAE,2FAA2F;KACxG;IACD,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,6DAA6D,EAAE;IAC9F,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;IACjD,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oDAAoD,EAAE;CACvF,CAAC","sourcesContent":["import { APP_NAME } from \"../config.js\";\nimport type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for model cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"color\", description: \"Set the session chip color: /color <1-6|name> (bare = pick one)\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{\n\t\tname: \"cd\",\n\t\tdescription: \"Change working directory: /cd <path> (bare = home, - = previous). Starts a session there.\",\n\t},\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n\t{ name: \"subagent\", description: \"Spawn a subagent directly: /subagent <mode> <task>\" },\n];\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAWH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAqGD,MAAM,WAAW,IAAI;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAqBD,MAAM,WAAW,kBAAkB;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACnB;AAoID,uFAAuF;AACvF,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAEvE;AAsHD;;;;;;;;;;;GAWG;AACH,wBAAgB,6BAA6B,CAC5C,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,IAAI,EAAE,EACb,IAAI,EAAE,MAAM,GACV,kBAAkB,CAuFpB;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,YAAY,SAAI,GACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAuHxD;AAED,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAyBzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.js\";\n\n/** Cache for normalized text to avoid redundant processing. Max 100 entries. */\nconst normalizeCache = new Map<string, string>();\nconst MAX_CACHE_SIZE = 100;\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Normalize line endings to LF\n * - Strip trailing whitespace from each line\n * - Normalize tabs to spaces (2 spaces per tab)\n * - Collapse multiple spaces to single space\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nfunction normalizeForFuzzyMatch(text: string): string {\n\t// Check cache first\n\tconst cached = normalizeCache.get(text);\n\tif (cached !== undefined) return cached;\n\n\tconst normalized = text\n\t\t.normalize(\"NFKC\")\n\t\t// Normalize line endings to LF\n\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t.replace(/\\r/g, \"\\n\")\n\t\t// Strip trailing whitespace per line\n\t\t.split(\"\\n\")\n\t\t.map((line) => {\n\t\t\t// Normalize tabs to 2 spaces\n\t\t\tlet normalized = line.replace(/\\t/g, \" \");\n\t\t\t// Collapse multiple spaces to single space (but preserve leading indentation pattern)\n\t\t\t// Only collapse spaces that are NOT at the start of the line (indentation)\n\t\t\tconst leadingSpaces = normalized.match(/^(\\s*)/)?.[1] ?? \"\";\n\t\t\tconst rest = normalized.slice(leadingSpaces.length);\n\t\t\tnormalized = leadingSpaces + rest.replace(/ {2,}/g, \" \");\n\t\t\treturn normalized.trimEnd();\n\t\t})\n\t\t.join(\"\\n\")\n\t\t// Smart single quotes → '\n\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t// Smart double quotes → \"\n\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t// Various dashes/hyphens → -\n\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t// Special spaces → regular space\n\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \");\n\n\t// Cache the result (with size limit)\n\tif (normalizeCache.size >= MAX_CACHE_SIZE) {\n\t\t// Remove oldest entry (first key)\n\t\tconst firstKey = normalizeCache.keys().next().value;\n\t\tif (firstKey !== undefined) {\n\t\t\tnormalizeCache.delete(firstKey);\n\t\t}\n\t}\n\tnormalizeCache.set(text, normalized);\n\n\treturn normalized;\n}\n\n/**\n * Line starts and line texts for one string. Each entry in `lines` includes its\n * own trailing newline, so `starts[i] + lines[i].length` is the start of line\n * `i + 1`. Used to translate a fuzzy match back into original coordinates.\n */\ninterface LineIndex {\n\ttext: string;\n\tstarts: number[];\n\tlines: string[];\n}\n\nfunction buildLineIndex(text: string): LineIndex {\n\tconst starts: number[] = [];\n\tconst lines: string[] = [];\n\tlet start = 0;\n\tfor (;;) {\n\t\tconst newline = text.indexOf(\"\\n\", start);\n\t\tif (newline === -1) {\n\t\t\tstarts.push(start);\n\t\t\tlines.push(text.slice(start));\n\t\t\treturn { text, starts, lines };\n\t\t}\n\t\tstarts.push(start);\n\t\tlines.push(text.slice(start, newline + 1));\n\t\tstart = newline + 1;\n\t}\n}\n\n/** Index of the line containing `offset` (greatest `i` with `starts[i] <= offset`). */\nfunction lineIndexAt(starts: number[], offset: number): number {\n\tlet low = 0;\n\tlet high = starts.length - 1;\n\twhile (low < high) {\n\t\tconst mid = (low + high + 1) >> 1;\n\t\tif (starts[mid] <= offset) low = mid;\n\t\telse high = mid - 1;\n\t}\n\treturn low;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n\t/**\n\t * When true, replace every occurrence of oldText instead of requiring it to\n\t * be unique. Default (false/undefined) keeps the uniqueness guardrail.\n\t */\n\treplaceAll?: boolean;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\t/**\n\t * Text written over the span. Usually the edit's `newText` verbatim; for a\n\t * fuzzy match that covered only part of a line, the untouched remainder of\n\t * the first/last line rides along in normalized form (see `resolveFuzzySpan`).\n\t */\n\treplacement: string;\n}\n\n/** A match located in, and expressed in coordinates of, the original content. */\ninterface ResolvedSpan {\n\tmatchIndex: number;\n\tmatchLength: number;\n\treplacement: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Translate a match found in fuzzy-normalized space back into a span of the\n * original content.\n *\n * Normalization never adds or removes a newline, so normalized line N always\n * corresponds to original line N; only columns within a line can shift (a tab\n * widens to two spaces, a run of spaces collapses, NFKC changes a character's\n * length). Rather than track per-character offsets through those transforms,\n * the span is widened to whole original lines, and whatever of the first and\n * last line the match did not cover is re-attached around `newText` in\n * normalized form.\n *\n * The practical effect: a match that covers whole lines - by far the common\n * case - rewrites exactly those lines and leaves every other byte of the file\n * untouched. Only a partial-line fuzzy match normalizes anything the edit did\n * not ask for, and never beyond the lines it landed on.\n */\nfunction resolveFuzzySpans(\n\toriginal: LineIndex,\n\tnormalized: LineIndex,\n\tnormStarts: number[],\n\tnormLength: number,\n\tnewText: string,\n): ResolvedSpan[] {\n\tconst spans: ResolvedSpan[] = [];\n\tconst lineOf = (offset: number) => lineIndexAt(normalized.starts, offset);\n\n\tlet i = 0;\n\twhile (i < normStarts.length) {\n\t\tconst firstLine = lineOf(normStarts[i]);\n\t\tlet lastLine = lineOf(normStarts[i] + normLength - 1);\n\n\t\t// Matches are ascending and non-overlapping. Absorb any that land inside\n\t\t// the same line block so the block is emitted once with every\n\t\t// substitution applied, rather than as colliding same-line spans.\n\t\tlet end = i + 1;\n\t\twhile (end < normStarts.length && lineOf(normStarts[end]) <= lastLine) {\n\t\t\tlastLine = Math.max(lastLine, lineOf(normStarts[end] + normLength - 1));\n\t\t\tend++;\n\t\t}\n\n\t\tconst blockStart = normalized.starts[firstLine];\n\t\tconst blockEnd = normalized.starts[lastLine] + normalized.lines[lastLine].length;\n\t\tlet replacement = \"\";\n\t\tlet cursor = blockStart;\n\t\tfor (let k = i; k < end; k++) {\n\t\t\treplacement += normalized.text.slice(cursor, normStarts[k]) + newText;\n\t\t\tcursor = normStarts[k] + normLength;\n\t\t}\n\t\treplacement += normalized.text.slice(cursor, blockEnd);\n\n\t\tconst matchIndex = original.starts[firstLine];\n\t\tconst matchEnd = original.starts[lastLine] + original.lines[lastLine].length;\n\t\tspans.push({ matchIndex, matchLength: matchEnd - matchIndex, replacement });\n\t\ti = end;\n\t}\n\n\treturn spans;\n}\n\n/**\n * Locate one edit's `oldText` in `content`, always returning spans in\n * `content`'s own coordinates.\n *\n * Three tiers, tried in order: exact, fuzzy-normalized, then the\n * indentation-tolerant line-block fallback. `occurrences` counts the matches the\n * winning tier found, which is what the uniqueness guardrail tests; `spans` can\n * be shorter, because two fuzzy matches sharing a line are emitted as one\n * rewrite of that line.\n */\nfunction findEditSpans(\n\tcontent: string,\n\tedit: { oldText: string; newText: string },\n\tlineIndexes: () => { original: LineIndex; normalized: LineIndex } | null,\n): { spans: ResolvedSpan[]; occurrences: number } {\n\t// Tier 1: exact. Already in original coordinates.\n\tconst exact = collectMatchIndices(content, edit.oldText);\n\tif (exact.length > 0) {\n\t\treturn {\n\t\t\tspans: exact.map((matchIndex) => ({\n\t\t\t\tmatchIndex,\n\t\t\t\tmatchLength: edit.oldText.length,\n\t\t\t\treplacement: edit.newText,\n\t\t\t})),\n\t\t\toccurrences: exact.length,\n\t\t};\n\t}\n\n\t// Tier 2: fuzzy. Located in normalized space, then translated back.\n\tconst indexes = lineIndexes();\n\tif (indexes) {\n\t\tconst fuzzyOldText = normalizeForFuzzyMatch(edit.oldText);\n\t\tconst fuzzy = collectMatchIndices(indexes.normalized.text, fuzzyOldText);\n\t\tif (fuzzy.length > 0) {\n\t\t\t// oldText did not match the file byte-for-byte, so the whitespace the model\n\t\t\t// used is its own rendering rather than a statement about the file. If\n\t\t\t// newText normalizes to the same thing, it asked for no change: leave the\n\t\t\t// span exactly as it is so the no-change error fires, instead of rewriting\n\t\t\t// the line's indentation to match the model's rendering of it.\n\t\t\tif (normalizeForFuzzyMatch(edit.newText) === fuzzyOldText) {\n\t\t\t\treturn {\n\t\t\t\t\tspans: resolveFuzzySpans(\n\t\t\t\t\t\tindexes.original,\n\t\t\t\t\t\tindexes.normalized,\n\t\t\t\t\t\tfuzzy,\n\t\t\t\t\t\tfuzzyOldText.length,\n\t\t\t\t\t\tedit.newText,\n\t\t\t\t\t).map((span) => ({\n\t\t\t\t\t\t...span,\n\t\t\t\t\t\treplacement: content.slice(span.matchIndex, span.matchIndex + span.matchLength),\n\t\t\t\t\t})),\n\t\t\t\t\toccurrences: fuzzy.length,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tspans: resolveFuzzySpans(indexes.original, indexes.normalized, fuzzy, fuzzyOldText.length, edit.newText),\n\t\t\t\toccurrences: fuzzy.length,\n\t\t\t};\n\t\t}\n\t}\n\n\t// Tier 3: indentation-tolerant line blocks. Already in original coordinates.\n\tconst blocks = findLineBlockMatches(content, edit.oldText).map((span) => ({\n\t\tmatchIndex: span.matchIndex,\n\t\tmatchLength: span.matchLength,\n\t\treplacement: edit.newText,\n\t}));\n\treturn { spans: blocks, occurrences: blocks.length };\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\n/**\n * Collect the start index of every non-overlapping occurrence of needle in\n * haystack. The needle must already be in the same space as haystack (raw for\n * exact matches, fuzzy-normalized when haystack is fuzzy-normalized).\n */\nfunction collectMatchIndices(haystack: string, needle: string): number[] {\n\tconst indices: number[] = [];\n\tif (needle.length === 0) return indices;\n\tlet from = 0;\n\twhile (true) {\n\t\tconst idx = haystack.indexOf(needle, from);\n\t\tif (idx === -1) break;\n\t\tindices.push(idx);\n\t\tfrom = idx + needle.length; // non-overlapping\n\t}\n\treturn indices;\n}\n\n/**\n * Per-line normalization for indentation-tolerant block matching. Applies the\n * same Unicode/space normalization as fuzzy matching, then strips all leading\n * and trailing whitespace so indentation differences are ignored entirely.\n */\nfunction blockNormalizeLine(line: string): string {\n\treturn normalizeForFuzzyMatch(line).trim();\n}\n\ninterface LineBlockMatch {\n\tmatchIndex: number;\n\tmatchLength: number;\n}\n\n/**\n * Indentation-tolerant fallback matcher. Compares oldText against content line\n * by line, ignoring each line's leading/trailing whitespace (and Unicode\n * formatting). Returns character spans in `content` for every block whose\n * trimmed lines equal the trimmed oldText lines. Replacement still happens in\n * the original content space, so surrounding formatting is preserved.\n */\nfunction findLineBlockMatches(content: string, oldText: string): LineBlockMatch[] {\n\tconst hadTrailingNewline = oldText.endsWith(\"\\n\");\n\tconst oldLines = oldText.split(\"\\n\");\n\tif (hadTrailingNewline) oldLines.pop();\n\tif (oldLines.length === 0) return [];\n\tconst trimmedOld = oldLines.map(blockNormalizeLine);\n\n\tconst contentLines = content.split(\"\\n\");\n\tconst k = trimmedOld.length;\n\tif (k > contentLines.length) return [];\n\n\t// Char offset of each line start within content.\n\tconst offsets = new Array<number>(contentLines.length);\n\tlet acc = 0;\n\tfor (let i = 0; i < contentLines.length; i++) {\n\t\toffsets[i] = acc;\n\t\tacc += contentLines[i].length + 1; // + newline\n\t}\n\n\tconst matches: LineBlockMatch[] = [];\n\tfor (let i = 0; i + k <= contentLines.length; i++) {\n\t\tlet ok = true;\n\t\tfor (let j = 0; j < k; j++) {\n\t\t\tif (blockNormalizeLine(contentLines[i + j]) !== trimmedOld[j]) {\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!ok) continue;\n\t\tconst matchIndex = offsets[i];\n\t\tlet matchLength = 0;\n\t\tfor (let j = 0; j < k; j++) matchLength += contentLines[i + j].length + (j < k - 1 ? 1 : 0);\n\t\t// Include the trailing newline when oldText carried one and a line follows the block.\n\t\tif (hadTrailingNewline && i + k < contentLines.length) matchLength += 1;\n\t\tmatches.push({ matchIndex, matchLength });\n\t}\n\treturn matches;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable.\n *\n * Every match, however loosely it was found, is resolved back to a span of the\n * *original* content before anything is written. A fuzzy or indentation-tolerant\n * match therefore rewrites only the lines it landed on: the rest of the file\n * keeps its exact bytes, and the diff callers render from `baseContent` is the\n * real change on disk rather than a normalized-vs-normalized view of it.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t\treplaceAll: edit.replaceAll === true,\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\n\t// Both line indexes are needed only if some edit reaches the fuzzy tier, and\n\t// they are identical for every edit, so build them at most once. Normalization\n\t// is line-preserving; if that ever fails to hold, the fuzzy tier is skipped\n\t// rather than risk translating a span against a mismatched line table.\n\tlet lineIndexesCache: { original: LineIndex; normalized: LineIndex } | null | undefined;\n\tconst lineIndexes = () => {\n\t\tif (lineIndexesCache === undefined) {\n\t\t\tconst original = buildLineIndex(baseContent);\n\t\t\tconst normalized = buildLineIndex(normalizeForFuzzyMatch(baseContent));\n\t\t\tlineIndexesCache = original.lines.length === normalized.lines.length ? { original, normalized } : null;\n\t\t}\n\t\treturn lineIndexesCache;\n\t};\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst { spans, occurrences } = findEditSpans(baseContent, edit, lineIndexes);\n\t\tif (spans.length === 0) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tif (edit.replaceAll) {\n\t\t\t// Replace every occurrence so the shared reverse-order applier rewrites them all.\n\t\t\tfor (const span of spans) {\n\t\t\t\tmatchedEdits.push({\n\t\t\t\t\teditIndex: i,\n\t\t\t\t\tmatchIndex: span.matchIndex,\n\t\t\t\t\tmatchLength: span.matchLength,\n\t\t\t\t\treplacement: span.replacement,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: spans[0].matchIndex,\n\t\t\tmatchLength: spans[0].matchLength,\n\t\t\treplacement: spans[0].replacement,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet newContent = baseContent;\n\tfor (let i = matchedEdits.length - 1; i >= 0; i--) {\n\t\tconst edit = matchedEdits[i];\n\t\tnewContent =\n\t\t\tnewContent.substring(0, edit.matchIndex) +\n\t\t\tedit.replacement +\n\t\t\tnewContent.substring(edit.matchIndex + edit.matchLength);\n\t}\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/**\n * Generate a unified diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n"]}
1
+ {"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAWH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAkOD,MAAM,WAAW,IAAI;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAqBD,MAAM,WAAW,kBAAkB;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACnB;AAsHD,uFAAuF;AACvF,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAEvE;AAyOD;;;;;;;;;;;GAWG;AACH,wBAAgB,6BAA6B,CAC5C,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,IAAI,EAAE,EACb,IAAI,EAAE,MAAM,GACV,kBAAkB,CA2FpB;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,YAAY,SAAI,GACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAuHxD;AAED,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAyBzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.js\";\n\n/** Cache for normalized text to avoid redundant processing. Max 100 entries. */\nconst normalizeCache = new Map<string, string>();\nconst MAX_CACHE_SIZE = 100;\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * A normalized string plus, for every one of its indices, the index in the\n * source text that produced it. `map` has one extra trailing entry so a\n * half-open normalized span `[a, b)` maps to the source span `[map[a], map[b])`.\n *\n * This is what lets a fuzzy match be written back over exactly the bytes it\n * matched. Without it the only way to place a normalized match in the original\n * was to widen it to whole lines and re-emit the untouched remainder in\n * normalized form - which silently converted tabs, smart quotes and NFKC\n * lookalikes on any line an edit happened to land on.\n */\ninterface NormalizedWithMap {\n\ttext: string;\n\tmap: number[];\n}\n\n/** Combining marks attach to the preceding base character and normalize with it. */\nconst COMBINING_MARK = /\\p{Mn}/u;\n\n/**\n * NFKC, applied per grapheme cluster so each output character can be traced to\n * the cluster that produced it. Clustering keeps `e` + U+0301 composing into\n * `é` the way whole-string NFKC would, while `fi` still expands to `fi` with both\n * characters pointing at the single source ligature.\n */\nfunction nfkcWithMap(text: string): NormalizedWithMap {\n\tlet out = \"\";\n\tconst map: number[] = [];\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst start = i;\n\t\tconst base = String.fromCodePoint(text.codePointAt(i) as number);\n\t\ti += base.length;\n\t\tlet cluster = base;\n\t\twhile (i < text.length) {\n\t\t\tconst next = String.fromCodePoint(text.codePointAt(i) as number);\n\t\t\tif (!COMBINING_MARK.test(next)) break;\n\t\t\tcluster += next;\n\t\t\ti += next.length;\n\t\t}\n\t\tconst composed = cluster.normalize(\"NFKC\");\n\t\tfor (let k = 0; k < composed.length; k++) map.push(start);\n\t\tout += composed;\n\t}\n\tmap.push(text.length);\n\treturn { text: out, map };\n}\n\n/** CRLF and lone CR collapse to LF. */\nfunction toLfWithMap(text: string): NormalizedWithMap {\n\tlet out = \"\";\n\tconst map: number[] = [];\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst ch = text[i];\n\t\tif (ch === \"\\r\") {\n\t\t\tmap.push(i);\n\t\t\tout += \"\\n\";\n\t\t\tif (text[i + 1] === \"\\n\") i++;\n\t\t\tcontinue;\n\t\t}\n\t\tmap.push(i);\n\t\tout += ch;\n\t}\n\tmap.push(text.length);\n\treturn { text: out, map };\n}\n\n/**\n * The per-line whitespace pass: tabs widen to two spaces, interior runs of two\n * or more spaces collapse to one (leading indentation is left alone), and\n * trailing whitespace is dropped.\n */\nfunction normalizeLineWhitespaceWithMap(text: string): NormalizedWithMap {\n\tlet out = \"\";\n\tconst map: number[] = [];\n\tlet lineStart = 0;\n\twhile (lineStart <= text.length) {\n\t\tlet lineEnd = text.indexOf(\"\\n\", lineStart);\n\t\tconst hasNewline = lineEnd !== -1;\n\t\tif (!hasNewline) lineEnd = text.length;\n\n\t\t// Tabs first, so indentation is measured the way the old chain measured it.\n\t\tlet expanded = \"\";\n\t\tconst expandedMap: number[] = [];\n\t\tfor (let i = lineStart; i < lineEnd; i++) {\n\t\t\tif (text[i] === \"\\t\") {\n\t\t\t\texpanded += \" \";\n\t\t\t\texpandedMap.push(i, i);\n\t\t\t} else {\n\t\t\t\texpanded += text[i];\n\t\t\t\texpandedMap.push(i);\n\t\t\t}\n\t\t}\n\n\t\tconst leadingLength = (expanded.match(/^\\s*/)?.[0] ?? \"\").length;\n\t\tlet emitted = \"\";\n\t\tconst emittedMap: number[] = [];\n\t\tfor (let i = 0; i < expanded.length; i++) {\n\t\t\t// Collapse only runs that start past the indentation.\n\t\t\tif (i >= leadingLength && expanded[i] === \" \" && emitted.endsWith(\" \") && emitted.length > leadingLength) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\temitted += expanded[i];\n\t\t\temittedMap.push(expandedMap[i]);\n\t\t}\n\t\t// trimEnd\n\t\tlet end = emitted.length;\n\t\twhile (end > 0 && /\\s/.test(emitted[end - 1])) end--;\n\n\t\tout += emitted.slice(0, end);\n\t\tfor (let i = 0; i < end; i++) map.push(emittedMap[i]);\n\n\t\tif (hasNewline) {\n\t\t\tout += \"\\n\";\n\t\t\tmap.push(lineEnd);\n\t\t\tlineStart = lineEnd + 1;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\tmap.push(text.length);\n\treturn { text: out, map };\n}\n\n/** Compose `outer` (indices into `inner.text`) onto `inner`'s own source indices. */\nfunction composeMaps(outer: number[], inner: number[]): number[] {\n\treturn outer.map((i) => inner[i] ?? inner[inner.length - 1]);\n}\n\n/**\n * Normalize text for fuzzy matching, keeping an index back to the source for\n * every character produced. Same output text as `normalizeForFuzzyMatch`.\n */\nfunction normalizeForFuzzyMatchWithMap(text: string): NormalizedWithMap {\n\tconst nfkc = nfkcWithMap(text);\n\tconst lf = toLfWithMap(nfkc.text);\n\tconst lines = normalizeLineWhitespaceWithMap(lf.text);\n\t// The final substitutions are one-for-one, so they leave the map untouched.\n\tconst substituted = applyCharSubstitutions(lines.text);\n\treturn { text: substituted, map: composeMaps(composeMaps(lines.map, lf.map), nfkc.map) };\n}\n\n/** The one-for-one Unicode substitutions: quotes, dashes and exotic spaces. */\nfunction applyCharSubstitutions(text: string): string {\n\treturn text\n\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \");\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Normalize line endings to LF\n * - Strip trailing whitespace from each line\n * - Normalize tabs to spaces (2 spaces per tab)\n * - Collapse multiple spaces to single space\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nfunction normalizeForFuzzyMatch(text: string): string {\n\t// Check cache first\n\tconst cached = normalizeCache.get(text);\n\tif (cached !== undefined) return cached;\n\n\tconst normalized = text\n\t\t.normalize(\"NFKC\")\n\t\t// Normalize line endings to LF\n\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t.replace(/\\r/g, \"\\n\")\n\t\t// Strip trailing whitespace per line\n\t\t.split(\"\\n\")\n\t\t.map((line) => {\n\t\t\t// Normalize tabs to 2 spaces\n\t\t\tlet normalized = line.replace(/\\t/g, \" \");\n\t\t\t// Collapse multiple spaces to single space (but preserve leading indentation pattern)\n\t\t\t// Only collapse spaces that are NOT at the start of the line (indentation)\n\t\t\tconst leadingSpaces = normalized.match(/^(\\s*)/)?.[1] ?? \"\";\n\t\t\tconst rest = normalized.slice(leadingSpaces.length);\n\t\t\tnormalized = leadingSpaces + rest.replace(/ {2,}/g, \" \");\n\t\t\treturn normalized.trimEnd();\n\t\t})\n\t\t.join(\"\\n\")\n\t\t// Smart single quotes → '\n\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t// Smart double quotes → \"\n\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t// Various dashes/hyphens → -\n\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t// Special spaces → regular space\n\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \");\n\n\t// Cache the result (with size limit)\n\tif (normalizeCache.size >= MAX_CACHE_SIZE) {\n\t\t// Remove oldest entry (first key)\n\t\tconst firstKey = normalizeCache.keys().next().value;\n\t\tif (firstKey !== undefined) {\n\t\t\tnormalizeCache.delete(firstKey);\n\t\t}\n\t}\n\tnormalizeCache.set(text, normalized);\n\n\treturn normalized;\n}\n\n/** Whether `index` in `text` is the first character of a line. */\nfunction isAtLineStart(text: string, index: number): boolean {\n\treturn index === 0 || text[index - 1] === \"\\n\";\n}\n\n/**\n * Indentation of `line`, with tabs widened the way `normalizeForFuzzyMatch`\n * widens them, so a tab-indented file and a two-space rendering of it compare\n * equal while genuinely different nesting levels do not.\n */\nfunction normalizedIndent(line: string): string {\n\treturn (line.match(/^[ \\t]*/)?.[0] ?? \"\").replace(/\\t/g, \" \");\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n\t/**\n\t * When true, replace every occurrence of oldText instead of requiring it to\n\t * be unique. Default (false/undefined) keeps the uniqueness guardrail.\n\t */\n\treplaceAll?: boolean;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\t/**\n\t * Text written over the span. Usually the edit's `newText` verbatim; for a\n\t * fuzzy match that covered only part of a line, the untouched remainder of\n\t * the first/last line rides along in normalized form (see `resolveFuzzySpan`).\n\t */\n\treplacement: string;\n}\n\n/** A match located in, and expressed in coordinates of, the original content. */\ninterface ResolvedSpan {\n\tmatchIndex: number;\n\tmatchLength: number;\n\treplacement: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Locate one edit's `oldText` in `content`, always returning spans in\n * `content`'s own coordinates.\n *\n * Three tiers, tried in order: exact, fuzzy-normalized, then the\n * indentation-tolerant line-block fallback. `occurrences` counts the matches the\n * winning tier found, which is what the uniqueness guardrail tests; `spans` can\n * be shorter, because two fuzzy matches sharing a line are emitted as one\n * rewrite of that line.\n */\nfunction findEditSpans(\n\tcontent: string,\n\tedit: { oldText: string; newText: string },\n\tfuzzyIndex: () => NormalizedWithMap | null,\n): { spans: ResolvedSpan[]; occurrences: number; noopFuzzySpan?: ResolvedSpan } {\n\t// An oldText that opens with indentation is a statement about a whole line, so\n\t// it must not match mid-line inside a more deeply indented one - that lands the\n\t// edit in a different block entirely. An oldText that opens with a non-blank\n\t// character claims nothing about indentation, so every tier stays tolerant.\n\tconst anchored = /^[ \\t]/.test(edit.oldText);\n\n\t// Tier 1: exact. Already in original coordinates.\n\tconst exact = collectMatchIndices(content, edit.oldText).filter((i) => !anchored || isAtLineStart(content, i));\n\tif (exact.length > 0) {\n\t\treturn {\n\t\t\tspans: exact.map((matchIndex) => ({\n\t\t\t\tmatchIndex,\n\t\t\t\tmatchLength: edit.oldText.length,\n\t\t\t\treplacement: edit.newText,\n\t\t\t})),\n\t\t\toccurrences: exact.length,\n\t\t};\n\t}\n\n\t// Tier 2: fuzzy. Located in normalized space, then mapped straight back onto\n\t// the bytes it matched - nothing outside the match is rewritten.\n\tconst normalized = fuzzyIndex();\n\tif (normalized) {\n\t\tconst fuzzyOldText = normalizeForFuzzyMatch(edit.oldText);\n\t\tconst normalizedText = normalized.text;\n\t\tconst fuzzy = collectMatchIndices(normalizedText, fuzzyOldText).filter(\n\t\t\t(i) => !anchored || isAtLineStart(normalizedText, i),\n\t\t);\n\t\tconst spanAt = (index: number, replacement: string): ResolvedSpan => {\n\t\t\tconst start = normalized.map[index];\n\t\t\tconst end = normalized.map[index + fuzzyOldText.length];\n\t\t\treturn { matchIndex: start, matchLength: end - start, replacement };\n\t\t};\n\n\t\t/**\n\t\t * Build the replacement for a fuzzy match.\n\t\t *\n\t\t * newText is written as the model wrote it, with one exception: indentation.\n\t\t * A fuzzy match means oldText was not on disk byte-for-byte, so the whitespace\n\t\t * in it is the model's rendering of the line rather than a statement about the\n\t\t * file - and newText inherits that rendering. Writing it back re-indents lines\n\t\t * the edit never meant to touch, which in a tab-indented file means every\n\t\t * fuzzy edit silently converts tabs to spaces.\n\t\t *\n\t\t * So when newText's indentation says the same thing oldText's did, the file's\n\t\t * own indentation is kept. An edit that means to re-indent says so by giving\n\t\t * newText a different indentation from oldText, and that still applies.\n\t\t */\n\t\tconst replacementFor = (index: number): string => {\n\t\t\tconst start = normalized.map[index];\n\t\t\tconst end = normalized.map[index + fuzzyOldText.length];\n\t\t\tif (!isAtLineStart(content, start)) return edit.newText;\n\t\t\tconst originalLines = content.slice(start, end).split(\"\\n\");\n\t\t\tconst newLines = edit.newText.split(\"\\n\");\n\t\t\tconst oldLines = edit.oldText.split(\"\\n\");\n\t\t\tif (originalLines.length !== newLines.length || oldLines.length !== newLines.length) {\n\t\t\t\treturn edit.newText;\n\t\t\t}\n\t\t\treturn newLines\n\t\t\t\t.map((line, i) => {\n\t\t\t\t\tconst newIndent = line.match(/^[ \\t]*/)?.[0] ?? \"\";\n\t\t\t\t\tconst oldIndent = oldLines[i].match(/^[ \\t]*/)?.[0] ?? \"\";\n\t\t\t\t\tif (normalizedIndent(newIndent) !== normalizedIndent(oldIndent)) return line;\n\t\t\t\t\treturn (originalLines[i].match(/^[ \\t]*/)?.[0] ?? \"\") + line.slice(newIndent.length);\n\t\t\t\t})\n\t\t\t\t.join(\"\\n\");\n\t\t};\n\n\t\tif (fuzzy.length > 0) {\n\t\t\t// oldText did not match the file byte-for-byte, so the whitespace the model\n\t\t\t// used is its own rendering rather than a statement about the file. If\n\t\t\t// newText normalizes to the same thing, it asked for no change: leave the\n\t\t\t// span exactly as it is so the no-change error fires, instead of rewriting\n\t\t\t// the line's indentation to match the model's rendering of it.\n\t\t\tif (normalizeForFuzzyMatch(edit.newText) === fuzzyOldText) {\n\t\t\t\t// oldText did not match byte-for-byte, so its whitespace is the model's\n\t\t\t\t// rendering rather than a statement about the file, and newText asks for\n\t\t\t\t// nothing the matcher can see. Leave the bytes alone and report the span\n\t\t\t\t// so the caller can name the character the model failed to reproduce.\n\t\t\t\tconst untouched = fuzzy.map((index) => {\n\t\t\t\t\tconst span = spanAt(index, \"\");\n\t\t\t\t\treturn { ...span, replacement: content.slice(span.matchIndex, span.matchIndex + span.matchLength) };\n\t\t\t\t});\n\t\t\t\treturn { spans: untouched, occurrences: fuzzy.length, noopFuzzySpan: untouched[0] };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tspans: fuzzy.map((index) => spanAt(index, replacementFor(index))),\n\t\t\t\toccurrences: fuzzy.length,\n\t\t\t};\n\t\t}\n\t}\n\n\t// Tier 3: indentation-tolerant line blocks. Already in original coordinates.\n\tconst blocks = findLineBlockMatches(content, edit.oldText, anchored).map((span) => ({\n\t\tmatchIndex: span.matchIndex,\n\t\tmatchLength: span.matchLength,\n\t\treplacement: edit.newText,\n\t}));\n\treturn { spans: blocks, occurrences: blocks.length };\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\n/**\n * Collect the start index of every non-overlapping occurrence of needle in\n * haystack. The needle must already be in the same space as haystack (raw for\n * exact matches, fuzzy-normalized when haystack is fuzzy-normalized).\n */\nfunction collectMatchIndices(haystack: string, needle: string): number[] {\n\tconst indices: number[] = [];\n\tif (needle.length === 0) return indices;\n\tlet from = 0;\n\twhile (true) {\n\t\tconst idx = haystack.indexOf(needle, from);\n\t\tif (idx === -1) break;\n\t\tindices.push(idx);\n\t\tfrom = idx + needle.length; // non-overlapping\n\t}\n\treturn indices;\n}\n\n/**\n * Per-line normalization for indentation-tolerant block matching. Applies the\n * same Unicode/space normalization as fuzzy matching, then strips all leading\n * and trailing whitespace so indentation differences are ignored entirely.\n */\nfunction blockNormalizeLine(line: string): string {\n\treturn normalizeForFuzzyMatch(line).trim();\n}\n\ninterface LineBlockMatch {\n\tmatchIndex: number;\n\tmatchLength: number;\n}\n\n/**\n * Indentation-tolerant fallback matcher. Compares oldText against content line\n * by line, ignoring each line's leading/trailing whitespace (and Unicode\n * formatting). Returns character spans in `content` for every block whose\n * trimmed lines equal the trimmed oldText lines. Replacement still happens in\n * the original content space, so surrounding formatting is preserved.\n */\nfunction findLineBlockMatches(content: string, oldText: string, anchored = false): LineBlockMatch[] {\n\tconst hadTrailingNewline = oldText.endsWith(\"\\n\");\n\tconst oldLines = oldText.split(\"\\n\");\n\tif (hadTrailingNewline) oldLines.pop();\n\tif (oldLines.length === 0) return [];\n\tconst trimmedOld = oldLines.map(blockNormalizeLine);\n\n\tconst contentLines = content.split(\"\\n\");\n\tconst k = trimmedOld.length;\n\tif (k > contentLines.length) return [];\n\n\t// Char offset of each line start within content.\n\tconst offsets = new Array<number>(contentLines.length);\n\tlet acc = 0;\n\tfor (let i = 0; i < contentLines.length; i++) {\n\t\toffsets[i] = acc;\n\t\tacc += contentLines[i].length + 1; // + newline\n\t}\n\n\tconst matches: LineBlockMatch[] = [];\n\tfor (let i = 0; i + k <= contentLines.length; i++) {\n\t\tlet ok = true;\n\t\tfor (let j = 0; j < k; j++) {\n\t\t\tif (blockNormalizeLine(contentLines[i + j]) !== trimmedOld[j]) {\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// Tier 3 ignores indentation by design. When oldText stated its own\n\t\t\t// indentation, honour that statement rather than matching any nesting level.\n\t\t\tif (anchored && normalizedIndent(contentLines[i + j]) !== normalizedIndent(oldLines[j])) {\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!ok) continue;\n\t\tconst matchIndex = offsets[i];\n\t\tlet matchLength = 0;\n\t\tfor (let j = 0; j < k; j++) matchLength += contentLines[i + j].length + (j < k - 1 ? 1 : 0);\n\t\t// Include the trailing newline when oldText carried one and a line follows the block.\n\t\tif (hadTrailingNewline && i + k < contentLines.length) matchLength += 1;\n\t\tmatches.push({ matchIndex, matchLength });\n\t}\n\treturn matches;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\n/**\n * Characters the fuzzy matcher erases. When an edit matched only fuzzily and its\n * newText normalizes to the same text, one of these is why: the file holds a\n * character the model reproduced as its plain-ASCII lookalike, so the change it\n * asked for is invisible to the matcher and can never be applied by retrying the\n * same text. Naming the character is the whole recovery - resend oldText with it.\n */\nconst NORMALIZED_AWAY_NAMES = new Map<number, string>([\n\t[0x0009, \"TAB\"],\n\t[0x00a0, \"NO-BREAK SPACE\"],\n\t[0x2002, \"EN SPACE\"],\n\t[0x2003, \"EM SPACE\"],\n\t[0x2009, \"THIN SPACE\"],\n\t[0x200a, \"HAIR SPACE\"],\n\t[0x2010, \"HYPHEN\"],\n\t[0x2011, \"NON-BREAKING HYPHEN\"],\n\t[0x2012, \"FIGURE DASH\"],\n\t[0x2013, \"EN DASH\"],\n\t[0x2014, \"EM DASH\"],\n\t[0x2015, \"HORIZONTAL BAR\"],\n\t[0x2018, \"LEFT SINGLE QUOTATION MARK\"],\n\t[0x2019, \"RIGHT SINGLE QUOTATION MARK\"],\n\t[0x201a, \"SINGLE LOW-9 QUOTATION MARK\"],\n\t[0x201b, \"SINGLE HIGH-REVERSED-9 QUOTATION MARK\"],\n\t[0x201c, \"LEFT DOUBLE QUOTATION MARK\"],\n\t[0x201d, \"RIGHT DOUBLE QUOTATION MARK\"],\n\t[0x201e, \"DOUBLE LOW-9 QUOTATION MARK\"],\n\t[0x201f, \"DOUBLE HIGH-REVERSED-9 QUOTATION MARK\"],\n\t[0x202f, \"NARROW NO-BREAK SPACE\"],\n\t[0x205f, \"MEDIUM MATHEMATICAL SPACE\"],\n\t[0x2212, \"MINUS SIGN\"],\n\t[0x3000, \"IDEOGRAPHIC SPACE\"],\n]);\n\nfunction formatCodePoint(ch: string): string {\n\tconst cp = ch.codePointAt(0) ?? 0;\n\tconst hex = `U+${cp.toString(16).toUpperCase().padStart(4, \"0\")}`;\n\tconst name = NORMALIZED_AWAY_NAMES.get(cp);\n\tif (name) return `${hex} ${name}`;\n\t// NFKC-only difference (ligature, full-width form, superscript, ...).\n\treturn `${hex} (normalizes to ${JSON.stringify(ch.normalize(\"NFKC\"))})`;\n}\n\n/** Cap on how many offending characters one error names before summarising. */\nconst MAX_REPORTED_CHARS = 5;\n\n/**\n * Every character in `text` that fuzzy normalization would not leave alone.\n *\n * All of them are listed rather than just the first: the match span is widened to\n * whole lines, so the first offender is often a leading tab the model never put\n * in its oldText, while the character it actually needs sits further along the\n * line. Naming one of them and guessing wrong is worse than naming them all.\n */\nfunction findNormalizedAwayChars(text: string): Array<{ ch: string; index: number }> {\n\tconst found: Array<{ ch: string; index: number }> = [];\n\tlet index = 0;\n\tfor (const ch of text) {\n\t\tconst cp = ch.codePointAt(0) ?? 0;\n\t\tif (NORMALIZED_AWAY_NAMES.has(cp) || ch.normalize(\"NFKC\") !== ch) {\n\t\t\tfound.push({ ch, index });\n\t\t}\n\t\tindex += ch.length;\n\t}\n\treturn found;\n}\n\n/** 1-indexed line and column of `offset` within `content`. */\nfunction lineAndColumn(content: string, offset: number): { line: number; column: number } {\n\tconst before = content.slice(0, offset);\n\tconst line = before.split(\"\\n\").length;\n\tconst column = offset - (before.lastIndexOf(\"\\n\") + 1) + 1;\n\treturn { line, column };\n}\n\n/**\n * The edit matched, but only after normalization erased the very difference it\n * asked for. Retrying the same oldText can never succeed, so say which character\n * is actually on disk and where.\n */\nfunction getFuzzyNoopError(\n\tpath: string,\n\teditIndex: number,\n\ttotalEdits: number,\n\tcontent: string,\n\tspan: ResolvedSpan,\n): Error {\n\tconst matched = content.slice(span.matchIndex, span.matchIndex + span.matchLength);\n\tconst which = totalEdits === 1 ? \"The edit\" : `edits[${editIndex}]`;\n\tconst offenders = findNormalizedAwayChars(matched);\n\tlet detail: string;\n\tif (offenders.length > 0) {\n\t\tconst shown = offenders.slice(0, MAX_REPORTED_CHARS).map((o) => {\n\t\t\tconst { line, column } = lineAndColumn(content, span.matchIndex + o.index);\n\t\t\treturn `${formatCodePoint(o.ch)} at line ${line}, column ${column}`;\n\t\t});\n\t\tconst more = offenders.length - shown.length;\n\t\tdetail =\n\t\t\t`the text it matched in ${path} contains ${shown.join(\"; \")}` +\n\t\t\t`${more > 0 ? `; and ${more} more` : \"\"}, which your oldText spelled as plain-ASCII lookalikes. ` +\n\t\t\t`Send oldText containing those exact characters and the replacement will apply.`;\n\t} else {\n\t\tdetail =\n\t\t\t`oldText matched ${path} only after whitespace normalization, and newText normalizes to the same text, ` +\n\t\t\t`so nothing would change. Send oldText exactly as the file spells it.`;\n\t}\n\treturn new Error(`No changes made to ${path}. ${which} asked for a change that is invisible to matching: ${detail}`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable.\n *\n * Every match, however loosely it was found, is resolved back to a span of the\n * *original* content before anything is written. A fuzzy or indentation-tolerant\n * match therefore rewrites only the lines it landed on: the rest of the file\n * keeps its exact bytes, and the diff callers render from `baseContent` is the\n * real change on disk rather than a normalized-vs-normalized view of it.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t\treplaceAll: edit.replaceAll === true,\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\n\t// Needed only if some edit reaches the fuzzy tier, and identical for every\n\t// edit, so build it at most once. A map that does not line up with its own\n\t// text would put spans in the wrong place, so the tier is skipped rather than\n\t// trusted if that ever fails to hold.\n\tlet normalizedCache: NormalizedWithMap | null | undefined;\n\tconst fuzzyIndex = () => {\n\t\tif (normalizedCache === undefined) {\n\t\t\tconst built = normalizeForFuzzyMatchWithMap(baseContent);\n\t\t\tnormalizedCache = built.map.length === built.text.length + 1 ? built : null;\n\t\t}\n\t\treturn normalizedCache;\n\t};\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst { spans, occurrences, noopFuzzySpan } = findEditSpans(baseContent, edit, fuzzyIndex);\n\t\tif (spans.length === 0) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\t\t// Raised per edit, not once for the whole call: a no-op hidden among edits\n\t\t// that do change bytes used to be swallowed and reported as a success.\n\t\tif (noopFuzzySpan) {\n\t\t\tthrow getFuzzyNoopError(path, i, normalizedEdits.length, baseContent, noopFuzzySpan);\n\t\t}\n\n\t\tif (edit.replaceAll) {\n\t\t\t// Replace every occurrence so the shared reverse-order applier rewrites them all.\n\t\t\tfor (const span of spans) {\n\t\t\t\tmatchedEdits.push({\n\t\t\t\t\teditIndex: i,\n\t\t\t\t\tmatchIndex: span.matchIndex,\n\t\t\t\t\tmatchLength: span.matchLength,\n\t\t\t\t\treplacement: span.replacement,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: spans[0].matchIndex,\n\t\t\tmatchLength: spans[0].matchLength,\n\t\t\treplacement: spans[0].replacement,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet newContent = baseContent;\n\tfor (let i = matchedEdits.length - 1; i >= 0; i--) {\n\t\tconst edit = matchedEdits[i];\n\t\tnewContent =\n\t\t\tnewContent.substring(0, edit.matchIndex) +\n\t\t\tedit.replacement +\n\t\t\tnewContent.substring(edit.matchIndex + edit.matchLength);\n\t}\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/**\n * Generate a unified diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n"]}