dsh-coding 0.0.0-stage → 0.1.1-rc1
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/LICENSE +21 -0
- package/README.md +91 -2
- package/cordis.patch.yml +233 -0
- package/docs/DETAIL.md +183 -0
- package/docs/DEVELOPMENT.md +189 -0
- package/icon.svg +6 -0
- package/lib/apply-patch.js +268 -0
- package/lib/client/capsule.js +120 -0
- package/lib/client/card.js +220 -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 +156 -0
- package/lib/client/mode-picker.js +77 -0
- package/lib/client/styles.js +283 -0
- package/lib/client.js +1691 -0
- package/lib/coding-projection.js +349 -0
- package/lib/config.js +204 -0
- package/lib/contract.js +124 -0
- package/lib/editor.js +23 -0
- package/lib/failures.js +142 -0
- package/lib/handoff.js +312 -0
- package/lib/index.js +115 -0
- package/lib/language.js +136 -0
- package/lib/messages.js +43 -0
- package/lib/models.js +154 -0
- package/lib/patch.js +235 -0
- package/lib/preset.js +1488 -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 +306 -0
- package/lib/state.js +550 -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 +72 -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 +193 -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 +112 -0
- package/lib/types/index.d.ts +144 -0
- package/lib/types/language.d.ts +56 -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 +164 -0
- package/lib/types/state.d.ts +261 -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 +7 -0
- package/locale/zh.json +7 -0
- package/package.json +129 -3
package/lib/language.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/** Values accepted by the settings surface. */
|
|
2
|
+
export const LANGUAGE_MODES = ['auto', 'zh', 'en'];
|
|
3
|
+
/** Malformed or unknown values fall back to automatic resolution. */
|
|
4
|
+
export function normalizeLanguageMode(value) {
|
|
5
|
+
return value === 'zh' || value === 'en' || value === 'auto' ? value : 'auto';
|
|
6
|
+
}
|
|
7
|
+
/** Lowercased primary language tag, ignoring the codeset and `@modifier`. */
|
|
8
|
+
function primaryTag(tag) {
|
|
9
|
+
if (typeof tag !== 'string')
|
|
10
|
+
return '';
|
|
11
|
+
return tag.trim().toLowerCase().replace(/_/g, '-').split('.')[0] ?? '';
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Map one BCP 47-style tag (or a POSIX `LANG` value) onto a shipped language.
|
|
15
|
+
* Chinese is the only match that selects Chinese; every other tag is English.
|
|
16
|
+
*/
|
|
17
|
+
export function languageOf(tag) {
|
|
18
|
+
const normalized = primaryTag(tag);
|
|
19
|
+
if (normalized === 'zh' || normalized.startsWith('zh-'))
|
|
20
|
+
return 'zh';
|
|
21
|
+
return 'en';
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The shipped language of one tag, or `undefined` when this package ships
|
|
25
|
+
* neither. A desktop language list is consulted in order, so an unsupported
|
|
26
|
+
* entry (`ja-JP`) must be skipped rather than folded into English.
|
|
27
|
+
*/
|
|
28
|
+
function shippedLanguageOf(tag) {
|
|
29
|
+
const normalized = primaryTag(tag);
|
|
30
|
+
if (normalized === 'zh' || normalized.startsWith('zh-'))
|
|
31
|
+
return 'zh';
|
|
32
|
+
if (normalized === 'en' || normalized.startsWith('en-'))
|
|
33
|
+
return 'en';
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A POSIX locale that states no language preference at all. `C.UTF-8` is a
|
|
38
|
+
* codeset variant of `C`, and it is the value a macOS login shell commonly
|
|
39
|
+
* exports — treating it as "English" is what made a Chinese desktop answer in
|
|
40
|
+
* English.
|
|
41
|
+
*/
|
|
42
|
+
export function isNeutralLocale(value) {
|
|
43
|
+
const base = primaryTag(value);
|
|
44
|
+
return base === '' || base === 'c' || base === 'posix';
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The DSH interface preference, read from the locale plugin's loader entry.
|
|
48
|
+
* `loader.entries()` covers the whole composition, so a nested row is found
|
|
49
|
+
* too; an unavailable loader simply means "no explicit preference".
|
|
50
|
+
*/
|
|
51
|
+
export function localePreferenceOf(loader) {
|
|
52
|
+
let entries;
|
|
53
|
+
try {
|
|
54
|
+
entries = typeof loader?.entries === 'function' ? [...loader.entries()] : [];
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
if (!Array.isArray(entries))
|
|
60
|
+
return undefined;
|
|
61
|
+
for (const entry of entries) {
|
|
62
|
+
const options = entry?.options ?? entry;
|
|
63
|
+
const name = options?.name;
|
|
64
|
+
if (typeof name !== 'string' || !name.includes('client-locale'))
|
|
65
|
+
continue;
|
|
66
|
+
const preference = options?.config?.preference;
|
|
67
|
+
if (typeof preference === 'string' && preference.trim() !== '')
|
|
68
|
+
return preference;
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
/** The host locale: POSIX locale variables first, then the OS default. */
|
|
73
|
+
export function hostLocaleOf(env = process.env) {
|
|
74
|
+
for (const name of ['LC_ALL', 'LC_MESSAGES', 'LANG']) {
|
|
75
|
+
const value = env[name];
|
|
76
|
+
if (typeof value !== 'string')
|
|
77
|
+
continue;
|
|
78
|
+
const trimmed = value.trim();
|
|
79
|
+
if (isNeutralLocale(trimmed))
|
|
80
|
+
continue;
|
|
81
|
+
return trimmed;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
return Intl.DateTimeFormat().resolvedOptions().locale;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return 'en';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Read the OS language list, tolerating a thunk that throws. */
|
|
91
|
+
function readSystemLanguages(input) {
|
|
92
|
+
if (typeof input === 'function') {
|
|
93
|
+
try {
|
|
94
|
+
const value = input();
|
|
95
|
+
return Array.isArray(value) ? value : [];
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return Array.isArray(input) ? input : [];
|
|
102
|
+
}
|
|
103
|
+
/** Resolve the language used by prompts, tool text, and todo items. */
|
|
104
|
+
export function resolveHostLanguage(inputs = {}) {
|
|
105
|
+
const mode = normalizeLanguageMode(inputs.mode);
|
|
106
|
+
if (mode !== 'auto')
|
|
107
|
+
return mode;
|
|
108
|
+
const preference = localePreferenceOf(inputs.loader);
|
|
109
|
+
if (preference !== undefined)
|
|
110
|
+
return languageOf(preference);
|
|
111
|
+
// The desktop decides its own interface language from this list, and the
|
|
112
|
+
// POSIX variables it inherits from a login shell carry no language at all.
|
|
113
|
+
for (const tag of readSystemLanguages(inputs.systemLanguages)) {
|
|
114
|
+
const language = shippedLanguageOf(tag);
|
|
115
|
+
if (language !== undefined)
|
|
116
|
+
return language;
|
|
117
|
+
}
|
|
118
|
+
return languageOf(inputs.locale !== undefined ? inputs.locale : hostLocaleOf());
|
|
119
|
+
}
|
|
120
|
+
/** Prompt section that fixes the conversation language for the session. */
|
|
121
|
+
export function languagePrompt(language) {
|
|
122
|
+
if (language === 'zh') {
|
|
123
|
+
return [
|
|
124
|
+
'Language: 本会话使用中文。',
|
|
125
|
+
'用中文回复用户,编写 todo 条目及其状态说明、计划摘要、澄清提问和交付说明。',
|
|
126
|
+
'代码、标识符、文件路径、命令与引用的报错原文保持原样,不做翻译。',
|
|
127
|
+
'只有用户切换 DSH 界面语言后,才改用对应语言。',
|
|
128
|
+
].join('\n');
|
|
129
|
+
}
|
|
130
|
+
return [
|
|
131
|
+
'Language: use English for this session.',
|
|
132
|
+
'Write chat replies, todo items and their status notes, plan summaries, clarifying questions, and delivery notes in English.',
|
|
133
|
+
'Keep code, identifiers, file paths, command lines, and quoted errors in their original form.',
|
|
134
|
+
'Switch language only when the user changes the DSH interface language.',
|
|
135
|
+
].join('\n');
|
|
136
|
+
}
|
package/lib/messages.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message sources and constructors this plugin contributes to the model-visible
|
|
3
|
+
* surface. Declaring the source kinds here (rather than inventing a user prompt)
|
|
4
|
+
* is what keeps an injected stage fragment and a control notice distinguishable
|
|
5
|
+
* from a real human message in derived history.
|
|
6
|
+
*
|
|
7
|
+
* @module dsh-coding/messages
|
|
8
|
+
*/
|
|
9
|
+
import { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
10
|
+
/** The one-line summary bound of a context notice. */
|
|
11
|
+
const SUMMARY_MAX = 120;
|
|
12
|
+
/**
|
|
13
|
+
* Build the per-step stage context message.
|
|
14
|
+
* @param text - complete stage fragment.
|
|
15
|
+
* @param summary - one-line account shown without expanding the row.
|
|
16
|
+
* @returns an immutable user-role context message.
|
|
17
|
+
*/
|
|
18
|
+
export function stageMessage(text, summary) {
|
|
19
|
+
return createUserMessage({
|
|
20
|
+
content: [{ type: 'text', text }],
|
|
21
|
+
source: {
|
|
22
|
+
kind: 'dsh-coding-stage',
|
|
23
|
+
form: 'notice',
|
|
24
|
+
summary: boundContextSummary(summary.slice(0, SUMMARY_MAX)),
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Build a control notice delivered by `agent.followup()` or `agent.steer()`.
|
|
30
|
+
* @param text - what the runtime decided and what the model should do.
|
|
31
|
+
* @param summary - one-line account for the conversation row.
|
|
32
|
+
* @returns an immutable user-role context message.
|
|
33
|
+
*/
|
|
34
|
+
export function controlMessage(text, summary) {
|
|
35
|
+
return createUserMessage({
|
|
36
|
+
content: [{ type: 'text', text }],
|
|
37
|
+
source: {
|
|
38
|
+
kind: 'dsh-coding-control',
|
|
39
|
+
form: 'notice',
|
|
40
|
+
summary: boundContextSummary(summary.slice(0, SUMMARY_MAX)),
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
}
|
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
|
+
}
|