dsh-coding 0.0.1 → 0.1.1-rc2
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/AGENTS.md +80 -0
- package/LICENSE +21 -21
- package/README.md +120 -54
- package/cordis.patch.yml +274 -4
- package/docs/CHANGELOG.md +47 -0
- package/docs/DETAIL.md +272 -0
- package/icon.svg +6 -6
- package/lib/apply-patch.js +268 -0
- package/lib/client/capsule.js +120 -0
- package/lib/client/card.js +308 -0
- package/lib/client/command-row.js +76 -0
- package/lib/client/config-page.js +392 -0
- package/lib/client/definition.js +164 -0
- package/lib/client/index.js +129 -0
- package/lib/client/locales.js +170 -0
- package/lib/client/mode-picker.js +77 -0
- package/lib/client/styles.js +283 -0
- package/lib/client.js +1802 -0
- package/lib/coding-projection.js +349 -0
- package/lib/config.js +218 -0
- package/lib/contract.js +138 -0
- package/lib/editor.js +23 -0
- package/lib/failures.js +142 -0
- package/lib/handoff.js +347 -0
- package/lib/index.js +110 -7
- package/lib/language.js +136 -0
- package/lib/memory.js +336 -0
- package/lib/messages.js +43 -0
- package/lib/models.js +154 -0
- package/lib/patch.js +235 -0
- package/lib/preset.js +1552 -0
- package/lib/reasoning-levels.js +28 -0
- package/lib/reasoning-projection.js +178 -0
- package/lib/reasoning.js +585 -0
- package/lib/stages.js +344 -0
- package/lib/state.js +585 -0
- package/lib/system-language.js +56 -0
- package/lib/types/apply-patch.d.ts +13 -0
- package/lib/types/client/capsule.d.ts +9 -0
- package/lib/types/client/card.d.ts +76 -0
- package/lib/types/client/command-row.d.ts +42 -0
- package/lib/types/client/config-page.d.ts +136 -0
- package/lib/types/client/definition.d.ts +51 -0
- package/lib/types/client/index.d.ts +10 -0
- package/lib/types/client/locales.d.ts +18 -0
- package/lib/types/client/mode-picker.d.ts +25 -0
- package/lib/types/client/styles.d.ts +28 -0
- package/lib/types/coding-projection.d.ts +116 -0
- package/lib/types/config.d.ts +208 -0
- package/lib/types/contract.d.ts +33 -0
- package/lib/types/editor.d.ts +9 -0
- package/lib/types/failures.d.ts +62 -0
- package/lib/types/handoff.d.ts +132 -0
- package/lib/types/index.d.ts +150 -0
- package/lib/types/language.d.ts +56 -0
- package/lib/types/memory.d.ts +71 -0
- package/lib/types/messages.d.ts +27 -0
- package/lib/types/models.d.ts +82 -0
- package/lib/types/patch.d.ts +37 -0
- package/lib/types/preset.d.ts +22 -0
- package/lib/types/reasoning-levels.d.ts +20 -0
- package/lib/types/reasoning-projection.d.ts +64 -0
- package/lib/types/reasoning.d.ts +141 -0
- package/lib/types/stages.d.ts +193 -0
- package/lib/types/state.d.ts +273 -0
- package/lib/types/system-language.d.ts +10 -0
- package/lib/types/verification-tool.d.ts +32 -0
- package/lib/types/verification.d.ts +77 -0
- package/lib/types/verifier.d.ts +9 -0
- package/lib/types/volatile.d.ts +17 -0
- package/lib/verification-tool.js +176 -0
- package/lib/verification.js +337 -0
- package/lib/verifier.js +25 -0
- package/lib/volatile.js +20 -0
- package/locale/en.json +3 -2
- package/locale/zh.json +3 -2
- package/package.json +84 -9
- package/lib/index.d.ts +0 -11
package/lib/models.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker model routing: one place that names the configured route of a worker
|
|
3
|
+
* role, resolves it, and proves it usable before dispatch.
|
|
4
|
+
*
|
|
5
|
+
* A worker must never fall back to the lead's own model, so the route is read
|
|
6
|
+
* from the configuration field named by the role, validated as `provider/model`,
|
|
7
|
+
* and checked against the live provider registry and model catalog before the
|
|
8
|
+
* subagent starts. Every lookup here goes to the live service: configuration is
|
|
9
|
+
* volatile and may change between two dispatches, so nothing is cached.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-coding/models
|
|
12
|
+
*/
|
|
13
|
+
import { parseWorkerRoute } from './config.js';
|
|
14
|
+
import { WORKER_PRESETS } from './stages.js';
|
|
15
|
+
/** Every worker role, in dispatch order. */
|
|
16
|
+
export const WORKER_ROLES = ['plan', 'implement', 'verify'];
|
|
17
|
+
/** The configuration field each role's route is read from. */
|
|
18
|
+
const WORKER_FIELDS = {
|
|
19
|
+
plan: 'plannerWorkerModel',
|
|
20
|
+
implement: 'implementWorkerModel',
|
|
21
|
+
verify: 'verifyWorkerModel',
|
|
22
|
+
};
|
|
23
|
+
/** The preset id each role is dispatched with. */
|
|
24
|
+
const WORKER_PRESET_BY_ROLE = {
|
|
25
|
+
plan: WORKER_PRESETS.planner,
|
|
26
|
+
implement: WORKER_PRESETS.implement,
|
|
27
|
+
verify: WORKER_PRESETS.verify,
|
|
28
|
+
};
|
|
29
|
+
/** The configuration field holding one role's route. */
|
|
30
|
+
export function workerField(role) {
|
|
31
|
+
return WORKER_FIELDS[role];
|
|
32
|
+
}
|
|
33
|
+
/** The preset id a worker role is dispatched with. */
|
|
34
|
+
export function workerPreset(role) {
|
|
35
|
+
return WORKER_PRESET_BY_ROLE[role];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Read, validate, and describe one role's configured route.
|
|
39
|
+
* @param config - verified configuration.
|
|
40
|
+
* @param role - worker about to be dispatched.
|
|
41
|
+
* @returns the parsed route plus its role, field, and rendered text.
|
|
42
|
+
* @throws when the field is not exactly `provider/model`.
|
|
43
|
+
*/
|
|
44
|
+
export function resolveWorkerRoute(config, role) {
|
|
45
|
+
const field = workerField(role);
|
|
46
|
+
const route = parseWorkerRoute(config[field], field);
|
|
47
|
+
return { role, field, provider: route.provider, model: route.model, text: `${route.provider}/${route.model}` };
|
|
48
|
+
}
|
|
49
|
+
/** A refused worker route: the configured value, and what the runtime offers instead. */
|
|
50
|
+
export class WorkerModelError extends Error {
|
|
51
|
+
code;
|
|
52
|
+
role;
|
|
53
|
+
field;
|
|
54
|
+
route;
|
|
55
|
+
available;
|
|
56
|
+
constructor(message, details) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = 'WorkerModelError';
|
|
59
|
+
this.code = details.code;
|
|
60
|
+
this.role = details.role;
|
|
61
|
+
this.field = details.field;
|
|
62
|
+
this.route = details.route;
|
|
63
|
+
this.available = details.available;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The provider ids the runtime currently registers, sorted.
|
|
68
|
+
* @param ctx - plugin context (or any object exposing the `llm` service).
|
|
69
|
+
* @returns the ids, or [] when the registry cannot be read.
|
|
70
|
+
*/
|
|
71
|
+
export function describeProviders(ctx) {
|
|
72
|
+
try {
|
|
73
|
+
const llm = ctx?.llm ?? ctx?.get?.('llm');
|
|
74
|
+
if (typeof llm?.listProviders !== 'function')
|
|
75
|
+
return [];
|
|
76
|
+
const providers = llm.listProviders();
|
|
77
|
+
if (!Array.isArray(providers))
|
|
78
|
+
return [];
|
|
79
|
+
const ids = providers
|
|
80
|
+
.map((provider) => provider?.id)
|
|
81
|
+
.filter((id) => typeof id === 'string' && id !== '');
|
|
82
|
+
return [...new Set(ids)].sort();
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The model ids one provider advertises, deduplicated and sorted.
|
|
90
|
+
* @param ctx - plugin context (or any object exposing the `llm` service).
|
|
91
|
+
* @param provider - provider id being inspected.
|
|
92
|
+
* @param signal - caller's abort signal; an aborted call lists nothing.
|
|
93
|
+
* @returns the ids, or [] when the catalog is unavailable.
|
|
94
|
+
*/
|
|
95
|
+
export async function listModelIds(ctx, provider, signal) {
|
|
96
|
+
if (signal?.aborted === true)
|
|
97
|
+
return [];
|
|
98
|
+
try {
|
|
99
|
+
const llm = ctx?.llm ?? ctx?.get?.('llm');
|
|
100
|
+
if (typeof llm?.listModels !== 'function')
|
|
101
|
+
return [];
|
|
102
|
+
const models = await llm.listModels(provider);
|
|
103
|
+
if (!Array.isArray(models))
|
|
104
|
+
return [];
|
|
105
|
+
const ids = models
|
|
106
|
+
.map((model) => model?.id)
|
|
107
|
+
.filter((id) => typeof id === 'string' && id !== '');
|
|
108
|
+
return [...new Set(ids)].sort();
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Refuse a worker dispatch whose configured route cannot be honoured.
|
|
116
|
+
*
|
|
117
|
+
* The check is deliberately narrow: an unreachable catalog defers to the
|
|
118
|
+
* dispatch instead of blocking it, because listing models may need credentials
|
|
119
|
+
* that the worker itself will supply. A registered-provider mismatch and a
|
|
120
|
+
* failing `resolveModelInfo` are both refusals, with the available alternatives
|
|
121
|
+
* named in the message.
|
|
122
|
+
* @param ctx - plugin context (or any object exposing the `llm` service).
|
|
123
|
+
* @param route - resolved route of the worker about to run.
|
|
124
|
+
* @param signal - caller's abort signal; an abort is rethrown untouched.
|
|
125
|
+
* @throws {WorkerModelError} when the provider is missing or the model unusable.
|
|
126
|
+
*/
|
|
127
|
+
export async function assertWorkerModel(ctx, route, signal) {
|
|
128
|
+
const providers = describeProviders(ctx);
|
|
129
|
+
if (providers.length > 0 && !providers.includes(route.provider)) {
|
|
130
|
+
const available = providers.slice(0, 10).join(', ') + (providers.length > 10 ? ', …' : '');
|
|
131
|
+
throw new WorkerModelError(`delegate_${route.role}: ${route.field} names LLM provider "${route.provider}", which is not registered; `
|
|
132
|
+
+ `available providers: ${available || '(none)'}. Fix ${route.field} in the plugin page or cordis.patch.yml; `
|
|
133
|
+
+ 'a worker never falls back to the lead\'s model.', { code: 'PROVIDER_MISSING', role: route.role, field: route.field, route: route.text, available: providers });
|
|
134
|
+
}
|
|
135
|
+
const llm = ctx?.llm ?? ctx?.get?.('llm');
|
|
136
|
+
if (typeof llm?.resolveModelInfo !== 'function')
|
|
137
|
+
return;
|
|
138
|
+
try {
|
|
139
|
+
await llm.resolveModelInfo(route.provider, route.model, signal);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (signal?.aborted === true)
|
|
143
|
+
throw error;
|
|
144
|
+
const ids = await listModelIds(ctx, route.provider, signal).catch(() => []);
|
|
145
|
+
const available = ids.slice(0, 10).join(', ') + (ids.length > 10 ? ', …' : '');
|
|
146
|
+
throw new WorkerModelError(`delegate_${route.role}: ${route.field} = "${route.text}" is not a usable model route: ${messageOf(error)}. `
|
|
147
|
+
+ `Available models for provider "${route.provider}": ${available || '(none advertised)'}. `
|
|
148
|
+
+ `Fix ${route.field} in the plugin page or cordis.patch.yml; the worker never falls back to the lead's model.`, { code: 'MODEL_UNAVAILABLE', role: route.role, field: route.field, route: route.text, available: ids });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Read an error's message, for a failure that may be any thrown value. */
|
|
152
|
+
function messageOf(error) {
|
|
153
|
+
return error instanceof Error ? error.message : String(error);
|
|
154
|
+
}
|
package/lib/patch.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parser and line-oriented applicator for the Codex `apply_patch` language.
|
|
3
|
+
*
|
|
4
|
+
* The format is a small, strict contract on purpose: it keeps edits reviewable,
|
|
5
|
+
* lets one call update several files, and gives a precise mismatch report when
|
|
6
|
+
* the model's context is stale.
|
|
7
|
+
*/
|
|
8
|
+
export const APPLY_PATCH_DESCRIPTION = [
|
|
9
|
+
'Edit files with the Codex patch format: "*** Begin Patch", one or more',
|
|
10
|
+
'"*** Add File:", "*** Delete File:", or "*** Update File:" sections, then "*** End Patch".',
|
|
11
|
+
'In hunk lines the first character is the operation marker: space (context), + (add), or - (delete);',
|
|
12
|
+
'use @@ to separate hunks and "*** End of File" to anchor a hunk at EOF.',
|
|
13
|
+
'Repeat a source-leading marker after the operation marker when the source line itself starts with one.',
|
|
14
|
+
'Read a file before updating it. Prefer this tool for multi-file or multi-hunk changes.',
|
|
15
|
+
'Example: "*** Begin Patch\\n*** Update File: src/a.ts\\n@@\\n-old\\n+new\\n*** End Patch".',
|
|
16
|
+
].join(' ');
|
|
17
|
+
function invalid(message) {
|
|
18
|
+
throw new Error(`apply_patch: ${message}`);
|
|
19
|
+
}
|
|
20
|
+
function isFileHeader(line) {
|
|
21
|
+
const trimmed = line.trim();
|
|
22
|
+
return trimmed.startsWith('*** Add File: ')
|
|
23
|
+
|| trimmed.startsWith('*** Delete File: ')
|
|
24
|
+
|| trimmed.startsWith('*** Update File: ');
|
|
25
|
+
}
|
|
26
|
+
function unwrapHeredoc(input) {
|
|
27
|
+
const normalized = input.replaceAll('\r\n', '\n').trim();
|
|
28
|
+
const lines = normalized.split('\n');
|
|
29
|
+
const first = lines[0]?.trim();
|
|
30
|
+
const last = lines.at(-1)?.trim();
|
|
31
|
+
if (lines.length >= 4
|
|
32
|
+
&& (first === '<<EOF' || first === "<<'EOF'" || first === '<<"EOF"')
|
|
33
|
+
&& last === 'EOF') {
|
|
34
|
+
return lines.slice(1, -1).join('\n').trim();
|
|
35
|
+
}
|
|
36
|
+
return normalized;
|
|
37
|
+
}
|
|
38
|
+
function pathFrom(line, prefix) {
|
|
39
|
+
const path = line.slice(prefix.length).trim();
|
|
40
|
+
if (path.length === 0)
|
|
41
|
+
invalid(`${prefix.trim()} requires a file path`);
|
|
42
|
+
return path;
|
|
43
|
+
}
|
|
44
|
+
function isChangeMarker(line) {
|
|
45
|
+
const marker = line.trimEnd();
|
|
46
|
+
return marker === '@@' || marker.startsWith('@@ ');
|
|
47
|
+
}
|
|
48
|
+
function isPotentialChangeMarker(line) {
|
|
49
|
+
return line.trimEnd().startsWith('@@');
|
|
50
|
+
}
|
|
51
|
+
/** Parse one complete Codex patch after normalizing CRLF input to LF. */
|
|
52
|
+
export function parsePatch(input) {
|
|
53
|
+
const lines = unwrapHeredoc(input).split('\n');
|
|
54
|
+
if (lines[0]?.trim() !== '*** Begin Patch') {
|
|
55
|
+
invalid('input must start with "*** Begin Patch"');
|
|
56
|
+
}
|
|
57
|
+
if (lines.at(-1)?.trim() !== '*** End Patch') {
|
|
58
|
+
invalid('input must end with "*** End Patch"');
|
|
59
|
+
}
|
|
60
|
+
const files = [];
|
|
61
|
+
let index = 1;
|
|
62
|
+
const end = lines.length - 1;
|
|
63
|
+
if (lines[index]?.trim().startsWith('*** Environment ID:') === true) {
|
|
64
|
+
invalid('environment selection is unavailable in this single-environment DSH plugin');
|
|
65
|
+
}
|
|
66
|
+
while (index < end) {
|
|
67
|
+
const header = lines[index++]?.trim();
|
|
68
|
+
if (header === undefined)
|
|
69
|
+
invalid('unexpected end of input');
|
|
70
|
+
if (header.startsWith('*** Add File: ')) {
|
|
71
|
+
const path = pathFrom(header, '*** Add File: ');
|
|
72
|
+
const content = [];
|
|
73
|
+
while (index < end && lines[index]?.startsWith('+') === true) {
|
|
74
|
+
content.push(lines[index].slice(1));
|
|
75
|
+
index += 1;
|
|
76
|
+
}
|
|
77
|
+
if (content.length === 0)
|
|
78
|
+
invalid(`add file ${JSON.stringify(path)} needs at least one content line`);
|
|
79
|
+
files.push({ kind: 'add', path, content: `${content.join('\n')}\n` });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (header.startsWith('*** Delete File: ')) {
|
|
83
|
+
files.push({ kind: 'delete', path: pathFrom(header, '*** Delete File: ') });
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (!header.startsWith('*** Update File: ')) {
|
|
87
|
+
invalid(`unexpected directive ${JSON.stringify(header)}`);
|
|
88
|
+
}
|
|
89
|
+
const path = pathFrom(header, '*** Update File: ');
|
|
90
|
+
let moveTo;
|
|
91
|
+
if (lines[index]?.trim().startsWith('*** Move to: ') === true) {
|
|
92
|
+
moveTo = pathFrom(lines[index].trim(), '*** Move to: ');
|
|
93
|
+
index += 1;
|
|
94
|
+
}
|
|
95
|
+
const hunks = [];
|
|
96
|
+
while (index < end && !isFileHeader(lines[index])) {
|
|
97
|
+
let context;
|
|
98
|
+
if (isPotentialChangeMarker(lines[index])) {
|
|
99
|
+
const marker = lines[index].trimEnd();
|
|
100
|
+
if (!isChangeMarker(marker)) {
|
|
101
|
+
invalid(`invalid update hunk marker ${JSON.stringify(lines[index])}`);
|
|
102
|
+
}
|
|
103
|
+
index += 1;
|
|
104
|
+
context = marker.length === 2 ? undefined : marker.slice(3);
|
|
105
|
+
}
|
|
106
|
+
const patchLines = [];
|
|
107
|
+
while (index < end
|
|
108
|
+
&& !isFileHeader(lines[index])
|
|
109
|
+
&& !isPotentialChangeMarker(lines[index])
|
|
110
|
+
&& lines[index].trimEnd() !== '*** End of File') {
|
|
111
|
+
const line = lines[index];
|
|
112
|
+
index += 1;
|
|
113
|
+
if (line.length === 0) {
|
|
114
|
+
invalid('update lines need a leading space, +, or - marker');
|
|
115
|
+
}
|
|
116
|
+
const marker = line[0];
|
|
117
|
+
if (marker !== ' ' && marker !== '+' && marker !== '-') {
|
|
118
|
+
invalid(`unexpected update line ${JSON.stringify(line)}`);
|
|
119
|
+
}
|
|
120
|
+
patchLines.push({
|
|
121
|
+
kind: marker === ' ' ? 'context' : marker === '+' ? 'add' : 'delete',
|
|
122
|
+
text: line.slice(1),
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
const endOfFile = lines[index]?.trimEnd() === '*** End of File';
|
|
126
|
+
if (endOfFile)
|
|
127
|
+
index += 1;
|
|
128
|
+
if (patchLines.length === 0) {
|
|
129
|
+
if (context !== undefined || endOfFile)
|
|
130
|
+
invalid('an update hunk needs context or changed lines');
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
hunks.push({
|
|
134
|
+
...(context === undefined ? {} : { context }),
|
|
135
|
+
lines: patchLines,
|
|
136
|
+
endOfFile,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
if (hunks.length === 0 && moveTo === undefined) {
|
|
140
|
+
invalid(`update file ${JSON.stringify(path)} has no changes`);
|
|
141
|
+
}
|
|
142
|
+
files.push({
|
|
143
|
+
kind: 'update',
|
|
144
|
+
path,
|
|
145
|
+
...(moveTo === undefined ? {} : { moveTo }),
|
|
146
|
+
hunks,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
if (files.length === 0)
|
|
150
|
+
invalid('no files were modified');
|
|
151
|
+
return files;
|
|
152
|
+
}
|
|
153
|
+
function splitText(text) {
|
|
154
|
+
if (text.length === 0)
|
|
155
|
+
return { lines: [], trailingNewline: false };
|
|
156
|
+
const trailingNewline = text.endsWith('\n');
|
|
157
|
+
const lines = text.split('\n');
|
|
158
|
+
if (trailingNewline)
|
|
159
|
+
lines.pop();
|
|
160
|
+
return { lines, trailingNewline };
|
|
161
|
+
}
|
|
162
|
+
function joinText(value) {
|
|
163
|
+
const body = value.lines.join('\n');
|
|
164
|
+
return value.trailingNewline ? `${body}\n` : body;
|
|
165
|
+
}
|
|
166
|
+
function findSequence(lines, expected, from, endOfFile) {
|
|
167
|
+
if (expected.length === 0)
|
|
168
|
+
return Math.min(from, lines.length);
|
|
169
|
+
if (expected.length > lines.length)
|
|
170
|
+
return -1;
|
|
171
|
+
const first = endOfFile ? Math.max(from, lines.length - expected.length) : from;
|
|
172
|
+
const last = lines.length - expected.length;
|
|
173
|
+
const matchers = [
|
|
174
|
+
(actual, wanted) => actual === wanted,
|
|
175
|
+
(actual, wanted) => actual.trimEnd() === wanted.trimEnd(),
|
|
176
|
+
(actual, wanted) => actual.trim() === wanted.trim(),
|
|
177
|
+
];
|
|
178
|
+
for (const matchesLine of matchers) {
|
|
179
|
+
for (let index = first; index <= last; index += 1) {
|
|
180
|
+
let matches = true;
|
|
181
|
+
for (let offset = 0; offset < expected.length; offset += 1) {
|
|
182
|
+
if (!matchesLine(lines[index + offset], expected[offset])) {
|
|
183
|
+
matches = false;
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (matches)
|
|
188
|
+
return index;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return -1;
|
|
192
|
+
}
|
|
193
|
+
function displayPatchLine(line) {
|
|
194
|
+
if (line.length === 0)
|
|
195
|
+
return '<empty>';
|
|
196
|
+
return line.replaceAll(' ', '[space]').replaceAll('\t', '[tab]');
|
|
197
|
+
}
|
|
198
|
+
function formatPatchExcerpt(lines, start, count) {
|
|
199
|
+
if (lines.length === 0)
|
|
200
|
+
return ' <empty file>';
|
|
201
|
+
const first = Math.max(0, Math.min(start, lines.length - 1));
|
|
202
|
+
return lines
|
|
203
|
+
.slice(first, first + count)
|
|
204
|
+
.map((line, offset) => ` ${first + offset + 1}: ${displayPatchLine(line)}`)
|
|
205
|
+
.join('\n');
|
|
206
|
+
}
|
|
207
|
+
function mismatchMessage(label, hunkIndex, expected, actual, from, endOfFile) {
|
|
208
|
+
const expectedPreview = expected
|
|
209
|
+
.slice(0, 12)
|
|
210
|
+
.map((line, index) => ` ${index + 1}: ${displayPatchLine(line)}`)
|
|
211
|
+
.join('\n');
|
|
212
|
+
const expectedSuffix = expected.length > 12 ? '\n ...' : '';
|
|
213
|
+
const excerptStart = endOfFile ? Math.max(0, actual.length - 6) : Math.max(0, from - 2);
|
|
214
|
+
const markerHint = expected.some((wanted) => wanted.length > 0 && actual.includes(`-${wanted}`))
|
|
215
|
+
? '\nHint: if a source line starts with a patch marker, repeat that marker after the operation marker; for example, `-- item` deletes the source line `- item`.'
|
|
216
|
+
: '';
|
|
217
|
+
return `could not find expected lines in ${label} hunk ${hunkIndex + 1} (search starts at line ${from + 1})\nExpected:\n${expectedPreview}${expectedSuffix}\nFile excerpt:\n${formatPatchExcerpt(actual, excerptStart, 10)}${markerHint}`;
|
|
218
|
+
}
|
|
219
|
+
/** Apply parsed update hunks and return LF-normalized text. */
|
|
220
|
+
export function applyHunks(original, hunks, label = 'file') {
|
|
221
|
+
const value = splitText(original.replaceAll('\r\n', '\n'));
|
|
222
|
+
let cursor = 0;
|
|
223
|
+
for (const [hunkIndex, hunk] of hunks.entries()) {
|
|
224
|
+
const expected = hunk.lines.filter((line) => line.kind !== 'add').map((line) => line.text);
|
|
225
|
+
const start = findSequence(value.lines, expected, cursor, hunk.endOfFile);
|
|
226
|
+
if (start < 0) {
|
|
227
|
+
invalid(mismatchMessage(label, hunkIndex, expected, value.lines, cursor, hunk.endOfFile));
|
|
228
|
+
}
|
|
229
|
+
const replacement = hunk.lines.filter((line) => line.kind !== 'delete').map((line) => line.text);
|
|
230
|
+
value.lines.splice(start, expected.length, ...replacement);
|
|
231
|
+
cursor = start + replacement.length;
|
|
232
|
+
value.trailingNewline = !hunk.endOfFile;
|
|
233
|
+
}
|
|
234
|
+
return joinText(value);
|
|
235
|
+
}
|