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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -2
  3. package/cordis.patch.yml +233 -0
  4. package/docs/DETAIL.md +183 -0
  5. package/docs/DEVELOPMENT.md +189 -0
  6. package/icon.svg +6 -0
  7. package/lib/apply-patch.js +268 -0
  8. package/lib/client/capsule.js +120 -0
  9. package/lib/client/card.js +220 -0
  10. package/lib/client/command-row.js +76 -0
  11. package/lib/client/config-page.js +392 -0
  12. package/lib/client/definition.js +164 -0
  13. package/lib/client/index.js +129 -0
  14. package/lib/client/locales.js +156 -0
  15. package/lib/client/mode-picker.js +77 -0
  16. package/lib/client/styles.js +283 -0
  17. package/lib/client.js +1691 -0
  18. package/lib/coding-projection.js +349 -0
  19. package/lib/config.js +204 -0
  20. package/lib/contract.js +124 -0
  21. package/lib/editor.js +23 -0
  22. package/lib/failures.js +142 -0
  23. package/lib/handoff.js +312 -0
  24. package/lib/index.js +115 -0
  25. package/lib/language.js +136 -0
  26. package/lib/messages.js +43 -0
  27. package/lib/models.js +154 -0
  28. package/lib/patch.js +235 -0
  29. package/lib/preset.js +1488 -0
  30. package/lib/reasoning-levels.js +28 -0
  31. package/lib/reasoning-projection.js +178 -0
  32. package/lib/reasoning.js +585 -0
  33. package/lib/stages.js +306 -0
  34. package/lib/state.js +550 -0
  35. package/lib/system-language.js +56 -0
  36. package/lib/types/apply-patch.d.ts +13 -0
  37. package/lib/types/client/capsule.d.ts +9 -0
  38. package/lib/types/client/card.d.ts +72 -0
  39. package/lib/types/client/command-row.d.ts +42 -0
  40. package/lib/types/client/config-page.d.ts +136 -0
  41. package/lib/types/client/definition.d.ts +51 -0
  42. package/lib/types/client/index.d.ts +10 -0
  43. package/lib/types/client/locales.d.ts +18 -0
  44. package/lib/types/client/mode-picker.d.ts +25 -0
  45. package/lib/types/client/styles.d.ts +28 -0
  46. package/lib/types/coding-projection.d.ts +116 -0
  47. package/lib/types/config.d.ts +193 -0
  48. package/lib/types/contract.d.ts +33 -0
  49. package/lib/types/editor.d.ts +9 -0
  50. package/lib/types/failures.d.ts +62 -0
  51. package/lib/types/handoff.d.ts +112 -0
  52. package/lib/types/index.d.ts +144 -0
  53. package/lib/types/language.d.ts +56 -0
  54. package/lib/types/messages.d.ts +27 -0
  55. package/lib/types/models.d.ts +82 -0
  56. package/lib/types/patch.d.ts +37 -0
  57. package/lib/types/preset.d.ts +22 -0
  58. package/lib/types/reasoning-levels.d.ts +20 -0
  59. package/lib/types/reasoning-projection.d.ts +64 -0
  60. package/lib/types/reasoning.d.ts +141 -0
  61. package/lib/types/stages.d.ts +164 -0
  62. package/lib/types/state.d.ts +261 -0
  63. package/lib/types/system-language.d.ts +10 -0
  64. package/lib/types/verification-tool.d.ts +32 -0
  65. package/lib/types/verification.d.ts +77 -0
  66. package/lib/types/verifier.d.ts +9 -0
  67. package/lib/types/volatile.d.ts +17 -0
  68. package/lib/verification-tool.js +176 -0
  69. package/lib/verification.js +337 -0
  70. package/lib/verifier.js +25 -0
  71. package/lib/volatile.js +20 -0
  72. package/locale/en.json +7 -0
  73. package/locale/zh.json +7 -0
  74. package/package.json +129 -3
@@ -0,0 +1,349 @@
1
+ import { STAGES_BY_MODE, asCheckpoint, asStage, entryStage, isCodingTool, stageInMode, } from './stages.js';
2
+ /** Projection key shared by the Host fold and every client reader. */
3
+ export const CODING_PROJECTION_KEY = 'dshCodingStage';
4
+ /** Preset id this bundle declares in `cordis.patch.yml`. */
5
+ export const CODING_PRESET_ID = 'dsh-coding';
6
+ /** How many closed turns one projection keeps; older cards fall back to live state. */
7
+ const MAX_TURNS = 60;
8
+ /** Whether a session header names this bundle's user-facing preset. */
9
+ export function isCodingSession(header) {
10
+ return header?.agentPreset === CODING_PRESET_ID
11
+ && (typeof header.delegationDepth === 'number' ? header.delegationDepth : 0) === 0;
12
+ }
13
+ /** Projection value before any event is folded. */
14
+ export function initialView(defaultMode) {
15
+ return {
16
+ active: false,
17
+ mode: defaultMode,
18
+ stage: entryStage(defaultMode),
19
+ allowedStages: STAGES_BY_MODE[defaultMode],
20
+ planItems: 0,
21
+ openPlanItems: 0,
22
+ edits: 0,
23
+ verification: null,
24
+ checkpoint: null,
25
+ plan: [],
26
+ pending: null,
27
+ latest: 0,
28
+ turns: [],
29
+ updatedAt: 0,
30
+ };
31
+ }
32
+ /** Reduced verification evidence, or null. */
33
+ function verificationOf(value) {
34
+ if (typeof value !== 'object' || value === null)
35
+ return null;
36
+ const v = value;
37
+ if (typeof v['passed'] !== 'boolean')
38
+ return null;
39
+ return {
40
+ passed: v['passed'],
41
+ kind: typeof v['kind'] === 'string' ? v['kind'] : '',
42
+ scope: typeof v['scope'] === 'string' ? v['scope'] : '',
43
+ command: typeof v['command'] === 'string' ? v['command'] : '',
44
+ failedTests: Array.isArray(v['failedTests'])
45
+ ? v['failedTests'].filter((item) => typeof item === 'string')
46
+ : [],
47
+ ranAt: typeof v['ranAt'] === 'number' ? v['ranAt'] : 0,
48
+ };
49
+ }
50
+ /** The stage or mode a Coding tool call is asking for, for the pending label. */
51
+ function requestedOf(tool, raw) {
52
+ if (typeof raw !== 'string')
53
+ return null;
54
+ let parsed;
55
+ try {
56
+ const value = JSON.parse(raw);
57
+ if (typeof value !== 'object' || value === null)
58
+ return null;
59
+ parsed = value;
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ for (const key of ['stage', 'mode', 'kind']) {
65
+ const candidate = parsed[key];
66
+ if (typeof candidate === 'string' && candidate !== '')
67
+ return candidate;
68
+ }
69
+ return null;
70
+ }
71
+ /** A mode value, when the checkpoint or command args name one. */
72
+ function modeOf(value) {
73
+ return value === 'auto' || value === 'consult' || value === 'review' || value === 'codex' ? value : undefined;
74
+ }
75
+ /** A stage value, when the command args name one. */
76
+ function stageOf(value) {
77
+ return asStage(value);
78
+ }
79
+ /** One task-list status value, or undefined when the event did not record one. */
80
+ function planStatusOf(item) {
81
+ const status = item.status;
82
+ return status === 'pending' || status === 'in_progress' || status === 'completed' ? status : undefined;
83
+ }
84
+ /**
85
+ * Fold one committed Session event into the projection.
86
+ * @param state - value covering every earlier event.
87
+ * @param event - next committed event.
88
+ * @param defaultMode - configured mode, used when a session switches preset mid-flight.
89
+ * @returns the next value; the same reference when the event is unrelated.
90
+ */
91
+ export function applyEvent(state, event, defaultMode) {
92
+ const data = event.data;
93
+ switch (event.type) {
94
+ case 'agent-preset/selected': {
95
+ if (typeof data?.agentPreset !== 'string')
96
+ return state;
97
+ const active = data.agentPreset === CODING_PRESET_ID;
98
+ if (active === state.active)
99
+ return state;
100
+ if (!active)
101
+ return { ...state, active: false };
102
+ // Joining the preset mid-session: reset to the configured entry state.
103
+ return {
104
+ ...state,
105
+ active: true,
106
+ mode: defaultMode,
107
+ stage: entryStage(defaultMode),
108
+ allowedStages: STAGES_BY_MODE[defaultMode],
109
+ checkpoint: null,
110
+ plan: [],
111
+ planItems: 0,
112
+ openPlanItems: 0,
113
+ edits: 0,
114
+ verification: null,
115
+ pending: null,
116
+ };
117
+ }
118
+ case 'tool/call': {
119
+ const name = data?.name;
120
+ if (typeof name !== 'string' || !isCodingTool(name))
121
+ return state;
122
+ return {
123
+ ...state,
124
+ pending: {
125
+ tool: name,
126
+ requested: requestedOf(name, data?.arguments),
127
+ callId: typeof data?.callId === 'string' ? data.callId : null,
128
+ },
129
+ updatedAt: typeof event.time === 'number' ? event.time : state.updatedAt,
130
+ };
131
+ }
132
+ case 'tool/result': {
133
+ // A checkpoint is whole-value, so it is adopted even when the matching
134
+ // `tool/call` sits before the loaded window (history paging) or the fold
135
+ // resumed from a persisted cache.
136
+ const checkpoint = asCheckpoint(data?.meta);
137
+ const sameCall = state.pending !== null
138
+ && (state.pending.callId === null
139
+ || state.pending.callId === data?.message?.toolCallId);
140
+ if (checkpoint === undefined) {
141
+ return sameCall ? { ...state, pending: null } : state;
142
+ }
143
+ return {
144
+ ...state,
145
+ mode: checkpoint.mode,
146
+ stage: checkpoint.stage,
147
+ allowedStages: checkpoint.allowedStages,
148
+ planItems: checkpoint.planItems,
149
+ openPlanItems: checkpoint.openPlanItems,
150
+ edits: checkpoint.edits,
151
+ verification: verificationOf(checkpoint.verification),
152
+ checkpoint,
153
+ pending: sameCall || state.pending === null ? null : state.pending,
154
+ updatedAt: checkpoint.updatedAt,
155
+ };
156
+ }
157
+ case 'command/run': {
158
+ if (data?.name !== 'coding')
159
+ return state;
160
+ const args = typeof data?.args === 'string' ? data.args.trim().toLowerCase() : '';
161
+ const [head, ...rest] = args.split(/\s+/u);
162
+ if (head === 'stage') {
163
+ const target = stageOf(rest.join(' '));
164
+ // A stage the mode does not open was refused by the live gate; folding
165
+ // the requested value would make the card show a stage that never ran.
166
+ if (target === undefined || !stageInMode(state.mode, target))
167
+ return state;
168
+ return { ...state, stage: target };
169
+ }
170
+ // `/coding set <mode>` is the silent pre-Turn picker path; `/coding <mode>`
171
+ // is the Turn-scoped switch. Both move the same card state.
172
+ if (head === 'set') {
173
+ const mode = modeOf(rest.join(' '));
174
+ if (mode === undefined)
175
+ return state;
176
+ return {
177
+ ...state,
178
+ mode,
179
+ stage: stageInMode(mode, state.stage) ? state.stage : entryStage(mode),
180
+ allowedStages: STAGES_BY_MODE[mode],
181
+ };
182
+ }
183
+ const mode = modeOf(head);
184
+ if (mode === undefined)
185
+ return state;
186
+ return {
187
+ ...state,
188
+ mode,
189
+ stage: stageInMode(mode, state.stage) ? state.stage : entryStage(mode),
190
+ allowedStages: STAGES_BY_MODE[mode],
191
+ };
192
+ }
193
+ case 'todo/write': {
194
+ const todos = data?.todos;
195
+ if (!Array.isArray(todos))
196
+ return state;
197
+ const plan = [];
198
+ for (const item of todos) {
199
+ if (typeof item !== 'object' || item === null)
200
+ continue;
201
+ const content = item.content;
202
+ const status = planStatusOf(item);
203
+ if (typeof content === 'string' && status !== undefined)
204
+ plan.push({ content, status });
205
+ }
206
+ return {
207
+ ...state,
208
+ plan,
209
+ planItems: plan.length,
210
+ openPlanItems: plan.filter(item => item.status !== 'completed').length,
211
+ updatedAt: typeof event.time === 'number' ? event.time : state.updatedAt,
212
+ };
213
+ }
214
+ case 'turn/start': {
215
+ // A new turn means no earlier call can still be running.
216
+ return state.pending === null ? state : { ...state, pending: null };
217
+ }
218
+ case 'turn/end': {
219
+ const turn = data?.turn;
220
+ if (typeof turn !== 'number' || !Number.isFinite(turn))
221
+ return state;
222
+ const latest = Math.max(state.latest, turn);
223
+ const frozen = {
224
+ turn,
225
+ mode: state.mode,
226
+ stage: state.stage,
227
+ verification: state.verification,
228
+ planItems: state.planItems,
229
+ openPlanItems: state.openPlanItems,
230
+ edits: state.edits,
231
+ };
232
+ const turns = [...state.turns.filter(item => item.turn !== turn), frozen].slice(-MAX_TURNS);
233
+ return { ...state, latest, turns, pending: null };
234
+ }
235
+ default:
236
+ return state;
237
+ }
238
+ }
239
+ /** Throw a helpful error for a value that cannot be a projection state. */
240
+ function invalid(what) {
241
+ throw new Error(`dsh-coding: ${what} is not a Coding stage projection value`);
242
+ }
243
+ /** Validate one persisted or wire value as {@link CodingStageView}. */
244
+ export function parseView(value) {
245
+ if (typeof value !== 'object' || value === null)
246
+ invalid('state');
247
+ const v = value;
248
+ if (typeof v['active'] !== 'boolean')
249
+ invalid('active');
250
+ const mode = modeOf(v['mode']) ?? invalid('mode');
251
+ const stage = stageOf(v['stage']) ?? invalid('stage');
252
+ if (!Array.isArray(v['allowedStages']))
253
+ invalid('allowedStages');
254
+ if (!Array.isArray(v['turns']))
255
+ invalid('turns');
256
+ const numeric = ['planItems', 'openPlanItems', 'edits', 'latest', 'updatedAt'];
257
+ for (const key of numeric)
258
+ if (typeof v[key] !== 'number')
259
+ invalid(key);
260
+ return {
261
+ active: v['active'],
262
+ mode,
263
+ stage,
264
+ allowedStages: v['allowedStages'].map(item => stageOf(item) ?? invalid('allowedStages')),
265
+ planItems: v['planItems'],
266
+ openPlanItems: v['openPlanItems'],
267
+ edits: v['edits'],
268
+ verification: verificationOf(v['verification']),
269
+ checkpoint: asCheckpoint(v['checkpoint']) ?? null,
270
+ plan: (Array.isArray(v['plan']) ? v['plan'] : []).map((item) => {
271
+ if (typeof item !== 'object' || item === null)
272
+ invalid('plan');
273
+ const entry = item;
274
+ const status = planStatusOf(entry) ?? invalid('plan.status');
275
+ const content = entry['content'];
276
+ if (typeof content !== 'string')
277
+ invalid('plan.content');
278
+ return { content, status };
279
+ }),
280
+ pending: pendingOf(v['pending']),
281
+ latest: v['latest'],
282
+ updatedAt: v['updatedAt'],
283
+ turns: v['turns'].map((item) => {
284
+ if (typeof item !== 'object' || item === null)
285
+ invalid('turns');
286
+ const turn = item;
287
+ return {
288
+ turn: typeof turn['turn'] === 'number' ? turn['turn'] : invalid('turns.turn'),
289
+ mode: modeOf(turn['mode']) ?? invalid('turns.mode'),
290
+ stage: stageOf(turn['stage']) ?? invalid('turns.stage'),
291
+ planItems: typeof turn['planItems'] === 'number' ? turn['planItems'] : invalid('turns.planItems'),
292
+ openPlanItems: typeof turn['openPlanItems'] === 'number' ? turn['openPlanItems'] : invalid('turns.openPlanItems'),
293
+ edits: typeof turn['edits'] === 'number' ? turn['edits'] : invalid('turns.edits'),
294
+ verification: verificationOf(turn['verification']),
295
+ };
296
+ }),
297
+ };
298
+ }
299
+ /** Validate a pending label, or null. */
300
+ function pendingOf(value) {
301
+ if (value === null || value === undefined)
302
+ return null;
303
+ if (typeof value !== 'object')
304
+ invalid('pending');
305
+ const pending = value;
306
+ if (typeof pending['tool'] !== 'string')
307
+ invalid('pending.tool');
308
+ return {
309
+ tool: pending['tool'],
310
+ requested: typeof pending['requested'] === 'string' ? pending['requested'] : null,
311
+ callId: typeof pending['callId'] === 'string' ? pending['callId'] : null,
312
+ };
313
+ }
314
+ /**
315
+ * Build the registrable projection definition.
316
+ *
317
+ * `defaultMode` is read lazily: the projection is folded during Session opens
318
+ * that can happen long after mount, and a page edit must apply to the next one.
319
+ *
320
+ * @param defaultMode - configured initial mode for a Coding session.
321
+ * @returns definition object accepted by `ctx.sessionProjections.register`.
322
+ */
323
+ export function codingProjection(defaultMode) {
324
+ const mode = () => modeOf(defaultMode()) ?? 'auto';
325
+ return {
326
+ key: CODING_PROJECTION_KEY,
327
+ // Bump when the fold's meaning changes: the persisted cache replays the
328
+ // suffix on top of a validated state, so an old checkpoint must be dropped.
329
+ // v2 added the whole-value checkpoint and the task-list snapshot a resume reads.
330
+ // v3 freezes plan progress and the edit total in every turn snapshot, so an
331
+ // old cache must be rebuilt or a history card cannot read those fields.
332
+ // v4 renames the first stage `recon` → `requirements`; legacy persisted values
333
+ // still parse through asStage, but the cache is rebuilt to drop the old id.
334
+ stateVersion: 4,
335
+ stateSchema: { parse: parseView },
336
+ init: (header) => ({
337
+ ...initialView(mode()),
338
+ active: isCodingSession(header),
339
+ }),
340
+ apply: (state, event) => applyEvent(state, event, mode()),
341
+ wire: {
342
+ viewSchema: { parse: parseView },
343
+ view: state => state,
344
+ // The tuple of closed turns is per-session detail; keeping it out of
345
+ // summaries avoids copying it into every Session-list row.
346
+ summary: false,
347
+ },
348
+ };
349
+ }
package/lib/config.js ADDED
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Configuration contract of the `dsh-coding` bundle.
3
+ *
4
+ * The same contract is stated three ways on purpose: {@link CodingConfig} for
5
+ * TypeScript, {@link Config} (Schemastery) for the Loader's activation-time
6
+ * validation, and {@link configJsonSchema} for non-Loader consumers such as the
7
+ * plugin page and the tests. `normalizeConfig` adds the checks a schema cannot
8
+ * state — in particular that a worker model names a real `provider/model`
9
+ * route, because a silent fall-back to the lead's own model is the one outcome
10
+ * this plugin must never allow.
11
+ *
12
+ * @module dsh-coding/config
13
+ */
14
+ import z from '@deepseek-ai/schemastery';
15
+ import { CODING_MODES } from './stages.js';
16
+ import { LANGUAGE_MODES, normalizeLanguageMode } from './language.js';
17
+ import { volatileValue } from './volatile.js';
18
+ export { volatileValue };
19
+ /** Reasoning-level policies the plugin accepts. */
20
+ export const REASONING_MODES = ['auto', 'low', 'high', 'max'];
21
+ /** Schemastery schema the Loader validates the bundle row's `config` with. */
22
+ export const Config = z.object({
23
+ // Volatile: the plugin manager page edits these in place, and the runtime
24
+ // reads the live value on every stage decision and dispatch.
25
+ defaultMode: z.union(CODING_MODES).default('auto').volatile(),
26
+ implementWorkerModel: z.string().required().volatile(),
27
+ verifyWorkerModel: z.string().required().volatile(),
28
+ plannerWorkerModel: z.string().required().volatile(),
29
+ // Volatile: the plugin page switches the conversation language in place, and
30
+ // the prompt reads the live value at assembly time.
31
+ language: z.union(LANGUAGE_MODES).default('auto').volatile(),
32
+ // Volatile: the plugin page switches the level in place, and every stage's
33
+ // reasoning decision reads the live value.
34
+ reasoning: z.union(REASONING_MODES).default('auto').volatile(),
35
+ // Retry budgets of the verify loop; a blocked delivery is the exit that keeps
36
+ // a failing run from looping. Change them in the bundle's patch config.
37
+ maxVerifyAttempts: z.natural().default(5),
38
+ maxSameFailure: z.natural().default(2),
39
+ // Hard deadline of one verification command (six minutes by default), so a
40
+ // hanging test script is terminated instead of awaited forever.
41
+ verificationTimeoutMs: z.natural().default(360000),
42
+ // A record has no volatile form; change it in the bundle's patch config.
43
+ verificationCommands: z.dict(z.string()).default({}),
44
+ });
45
+ /** The same contract as plain JSON Schema, for consumers that never load the plugin. */
46
+ export const configJsonSchema = {
47
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
48
+ title: 'dsh-coding configuration',
49
+ type: 'object',
50
+ additionalProperties: false,
51
+ required: ['implementWorkerModel', 'verifyWorkerModel', 'plannerWorkerModel'],
52
+ properties: {
53
+ defaultMode: {
54
+ type: 'string',
55
+ enum: [...CODING_MODES],
56
+ default: 'auto',
57
+ description: 'Mode a new Coding session starts in.',
58
+ },
59
+ implementWorkerModel: {
60
+ type: 'string',
61
+ pattern: '^[^/\\s]+/[^/\\s]+$',
62
+ description: 'provider/model route for the implement worker; never inherited from the lead.',
63
+ },
64
+ verifyWorkerModel: {
65
+ type: 'string',
66
+ pattern: '^[^/\\s]+/[^/\\s]+$',
67
+ description: 'provider/model route for the verify worker; never inherited from the lead.',
68
+ },
69
+ plannerWorkerModel: {
70
+ type: 'string',
71
+ pattern: '^[^/\\s]+/[^/\\s]+$',
72
+ description: 'provider/model route for the planner worker (pro model); never inherited from the lead.',
73
+ },
74
+ language: {
75
+ type: 'string',
76
+ enum: [...LANGUAGE_MODES],
77
+ default: 'auto',
78
+ description: 'Conversation language: auto follows the DSH interface, then the host locale.',
79
+ },
80
+ reasoning: {
81
+ type: 'string',
82
+ enum: [...REASONING_MODES],
83
+ default: 'auto',
84
+ description: 'Reasoning level: auto classifies each turn; low, high, and max pin every turn.',
85
+ },
86
+ maxVerifyAttempts: {
87
+ type: 'integer',
88
+ minimum: 0,
89
+ default: 5,
90
+ description: 'Failed verifications allowed before the run delivers blocked; 0 means no limit.',
91
+ },
92
+ maxSameFailure: {
93
+ type: 'integer',
94
+ minimum: 0,
95
+ default: 2,
96
+ description: 'Repeats of the identical failure allowed before delivering blocked; 0 means no limit.',
97
+ },
98
+ verificationTimeoutMs: {
99
+ type: 'integer',
100
+ minimum: 0,
101
+ default: 360000,
102
+ description: 'Longest running time of one verification command in ms; a timeout counts as a failed verification; 0 means no limit.',
103
+ },
104
+ verificationCommands: {
105
+ type: 'object',
106
+ additionalProperties: { type: 'string' },
107
+ default: {},
108
+ description: 'Verification command overrides keyed by kind or kind:scope.',
109
+ },
110
+ },
111
+ };
112
+ /** The verification kinds `run_verification` accepts. */
113
+ export const VERIFICATION_KINDS = ['test', 'build', 'lint', 'typecheck'];
114
+ /** The verification scopes `run_verification` accepts. */
115
+ export const VERIFICATION_SCOPES = ['targeted', 'package', 'full'];
116
+ /**
117
+ * Parse a `provider/model` route. Both halves are required: an omitted provider
118
+ * would let the request silently inherit the lead's route, which is exactly the
119
+ * fall-back the plugin refuses.
120
+ * @param raw - configured route text.
121
+ * @param field - configuration field name, for an actionable failure.
122
+ * @returns the split route.
123
+ * @throws when the value is not exactly `provider/model`.
124
+ */
125
+ export function parseWorkerRoute(raw, field) {
126
+ const text = typeof raw === 'string' ? raw.trim() : '';
127
+ if (text === '') {
128
+ throw new Error(`dsh-coding: ${field} is required and must be a "provider/model" route `
129
+ + '(for example "deepseek-account/deepseek-flash"); the worker never inherits the lead\'s model');
130
+ }
131
+ const match = /^([^/\s]+)\/([^/\s]+)$/u.exec(text);
132
+ if (match === null) {
133
+ throw new Error(`dsh-coding: ${field} must be "provider/model" (got ${JSON.stringify(text)}); `
134
+ + 'the worker never inherits the lead\'s model');
135
+ }
136
+ return { provider: match[1], model: match[2] };
137
+ }
138
+ /**
139
+ * Verify a decoded (or directly applied) configuration and fill the defaults a
140
+ * direct `apply()` call would otherwise miss.
141
+ * @param raw - Loader-validated config, or a hand-authored object in tests.
142
+ * @returns the verified configuration.
143
+ * @throws when a worker route is absent or malformed.
144
+ */
145
+ export function normalizeConfig(raw) {
146
+ const mode = volatileValue(raw?.defaultMode);
147
+ const maxVerifyAttempts = volatileValue(raw?.maxVerifyAttempts);
148
+ const maxSameFailure = volatileValue(raw?.maxSameFailure);
149
+ const verificationTimeoutMs = volatileValue(raw?.verificationTimeoutMs);
150
+ const commands = volatileValue(raw?.verificationCommands);
151
+ const clean = {};
152
+ if (typeof commands === 'object' && commands !== null) {
153
+ for (const [key, value] of Object.entries(commands)) {
154
+ if (typeof value === 'string' && value.trim() !== '')
155
+ clean[key] = value;
156
+ }
157
+ }
158
+ const implementWorkerModel = volatileValue(raw?.implementWorkerModel);
159
+ const verifyWorkerModel = volatileValue(raw?.verifyWorkerModel);
160
+ const plannerWorkerModel = volatileValue(raw?.plannerWorkerModel);
161
+ const language = volatileValue(raw?.language);
162
+ const reasoning = volatileValue(raw?.reasoning);
163
+ // Parse eagerly so a malformed route fails activation, not the first dispatch.
164
+ parseWorkerRoute(implementWorkerModel, 'implementWorkerModel');
165
+ parseWorkerRoute(verifyWorkerModel, 'verifyWorkerModel');
166
+ parseWorkerRoute(plannerWorkerModel, 'plannerWorkerModel');
167
+ return {
168
+ defaultMode: mode !== undefined && CODING_MODES.includes(mode) ? mode : 'auto',
169
+ implementWorkerModel: String(implementWorkerModel).trim(),
170
+ verifyWorkerModel: String(verifyWorkerModel).trim(),
171
+ plannerWorkerModel: String(plannerWorkerModel).trim(),
172
+ language: normalizeLanguageMode(language),
173
+ reasoning: REASONING_MODES.includes(reasoning)
174
+ ? reasoning
175
+ : 'auto',
176
+ maxVerifyAttempts: retryBudget(maxVerifyAttempts, 5),
177
+ maxSameFailure: retryBudget(maxSameFailure, 2),
178
+ verificationTimeoutMs: retryBudget(verificationTimeoutMs, 360000),
179
+ verificationCommands: clean,
180
+ };
181
+ }
182
+ /**
183
+ * Read one non-negative integer setting (a retry budget or a timeout): the
184
+ * value when it is a non-negative integer, the default otherwise.
185
+ * @param value - decoded configuration value.
186
+ * @param fallback - default used when the value is absent or out of range.
187
+ * @returns the budget or timeout, where `0` means unlimited.
188
+ */
189
+ function retryBudget(value, fallback) {
190
+ return Number.isInteger(value) && value >= 0 ? value : fallback;
191
+ }
192
+ /**
193
+ * Pick the configured command for a verification request.
194
+ * @param config - verified configuration.
195
+ * @param kind - requested kind.
196
+ * @param scope - requested scope.
197
+ * @returns the most specific configured command, when one exists.
198
+ */
199
+ export function configuredCommand(config, kind, scope) {
200
+ const scoped = config.verificationCommands[`${kind}:${scope}`];
201
+ if (scoped !== undefined)
202
+ return scoped;
203
+ return config.verificationCommands[kind];
204
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The delivery contract, split into the stage that owns each rule.
3
+ *
4
+ * Nothing here is a global system prompt: one fragment is injected as
5
+ * per-step context for the stage actually in force, so the model reads the rule
6
+ * it can act on now. That also keeps a long session from carrying every rule of
7
+ * every stage in its system prompt.
8
+ *
9
+ * @module dsh-coding/contract
10
+ */
11
+ import { stagePath } from './stages.js';
12
+ /** One paragraph per mode, injected with every stage fragment. */
13
+ export const MODE_CONTRACT = {
14
+ auto: 'Mode `auto`: the requirements stage decides the workflow for this request. Understand what the user is '
15
+ + 'asking and inspect enough of the project to classify it: a question, explanation, or advice → `consult` '
16
+ + '(also the fallback when the request is unclear or you are unsure); a review of existing behavior → '
17
+ + '`review`; a change to the codebase → `codex`. Do not over-interpret the request, widen its scope, or '
18
+ + 'design beyond it. State the chosen workflow in one line, call `coding_mode` with that mode, then follow '
19
+ + 'the chosen mode\'s stages and rules. Auto opens only requirements; `coding_stage` cannot advance until '
20
+ + 'a mode is chosen.',
21
+ consult: 'Mode `consult` (Q&A): answer the question directly. Give 1-3 options with tradeoffs, one '
22
+ + 'recommendation, a short plan, and the decision you need from the user. Do not edit files, run '
23
+ + 'tests, or create a todo list unless the user asks for implementation.',
24
+ review: 'Mode `review`: report concrete findings with `file:line` and a reproducible scenario, ordered by '
25
+ + 'impact. Do not edit files unless the user explicitly asks for a fix; use the verify stage to '
26
+ + 'check the claims you make.',
27
+ codex: 'Mode `codex`: inspect, plan the work, delegate the edit to the implement worker, verify the result, '
28
+ + 'then deliver. The runtime enforces this order; a skipped gate is refused. The handoff recorded in '
29
+ + 'requirements is the context every worker receives; keep it current instead of repeating history.',
30
+ };
31
+ /** The rule set owned by each stage. */
32
+ export const STAGE_CONTRACT = {
33
+ requirements: [
34
+ '### requirements — analyse the request and the ground truth',
35
+ '- Read every applicable `AGENTS.md`, then the files the task touches. Never rely on remembered code.',
36
+ '- Name the request before deciding: what the user wants, the deliverable, and the constraints. Ask only '
37
+ + 'when a wrong guess would waste real work; otherwise record the assumption and keep moving.',
38
+ '- Note the project state that matters to this request: entry points, existing patterns, the package '
39
+ + 'manager, and the narrowest check that will prove the work.',
40
+ '- Use `read`, `grep`, and `glob`; one inspection command is fine. Do not edit, plan, or verify yet.',
41
+ '- Record the handoff with `coding_handoff({ goal, constraints, acceptance })` before advancing: codex '
42
+ + 'cannot enter plan without a goal, and the planner only sees this text.',
43
+ '- Advance with `coding_stage({"stage":"plan"})` once you can name the affected files; in `auto` mode, '
44
+ + 'choose the workflow with `coding_mode` first.',
45
+ ].join('\n'),
46
+ plan: [
47
+ '### plan — define done',
48
+ '- Record what requirements established in the handoff: what the user asked for (goal, deliverable, '
49
+ + 'constraints) and what the project actually looks like (entry points, patterns, checks). If either is '
50
+ + 'missing, inspect now instead of guessing; a fact that stays in the conversation never reaches a worker.',
51
+ '- Call `delegate_plan` when the work is more than a one-file edit: it explores read-only and returns '
52
+ + 'single-purpose sub-tasks. For each task settle the boundary and handoff first: goal, files in scope, '
53
+ + 'acceptance check, and what it must not touch. Order tasks so each depends only on earlier ones.',
54
+ '- Every todo item and every planner task must name an observable acceptance check; record the definition '
55
+ + 'of done with `coding_handoff({ acceptance: [...] })`. codex cannot enter verify without it.',
56
+ '- Call `todo_write` with one verifiable item per task (3-6) and exactly one `in_progress`. Keep each '
57
+ + 'implement brief self-contained so the worker\'s context and tokens stay bounded.',
58
+ '- Choose the smallest approach: reuse existing functions, types, and patterns. Add no abstraction, '
59
+ + 'dependency, or drive-by refactor the task does not need.',
60
+ '- `coding_stage` refuses `implement` until the list is written.',
61
+ ].join('\n'),
62
+ implement: [
63
+ '### implement — delegate the edit',
64
+ '- You cannot edit files in this stage: `apply_patch`, `edit`, and `write` are not in your tool table.',
65
+ '- Call `delegate_implement` with a self-contained task: goal, acceptance criteria, exact files, and '
66
+ + 'the excerpts the worker needs. The worker has a fresh context and only the editing tools.',
67
+ '- Pass the handoff\'s goal, constraints, and the current task\'s acceptance into the brief; do not make '
68
+ + 'the worker re-derive them.',
69
+ '- The worker returns a structured report (files, summary, notes). The runtime counts only reported '
70
+ + 'edits toward the verify gate; you can inspect the files yourself in the verify stage.',
71
+ '- One worker call per coherent change; split unrelated changes instead of batching them.',
72
+ ].join('\n'),
73
+ verify: [
74
+ '### verify — prove it',
75
+ '- Run the narrowest check first: `run_verification` with `scope:"targeted"`, then `package`, then '
76
+ + '`full` when the change reaches across packages.',
77
+ '- A behavior change needs a test that would have failed before it. `delegate_verify` investigates a '
78
+ + 'failure without editing.',
79
+ '- A task without an acceptance check cannot enter verify; record it with `coding_handoff` first.',
80
+ '- The runtime caps fix/verify retries (`maxVerifyAttempts` / `maxSameFailure`). When the budget is '
81
+ + 'exhausted, stop: advance to deliver and report a BLOCKED delivery naming the failing check, or ask the user.',
82
+ '- Keep the task list current: mark a finished check completed with `todo_write`; the deliver gate '
83
+ + 'reads recorded evidence, not the list.',
84
+ '- A failing check means: go back to implement, fix it, verify again. The deliver gate reads the '
85
+ + 'recorded verification result, so an unrun or failed check cannot be talked past.',
86
+ ].join('\n'),
87
+ deliver: [
88
+ '### deliver — report compactly',
89
+ '- Close the task list first: mark the finished items completed with `todo_write`, so no step stays '
90
+ + 'in_progress after delivery.',
91
+ '- Lead with the outcome: what changed and why. Then the files touched as backticked paths, the '
92
+ + 'verification evidence (command and result), and residual risk.',
93
+ '- If the last check failed and the retry budget is exhausted, this is a BLOCKED delivery: state the '
94
+ + 'failing check, command, exit code, and last error; never claim success.',
95
+ '- Do not dump diffs, logs, or large files; refer to paths. No step-by-step narration.',
96
+ '- If something could not be verified, say what and why. Never report a passing check you did not run.',
97
+ ].join('\n'),
98
+ };
99
+ /** One-line communication rule shared by every stage. */
100
+ export const COMMUNICATION_RULE = 'Send at most one short sentence before a group of tool calls, and only when it helps. Do not narrate '
101
+ + 'deliberation or restate tool output.';
102
+ /**
103
+ * Render the per-step context message. Kept terse: it rides in every request of
104
+ * the session, so each line must earn its tokens.
105
+ * @param input - mode, stage, and the rendered status line.
106
+ * @returns the injected context text.
107
+ */
108
+ export function stageContext(input) {
109
+ const lines = [
110
+ '## dsh-coding runtime (enforced by the plugin, not advice)',
111
+ `${MODE_CONTRACT[input.mode]}`,
112
+ `Stage path for this mode: ${stagePath(input.mode)}. Current stage: **${input.stage}**.`,
113
+ `Status: ${input.status}`,
114
+ ...input.handoff === undefined || input.handoff === ''
115
+ ? []
116
+ : ['', '## Handoff (recorded by earlier stages)', input.handoff],
117
+ ...input.rejection === undefined ? [] : [`The last stage advance was refused: ${input.rejection}`],
118
+ '',
119
+ STAGE_CONTRACT[input.stage],
120
+ '',
121
+ COMMUNICATION_RULE,
122
+ ];
123
+ return lines.join('\n');
124
+ }