zidane 6.5.0 → 6.5.2
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.
- package/dist/{acp-B-AOovHz.js → acp-565X8nVP.js} +6 -7
- package/dist/{acp-B-AOovHz.js.map → acp-565X8nVP.js.map} +1 -1
- package/dist/acp-cli.js +6 -6
- package/dist/acp.d.ts +1 -1
- package/dist/acp.d.ts.map +1 -1
- package/dist/acp.js +1 -1
- package/dist/{agent-SQ6rxfpT.js → agent-CvO7UOxv.js} +1427 -610
- package/dist/agent-CvO7UOxv.js.map +1 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -2
- package/dist/{anthropic-D3lkw5mv.js → anthropic-Dov2mC5e.js} +3 -3
- package/dist/{anthropic-D3lkw5mv.js.map → anthropic-Dov2mC5e.js.map} +1 -1
- package/dist/{auth-BzYbbdN_.js → auth-B8ZuBcKC.js} +5 -5
- package/dist/{auth-BzYbbdN_.js.map → auth-B8ZuBcKC.js.map} +1 -1
- package/dist/chat/pure.d.ts +4 -4
- package/dist/chat/pure.js +3 -3
- package/dist/chat.d.ts +114 -5
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +6 -6
- package/dist/context-segments-1mcqSCM3.js +494 -0
- package/dist/context-segments-1mcqSCM3.js.map +1 -0
- package/dist/{context-transport-CDBatvQc.js → context-transport-ClvadrlH.js} +3 -3
- package/dist/{context-transport-CDBatvQc.js.map → context-transport-ClvadrlH.js.map} +1 -1
- package/dist/contexts/daytona.d.ts +1 -1
- package/dist/contexts/e2b.d.ts +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/eval.js +1 -1
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +3 -3
- package/dist/{index-CWBSrqI6.d.ts → index-DfERTrql.d.ts} +178 -6
- package/dist/index-DfERTrql.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +9 -10
- package/dist/index.js.map +1 -1
- package/dist/{login-XZDS4K2o.js → login-Cl6ML2XN.js} +2 -2
- package/dist/{login-XZDS4K2o.js.map → login-Cl6ML2XN.js.map} +1 -1
- package/dist/{mcp-D27rP47I.js → mcp-DdntU47g.js} +3 -3
- package/dist/{mcp-D27rP47I.js.map → mcp-DdntU47g.js.map} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +1 -1
- package/dist/{messages-C01kKGj0.js → messages-C_H9soi5.js} +2 -3
- package/dist/{messages-C01kKGj0.js.map → messages-C_H9soi5.js.map} +1 -1
- package/dist/{openai-compat-B3c_hzwf.js → openai-compat-CnHeo4Lz.js} +216 -3
- package/dist/openai-compat-CnHeo4Lz.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/anthropic.js +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/arcee.js +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/baseten.js +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/cerebras.js +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/local.js +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai-compat.js +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openai.js +2 -2
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/openrouter.js +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.js +1 -1
- package/dist/{providers-z1vU0b2Q.js → providers-B6mFe7OD.js} +3 -3
- package/dist/{providers-z1vU0b2Q.js.map → providers-B6mFe7OD.js.map} +1 -1
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +4 -4
- package/dist/restate.d.ts +178 -2
- package/dist/restate.d.ts.map +1 -1
- package/dist/restate.js +458 -4
- package/dist/restate.js.map +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/{session-cr9VdoEO.js → session-VpLrNaFQ.js} +2 -2
- package/dist/{session-cr9VdoEO.js.map → session-VpLrNaFQ.js.map} +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/session.js +2 -2
- package/dist/skills.d.ts +1 -1
- package/dist/{stdio-O-m9WVkE.js → stdio-BQeCMmuK.js} +2 -2
- package/dist/{stdio-O-m9WVkE.js.map → stdio-BQeCMmuK.js.map} +1 -1
- package/dist/{stdio-loader-BSGQmG4L.js → stdio-loader-BN1l1ZAG.js} +2 -2
- package/dist/{stdio-loader-BSGQmG4L.js.map → stdio-loader-BN1l1ZAG.js.map} +1 -1
- package/dist/{tool-formatters-gFqQbzPY.d.ts → tool-formatters-B2gBbKaS.d.ts} +2 -2
- package/dist/{tool-formatters-gFqQbzPY.d.ts.map → tool-formatters-B2gBbKaS.d.ts.map} +1 -1
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +1 -2
- package/dist/{transcript-anchors-qCs3wZpu.d.ts → transcript-anchors-CeIxhKP7.d.ts} +2 -2
- package/dist/{transcript-anchors-qCs3wZpu.d.ts.map → transcript-anchors-CeIxhKP7.d.ts.map} +1 -1
- package/dist/{transcript-anchors-D4IxJifV.js → transcript-anchors-CmFKUw8M.js} +139 -19
- package/dist/transcript-anchors-CmFKUw8M.js.map +1 -0
- package/dist/tui.d.ts +74 -3
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +819 -83
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-M9-jUyDd.d.ts → turn-operations-Dyv3Z-Ff.d.ts} +3 -3
- package/dist/{turn-operations-M9-jUyDd.d.ts.map → turn-operations-Dyv3Z-Ff.d.ts.map} +1 -1
- package/dist/{turn-operations-CAvi8NYt.js → turn-operations-iGu5J08j.js} +2 -2
- package/dist/{turn-operations-CAvi8NYt.js.map → turn-operations-iGu5J08j.js.map} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/{xai-BPwMQSuF.js → xai-Du6Wfnlb.js} +2 -2
- package/dist/{xai-BPwMQSuF.js.map → xai-Du6Wfnlb.js.map} +1 -1
- package/docs/CHAT.md +42 -1
- package/docs/INTERACTIONS.md +39 -0
- package/docs/RESTATE.md +102 -3
- package/docs/TUI.md +28 -2
- package/package.json +1 -1
- package/dist/agent-SQ6rxfpT.js.map +0 -1
- package/dist/aliasing-lVFbm81n.js +0 -217
- package/dist/aliasing-lVFbm81n.js.map +0 -1
- package/dist/context-breakdown-Dzo25N45.js +0 -155
- package/dist/context-breakdown-Dzo25N45.js.map +0 -1
- package/dist/edit-utils-EGosADZq.js +0 -234
- package/dist/edit-utils-EGosADZq.js.map +0 -1
- package/dist/index-CWBSrqI6.d.ts.map +0 -1
- package/dist/openai-compat-B3c_hzwf.js.map +0 -1
- package/dist/tool-state-DTs-3ZHH.js +0 -653
- package/dist/tool-state-DTs-3ZHH.js.map +0 -1
- package/dist/transcript-anchors-D4IxJifV.js.map +0 -1
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
import { n as estimateTokens } from "./utils-ngQzYzZD.js";
|
|
2
|
+
//#region src/tools/edit-utils.ts
|
|
3
|
+
/**
|
|
4
|
+
* Internal helpers shared between the `edit` and `multi_edit` tools.
|
|
5
|
+
*
|
|
6
|
+
* Not part of the public API — intentionally not re-exported from `tools/index.ts`
|
|
7
|
+
* or the package barrel.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Count exact (non-overlapping) occurrences of `needle` in `haystack`.
|
|
11
|
+
* Returns 0 for an empty needle — both edit tools reject empty `old_string`
|
|
12
|
+
* up front, so this branch is defensive rather than semantic.
|
|
13
|
+
*/
|
|
14
|
+
function countExactMatches(haystack, needle) {
|
|
15
|
+
if (needle.length === 0) return 0;
|
|
16
|
+
let count = 0;
|
|
17
|
+
let idx = 0;
|
|
18
|
+
while (true) {
|
|
19
|
+
const next = haystack.indexOf(needle, idx);
|
|
20
|
+
if (next === -1) break;
|
|
21
|
+
count++;
|
|
22
|
+
idx = next + needle.length;
|
|
23
|
+
}
|
|
24
|
+
return count;
|
|
25
|
+
}
|
|
26
|
+
/** Map curly quotes (any of the four) to their straight ASCII equivalents. */
|
|
27
|
+
function normalizeQuotes(str) {
|
|
28
|
+
return str.replaceAll("‘", "'").replaceAll("’", "'").replaceAll("“", "\"").replaceAll("”", "\"");
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Substitutions Anthropic's API applies to assistant output before the model
|
|
32
|
+
* sees it. The model emits the sanitized form; the file on disk contains the
|
|
33
|
+
* unsanitized form. We undo the substitutions on `old_string` so the search
|
|
34
|
+
* lands on the actual file contents.
|
|
35
|
+
*
|
|
36
|
+
* Verbatim from `claude-code/tools/FileEditTool/utils.ts`.
|
|
37
|
+
*/
|
|
38
|
+
const DESANITIZATIONS = [
|
|
39
|
+
["<fnr>", "<function_results>"],
|
|
40
|
+
["<n>", "<name>"],
|
|
41
|
+
["</n>", "</name>"],
|
|
42
|
+
["<o>", "<output>"],
|
|
43
|
+
["</o>", "</output>"],
|
|
44
|
+
["<e>", "<error>"],
|
|
45
|
+
["</e>", "</error>"],
|
|
46
|
+
["<s>", "<system>"],
|
|
47
|
+
["</s>", "</system>"],
|
|
48
|
+
["<r>", "<result>"],
|
|
49
|
+
["</r>", "</result>"],
|
|
50
|
+
["< META_START >", "<META_START>"],
|
|
51
|
+
["< META_END >", "<META_END>"],
|
|
52
|
+
["< EOT >", "<EOT>"],
|
|
53
|
+
["< META >", "<META>"],
|
|
54
|
+
["< SOS >", "<SOS>"],
|
|
55
|
+
["\n\nH:", "\n\nHuman:"],
|
|
56
|
+
["\n\nA:", "\n\nAssistant:"]
|
|
57
|
+
];
|
|
58
|
+
/**
|
|
59
|
+
* Apply the SDK desanitization table to a string. Exported so the edit tools
|
|
60
|
+
* can apply it to `new_string` whenever `old_string` matched via a
|
|
61
|
+
* desanitize-class fallback — keeps the file's unsanitized form on disk
|
|
62
|
+
* instead of writing the model's abbreviated form back.
|
|
63
|
+
*/
|
|
64
|
+
function desanitize(s) {
|
|
65
|
+
let out = s;
|
|
66
|
+
for (const [from, to] of DESANITIZATIONS) out = out.replaceAll(from, to);
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Strip line-number prefixes from each line of a needle, used as a recovery
|
|
71
|
+
* fallback when the model pastes a `read_file` chunk verbatim into
|
|
72
|
+
* `old_string` — the on-disk file doesn't carry the metadata prefix.
|
|
73
|
+
*
|
|
74
|
+
* Accepts three separator characters so a model that learned on a different
|
|
75
|
+
* agent stack still works here: `\t` (Claude Code compact, our default),
|
|
76
|
+
* `|`, and `→`. Pattern: optional leading whitespace, 1-9 digits, then one
|
|
77
|
+
* of `\t | →`. The 9-digit ceiling covers files up to ~1B lines without
|
|
78
|
+
* overshooting into legitimate `\d{N}<sep>` content like Markdown table
|
|
79
|
+
* cells with long numeric IDs.
|
|
80
|
+
*/
|
|
81
|
+
const LINE_NUMBER_PREFIX_RE = /^[ \t]*\d{1,9}[\t|\u2192]/gm;
|
|
82
|
+
function stripLineNumberPrefixes(s) {
|
|
83
|
+
return s.replace(LINE_NUMBER_PREFIX_RE, "");
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Search `target` in `normFile` and slice the matching span out of the
|
|
87
|
+
* original `haystack`, counting all non-overlapping occurrences. `normFile`
|
|
88
|
+
* is the haystack with whatever transform (quotes / desanitize / combined)
|
|
89
|
+
* was applied to make the indices align — slicing the original haystack
|
|
90
|
+
* preserves the file's actual typography so `replace_all` writes back the
|
|
91
|
+
* file's form, not the model's.
|
|
92
|
+
*
|
|
93
|
+
* Pre-condition: `normFile.length === haystack.length` (every transform
|
|
94
|
+
* we use is one-to-one). Returns null on miss.
|
|
95
|
+
*/
|
|
96
|
+
function locateAndCount(haystack, normFile, target, via) {
|
|
97
|
+
const idx = normFile.indexOf(target);
|
|
98
|
+
if (idx === -1) return null;
|
|
99
|
+
const actual = haystack.slice(idx, idx + target.length);
|
|
100
|
+
let occ = 0;
|
|
101
|
+
let cursor = 0;
|
|
102
|
+
while (true) {
|
|
103
|
+
const next = normFile.indexOf(target, cursor);
|
|
104
|
+
if (next === -1) break;
|
|
105
|
+
occ++;
|
|
106
|
+
cursor = next + target.length;
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
actual,
|
|
110
|
+
occurrences: occ,
|
|
111
|
+
via
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function resolveOldString(haystack, needle) {
|
|
115
|
+
const exact = countExactMatches(haystack, needle);
|
|
116
|
+
if (exact > 0) return {
|
|
117
|
+
actual: needle,
|
|
118
|
+
occurrences: exact,
|
|
119
|
+
via: "exact"
|
|
120
|
+
};
|
|
121
|
+
const normNeedle = normalizeQuotes(needle);
|
|
122
|
+
const normFile = normalizeQuotes(haystack);
|
|
123
|
+
if (normNeedle !== needle || normFile !== haystack) {
|
|
124
|
+
const m = locateAndCount(haystack, normFile, normNeedle, "quotes");
|
|
125
|
+
if (m) return m;
|
|
126
|
+
}
|
|
127
|
+
const desan = desanitize(needle);
|
|
128
|
+
if (desan !== needle) {
|
|
129
|
+
const desanCount = countExactMatches(haystack, desan);
|
|
130
|
+
if (desanCount === 1) return {
|
|
131
|
+
actual: desan,
|
|
132
|
+
occurrences: desanCount,
|
|
133
|
+
via: "desanitize"
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const combo = desanitize(normNeedle);
|
|
137
|
+
if (combo !== needle) {
|
|
138
|
+
const m = locateAndCount(haystack, normFile, combo, "quotes+desanitize");
|
|
139
|
+
if (m && m.occurrences === 1) return m;
|
|
140
|
+
}
|
|
141
|
+
const stripped = stripLineNumberPrefixes(needle);
|
|
142
|
+
if (stripped !== needle && stripped.trim().length > 0) {
|
|
143
|
+
const count = countExactMatches(haystack, stripped);
|
|
144
|
+
if (count > 0) return {
|
|
145
|
+
actual: stripped,
|
|
146
|
+
occurrences: count,
|
|
147
|
+
via: "line-numbers"
|
|
148
|
+
};
|
|
149
|
+
const strippedNorm = normalizeQuotes(stripped);
|
|
150
|
+
if (strippedNorm !== stripped || normFile !== haystack) {
|
|
151
|
+
const m = locateAndCount(haystack, normFile, strippedNorm, "quotes+line-numbers");
|
|
152
|
+
if (m) return m;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Short human-readable label for a recovery path, used by `edit` /
|
|
159
|
+
* `multi_edit` to flag non-exact matches in their result messages — when a
|
|
160
|
+
* fallback mistargets, the model (and the user reading the transcript) can
|
|
161
|
+
* see WHICH transform fired instead of silently trusting the edit.
|
|
162
|
+
*/
|
|
163
|
+
function describeVia(via) {
|
|
164
|
+
switch (via) {
|
|
165
|
+
case "exact": return "exact match";
|
|
166
|
+
case "quotes": return "curly-quote normalization";
|
|
167
|
+
case "desanitize": return "sanitization recovery (e.g. <n> → <name>)";
|
|
168
|
+
case "quotes+desanitize": return "sanitization recovery + curly-quote normalization";
|
|
169
|
+
case "line-numbers": return "line-number-prefix stripping";
|
|
170
|
+
case "quotes+line-numbers": return "line-number-prefix stripping + curly-quote normalization";
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Apply the same recovery transforms used to find `old_string` to
|
|
175
|
+
* `new_string`, so the file gets back its native form: desanitize when
|
|
176
|
+
* the model emitted `<n>` for `<name>`, strip line-number prefixes when
|
|
177
|
+
* the match required them, then re-curlify when the match required
|
|
178
|
+
* quote normalization. Shared between `edit` and `multi_edit`.
|
|
179
|
+
*/
|
|
180
|
+
function styleReplacementForVia(replacement, via, actual) {
|
|
181
|
+
let out = replacement;
|
|
182
|
+
if (via === "desanitize" || via === "quotes+desanitize") out = desanitize(out);
|
|
183
|
+
if (via === "line-numbers" || via === "quotes+line-numbers") out = stripLineNumberPrefixes(out);
|
|
184
|
+
if (via === "quotes" || via === "quotes+desanitize" || via === "quotes+line-numbers") out = preserveQuoteStyle(actual, out);
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* When `old_string` matched via curly-quote normalization, re-style
|
|
189
|
+
* `new_string` so the file's typography is preserved across the edit.
|
|
190
|
+
* Detects whether the matched file region had curly singles, doubles, or
|
|
191
|
+
* both, and applies the matching curlification to the replacement.
|
|
192
|
+
*
|
|
193
|
+
* Apostrophes in contractions (`don't`, `it's`) get the right-single curly
|
|
194
|
+
* quote regardless of opening context — that's the canonical typographer's
|
|
195
|
+
* convention for English. Other quotes use a simple
|
|
196
|
+
* preceded-by-whitespace-or-opening-punctuation heuristic.
|
|
197
|
+
*/
|
|
198
|
+
function preserveQuoteStyle(actual, replacement) {
|
|
199
|
+
const hasDouble = actual.includes("“") || actual.includes("”");
|
|
200
|
+
const hasSingle = actual.includes("‘") || actual.includes("’");
|
|
201
|
+
if (!hasDouble && !hasSingle) return replacement;
|
|
202
|
+
let out = replacement;
|
|
203
|
+
if (hasDouble) out = applyCurly(out, "\"", "“", "”", false);
|
|
204
|
+
if (hasSingle) out = applyCurly(out, "'", "‘", "’", true);
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
function applyCurly(s, straight, left, right, contractionAware) {
|
|
208
|
+
const chars = [...s];
|
|
209
|
+
const result = [];
|
|
210
|
+
for (let i = 0; i < chars.length; i++) {
|
|
211
|
+
if (chars[i] !== straight) {
|
|
212
|
+
result.push(chars[i]);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (contractionAware) {
|
|
216
|
+
const prev = i > 0 ? chars[i - 1] : "";
|
|
217
|
+
const next = i < chars.length - 1 ? chars[i + 1] : "";
|
|
218
|
+
if (/\p{L}/u.test(prev) && /\p{L}/u.test(next)) {
|
|
219
|
+
result.push(right);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
result.push(isOpeningContext(chars, i) ? left : right);
|
|
224
|
+
}
|
|
225
|
+
return result.join("");
|
|
226
|
+
}
|
|
227
|
+
function isOpeningContext(chars, i) {
|
|
228
|
+
if (i === 0) return true;
|
|
229
|
+
const prev = chars[i - 1];
|
|
230
|
+
return prev === " " || prev === " " || prev === "\n" || prev === "\r" || prev === "(" || prev === "[" || prev === "{" || prev === "—" || prev === "–";
|
|
231
|
+
}
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region src/chat/context-breakdown.ts
|
|
234
|
+
const LABELS = {
|
|
235
|
+
systemPrompt: "System prompt",
|
|
236
|
+
rules: "Rules (AGENTS.md)",
|
|
237
|
+
tools: "Tool definitions",
|
|
238
|
+
mcpTools: "MCP tools",
|
|
239
|
+
mcpInstructions: "MCP instructions",
|
|
240
|
+
skills: "Skills",
|
|
241
|
+
subagentDefs: "Subagent definitions",
|
|
242
|
+
conversation: "Conversation",
|
|
243
|
+
mcpToolsDeferred: "MCP tools (deferred)",
|
|
244
|
+
toolsDeferred: "System tools (deferred)",
|
|
245
|
+
autocompactBuffer: "Autocompact buffer",
|
|
246
|
+
freeSpace: "Free space"
|
|
247
|
+
};
|
|
248
|
+
/** Sum the heuristic token sizes of a list of strings. */
|
|
249
|
+
function sumEstimate(parts) {
|
|
250
|
+
let total = 0;
|
|
251
|
+
for (const p of parts) total += estimateTokens(p);
|
|
252
|
+
return total;
|
|
253
|
+
}
|
|
254
|
+
function mcpGroupTokens(group) {
|
|
255
|
+
const items = group.tools.map((t) => ({
|
|
256
|
+
id: `${group.server}:${t.name}`,
|
|
257
|
+
label: t.name,
|
|
258
|
+
tokens: estimateTokens(t.json),
|
|
259
|
+
estimated: true
|
|
260
|
+
}));
|
|
261
|
+
let total = 0;
|
|
262
|
+
for (const it of items) total += it.tokens;
|
|
263
|
+
return {
|
|
264
|
+
total,
|
|
265
|
+
items
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Shape a {@link ContextSnapshot} into a render-ready {@link ContextBreakdown}.
|
|
270
|
+
*
|
|
271
|
+
* Live categories (system prompt, tools, MCP tools/instructions, skills,
|
|
272
|
+
* memory, subagent defs, conversation) sum to `snapshot.used` — `conversation`
|
|
273
|
+
* absorbs the remainder so the bar matches the provider-reported total exactly.
|
|
274
|
+
* Deferred + autocompact + free-space buckets follow.
|
|
275
|
+
*
|
|
276
|
+
* When `snapshot.exact` carries provider counts, the matching categories use
|
|
277
|
+
* them (system, tools) and drop their `estimated` flag; everything else stays
|
|
278
|
+
* on the heuristic.
|
|
279
|
+
*/
|
|
280
|
+
function buildContextBreakdown(snapshot) {
|
|
281
|
+
const exact = snapshot.exact;
|
|
282
|
+
const systemExact = typeof exact?.system === "number";
|
|
283
|
+
const rulesTokens = snapshot.rulesBlock ? estimateTokens(snapshot.rulesBlock) : 0;
|
|
284
|
+
const rulesItems = (snapshot.rulesFiles ?? []).map((f) => ({
|
|
285
|
+
id: f.path,
|
|
286
|
+
label: f.path,
|
|
287
|
+
tokens: 0,
|
|
288
|
+
estimated: false
|
|
289
|
+
}));
|
|
290
|
+
const skillsTokens = snapshot.skillsCatalog ? estimateTokens(snapshot.skillsCatalog) : 0;
|
|
291
|
+
const mcpInstructionsTokens = snapshot.mcpInstructions ? estimateTokens(snapshot.mcpInstructions) : 0;
|
|
292
|
+
const subagentTokens = snapshot.subagentDefs ? estimateTokens(snapshot.subagentDefs) : 0;
|
|
293
|
+
const embeddedSubsections = rulesTokens + skillsTokens + mcpInstructionsTokens + subagentTokens;
|
|
294
|
+
const systemTotal = systemExact ? exact.system : estimateTokens(snapshot.system);
|
|
295
|
+
const baseSystemTokens = Math.max(0, systemTotal - embeddedSubsections);
|
|
296
|
+
const nativeToolsEst = sumEstimate(snapshot.toolsJson);
|
|
297
|
+
const mcpDisclosed = snapshot.mcpGroups.map(mcpGroupTokens);
|
|
298
|
+
const mcpToolsEst = mcpDisclosed.reduce((a, g) => a + g.total, 0);
|
|
299
|
+
let nativeToolsTokens = nativeToolsEst;
|
|
300
|
+
let mcpToolsTokens = mcpToolsEst;
|
|
301
|
+
let toolsEstimated = true;
|
|
302
|
+
if (systemExact && typeof exact?.systemAndTools === "number") {
|
|
303
|
+
const exactToolsTotal = Math.max(0, exact.systemAndTools - exact.system);
|
|
304
|
+
const estTotal = nativeToolsEst + mcpToolsEst;
|
|
305
|
+
if (estTotal > 0) {
|
|
306
|
+
nativeToolsTokens = Math.round(exactToolsTotal * (nativeToolsEst / estTotal));
|
|
307
|
+
mcpToolsTokens = exactToolsTotal - nativeToolsTokens;
|
|
308
|
+
} else {
|
|
309
|
+
nativeToolsTokens = exactToolsTotal;
|
|
310
|
+
mcpToolsTokens = 0;
|
|
311
|
+
}
|
|
312
|
+
toolsEstimated = false;
|
|
313
|
+
}
|
|
314
|
+
const live = [];
|
|
315
|
+
const push = (id, tokens, estimated, items) => {
|
|
316
|
+
if (tokens <= 0 && !items?.length) return;
|
|
317
|
+
live.push({
|
|
318
|
+
id,
|
|
319
|
+
label: LABELS[id],
|
|
320
|
+
tokens: Math.max(0, tokens),
|
|
321
|
+
estimated,
|
|
322
|
+
...items?.length ? { items } : {}
|
|
323
|
+
});
|
|
324
|
+
};
|
|
325
|
+
push("systemPrompt", baseSystemTokens, !systemExact);
|
|
326
|
+
push("rules", rulesTokens, true, rulesItems);
|
|
327
|
+
push("skills", skillsTokens, true);
|
|
328
|
+
push("mcpInstructions", mcpInstructionsTokens, true);
|
|
329
|
+
push("subagentDefs", subagentTokens, true);
|
|
330
|
+
push("tools", nativeToolsTokens, toolsEstimated);
|
|
331
|
+
push("mcpTools", mcpToolsTokens, toolsEstimated, mcpDisclosed.flatMap((g) => g.items));
|
|
332
|
+
const accountedStatic = live.reduce((a, c) => a + c.tokens, 0);
|
|
333
|
+
push("conversation", Math.max(0, snapshot.used - accountedStatic), !(systemExact && !toolsEstimated));
|
|
334
|
+
const deferred = [];
|
|
335
|
+
const deferredNativeTools = sumEstimate(snapshot.deferredToolsJson);
|
|
336
|
+
if (deferredNativeTools > 0) deferred.push({
|
|
337
|
+
id: "toolsDeferred",
|
|
338
|
+
label: LABELS.toolsDeferred,
|
|
339
|
+
tokens: deferredNativeTools,
|
|
340
|
+
estimated: true,
|
|
341
|
+
deferred: true
|
|
342
|
+
});
|
|
343
|
+
const deferredMcp = snapshot.deferredMcpGroups.map(mcpGroupTokens);
|
|
344
|
+
const deferredMcpTotal = deferredMcp.reduce((a, g) => a + g.total, 0);
|
|
345
|
+
if (deferredMcpTotal > 0) deferred.push({
|
|
346
|
+
id: "mcpToolsDeferred",
|
|
347
|
+
label: LABELS.mcpToolsDeferred,
|
|
348
|
+
tokens: deferredMcpTotal,
|
|
349
|
+
estimated: true,
|
|
350
|
+
deferred: true,
|
|
351
|
+
items: deferredMcp.flatMap((g) => g.items)
|
|
352
|
+
});
|
|
353
|
+
if (snapshot.autocompactBuffer > 0) deferred.push({
|
|
354
|
+
id: "autocompactBuffer",
|
|
355
|
+
label: LABELS.autocompactBuffer,
|
|
356
|
+
tokens: snapshot.autocompactBuffer,
|
|
357
|
+
estimated: false,
|
|
358
|
+
deferred: true
|
|
359
|
+
});
|
|
360
|
+
const free = Math.max(0, snapshot.effectiveWindow - snapshot.used);
|
|
361
|
+
deferred.push({
|
|
362
|
+
id: "freeSpace",
|
|
363
|
+
label: LABELS.freeSpace,
|
|
364
|
+
tokens: free,
|
|
365
|
+
estimated: false,
|
|
366
|
+
deferred: true
|
|
367
|
+
});
|
|
368
|
+
const categories = [...live, ...deferred];
|
|
369
|
+
const hasEstimates = live.some((c) => c.estimated && c.tokens > 0);
|
|
370
|
+
const fraction = snapshot.effectiveWindow > 0 ? Math.max(0, Math.min(1, snapshot.used / snapshot.effectiveWindow)) : 0;
|
|
371
|
+
return {
|
|
372
|
+
modelId: snapshot.modelId,
|
|
373
|
+
used: snapshot.used,
|
|
374
|
+
effectiveWindow: snapshot.effectiveWindow,
|
|
375
|
+
fraction,
|
|
376
|
+
categories,
|
|
377
|
+
hasEstimates,
|
|
378
|
+
...snapshot.usage ? { usage: snapshot.usage } : {},
|
|
379
|
+
...snapshot.extensionSections?.length ? { extensionSections: snapshot.extensionSections } : {},
|
|
380
|
+
...snapshot.activeSkills?.length ? { activeSkills: snapshot.activeSkills } : {}
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
//#endregion
|
|
384
|
+
//#region src/chat/context-segments.ts
|
|
385
|
+
/**
|
|
386
|
+
* Context segments — pure transforms.
|
|
387
|
+
*
|
|
388
|
+
* Sibling to `context-breakdown.ts`: where that module answers "how many
|
|
389
|
+
* tokens is each part of my context", this one answers "what IS each part,
|
|
390
|
+
* and where did it come from". It turns the same assembled-prompt pieces into
|
|
391
|
+
* a flat list of {@link ContextSegment}s carrying the actual TEXT plus its
|
|
392
|
+
* provenance, so a UI can list every chunk loaded by default in a session,
|
|
393
|
+
* let the user read it, and open the file behind it when there is one.
|
|
394
|
+
*
|
|
395
|
+
* No React, no node — a browser-context renderer imports these via
|
|
396
|
+
* `zidane/chat/pure`.
|
|
397
|
+
*
|
|
398
|
+
* Provenance is honest about what can and can't be opened:
|
|
399
|
+
* - `'file'` — a real path on disk (AGENTS.md / CLAUDE.md / ruler md).
|
|
400
|
+
* The only origin that carries `path`, hence the only one
|
|
401
|
+
* a host can hand to `$EDITOR`.
|
|
402
|
+
* - `'built-in'` — compiled into the binary (base doctrine, subagent defs).
|
|
403
|
+
* - `'generated'` — assembled at prompt time from discovered state (the
|
|
404
|
+
* skills catalog is rendered from the skill manifests).
|
|
405
|
+
* - `'mcp'` — served by a remote MCP server at connect time.
|
|
406
|
+
*/
|
|
407
|
+
/**
|
|
408
|
+
* Remove the first occurrence of `part` from `whole`, collapsing the seam.
|
|
409
|
+
*
|
|
410
|
+
* Used to carve the rules block out of the base system so the "System prompt"
|
|
411
|
+
* segment reports only doctrine + env. Substring-based because that's the
|
|
412
|
+
* contract the assembly documents (`rulesBlock` IS a substring of
|
|
413
|
+
* `baseSystem`); a miss leaves `whole` untouched, which degrades to
|
|
414
|
+
* over-reporting the base row rather than dropping text on the floor.
|
|
415
|
+
*/
|
|
416
|
+
function removeFirst(whole, part) {
|
|
417
|
+
if (!part) return whole;
|
|
418
|
+
const at = whole.indexOf(part);
|
|
419
|
+
if (at < 0) return whole;
|
|
420
|
+
return `${whole.slice(0, at)}${whole.slice(at + part.length)}`.replace(/\n{3,}/g, "\n\n").trim();
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Best-effort display name for an instruction file: its basename, with the
|
|
424
|
+
* parent directory prefixed when the basename alone would be ambiguous
|
|
425
|
+
* (`AGENTS.md` appears at up to four paths per scope). Path-separator handling
|
|
426
|
+
* covers both POSIX and Windows so this stays node-free.
|
|
427
|
+
*/
|
|
428
|
+
function fileLabel(path) {
|
|
429
|
+
const parts = path.split(/[/\\]/).filter(Boolean);
|
|
430
|
+
const base = parts.at(-1) ?? path;
|
|
431
|
+
const parent = parts.at(-2);
|
|
432
|
+
return parent?.startsWith(".") ? `${parent}/${base}` : base;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Shape assembled-prompt pieces into a flat, render-ready segment list.
|
|
436
|
+
*
|
|
437
|
+
* Order is prompt order — base doctrine, then instruction files (broadest
|
|
438
|
+
* scope first, as `discoverAgentsMd` returns them), then the appended
|
|
439
|
+
* catalogs. Empty / whitespace-only pieces are dropped so the list never
|
|
440
|
+
* shows a zero-byte row.
|
|
441
|
+
*/
|
|
442
|
+
function buildContextSegments(input) {
|
|
443
|
+
const segments = [];
|
|
444
|
+
const push = (seg) => {
|
|
445
|
+
if (!seg.text.trim()) return;
|
|
446
|
+
segments.push({
|
|
447
|
+
...seg,
|
|
448
|
+
tokens: estimateTokens(seg.text)
|
|
449
|
+
});
|
|
450
|
+
};
|
|
451
|
+
const base = input.baseSystem ?? input.system ?? "";
|
|
452
|
+
const overridden = input.systemPath !== void 0;
|
|
453
|
+
push({
|
|
454
|
+
id: "system",
|
|
455
|
+
label: "System prompt",
|
|
456
|
+
origin: overridden ? "file" : "built-in",
|
|
457
|
+
detail: overridden ? "SYSTEM.md override + environment" : "doctrine + environment",
|
|
458
|
+
text: input.rulesBlock ? removeFirst(base, input.rulesBlock) : base,
|
|
459
|
+
...input.systemPath !== void 0 ? { path: input.systemPath } : {}
|
|
460
|
+
});
|
|
461
|
+
for (const file of input.rulesFiles ?? []) push({
|
|
462
|
+
id: `rules:${file.path}`,
|
|
463
|
+
label: fileLabel(file.path),
|
|
464
|
+
origin: "file",
|
|
465
|
+
...file.source ? { detail: file.source } : {},
|
|
466
|
+
text: file.contents,
|
|
467
|
+
path: file.path
|
|
468
|
+
});
|
|
469
|
+
push({
|
|
470
|
+
id: "skills",
|
|
471
|
+
label: "Skills catalog",
|
|
472
|
+
origin: "generated",
|
|
473
|
+
detail: "name + description per skill (bodies load on activation)",
|
|
474
|
+
text: input.skillsCatalog ?? ""
|
|
475
|
+
});
|
|
476
|
+
push({
|
|
477
|
+
id: "mcp-instructions",
|
|
478
|
+
label: "MCP instructions",
|
|
479
|
+
origin: "mcp",
|
|
480
|
+
detail: "served by the connected servers",
|
|
481
|
+
text: input.mcpInstructions ?? ""
|
|
482
|
+
});
|
|
483
|
+
push({
|
|
484
|
+
id: "subagent-defs",
|
|
485
|
+
label: "Subagent definitions",
|
|
486
|
+
origin: "built-in",
|
|
487
|
+
text: input.subagentDefs ?? ""
|
|
488
|
+
});
|
|
489
|
+
return segments;
|
|
490
|
+
}
|
|
491
|
+
//#endregion
|
|
492
|
+
export { stripLineNumberPrefixes as a, resolveOldString as i, buildContextBreakdown as n, styleReplacementForVia as o, describeVia as r, buildContextSegments as t };
|
|
493
|
+
|
|
494
|
+
//# sourceMappingURL=context-segments-1mcqSCM3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-segments-1mcqSCM3.js","names":[],"sources":["../src/tools/edit-utils.ts","../src/chat/context-breakdown.ts","../src/chat/context-segments.ts"],"sourcesContent":["/**\n * Internal helpers shared between the `edit` and `multi_edit` tools.\n *\n * Not part of the public API — intentionally not re-exported from `tools/index.ts`\n * or the package barrel.\n */\n\n/**\n * Count exact (non-overlapping) occurrences of `needle` in `haystack`.\n * Returns 0 for an empty needle — both edit tools reject empty `old_string`\n * up front, so this branch is defensive rather than semantic.\n */\nexport function countExactMatches(haystack: string, needle: string): number {\n if (needle.length === 0)\n return 0\n let count = 0\n let idx = 0\n while (true) {\n const next = haystack.indexOf(needle, idx)\n if (next === -1)\n break\n count++\n idx = next + needle.length\n }\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Curly-quote normalization + SDK-sanitization fallbacks\n// ---------------------------------------------------------------------------\n//\n// Models can't reliably emit Unicode curly quotes, and the Anthropic API\n// silently sanitizes a handful of XML-like tags before they hit the model\n// (`<name>` → `<n>`, etc.). When `old_string` doesn't match exactly, we retry\n// against the same content with both transforms applied so an \"old_string not\n// found\" failure that's only typographical resolves on the second pass.\n//\n// Mirrors the Claude Code Edit tool's recovery strategy. Verbatim port of the\n// quote constants and the desanitization table; the resolve loop below is\n// reorganized to share state between exact / quote-normalized / desanitized.\n\nexport const LEFT_SINGLE_CURLY_QUOTE = '\\u2018'\nexport const RIGHT_SINGLE_CURLY_QUOTE = '\\u2019'\nexport const LEFT_DOUBLE_CURLY_QUOTE = '\\u201C'\nexport const RIGHT_DOUBLE_CURLY_QUOTE = '\\u201D'\n\n/** Map curly quotes (any of the four) to their straight ASCII equivalents. */\nexport function normalizeQuotes(str: string): string {\n return str\n .replaceAll(LEFT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(RIGHT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '\"')\n .replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '\"')\n}\n\n/**\n * Substitutions Anthropic's API applies to assistant output before the model\n * sees it. The model emits the sanitized form; the file on disk contains the\n * unsanitized form. We undo the substitutions on `old_string` so the search\n * lands on the actual file contents.\n *\n * Verbatim from `claude-code/tools/FileEditTool/utils.ts`.\n */\nconst DESANITIZATIONS: ReadonlyArray<readonly [string, string]> = [\n ['<fnr>', '<function_results>'],\n ['<n>', '<name>'],\n ['</n>', '</name>'],\n ['<o>', '<output>'],\n ['</o>', '</output>'],\n ['<e>', '<error>'],\n ['</e>', '</error>'],\n ['<s>', '<system>'],\n ['</s>', '</system>'],\n ['<r>', '<result>'],\n ['</r>', '</result>'],\n ['< META_START >', '<META_START>'],\n ['< META_END >', '<META_END>'],\n ['< EOT >', '<EOT>'],\n ['< META >', '<META>'],\n ['< SOS >', '<SOS>'],\n ['\\n\\nH:', '\\n\\nHuman:'],\n ['\\n\\nA:', '\\n\\nAssistant:'],\n]\n\n/**\n * Apply the SDK desanitization table to a string. Exported so the edit tools\n * can apply it to `new_string` whenever `old_string` matched via a\n * desanitize-class fallback — keeps the file's unsanitized form on disk\n * instead of writing the model's abbreviated form back.\n */\nexport function desanitize(s: string): string {\n let out = s\n for (const [from, to] of DESANITIZATIONS)\n out = out.replaceAll(from, to)\n return out\n}\n\n/**\n * Strip line-number prefixes from each line of a needle, used as a recovery\n * fallback when the model pastes a `read_file` chunk verbatim into\n * `old_string` — the on-disk file doesn't carry the metadata prefix.\n *\n * Accepts three separator characters so a model that learned on a different\n * agent stack still works here: `\\t` (Claude Code compact, our default),\n * `|`, and `→`. Pattern: optional leading whitespace, 1-9 digits, then one\n * of `\\t | →`. The 9-digit ceiling covers files up to ~1B lines without\n * overshooting into legitimate `\\d{N}<sep>` content like Markdown table\n * cells with long numeric IDs.\n */\nconst LINE_NUMBER_PREFIX_RE = /^[ \\t]*\\d{1,9}[\\t|\\u2192]/gm\nexport function stripLineNumberPrefixes(s: string): string {\n return s.replace(LINE_NUMBER_PREFIX_RE, '')\n}\n\n/**\n * Locate the actual substring in `haystack` that corresponds to `needle`,\n * recovering from typographical mismatch on six escalating fallbacks:\n *\n * 1. Exact substring match (the happy path — no transformation).\n * 2. Curly-quote normalization on both sides — when the model emits straight\n * quotes but the file has curly ones (or vice versa), the slice of the\n * file at the matched position carries the file's actual typography.\n * 3. Anthropic-sanitization undo on the needle — the model's `<n>` becomes\n * the file's `<name>`, etc.\n * 4. Combined: desanitize + quote normalization on the needle.\n * 5. Line-number-prefix strip — when the model pasted a numbered `read_file`\n * chunk verbatim into `old_string` and the file carries no such prefix.\n * 6. Combined: line-number strip + quote normalization — paste-back of a\n * numbered chunk against a file whose typography differs from the model's.\n *\n * Returns `{ actual, occurrences }` — `actual` is the string that exists in\n * the file (use this to do the actual replace; preserves the file's\n * typography). `occurrences` is the count of those matches in the file.\n *\n * Fallbacks 3-4 (desanitize-class) only fire when the transformed needle is\n * UNIQUE in the file — they rewrite the needle's meaning rather than its\n * typography, so an ambiguous match risks silently retargeting the wrong\n * text (see the inline comment at step 3).\n *\n * Returns `null` when no recovery worked.\n */\nexport interface ResolvedMatch {\n actual: string\n occurrences: number\n /** Recovery path — `'exact'` when no transformation was applied. */\n via: 'exact' | 'quotes' | 'desanitize' | 'quotes+desanitize' | 'line-numbers' | 'quotes+line-numbers'\n}\n\n/**\n * Search `target` in `normFile` and slice the matching span out of the\n * original `haystack`, counting all non-overlapping occurrences. `normFile`\n * is the haystack with whatever transform (quotes / desanitize / combined)\n * was applied to make the indices align — slicing the original haystack\n * preserves the file's actual typography so `replace_all` writes back the\n * file's form, not the model's.\n *\n * Pre-condition: `normFile.length === haystack.length` (every transform\n * we use is one-to-one). Returns null on miss.\n */\nfunction locateAndCount(\n haystack: string,\n normFile: string,\n target: string,\n via: ResolvedMatch['via'],\n): ResolvedMatch | null {\n const idx = normFile.indexOf(target)\n if (idx === -1)\n return null\n const actual = haystack.slice(idx, idx + target.length)\n let occ = 0\n let cursor = 0\n while (true) {\n const next = normFile.indexOf(target, cursor)\n if (next === -1)\n break\n occ++\n cursor = next + target.length\n }\n return { actual, occurrences: occ, via }\n}\n\nexport function resolveOldString(haystack: string, needle: string): ResolvedMatch | null {\n // 1. Exact match — happy path.\n const exact = countExactMatches(haystack, needle)\n if (exact > 0)\n return { actual: needle, occurrences: exact, via: 'exact' }\n\n // 2. Curly-quote normalization. Either side can carry curly quotes:\n // model emitted straight + file has curly, OR model emitted curly +\n // file has straight. Normalize both and look there. Slice the original\n // haystack to recover the actual file-side typography.\n const normNeedle = normalizeQuotes(needle)\n const normFile = normalizeQuotes(haystack)\n if (normNeedle !== needle || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, normNeedle, 'quotes')\n if (m)\n return m\n }\n\n // 3. Desanitize the needle — model-side substitution undo (`<n>` → `<name>`,\n // etc.) The file always has the unsanitized form; only the model emits\n // the abbreviated version.\n //\n // Desanitize-class fallbacks additionally require a UNIQUE transformed\n // match. Unlike the quote / line-number transforms (typography-only /\n // verbatim paste-back), this one rewrites the needle's meaning — a model\n // that genuinely meant the literal `<n>` against a file full of `<name>`\n // would otherwise silently retarget every occurrence under `replace_all`.\n // A unique hit bounds the blast radius to one visible replacement.\n const desan = desanitize(needle)\n if (desan !== needle) {\n const desanCount = countExactMatches(haystack, desan)\n if (desanCount === 1)\n return { actual: desan, occurrences: desanCount, via: 'desanitize' }\n }\n\n // 4. Combined: desanitize + quote normalization. Hit when the model\n // emitted both sanitized tokens and straight quotes, but the file has\n // the unsanitized form with curly quotes. Same uniqueness requirement\n // as #3.\n const combo = desanitize(normNeedle)\n if (combo !== needle) {\n const m = locateAndCount(haystack, normFile, combo, 'quotes+desanitize')\n if (m && m.occurrences === 1)\n return m\n }\n\n // 5. Line-number-prefix strip. When `read_file` returns line-numbered\n // output and the model pasted the chunk verbatim into `old_string`,\n // the on-disk file doesn't carry those prefixes. Strip them and\n // retry; the file-side `actual` is the prefix-free needle so the\n // replacement lands on real bytes.\n //\n // Guard against a needle that strips down to whitespace-only (e.g.\n // `1\\t\\n2\\t\\n3\\t` → `\\n\\n`). Searching for `\\n\\n` would match arbitrary\n // blank-line patterns anywhere in the file — a high false-positive risk.\n // Require the stripped needle to carry at least one non-whitespace\n // character before we trust the result.\n const stripped = stripLineNumberPrefixes(needle)\n if (stripped !== needle && stripped.trim().length > 0) {\n const count = countExactMatches(haystack, stripped)\n if (count > 0)\n return { actual: stripped, occurrences: count, via: 'line-numbers' }\n\n // 6. Combined: line-number strip + curly-quote normalization. The\n // typography mismatch may live in the file, the needle, or both.\n const strippedNorm = normalizeQuotes(stripped)\n if (strippedNorm !== stripped || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, strippedNorm, 'quotes+line-numbers')\n if (m)\n return m\n }\n }\n\n return null\n}\n\n/**\n * Short human-readable label for a recovery path, used by `edit` /\n * `multi_edit` to flag non-exact matches in their result messages — when a\n * fallback mistargets, the model (and the user reading the transcript) can\n * see WHICH transform fired instead of silently trusting the edit.\n */\nexport function describeVia(via: ResolvedMatch['via']): string {\n switch (via) {\n case 'exact': return 'exact match'\n case 'quotes': return 'curly-quote normalization'\n case 'desanitize': return 'sanitization recovery (e.g. <n> → <name>)'\n case 'quotes+desanitize': return 'sanitization recovery + curly-quote normalization'\n case 'line-numbers': return 'line-number-prefix stripping'\n case 'quotes+line-numbers': return 'line-number-prefix stripping + curly-quote normalization'\n }\n}\n\n/**\n * Apply the same recovery transforms used to find `old_string` to\n * `new_string`, so the file gets back its native form: desanitize when\n * the model emitted `<n>` for `<name>`, strip line-number prefixes when\n * the match required them, then re-curlify when the match required\n * quote normalization. Shared between `edit` and `multi_edit`.\n */\nexport function styleReplacementForVia(\n replacement: string,\n via: ResolvedMatch['via'],\n actual: string,\n): string {\n let out = replacement\n if (via === 'desanitize' || via === 'quotes+desanitize')\n out = desanitize(out)\n if (via === 'line-numbers' || via === 'quotes+line-numbers')\n out = stripLineNumberPrefixes(out)\n if (via === 'quotes' || via === 'quotes+desanitize' || via === 'quotes+line-numbers')\n out = preserveQuoteStyle(actual, out)\n return out\n}\n\n/**\n * When `old_string` matched via curly-quote normalization, re-style\n * `new_string` so the file's typography is preserved across the edit.\n * Detects whether the matched file region had curly singles, doubles, or\n * both, and applies the matching curlification to the replacement.\n *\n * Apostrophes in contractions (`don't`, `it's`) get the right-single curly\n * quote regardless of opening context — that's the canonical typographer's\n * convention for English. Other quotes use a simple\n * preceded-by-whitespace-or-opening-punctuation heuristic.\n */\nexport function preserveQuoteStyle(actual: string, replacement: string): string {\n const hasDouble = actual.includes(LEFT_DOUBLE_CURLY_QUOTE) || actual.includes(RIGHT_DOUBLE_CURLY_QUOTE)\n const hasSingle = actual.includes(LEFT_SINGLE_CURLY_QUOTE) || actual.includes(RIGHT_SINGLE_CURLY_QUOTE)\n if (!hasDouble && !hasSingle)\n return replacement\n\n let out = replacement\n if (hasDouble)\n out = applyCurly(out, '\"', LEFT_DOUBLE_CURLY_QUOTE, RIGHT_DOUBLE_CURLY_QUOTE, false)\n if (hasSingle)\n out = applyCurly(out, '\\'', LEFT_SINGLE_CURLY_QUOTE, RIGHT_SINGLE_CURLY_QUOTE, true)\n return out\n}\n\nfunction applyCurly(\n s: string,\n straight: string,\n left: string,\n right: string,\n contractionAware: boolean,\n): string {\n const chars = [...s]\n const result: string[] = []\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] !== straight) {\n result.push(chars[i])\n continue\n }\n if (contractionAware) {\n const prev = i > 0 ? chars[i - 1] : ''\n const next = i < chars.length - 1 ? chars[i + 1] : ''\n // Letter-quote-letter is a contraction, not a quote — always right.\n if (/\\p{L}/u.test(prev) && /\\p{L}/u.test(next)) {\n result.push(right)\n continue\n }\n }\n result.push(isOpeningContext(chars, i) ? left : right)\n }\n return result.join('')\n}\n\nfunction isOpeningContext(chars: string[], i: number): boolean {\n if (i === 0)\n return true\n const prev = chars[i - 1]\n return prev === ' ' || prev === '\\t' || prev === '\\n' || prev === '\\r'\n || prev === '(' || prev === '[' || prev === '{'\n || prev === '\\u2014' || prev === '\\u2013' // em / en dash\n}\n","/**\n * Context-usage breakdown — pure transforms.\n *\n * Turns a {@link ContextSnapshot} (the raw pieces the agent assembled for a\n * run: system prompt, wire tools, deferred tools, MCP tools/instructions,\n * skills catalog, ...) plus the real last-turn token total into a categorized\n * {@link ContextBreakdown} the TUI panel / GUI popover render.\n *\n * No React, no node — a browser-context renderer imports these via\n * `zidane/chat/pure`. The snapshot is captured main-side (TUI direct, GUI in\n * `main/chat`) because building it reads provider/agent state; only the pure\n * shaping lives here.\n *\n * Accuracy: per-category counts are estimates when no provider `countTokens`\n * is available — the heuristic ({@link estimateTokens}, ~4 bytes/token) sizes\n * each static segment and the bar is reconciled so it always sums to the real\n * last-turn total (`conversation = realTotal - sum(static)`). When a provider\n * exposes exact counts (Anthropic, OpenAI), the caller passes them in via\n * {@link ContextSnapshot.exact} and the corresponding categories drop their\n * `estimated` flag. Exact buckets (free space, autocompact buffer) are never\n * estimated.\n */\n\nimport type { SessionTurn } from '../types'\nimport { estimateTokens } from '../compact/utils'\n\n/**\n * Stable identifiers for each breakdown category. Drives swatch color +\n * ordering in both UIs. `*Deferred` buckets are tools/MCP that exist but are\n * NOT currently on the wire (lazy disclosure); `autocompactBuffer` is the\n * reserved output headroom; `freeSpace` is the remaining window.\n */\nexport type ContextCategoryId\n = | 'systemPrompt'\n | 'rules'\n | 'tools'\n | 'mcpTools'\n | 'mcpInstructions'\n | 'skills'\n | 'subagentDefs'\n | 'conversation'\n | 'mcpToolsDeferred'\n | 'toolsDeferred'\n | 'autocompactBuffer'\n | 'freeSpace'\n\n/**\n * Exact last-turn token usage split (provider-reported — always exact). Drives\n * the cache breakdown shown below the categories. `cacheRead + cacheCreation +\n * input` equals the live context total (`used`).\n */\nexport interface ContextUsageSplit {\n /** Fresh, uncached input tokens this turn. */\n input: number\n /** Tokens served from the prompt cache (the cached prefix). */\n cacheRead: number\n /** Tokens written to the cache this turn. */\n cacheCreation: number\n /** Assistant output tokens (not part of the input window; informational). */\n output: number\n}\n\n/** One display row contributed by an extension to the context panel. */\nexport interface ContextExtensionRow {\n label: string\n value: string\n}\n\n/** Extension-owned context panel section. Core treats rows as opaque display data. */\nexport interface ContextExtensionSection {\n id: string\n label: string\n /** Optional section-title foreground color. UIs fall back to their theme accent. */\n accentColor?: string\n rows: readonly ContextExtensionRow[]\n}\n\n/** Data exposed to extension context-breakdown contributors. */\nexport interface ContextBreakdownContributionContext {\n turns: readonly SessionTurn[]\n}\n\n/** Extension hook for adding opaque rows to the context panel. */\nexport type ContextBreakdownContributor\n = (ctx: ContextBreakdownContributionContext) =>\n | ContextExtensionSection\n | readonly ContextExtensionSection[]\n | null\n | undefined\n | Promise<ContextExtensionSection | readonly ContextExtensionSection[] | null | undefined>\n\n/** One expandable child row under a category (e.g. a single MCP tool / memory file). */\nexport interface ContextItem {\n /** Stable-ish key for rendering (tool name, file path). */\n id: string\n /** Display label. */\n label: string\n /** Token count for this item. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n}\n\n/** One category row in the breakdown. */\nexport interface ContextCategory {\n id: ContextCategoryId\n /** Display label (e.g. \"Tool definitions\"). */\n label: string\n /** Token count for the category. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n /**\n * True for buckets that are NOT counted against the live window total\n * (deferred tools, free space, autocompact buffer) — the UI renders these\n * dimmed / below a divider, mirroring Claude Code's layout.\n */\n deferred?: boolean\n /** Optional expandable child rows (per MCP tool, per memory file, ...). */\n items?: ContextItem[]\n}\n\n/** The shaped, render-ready breakdown. */\nexport interface ContextBreakdown {\n /** Model id the snapshot was built for. */\n modelId: string\n /**\n * Real last-turn context size (provider-reported `input + cacheRead +\n * cacheCreation`) — the SAME number the footer/orb shows. The non-deferred\n * categories always sum to this.\n */\n used: number\n /** Effective window (raw - output reserve), the bar's denominator. */\n effectiveWindow: number\n /** `used / effectiveWindow`, clamped to [0, 1]. */\n fraction: number\n /** Live categories (sum to `used`) followed by deferred + free-space buckets. */\n categories: ContextCategory[]\n /** True when ANY live category is estimated (drives the panel's footnote). */\n hasEstimates: boolean\n /**\n * Exact last-turn usage split (cache read / write / fresh input / output),\n * when the host supplied it. Always exact — rendered as an informational\n * section below the categories. Absent when no usage is available yet.\n */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /**\n * Names of currently-active skills. Informational — an activated skill's body\n * lands in the conversation (tool-results), so its tokens are already counted\n * under Conversation; this just surfaces \"which skills are loaded\". Empty/absent\n * when none are active.\n */\n activeSkills?: string[]\n}\n\n/** Host-supplied options for `agent.getContextBreakdown`. */\nexport interface ContextBreakdownOptions {\n /**\n * Effective context window (`rawWindow - outputReserve`) for the active\n * model, resolved by the host via the chat model registry. Drives free-space\n * + fraction. When omitted, defaults to `used` (no headroom shown).\n */\n effectiveWindow?: number\n /**\n * Active model id — used for the exact `countTokens` call + the header label.\n * Only consulted on the PRE-RUN path (no snapshot yet); once a run has fired,\n * the snapshot's own model wins. When omitted, the provider default is used.\n */\n model?: string\n /** Tokens reserved for output (autocompact buffer). Defaults to 0. */\n autocompactBuffer?: number\n /**\n * Auto-compact threshold as a fraction of the window (0–1), when enabled.\n * When set, the \"Autocompact buffer\" bucket represents the ENTIRE tail from\n * the threshold to the end of the window (`(1 − threshold) × window`) rather\n * than just the reserved-output tokens — so the bar/row show exactly where\n * compaction fires. When omitted, `autocompactBuffer` is used as-is.\n */\n compactThreshold?: number\n /** Abort signal forwarded to the provider's `countTokens`. */\n signal?: AbortSignal\n}\n\n/** Tools grouped by MCP server, for the expandable per-server rows. */\nexport interface ContextMcpGroup {\n server: string\n /** Wire tool specs for this server (their JSON size is measured). */\n tools: { name: string, json: string }[]\n}\n\n/**\n * Exact per-segment counts from a provider's `countTokens`, when available.\n * Each field is the count of the cumulative payload up to and including that\n * segment, so categories are derived by differencing (see\n * {@link buildContextBreakdown}). Any subset may be present; missing fields\n * fall back to the heuristic for that category.\n */\nexport interface ContextExactCounts {\n /** Tokens for system prompt alone. */\n system?: number\n /** Tokens for system + tools (so tools = systemAndTools - system). */\n systemAndTools?: number\n /** Tokens for the full payload (system + tools + messages) = the real total. */\n full?: number\n}\n\n/**\n * Raw inputs captured at agent prompt-assembly time. Everything here is what\n * actually went on (or was withheld from) the wire for the last run.\n */\nexport interface ContextSnapshot {\n modelId: string\n /** Full rendered system prompt (marker-stripped, as sent). */\n system: string\n /**\n * Host-composed base system BEFORE the agent appended skills / searchable /\n * MCP-instructions catalogs. Includes the rules block. The \"System prompt\"\n * (base doctrine) bucket = base − rules − env-noise. Defaults to `system`\n * when not provided (back-compat).\n */\n baseSystem?: string\n /** Rendered AGENTS.md/CLAUDE.md rules block (a substring of `baseSystem`). */\n rulesBlock?: string\n /** Source files behind the rules block, for per-file rows. */\n rulesFiles?: { path: string, source: string }[]\n /** Wire tool specs currently disclosed to the model, as JSON strings. */\n toolsJson: string[]\n /** Lazy tool entries NOT currently disclosed (deferred), as JSON strings. */\n deferredToolsJson: string[]\n /** MCP tools grouped by server (disclosed ones). */\n mcpGroups: ContextMcpGroup[]\n /** Deferred (undisclosed) MCP tools grouped by server. */\n deferredMcpGroups: ContextMcpGroup[]\n /** Rendered MCP instructions block, if any. */\n mcpInstructions?: string\n /** Rendered skills catalog text, if any. */\n skillsCatalog?: string\n /** Searchable / subagent (spawn) tool definitions text, if any. */\n subagentDefs?: string\n /** Memory / rules files in context. */\n /** Real last-turn total (input + cacheRead + cacheCreation). */\n used: number\n /** Effective window (raw - output reserve). */\n effectiveWindow: number\n /** Tokens reserved for output (autocompact buffer). */\n autocompactBuffer: number\n /** Exact per-segment counts from the provider, when available. */\n exact?: ContextExactCounts\n /** Exact last-turn usage split, when available (passed straight through). */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /** Names of currently-active skills (passed straight through). */\n activeSkills?: string[]\n}\n\nconst LABELS: Record<ContextCategoryId, string> = {\n systemPrompt: 'System prompt',\n rules: 'Rules (AGENTS.md)',\n tools: 'Tool definitions',\n mcpTools: 'MCP tools',\n mcpInstructions: 'MCP instructions',\n skills: 'Skills',\n subagentDefs: 'Subagent definitions',\n conversation: 'Conversation',\n mcpToolsDeferred: 'MCP tools (deferred)',\n toolsDeferred: 'System tools (deferred)',\n autocompactBuffer: 'Autocompact buffer',\n freeSpace: 'Free space',\n}\n\n/** Sum the heuristic token sizes of a list of strings. */\nfunction sumEstimate(parts: readonly string[]): number {\n let total = 0\n for (const p of parts)\n total += estimateTokens(p)\n return total\n}\n\nfunction mcpGroupTokens(group: ContextMcpGroup): { total: number, items: ContextItem[] } {\n const items: ContextItem[] = group.tools.map(t => ({\n id: `${group.server}:${t.name}`,\n label: t.name,\n tokens: estimateTokens(t.json),\n estimated: true,\n }))\n let total = 0\n for (const it of items)\n total += it.tokens\n return { total, items }\n}\n\n/**\n * Shape a {@link ContextSnapshot} into a render-ready {@link ContextBreakdown}.\n *\n * Live categories (system prompt, tools, MCP tools/instructions, skills,\n * memory, subagent defs, conversation) sum to `snapshot.used` — `conversation`\n * absorbs the remainder so the bar matches the provider-reported total exactly.\n * Deferred + autocompact + free-space buckets follow.\n *\n * When `snapshot.exact` carries provider counts, the matching categories use\n * them (system, tools) and drop their `estimated` flag; everything else stays\n * on the heuristic.\n */\nexport function buildContextBreakdown(snapshot: ContextSnapshot): ContextBreakdown {\n const exact = snapshot.exact\n const systemExact = typeof exact?.system === 'number'\n\n // --- System-embedded sub-sections (heuristic) ----------------------------\n // The exact `count_tokens` system number covers the WHOLE system text. The\n // appended catalogs (rules / skills / MCP instructions / subagent defs) all\n // live inside it, so we size each heuristically and let the \"System prompt\"\n // (base doctrine) bucket absorb the remainder — keeping the system group's\n // sum exact while still attributing each section.\n const rulesTokens = snapshot.rulesBlock ? estimateTokens(snapshot.rulesBlock) : 0\n const rulesItems: ContextItem[] = (snapshot.rulesFiles ?? []).map(f => ({\n id: f.path,\n label: f.path,\n // Per-file size isn't separable from the rendered block; show the path only\n // (tokens 0, not estimated — there's nothing to estimate) so the row lists\n // sources without implying a per-file count or a `~` marker.\n tokens: 0,\n estimated: false,\n }))\n const skillsTokens = snapshot.skillsCatalog ? estimateTokens(snapshot.skillsCatalog) : 0\n const mcpInstructionsTokens = snapshot.mcpInstructions ? estimateTokens(snapshot.mcpInstructions) : 0\n const subagentTokens = snapshot.subagentDefs ? estimateTokens(snapshot.subagentDefs) : 0\n const embeddedSubsections = rulesTokens + skillsTokens + mcpInstructionsTokens + subagentTokens\n\n // System TOTAL (whole system text) — exact when available.\n const systemTotal = systemExact ? exact!.system! : estimateTokens(snapshot.system)\n // Base doctrine = system total minus the attributed sub-sections.\n const baseSystemTokens = Math.max(0, systemTotal - embeddedSubsections)\n\n // --- Native tool definitions (non-MCP, disclosed) ------------------------\n // When exact `systemAndTools` is available it covers BOTH native + MCP tools,\n // so we split that combined number proportionally by heuristic weight rather\n // than claiming exactness per sub-bucket.\n const nativeToolsEst = sumEstimate(snapshot.toolsJson)\n const mcpDisclosed = snapshot.mcpGroups.map(mcpGroupTokens)\n const mcpToolsEst = mcpDisclosed.reduce((a, g) => a + g.total, 0)\n\n let nativeToolsTokens = nativeToolsEst\n let mcpToolsTokens = mcpToolsEst\n let toolsEstimated = true\n if (systemExact && typeof exact?.systemAndTools === 'number') {\n const exactToolsTotal = Math.max(0, exact.systemAndTools - exact.system!)\n const estTotal = nativeToolsEst + mcpToolsEst\n if (estTotal > 0) {\n nativeToolsTokens = Math.round(exactToolsTotal * (nativeToolsEst / estTotal))\n mcpToolsTokens = exactToolsTotal - nativeToolsTokens\n }\n else {\n nativeToolsTokens = exactToolsTotal\n mcpToolsTokens = 0\n }\n toolsEstimated = false\n }\n\n // --- Live categories -----------------------------------------------------\n // Detailed split. The system-embedded sub-sections (rules / skills / MCP\n // instructions / subagent defs) are heuristic; the \"System prompt\" base\n // bucket carries the exact remainder so the whole system group still sums to\n // the exact system count. Tools/MCP-tools/conversation are split as before.\n const live: ContextCategory[] = []\n const push = (id: ContextCategoryId, tokens: number, estimated: boolean, items?: ContextItem[]) => {\n if (tokens <= 0 && !items?.length)\n return\n live.push({ id, label: LABELS[id], tokens: Math.max(0, tokens), estimated, ...(items?.length ? { items } : {}) })\n }\n\n // System group: base doctrine (exact remainder) + attributed sub-sections.\n push('systemPrompt', baseSystemTokens, !systemExact)\n push('rules', rulesTokens, true, rulesItems)\n push('skills', skillsTokens, true)\n push('mcpInstructions', mcpInstructionsTokens, true)\n push('subagentDefs', subagentTokens, true)\n // Tools.\n push('tools', nativeToolsTokens, toolsEstimated)\n push('mcpTools', mcpToolsTokens, toolsEstimated, mcpDisclosed.flatMap(g => g.items))\n\n // --- Conversation = remainder (keeps the bar summing to `used`) ----------\n const accountedStatic = live.reduce((a, c) => a + c.tokens, 0)\n const conversationTokens = Math.max(0, snapshot.used - accountedStatic)\n // Exact when both system AND tools were exactly counted — then the remainder\n // (used − exactSystem − exactTools) is itself exact, since `used` is the\n // provider-reported total.\n const conversationEstimated = !(systemExact && !toolsEstimated)\n push('conversation', conversationTokens, conversationEstimated)\n\n // --- Deferred buckets (not counted against `used`) -----------------------\n const deferred: ContextCategory[] = []\n const deferredNativeTools = sumEstimate(snapshot.deferredToolsJson)\n if (deferredNativeTools > 0) {\n deferred.push({ id: 'toolsDeferred', label: LABELS.toolsDeferred, tokens: deferredNativeTools, estimated: true, deferred: true })\n }\n const deferredMcp = snapshot.deferredMcpGroups.map(mcpGroupTokens)\n const deferredMcpTotal = deferredMcp.reduce((a, g) => a + g.total, 0)\n if (deferredMcpTotal > 0) {\n deferred.push({\n id: 'mcpToolsDeferred',\n label: LABELS.mcpToolsDeferred,\n tokens: deferredMcpTotal,\n estimated: true,\n deferred: true,\n items: deferredMcp.flatMap(g => g.items),\n })\n }\n\n // --- Autocompact buffer + free space (exact) -----------------------------\n if (snapshot.autocompactBuffer > 0) {\n deferred.push({ id: 'autocompactBuffer', label: LABELS.autocompactBuffer, tokens: snapshot.autocompactBuffer, estimated: false, deferred: true })\n }\n const free = Math.max(0, snapshot.effectiveWindow - snapshot.used)\n deferred.push({ id: 'freeSpace', label: LABELS.freeSpace, tokens: free, estimated: false, deferred: true })\n\n const categories = [...live, ...deferred]\n const hasEstimates = live.some(c => c.estimated && c.tokens > 0)\n const fraction = snapshot.effectiveWindow > 0\n ? Math.max(0, Math.min(1, snapshot.used / snapshot.effectiveWindow))\n : 0\n\n return {\n modelId: snapshot.modelId,\n used: snapshot.used,\n effectiveWindow: snapshot.effectiveWindow,\n fraction,\n categories,\n hasEstimates,\n ...(snapshot.usage ? { usage: snapshot.usage } : {}),\n ...(snapshot.extensionSections?.length ? { extensionSections: snapshot.extensionSections } : {}),\n ...(snapshot.activeSkills?.length ? { activeSkills: snapshot.activeSkills } : {}),\n }\n}\n","/**\n * Context segments — pure transforms.\n *\n * Sibling to `context-breakdown.ts`: where that module answers \"how many\n * tokens is each part of my context\", this one answers \"what IS each part,\n * and where did it come from\". It turns the same assembled-prompt pieces into\n * a flat list of {@link ContextSegment}s carrying the actual TEXT plus its\n * provenance, so a UI can list every chunk loaded by default in a session,\n * let the user read it, and open the file behind it when there is one.\n *\n * No React, no node — a browser-context renderer imports these via\n * `zidane/chat/pure`.\n *\n * Provenance is honest about what can and can't be opened:\n * - `'file'` — a real path on disk (AGENTS.md / CLAUDE.md / ruler md).\n * The only origin that carries `path`, hence the only one\n * a host can hand to `$EDITOR`.\n * - `'built-in'` — compiled into the binary (base doctrine, subagent defs).\n * - `'generated'` — assembled at prompt time from discovered state (the\n * skills catalog is rendered from the skill manifests).\n * - `'mcp'` — served by a remote MCP server at connect time.\n */\n\nimport { estimateTokens } from '../compact/utils'\n\n/** Where a segment's text came from. Only `'file'` segments carry a `path`. */\nexport type ContextSegmentOrigin = 'built-in' | 'file' | 'generated' | 'mcp'\n\n/** One chunk of text present in the session's default context. */\nexport interface ContextSegment {\n /** Stable key for rendering (`'system'`, `'rules:<path>'`, `'skills'`, ...). */\n id: string\n /** Display label (e.g. \"System prompt\", or the file's basename). */\n label: string\n origin: ContextSegmentOrigin\n /**\n * Short right-hand qualifier — the instruction scope for files, the server\n * list for MCP, a count for the skills catalog. Absent when there's nothing\n * useful to add beyond the origin badge.\n */\n detail?: string\n /** The text itself, as it sits in the prompt. Empty segments are dropped. */\n text: string\n /**\n * Absolute path of the file backing this segment. Present only for\n * `origin: 'file'` — a host uses it as the \"open in $EDITOR\" target.\n */\n path?: string\n /**\n * Heuristic token size (~4 bytes/token). Always an estimate: exact\n * per-segment counts aren't separable from the single system-prompt string\n * the provider counts, which is why {@link ContextSegment} carries no\n * `estimated` flag — every value here is one.\n */\n tokens: number\n}\n\n/**\n * A host-discovered instruction file. Structurally compatible with\n * `AgentsMdFile` from `./agents-md` (whose `source` field is the SCOPE, not\n * the text — `contents` is the text), so callers can pass those straight in.\n */\nexport interface ContextSegmentFile {\n path: string\n /** Instruction scope — `'project'` / `'user'`, surfaced as the row detail. */\n source?: string\n contents: string\n}\n\n/**\n * The assembled-prompt pieces {@link buildContextSegments} shapes. Mirrors the\n * subset of the agent's `ContextAssembly` that carries text, plus host-side\n * instruction files (which the assembly only knows as paths).\n */\nexport interface ContextSegmentsInput {\n /**\n * Host-composed base system BEFORE the agent appended its catalogs. The\n * rules block is a substring of this; the \"System prompt\" segment is the\n * remainder. Falls back to `system` when absent, which over-attributes the\n * appended catalogs into the base row rather than losing them.\n */\n baseSystem?: string\n /** Full rendered system prompt as sent. Used as the `baseSystem` fallback. */\n system?: string\n /**\n * Rendered instruction block (a substring of `baseSystem`). Subtracted from\n * the base so its text isn't reported twice — once as doctrine and once as\n * per-file rows.\n */\n rulesBlock?: string\n /** The files behind `rulesBlock`, each with its own text. */\n rulesFiles?: readonly ContextSegmentFile[]\n /**\n * Absolute path of a `SYSTEM.md` override backing the base prompt. When set,\n * the \"System prompt\" segment reports `origin: 'file'` and becomes openable\n * — the doctrine is the user's file, not compiled-in text.\n */\n systemPath?: string\n /** Rendered skills catalog (the per-skill blurbs, not skill bodies). */\n skillsCatalog?: string\n /** Rendered MCP instructions block. */\n mcpInstructions?: string\n /** Searchable / subagent (spawn) tool catalog text. */\n subagentDefs?: string\n}\n\n/**\n * Remove the first occurrence of `part` from `whole`, collapsing the seam.\n *\n * Used to carve the rules block out of the base system so the \"System prompt\"\n * segment reports only doctrine + env. Substring-based because that's the\n * contract the assembly documents (`rulesBlock` IS a substring of\n * `baseSystem`); a miss leaves `whole` untouched, which degrades to\n * over-reporting the base row rather than dropping text on the floor.\n */\nfunction removeFirst(whole: string, part: string): string {\n if (!part)\n return whole\n const at = whole.indexOf(part)\n if (at < 0)\n return whole\n return `${whole.slice(0, at)}${whole.slice(at + part.length)}`.replace(/\\n{3,}/g, '\\n\\n').trim()\n}\n\n/**\n * Best-effort display name for an instruction file: its basename, with the\n * parent directory prefixed when the basename alone would be ambiguous\n * (`AGENTS.md` appears at up to four paths per scope). Path-separator handling\n * covers both POSIX and Windows so this stays node-free.\n */\nfunction fileLabel(path: string): string {\n const parts = path.split(/[/\\\\]/).filter(Boolean)\n const base = parts.at(-1) ?? path\n const parent = parts.at(-2)\n // A dotted parent (`.agents`, `.zidane`, `.claude`, `.ruler`) is the\n // meaningful discriminator between same-named instruction files.\n return parent?.startsWith('.') ? `${parent}/${base}` : base\n}\n\n/**\n * Shape assembled-prompt pieces into a flat, render-ready segment list.\n *\n * Order is prompt order — base doctrine, then instruction files (broadest\n * scope first, as `discoverAgentsMd` returns them), then the appended\n * catalogs. Empty / whitespace-only pieces are dropped so the list never\n * shows a zero-byte row.\n */\nexport function buildContextSegments(input: ContextSegmentsInput): ContextSegment[] {\n const segments: ContextSegment[] = []\n const push = (seg: Omit<ContextSegment, 'tokens'>) => {\n if (!seg.text.trim())\n return\n segments.push({ ...seg, tokens: estimateTokens(seg.text) })\n }\n\n // --- Base doctrine -------------------------------------------------------\n // `baseSystem` minus the rules block. The per-file rows below carry the\n // instruction text, so leaving the block in would double-report it.\n const base = input.baseSystem ?? input.system ?? ''\n const overridden = input.systemPath !== undefined\n push({\n id: 'system',\n label: 'System prompt',\n // An override makes this a real file on disk; without one it's compiled in.\n origin: overridden ? 'file' : 'built-in',\n detail: overridden ? 'SYSTEM.md override + environment' : 'doctrine + environment',\n text: input.rulesBlock ? removeFirst(base, input.rulesBlock) : base,\n ...(input.systemPath !== undefined ? { path: input.systemPath } : {}),\n })\n\n // --- Instruction files ---------------------------------------------------\n // The only file-backed segments, and so the only openable ones.\n for (const file of input.rulesFiles ?? []) {\n push({\n id: `rules:${file.path}`,\n label: fileLabel(file.path),\n origin: 'file',\n ...(file.source ? { detail: file.source } : {}),\n text: file.contents,\n path: file.path,\n })\n }\n\n // --- Appended catalogs ---------------------------------------------------\n push({\n id: 'skills',\n label: 'Skills catalog',\n origin: 'generated',\n detail: 'name + description per skill (bodies load on activation)',\n text: input.skillsCatalog ?? '',\n })\n push({\n id: 'mcp-instructions',\n label: 'MCP instructions',\n origin: 'mcp',\n detail: 'served by the connected servers',\n text: input.mcpInstructions ?? '',\n })\n push({\n id: 'subagent-defs',\n label: 'Subagent definitions',\n origin: 'built-in',\n text: input.subagentDefs ?? '',\n })\n\n return segments\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,kBAAkB,UAAkB,QAAwB;CAC1E,IAAI,OAAO,WAAW,GACpB,OAAO;CACT,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,OAAO,MAAM;EACX,MAAM,OAAO,SAAS,QAAQ,QAAQ,GAAG;EACzC,IAAI,SAAS,IACX;EACF;EACA,MAAM,OAAO,OAAO;CACtB;CACA,OAAO;AACT;;AAsBA,SAAgB,gBAAgB,KAAqB;CACnD,OAAO,IACJ,WAAA,KAAoC,GAAI,CAAC,CACzC,WAAA,KAAqC,GAAI,CAAC,CAC1C,WAAA,KAAoC,IAAG,CAAC,CACxC,WAAA,KAAqC,IAAG;AAC7C;;;;;;;;;AAUA,MAAM,kBAA4D;CAChE,CAAC,SAAS,oBAAoB;CAC9B,CAAC,OAAO,QAAQ;CAChB,CAAC,QAAQ,SAAS;CAClB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,OAAO,SAAS;CACjB,CAAC,QAAQ,UAAU;CACnB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,OAAO,UA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QAAQ;EACR,QAAQ;EACR,MAAM,MAAM,mBAAmB;CACjC,CAAC;CACD,KAAK;EACH,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,MAAM,MAAM,gBAAgB;CAC9B,CAAC;CAED,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as createStderrLineEmitter } from "./mcp-
|
|
1
|
+
import { r as createStderrLineEmitter } from "./mcp-DdntU47g.js";
|
|
2
2
|
import { Buffer } from "node:buffer";
|
|
3
3
|
//#region src/mcp/context-transport.ts
|
|
4
4
|
/**
|
|
@@ -10,7 +10,7 @@ import { Buffer } from "node:buffer";
|
|
|
10
10
|
async function createContextStdioTransport(options) {
|
|
11
11
|
const { name, context, handle, command, cwd, env, hooks } = options;
|
|
12
12
|
if (!context.execStream) throw new Error(`MCP server "${name}" is configured with \`scope: 'context'\`, but the '${context.type}' execution context does not support live streams (\`execStream\`). Use \`scope: 'host'\` for this server, or switch to a context that advertises \`capabilities.stream\`.`);
|
|
13
|
-
const { ReadBuffer, serializeMessage } = await import("./stdio-
|
|
13
|
+
const { ReadBuffer, serializeMessage } = await import("./stdio-BQeCMmuK.js").then((n) => n.r);
|
|
14
14
|
const readBuffer = new ReadBuffer();
|
|
15
15
|
let stream = null;
|
|
16
16
|
let closed = false;
|
|
@@ -81,4 +81,4 @@ async function createContextStdioTransport(options) {
|
|
|
81
81
|
//#endregion
|
|
82
82
|
export { createContextStdioTransport };
|
|
83
83
|
|
|
84
|
-
//# sourceMappingURL=context-transport-
|
|
84
|
+
//# sourceMappingURL=context-transport-ClvadrlH.js.map
|