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.
Files changed (78) hide show
  1. package/AGENTS.md +80 -0
  2. package/LICENSE +21 -21
  3. package/README.md +120 -54
  4. package/cordis.patch.yml +274 -4
  5. package/docs/CHANGELOG.md +47 -0
  6. package/docs/DETAIL.md +272 -0
  7. package/icon.svg +6 -6
  8. package/lib/apply-patch.js +268 -0
  9. package/lib/client/capsule.js +120 -0
  10. package/lib/client/card.js +308 -0
  11. package/lib/client/command-row.js +76 -0
  12. package/lib/client/config-page.js +392 -0
  13. package/lib/client/definition.js +164 -0
  14. package/lib/client/index.js +129 -0
  15. package/lib/client/locales.js +170 -0
  16. package/lib/client/mode-picker.js +77 -0
  17. package/lib/client/styles.js +283 -0
  18. package/lib/client.js +1802 -0
  19. package/lib/coding-projection.js +349 -0
  20. package/lib/config.js +218 -0
  21. package/lib/contract.js +138 -0
  22. package/lib/editor.js +23 -0
  23. package/lib/failures.js +142 -0
  24. package/lib/handoff.js +347 -0
  25. package/lib/index.js +110 -7
  26. package/lib/language.js +136 -0
  27. package/lib/memory.js +336 -0
  28. package/lib/messages.js +43 -0
  29. package/lib/models.js +154 -0
  30. package/lib/patch.js +235 -0
  31. package/lib/preset.js +1552 -0
  32. package/lib/reasoning-levels.js +28 -0
  33. package/lib/reasoning-projection.js +178 -0
  34. package/lib/reasoning.js +585 -0
  35. package/lib/stages.js +344 -0
  36. package/lib/state.js +585 -0
  37. package/lib/system-language.js +56 -0
  38. package/lib/types/apply-patch.d.ts +13 -0
  39. package/lib/types/client/capsule.d.ts +9 -0
  40. package/lib/types/client/card.d.ts +76 -0
  41. package/lib/types/client/command-row.d.ts +42 -0
  42. package/lib/types/client/config-page.d.ts +136 -0
  43. package/lib/types/client/definition.d.ts +51 -0
  44. package/lib/types/client/index.d.ts +10 -0
  45. package/lib/types/client/locales.d.ts +18 -0
  46. package/lib/types/client/mode-picker.d.ts +25 -0
  47. package/lib/types/client/styles.d.ts +28 -0
  48. package/lib/types/coding-projection.d.ts +116 -0
  49. package/lib/types/config.d.ts +208 -0
  50. package/lib/types/contract.d.ts +33 -0
  51. package/lib/types/editor.d.ts +9 -0
  52. package/lib/types/failures.d.ts +62 -0
  53. package/lib/types/handoff.d.ts +132 -0
  54. package/lib/types/index.d.ts +150 -0
  55. package/lib/types/language.d.ts +56 -0
  56. package/lib/types/memory.d.ts +71 -0
  57. package/lib/types/messages.d.ts +27 -0
  58. package/lib/types/models.d.ts +82 -0
  59. package/lib/types/patch.d.ts +37 -0
  60. package/lib/types/preset.d.ts +22 -0
  61. package/lib/types/reasoning-levels.d.ts +20 -0
  62. package/lib/types/reasoning-projection.d.ts +64 -0
  63. package/lib/types/reasoning.d.ts +141 -0
  64. package/lib/types/stages.d.ts +193 -0
  65. package/lib/types/state.d.ts +273 -0
  66. package/lib/types/system-language.d.ts +10 -0
  67. package/lib/types/verification-tool.d.ts +32 -0
  68. package/lib/types/verification.d.ts +77 -0
  69. package/lib/types/verifier.d.ts +9 -0
  70. package/lib/types/volatile.d.ts +17 -0
  71. package/lib/verification-tool.js +176 -0
  72. package/lib/verification.js +337 -0
  73. package/lib/verifier.js +25 -0
  74. package/lib/volatile.js +20 -0
  75. package/locale/en.json +3 -2
  76. package/locale/zh.json +3 -2
  77. package/package.json +84 -9
  78. package/lib/index.d.ts +0 -11
package/lib/preset.js ADDED
@@ -0,0 +1,1552 @@
1
+ /**
2
+ * The Coding runtime preset plugin.
3
+ *
4
+ * Three enforcement layers, deliberately independent:
5
+ *
6
+ * 1. `tools/pre-execute` — a friendly, actionable denial (`{ kind: 'deny' }`,
7
+ * never `ask`: this is a rule, not a question for the user).
8
+ * 2. `ctx.tools.guard()` — the monotonic backstop. It runs after pre-execute
9
+ * resolves to `allow`, so no later listener order or approval channel can
10
+ * let a stage-forbidden call through.
11
+ * 3. `agent/pre-step` — the stage contract injected as step context, plus a
12
+ * one-shot step rejection when the model tried to skip a gate.
13
+ *
14
+ * The tool table is trimmed (`agent.ctx.tools.restrict({ allow })`) during
15
+ * `implement`, so the model does not even see the edit tools it may not use.
16
+ *
17
+ * @module dsh-coding/preset
18
+ */
19
+ import { defineTool } from '@deepseek-ai/dsh-tools';
20
+ import { ReasoningController } from './reasoning.js';
21
+ import { reasoningProjection } from './reasoning-projection.js';
22
+ import { writeMemoryDocument } from './memory.js';
23
+ import { controlMessage, stageMessage } from './messages.js';
24
+ import { failureNotice, makeFailure } from './failures.js';
25
+ import { assertWorkerModel, describeProviders, resolveWorkerRoute, workerPreset, WORKER_ROLES, } from './models.js';
26
+ import { handoffDigest, handoffForWorker, mergeHandoff, } from './handoff.js';
27
+ import { CODING_MODES, CODING_STAGES, TOOL, WORKER_PRESETS, asCheckpoint, needsWorkspaceInstructions, stagePath, toolClass, } from './stages.js';
28
+ import { CodingStateStore, applyMode, applyStage, checkAdvance, checkTool, checkpointOf, clearFailure, clearRefusal, isLeadAgent, recordFailure, recordRefusal, recordVerification, resetVerification, restoreFromView, sessionIdOf, statusLine, tableTrim, takeFailureNotice, takeLastRefusal, } from './state.js';
29
+ import { stageContext } from './contract.js';
30
+ import { registerVerificationTool } from './verification-tool.js';
31
+ import { codingProjection } from './coding-projection.js';
32
+ import { languagePrompt, resolveHostLanguage } from './language.js';
33
+ import { systemLanguages } from './system-language.js';
34
+ /** Cordis plugin name used by loader diagnostics. */
35
+ export const name = 'dsh-coding-preset';
36
+ /**
37
+ * Hard dependencies: this preset cannot honour its own gates without the
38
+ * delegation backend or the structured verifier, so it fails loudly instead of
39
+ * silently downgrading to advice. The preset registry is deliberately NOT a
40
+ * dependency: the worker preset is selected through `ctx.subagents`, and a
41
+ * preset-scope plugin should not need the registry that mounted it.
42
+ */
43
+ export const inject = [
44
+ 'tools',
45
+ 'systemPrompt',
46
+ 'dshCodingRuntime',
47
+ 'subagents',
48
+ 'subprocess',
49
+ 'llm',
50
+ // The per-turn conversation card reads this projection; without it the
51
+ // session still runs, it just loses its visible stage surface.
52
+ 'sessionProjections',
53
+ ];
54
+ /** Structured report the implement worker must return. */
55
+ const IMPLEMENT_REPORT_SCHEMA = {
56
+ type: 'object',
57
+ additionalProperties: false,
58
+ required: ['ok', 'summary', 'files'],
59
+ properties: {
60
+ ok: { type: 'boolean' },
61
+ summary: { type: 'string' },
62
+ files: { type: 'array', items: { type: 'string' } },
63
+ notes: { type: 'string' },
64
+ },
65
+ };
66
+ /** Structured report the verify worker must return. */
67
+ const VERIFY_REPORT_SCHEMA = {
68
+ type: 'object',
69
+ additionalProperties: false,
70
+ required: ['ok', 'summary'],
71
+ properties: {
72
+ ok: { type: 'boolean' },
73
+ summary: { type: 'string' },
74
+ command: { type: 'string' },
75
+ kind: { type: 'string', enum: ['test', 'build', 'lint', 'typecheck'] },
76
+ scope: { type: 'string', enum: ['targeted', 'package', 'full'] },
77
+ failedTests: { type: 'array', items: { type: 'string' } },
78
+ findings: { type: 'array', items: { type: 'string' } },
79
+ },
80
+ };
81
+ /** Structured report the planner worker must return. */
82
+ const PLANNER_REPORT_SCHEMA = {
83
+ type: 'object',
84
+ additionalProperties: false,
85
+ required: ['ok', 'summary', 'tasks'],
86
+ properties: {
87
+ ok: { type: 'boolean' },
88
+ summary: { type: 'string' },
89
+ tasks: {
90
+ type: 'array',
91
+ items: {
92
+ type: 'object',
93
+ additionalProperties: false,
94
+ required: ['goal', 'acceptance'],
95
+ properties: {
96
+ goal: { type: 'string' },
97
+ files: { type: 'array', items: { type: 'string' } },
98
+ acceptance: { type: 'string' },
99
+ avoid: { type: 'string' },
100
+ },
101
+ },
102
+ },
103
+ },
104
+ };
105
+ /** Every string of an untyped array, dropping anything else. */
106
+ function stringList(candidate) {
107
+ return Array.isArray(candidate) ? candidate.filter((item) => typeof item === 'string') : [];
108
+ }
109
+ /**
110
+ * Normalize the planner's task list into handoff tasks. The value crossed a
111
+ * provider boundary, so an item may still be a bare string from an older
112
+ * prompt; an object item must name a goal, and every other field is optional.
113
+ * @param value - `structured.tasks` of the planner worker.
114
+ * @returns the normalized tasks, dropping the ones without a goal.
115
+ */
116
+ function asHandoffTasks(value) {
117
+ if (!Array.isArray(value))
118
+ return [];
119
+ const tasks = [];
120
+ for (const item of value) {
121
+ if (typeof item === 'string') {
122
+ const goal = item.trim();
123
+ if (goal !== '')
124
+ tasks.push({ goal, files: [], acceptance: '' });
125
+ continue;
126
+ }
127
+ if (typeof item !== 'object' || item === null)
128
+ continue;
129
+ const raw = item;
130
+ const goal = typeof raw['goal'] === 'string' ? raw['goal'].trim() : '';
131
+ if (goal === '')
132
+ continue;
133
+ const acceptance = typeof raw['acceptance'] === 'string' ? raw['acceptance'].trim() : '';
134
+ const avoid = typeof raw['avoid'] === 'string' ? raw['avoid'].trim() : '';
135
+ tasks.push({
136
+ goal,
137
+ files: stringList(raw['files']),
138
+ acceptance,
139
+ ...avoid === '' ? {} : { avoid },
140
+ });
141
+ }
142
+ return tasks;
143
+ }
144
+ /**
145
+ * Validate the child's structured value. The value crossed a provider boundary,
146
+ * so nothing about its shape is assumed.
147
+ * @param value - `SubagentResult.structured`.
148
+ * @returns the narrowed report, or undefined when the child produced none.
149
+ */
150
+ function asWorkerReport(value) {
151
+ if (typeof value !== 'object' || value === null)
152
+ return undefined;
153
+ const v = value;
154
+ if (typeof v['ok'] !== 'boolean' || typeof v['summary'] !== 'string')
155
+ return undefined;
156
+ const kind = v['kind'];
157
+ const scope = v['scope'];
158
+ return {
159
+ ok: v['ok'],
160
+ summary: v['summary'],
161
+ files: stringList(v['files']),
162
+ ...typeof v['notes'] === 'string' ? { notes: v['notes'] } : {},
163
+ ...typeof v['command'] === 'string' ? { command: v['command'] } : {},
164
+ ...kind === 'test' || kind === 'build' || kind === 'lint' || kind === 'typecheck' ? { kind } : {},
165
+ ...scope === 'targeted' || scope === 'package' || scope === 'full' ? { scope } : {},
166
+ failedTests: stringList(v['failedTests']),
167
+ tasks: asHandoffTasks(v['tasks']),
168
+ findings: stringList(v['findings']),
169
+ };
170
+ }
171
+ /** Read the delegation plan as worker-facing text. */
172
+ function planText(state) {
173
+ const items = state.plan?.items ?? [];
174
+ if (items.length === 0)
175
+ return '(no structured task list)';
176
+ return items.map(item => `- [${item.status}] ${item.content}`).join('\n');
177
+ }
178
+ /**
179
+ * The handoff fragment one worker receives, as prompt lines. The roles differ:
180
+ * the planner gets the problem, the implementer the decisions and tasks, the
181
+ * verifier the definition of done and what already changed.
182
+ * @param state - live session state carrying the handoff.
183
+ * @param role - worker about to run.
184
+ * @returns the prompt lines, or [] when the handoff has nothing for this role.
185
+ */
186
+ function handoffSection(state, role) {
187
+ const text = handoffForWorker(state.handoff, role);
188
+ return text === '' ? [] : ['', '## Handoff', text];
189
+ }
190
+ /** Whether the handoff already carries the plan task list the workers read. */
191
+ function hasHandoffTasks(state) {
192
+ return (state.handoff?.tasks.length ?? 0) > 0;
193
+ }
194
+ /** Characters kept from a brief's first line in the subagent catalog label. */
195
+ const LABEL_LIMIT = 60;
196
+ /**
197
+ * One-line catalog label for a dispatched worker: the role plus the brief's
198
+ * first non-empty line, collapsed and capped. The catalog keeps every child for
199
+ * the life of the session, so the label is what lets a reader tell two runs
200
+ * apart.
201
+ * @param role - worker role.
202
+ * @param task - the brief the lead handed the worker.
203
+ * @returns a single-line label no longer than the cap plus its role prefix.
204
+ */
205
+ export function workerLabel(role, task) {
206
+ const firstLine = task
207
+ .split(/\r?\n/u)
208
+ .map(line => line.trim())
209
+ .find(line => line !== '') ?? '';
210
+ const summary = Array.from(firstLine.replace(/\s+/gu, ' ')).slice(0, LABEL_LIMIT).join('').trim();
211
+ return summary === '' ? `${role}: change` : `${role}: ${summary}`;
212
+ }
213
+ /** Implement-worker prompt: self-contained, because the child has no parent context. */
214
+ function implementPrompt(task, files, acceptance, state) {
215
+ return [
216
+ 'You are the implement worker of the DSH Coding runtime. You have a fresh context: this task is complete on its own.',
217
+ 'Rules:',
218
+ '- The repository instructions (AGENTS.md) are already injected into this session: follow them; do not read the file again.',
219
+ '- Read a file before editing it. Prefer apply_patch for multi-file or multi-hunk changes; use edit for one literal replacement and write for a new file.',
220
+ '- Change only what the task needs: no drive-by refactor, no unrelated reformatting, no new dependency.',
221
+ '- `acceptance` is the standard this change is measured against: satisfy it. Do not edit files outside the handoff.',
222
+ '- Never commit, push, tag, or open a pull request.',
223
+ '- Finish by calling structured_output exactly once with { ok, summary, files, notes }; files lists every path you changed.',
224
+ '',
225
+ '## Task',
226
+ task,
227
+ ...acceptance === undefined ? [] : ['', '## Acceptance criteria', acceptance],
228
+ ...files.length === 0 ? [] : ['', '## Files in scope', ...files.map(file => `- ${file}`)],
229
+ ...handoffSection(state, 'implement'),
230
+ ...hasHandoffTasks(state) ? [] : ['', '## Task list from the lead', planText(state)],
231
+ ].join('\n');
232
+ }
233
+ /** Verify-worker prompt: read-only investigation of one check. */
234
+ function verifyPrompt(task, state, withInstructions = false) {
235
+ return [
236
+ 'You are the verify worker of the DSH Coding runtime. You cannot edit files; you run checks and report evidence.',
237
+ 'Rules:',
238
+ ...withInstructions
239
+ ? ['- The repository instructions (AGENTS.md) are already injected into this session: follow them; do not read the file again.']
240
+ : [],
241
+ '- Use run_verification to execute a check; inspect the failing output it returns.',
242
+ '- Report findings with file:line and a reproducible scenario, ordered by impact.',
243
+ '- Report the command you actually ran, and put every conclusion about the acceptance criteria into findings.',
244
+ '- Never claim a passing check you did not run.',
245
+ '- Finish by calling structured_output exactly once with { ok, summary, command, kind, scope, failedTests, findings }.',
246
+ '',
247
+ '## Task',
248
+ task,
249
+ ...handoffSection(state, 'verify'),
250
+ '',
251
+ '## Current state',
252
+ statusLine(state),
253
+ ...hasHandoffTasks(state) ? [] : ['', '## Task list from the lead', planText(state)],
254
+ ].join('\n');
255
+ }
256
+ /** Planner-worker prompt: explore read-only and return single-purpose tasks. */
257
+ function plannerPrompt(task, state) {
258
+ return [
259
+ 'You are the planner worker of the DSH Coding runtime. You have a fresh context: the requirement below is complete on its own.',
260
+ 'Rules:',
261
+ '- Explore the workspace first: read AGENTS.md, the README, the package manifests, and the files the requirement touches. Use read, glob, grep, and web.',
262
+ '- Then analyse the requirement against what the workspace actually contains.',
263
+ '- State in `summary` what the user actually asked for, what the workspace currently contains, and why the tasks are ordered this way.',
264
+ '- For every task give `goal` (what changes), `files` (the exact paths in scope), `acceptance` (an observable check that proves it is done), and `avoid` (what it must not touch). One coherent change per task, so an implement worker can finish it from that text alone.',
265
+ '- Produce single-purpose sub-tasks: each task does exactly one thing (one file or one coherent unit), is imperative, and is verifiable. Never bundle unrelated work into one task.',
266
+ '- Order the tasks so each later task depends only on earlier ones.',
267
+ '- Finish by calling structured_output exactly once with { ok, summary, tasks }; tasks is an array of objects { goal, files, acceptance, avoid }.',
268
+ '',
269
+ '## Requirement',
270
+ task,
271
+ ...handoffSection(state, 'plan'),
272
+ '',
273
+ '## Current state',
274
+ statusLine(state),
275
+ ].join('\n');
276
+ }
277
+ /** The Coding runtime plugin body. */
278
+ export async function apply(ctx) {
279
+ const settings = ctx.dshCodingRuntime;
280
+ const config = () => settings.options;
281
+ /**
282
+ * 主 Agent 自身是否就是配置的 planner 路由:这时 planner worker 是多余的,
283
+ * 门禁直接放行。读不到模型选择时按“不是”处理,门禁照常生效。
284
+ */
285
+ const leadIsPlanner = (agent) => {
286
+ try {
287
+ const current = agent?.model?.current?.();
288
+ if (typeof current?.provider !== 'string' || typeof current?.model !== 'string')
289
+ return false;
290
+ const route = resolveWorkerRoute(config(), 'plan');
291
+ return current.provider === route.provider && current.model === route.model;
292
+ }
293
+ catch {
294
+ return false;
295
+ }
296
+ };
297
+ /** 门禁需要的运行时事实:主 Agent 的路由,以及 `requirePlanner` 开关。 */
298
+ const advanceOptions = (agent) => ({
299
+ leadIsPlanner: leadIsPlanner(agent),
300
+ plannerGate: config().requirePlanner !== 'off',
301
+ });
302
+ const store = new CodingStateStore(config);
303
+ /** Current conversation language, used for the user-facing failure notice. */
304
+ const currentLanguage = () => resolveHostLanguage({
305
+ mode: config().language,
306
+ loader: ctx.get?.('loader') ?? ctx.loader,
307
+ systemLanguages,
308
+ });
309
+ /**
310
+ * Record a blocking failure and log it once. The next step consumes the
311
+ * pending notice; the status line and checkpoint keep the failure until the
312
+ * same subsystem succeeds.
313
+ */
314
+ const fail = (state, point, error) => {
315
+ const failure = makeFailure(point, error, currentLanguage());
316
+ recordFailure(state, failure);
317
+ ctx.logger?.warn?.(`dsh-coding: ${point} failed: ${failure.reason}`);
318
+ };
319
+ try {
320
+ await preflight(ctx, config());
321
+ }
322
+ catch (error) {
323
+ throw new Error(`${messageOf(error)}\nWhat to do: fix the worker model routes and composition in the plugin page `
324
+ + '(or cordis.patch.yml), then restart DSH.');
325
+ }
326
+ // ── Conversation language ─────────────────────────────────────────────────
327
+ // Fixed per request at assembly time, so a settings change or a DSH language
328
+ // switch reaches the next turn without a remount. Auto resolves DSH's own
329
+ // preference, then the OS language list, then the host locale.
330
+ registerLanguage(ctx, config);
331
+ // ── Durable stage projection ──────────────────────────────────────────────
332
+ // The conversation card reads this, never the in-memory state machine, so a
333
+ // reloaded session shows the stage, plan, and verification the log recorded.
334
+ let projectionHandle;
335
+ let projectionError;
336
+ let projectionReady = Promise.resolve();
337
+ ctx.inject(['sessionProjections'], (child) => {
338
+ child.effect(() => {
339
+ let disposed = false;
340
+ let handle;
341
+ projectionReady = Promise.resolve(child.sessionProjections.register(codingProjection(() => config().defaultMode)))
342
+ .then((ready) => {
343
+ if (disposed) {
344
+ void ready?.dispose?.();
345
+ return undefined;
346
+ }
347
+ handle = ready;
348
+ projectionHandle = ready;
349
+ return ready;
350
+ })
351
+ .catch((error) => {
352
+ ctx.logger?.warn?.(`dsh-coding: could not register the stage projection: ${messageOf(error)}`);
353
+ projectionError = error;
354
+ return undefined;
355
+ });
356
+ return () => {
357
+ disposed = true;
358
+ projectionHandle = undefined;
359
+ void handle?.dispose?.();
360
+ };
361
+ }, 'dsh-coding: stage projection');
362
+ });
363
+ // ── Durable reasoning choice ─────────────────────────────────────────────
364
+ // The controller reads this through `snapshot()`; registering it keeps the
365
+ // chat-box pick and the `coding_reasoning` override across a Host restart.
366
+ ctx.inject(['sessionProjections'], (child) => {
367
+ child.effect(() => {
368
+ let disposed = false;
369
+ let handle;
370
+ Promise.resolve(child.sessionProjections.register(reasoningProjection))
371
+ .then((registered) => {
372
+ if (disposed) {
373
+ void registered?.dispose?.();
374
+ return undefined;
375
+ }
376
+ handle = registered;
377
+ return registered;
378
+ })
379
+ .catch((error) => {
380
+ ctx.logger?.warn?.(`dsh-coding: could not register the reasoning projection: ${messageOf(error)}`);
381
+ return undefined;
382
+ });
383
+ return () => {
384
+ disposed = true;
385
+ void handle?.dispose?.();
386
+ };
387
+ }, 'dsh-coding: reasoning projection');
388
+ });
389
+ /** Resolve the live state of a lead agent, creating it on first touch. */
390
+ const stateOf = (agent) => {
391
+ if (!isLeadAgent(agent))
392
+ return undefined;
393
+ const sessionId = sessionIdOf(agent);
394
+ if (sessionId === undefined)
395
+ return undefined;
396
+ return store.peek(agent) ?? store.ensure(agent, sessionId);
397
+ };
398
+ /** Automatic / pinned / overridden reasoning level for this agent. */
399
+ const reasoning = new ReasoningController(ctx, config, {
400
+ turnOf: (agent) => stateOf(agent)?.turn ?? 0,
401
+ planOf: (agent) => stateOf(agent)?.plan?.items ?? [],
402
+ });
403
+ /**
404
+ * Re-derive the lead's visible tool table for the current stage. The
405
+ * restriction is scoped to the agent, so it disappears with that Agent; the
406
+ * returned disposer is kept so a stage change lifts it immediately.
407
+ */
408
+ const syncTable = (agent, state) => {
409
+ state.tableRestriction?.();
410
+ state.tableRestriction = undefined;
411
+ const allow = tableTrim(state.stage);
412
+ if (allow === undefined)
413
+ return;
414
+ let known;
415
+ try {
416
+ known = new Set(ctx.tools.schemas(agent).map(schema => schema.name));
417
+ }
418
+ catch (error) {
419
+ fail(state, 'tool-table', error);
420
+ return;
421
+ }
422
+ // `restrict` rejects unknown names; keep only the verbs this scope actually has.
423
+ const filtered = allow.filter(toolName => known.has(toolName));
424
+ if (!filtered.includes(TOOL.implement)) {
425
+ ctx.logger?.warn?.('dsh-coding: delegation tool is missing; the implement table was not trimmed');
426
+ return;
427
+ }
428
+ try {
429
+ state.tableRestriction = agent.ctx.tools.restrict({ allow: filtered });
430
+ }
431
+ catch (error) {
432
+ ctx.logger?.warn?.(`dsh-coding: could not trim the implement tool table: ${String(error)}`);
433
+ fail(state, 'tool-table', error);
434
+ }
435
+ };
436
+ /**
437
+ * Seed a resumed session from its durable projection. The live state is a
438
+ * cache; the Session log is the source of truth for the stage, plan, and
439
+ * verification the resumed conversation already recorded.
440
+ */
441
+ const restore = async (agent, state) => {
442
+ await projectionReady;
443
+ const handle = projectionHandle;
444
+ if (handle === undefined) {
445
+ // Registration is the only path that fills the handle, so its failure is
446
+ // what leaves a resumed session without its durable stage.
447
+ if (projectionError !== undefined)
448
+ fail(state, 'projection', projectionError);
449
+ return;
450
+ }
451
+ let view;
452
+ try {
453
+ view = handle.stateOf(agent.session);
454
+ }
455
+ catch (error) {
456
+ ctx.logger?.warn?.(`dsh-coding: could not read the stage projection: ${messageOf(error)}`);
457
+ fail(state, 'restore', error);
458
+ return;
459
+ }
460
+ if (view === undefined || view.active !== true)
461
+ return;
462
+ if (view.checkpoint === null && view.plan.length === 0)
463
+ return;
464
+ restoreFromView(state, view);
465
+ };
466
+ // ── Layer 1: friendly waterfall denial ────────────────────────────────────
467
+ ctx.effect(() => ctx.on('tools/pre-execute', async (exec, next) => {
468
+ const state = stateOf(exec.agent);
469
+ if (state === undefined)
470
+ return next();
471
+ const verdict = checkTool(state, exec.name);
472
+ if (verdict.deny !== undefined)
473
+ return { kind: 'deny', reason: verdict.deny };
474
+ return next();
475
+ }), 'dsh-coding: pre-execute gate');
476
+ // ── Layer 2: monotonic guard (runs after pre-execute allowed the call) ────
477
+ ctx.effect(() => ctx.tools.guard((exec) => {
478
+ const state = stateOf(exec.agent);
479
+ if (state === undefined)
480
+ return undefined;
481
+ return checkTool(state, exec.name).deny;
482
+ }), 'dsh-coding: stage guard');
483
+ // ── Result observation: requirements evidence + structured follow-ups ────
484
+ ctx.effect(() => ctx.on('tools/post-execute', async (exec, result, next) => {
485
+ const downstream = await next();
486
+ const state = stateOf(exec.agent);
487
+ if (state === undefined)
488
+ return downstream;
489
+ if (result.isError !== true && state.stage === 'requirements') {
490
+ const kind = toolClass(exec.name);
491
+ if (kind === 'read' || kind === 'exec')
492
+ state.requirementsObserved += 1;
493
+ }
494
+ const notices = [];
495
+ const checkpoint = asCheckpoint(result.value?.checkpoint);
496
+ if (checkpoint?.verification !== undefined && checkpoint.verification.passed === false) {
497
+ const failed = checkpoint.verification.failedTests;
498
+ const attempts = checkpoint.verifyBlocked?.attempts ?? checkpoint.verifyAttempts ?? 0;
499
+ const evidence = [
500
+ failed.length === 0 ? '' : `Failing tests: ${failed.join('; ')}`,
501
+ `Command: ${checkpoint.verification.command} (exit ${String(checkpoint.verification.exitCode)})`,
502
+ ].filter(line => line !== '');
503
+ notices.push(stageMessage(checkpoint.verifyBlocked === undefined
504
+ ? [
505
+ 'Verification failed. Do not deliver.',
506
+ ...evidence,
507
+ 'Return to the implement stage, fix the failure with delegate_implement, then verify again.',
508
+ attempts > 0 ? `Attempt ${attempts} of the retry budget recorded.` : '',
509
+ ].filter(line => line !== '').join('\n')
510
+ : [
511
+ `Verification retry budget exhausted after ${attempts} attempt(s). Do not retry the same failure.`,
512
+ 'Stop the fix/verify loop: make a materially different fix, ask the user for a decision,',
513
+ 'or advance to deliver and report a BLOCKED delivery naming the failing check and the last error.',
514
+ ...evidence,
515
+ ].join('\n'), `verification failed: ${checkpoint.verification.kind}`));
516
+ }
517
+ if (exec.name === TOOL.stage) {
518
+ const value = result.value;
519
+ if (value?.ok === false && value.soft !== true && typeof value.reason === 'string') {
520
+ notices.push(stageMessage(`The stage advance was refused: ${value.reason}\nThe next step is blocked until the gate is satisfied.`, 'stage advance refused'));
521
+ }
522
+ }
523
+ if (notices.length === 0)
524
+ return downstream;
525
+ return {
526
+ ...downstream,
527
+ additionalContexts: [...downstream.additionalContexts ?? [], ...notices],
528
+ };
529
+ }), 'dsh-coding: post-execute notice');
530
+ // The Host emits this synchronously from `inbox.claim()`, before it reads
531
+ // `model.current()` for step preparation, so it is the only point where an
532
+ // automatic effort can reach the turn's first step. A cold capability cache
533
+ // writes nothing; `agent/pre-step` then applies the level from the next step.
534
+ ctx.effect(() => ctx.on('agent/inbox/claimed', (payload) => {
535
+ try {
536
+ reasoning.applySync(payload.agent, payload.message, typeof payload.turn === 'number' ? payload.turn : undefined);
537
+ }
538
+ catch (error) {
539
+ ctx.logger?.warn?.(`dsh-coding: reasoning claim failed: ${messageOf(error)}`);
540
+ }
541
+ }), 'dsh-coding: reasoning claim');
542
+ // ── Layer 3: stage context and gate-skip rejection ────────────────────────
543
+ ctx.effect(() => ctx.on('agent/pre-step', async (payload, next) => {
544
+ const agent = payload.agent;
545
+ const state = stateOf(agent);
546
+ // Always delegate first: other listeners own their own decisions.
547
+ const decision = await next();
548
+ if (state === undefined)
549
+ return decision;
550
+ state.turn = typeof payload.turn === 'number' ? payload.turn : state.turn;
551
+ state.step = typeof payload.step === 'number' ? payload.step : state.step;
552
+ if (decision.kind === 'reject')
553
+ return decision;
554
+ try {
555
+ // The projection is the durable copy: a chat-box pick may have landed
556
+ // since the last step, so fold it back before classifying this one.
557
+ reasoning.syncProjection(agent);
558
+ }
559
+ catch (error) {
560
+ ctx.logger?.warn?.(`dsh-coding: could not sync the reasoning choice: ${messageOf(error)}`);
561
+ fail(state, 'reasoning', error);
562
+ }
563
+ try {
564
+ await reasoning.apply(agent, payload.signal, decision.messages);
565
+ }
566
+ catch (error) {
567
+ ctx.logger?.warn?.(`dsh-coding: could not apply the reasoning level: ${messageOf(error)}`);
568
+ fail(state, 'reasoning', error);
569
+ }
570
+ const refusal = state.refusal;
571
+ if (refusal !== undefined) {
572
+ // The model tried to skip a gate: end this turn blocked, once. The reason
573
+ // is kept for the next step's contract, because a rejected step drops its
574
+ // own messages and the turn ends without them.
575
+ clearRefusal(state);
576
+ ctx.logger?.info?.(`dsh-coding: blocked a step that skipped the ${refusal.target} gate`);
577
+ return { kind: 'reject' };
578
+ }
579
+ const rejection = takeLastRefusal(state);
580
+ const text = stageContext({
581
+ mode: state.mode,
582
+ stage: state.stage,
583
+ status: statusLine(state),
584
+ handoff: handoffDigest(state.handoff),
585
+ ...rejection === undefined ? {} : { rejection },
586
+ });
587
+ // Read after this step's own failures, so a failure raised above travels
588
+ // with the same step's contract. The notice is one-shot: a later step
589
+ // repeats neither the card nor the message.
590
+ const pending = takeFailureNotice(state);
591
+ const messages = [
592
+ ...decision.messages,
593
+ stageMessage(text, `coding stage: ${state.stage}`),
594
+ ];
595
+ if (pending !== undefined) {
596
+ messages.push(controlMessage(failureNotice(pending, currentLanguage()), `runtime failure: ${pending.point}`));
597
+ }
598
+ return { ...decision, messages };
599
+ }), 'dsh-coding: stage context');
600
+ // ── Durable folds: the plan lives in the Session log ──────────────────────
601
+ ctx.effect(() => ctx.on('session/event', (session, event) => {
602
+ if (event.type !== 'todo/write')
603
+ return;
604
+ const sessionId = session?.header?.id;
605
+ if (typeof sessionId !== 'string')
606
+ return;
607
+ const state = store.bySessionId(sessionId);
608
+ if (state === undefined)
609
+ return;
610
+ const todos = event.data.todos;
611
+ if (!Array.isArray(todos))
612
+ return;
613
+ const items = todos
614
+ .filter((item) => (typeof item === 'object' && item !== null
615
+ && typeof item.content === 'string'
616
+ && (item.status === 'pending'
617
+ || item.status === 'in_progress'
618
+ || item.status === 'completed')))
619
+ .map(item => ({ content: item.content, status: item.status }));
620
+ state.plan = { items, at: typeof event.time === 'number' ? event.time : Date.now() };
621
+ state.updatedAt = state.plan.at;
622
+ }), 'dsh-coding: plan fold');
623
+ // ── Per-agent lifecycle ───────────────────────────────────────────────────
624
+ ctx.effect(() => ctx.on('agent/created', async ({ agent }) => {
625
+ const state = stateOf(agent);
626
+ if (state === undefined)
627
+ return;
628
+ // Warm the effort table so the first claimed message can pick a level
629
+ // synchronously, before the Host snapshots the step's selection.
630
+ void reasoning.prewarm(agent).catch(() => { });
631
+ // Fresh sessions have an empty projection, so this is a no-op for them.
632
+ await restore(agent, state);
633
+ syncTable(agent, state);
634
+ }), 'dsh-coding: agent created');
635
+ ctx.effect(() => ctx.on('agent/disposed', ({ agent }) => {
636
+ store.release(agent, sessionIdOf(agent));
637
+ }), 'dsh-coding: agent disposed');
638
+ // ── Control verbs ─────────────────────────────────────────────────────────
639
+ ctx.effect(() => ctx.tools.register(defineTool({
640
+ name: TOOL.stage,
641
+ description: [
642
+ 'Inspect or advance the enforced coding stage (requirements, plan, implement, verify, deliver).',
643
+ 'Omit `stage` to read the current stage and gate status.',
644
+ 'In auto mode only requirements is open: choose the workflow with coding_mode before advancing.',
645
+ 'The plugin decides whether the move is allowed: plan needs a requirements observation,',
646
+ 'implement needs a todo_write task list, verify needs a landed implement-worker edit,',
647
+ 'and deliver needs a passing run_verification. A refused move repeats the reason;',
648
+ 'a move that skips a gate also blocks the next step.',
649
+ 'Under codex, plan also needs a recorded handoff goal and verify a recorded acceptance criterion;',
650
+ 'once the verification retry budget is exhausted, deliver is granted but the delivery is BLOCKED.',
651
+ ].join(' '),
652
+ parameters: {
653
+ stage: {
654
+ type: 'string',
655
+ enum: [...CODING_STAGES],
656
+ description: 'Target stage. Omit to inspect the current state.',
657
+ },
658
+ note: {
659
+ type: 'string',
660
+ description: 'One line on why you are moving; recorded in the transition log.',
661
+ },
662
+ },
663
+ output: {
664
+ schema: {
665
+ type: 'object',
666
+ additionalProperties: false,
667
+ properties: {
668
+ ok: { type: 'boolean', required: true },
669
+ stage: { type: 'string', required: true },
670
+ mode: { type: 'string', required: true },
671
+ status: { type: 'string', required: true },
672
+ reason: { type: 'string' },
673
+ soft: { type: 'boolean' },
674
+ blocked: { type: 'boolean' },
675
+ checkpoint: { type: 'json' },
676
+ },
677
+ },
678
+ render: (_args, value) => [{
679
+ type: 'text',
680
+ text: value.ok === true
681
+ ? value.blocked === true
682
+ ? `delivery BLOCKED: ${value.stage}; ${value.status}`
683
+ : `stage ${value.stage} (${value.mode}); ${value.status}`
684
+ : `stage advance refused: ${String(value.reason ?? '')}`,
685
+ }],
686
+ presentationMeta: (_args, value) => value.checkpoint,
687
+ },
688
+ async execute(args, exec) {
689
+ if (exec.agent === undefined)
690
+ throw new Error('coding_stage requires an owning agent session');
691
+ const state = stateOf(exec.agent);
692
+ if (state === undefined)
693
+ throw new Error('coding_stage: this agent is not a Coding lead session');
694
+ if (args?.stage === undefined) {
695
+ return {
696
+ ok: true,
697
+ stage: state.stage,
698
+ mode: state.mode,
699
+ status: statusLine(state),
700
+ checkpoint: checkpointOf(state),
701
+ };
702
+ }
703
+ const check = checkAdvance(state, args.stage, advanceOptions(exec.agent));
704
+ if (!check.ok) {
705
+ const reason = check.reason ?? 'the stage gate refused this move';
706
+ // Auto's workflow choice is a decision, not a skipped gate: report it
707
+ // without arming the one-shot step rejection meant for jumping a gate.
708
+ if (check.soft !== true)
709
+ recordRefusal(state, args.stage, reason);
710
+ return {
711
+ ok: false,
712
+ stage: state.stage,
713
+ mode: state.mode,
714
+ status: statusLine(state),
715
+ reason,
716
+ ...check.soft === true ? { soft: true } : {},
717
+ checkpoint: checkpointOf(state),
718
+ };
719
+ }
720
+ applyStage(state, args.stage, args.note?.trim() || 'model requested the next stage');
721
+ // A granted exit from an exhausted retry budget is a blocked delivery:
722
+ // the report must name the failing check instead of claiming success.
723
+ if (check.blocked === true)
724
+ state.deliveryBlocked = true;
725
+ syncTable(exec.agent, state);
726
+ return {
727
+ ok: true,
728
+ stage: state.stage,
729
+ mode: state.mode,
730
+ status: statusLine(state),
731
+ ...check.blocked === true ? { blocked: true } : {},
732
+ checkpoint: checkpointOf(state),
733
+ };
734
+ },
735
+ })), 'dsh-coding: coding_stage');
736
+ ctx.effect(() => ctx.tools.register(defineTool({
737
+ name: TOOL.mode,
738
+ description: [
739
+ 'Inspect or switch the workflow mode: auto (requirements chooses the workflow), consult (Q&A), review, or codex.',
740
+ 'A mode determines the stage set: auto opens only requirements; consult requirements/plan/deliver; review requirements/verify/deliver;',
741
+ 'codex all five. Switching to a mode that does not open the current stage resets to that mode\'s first stage.',
742
+ 'In auto mode call this in requirements, once, to choose the concrete workflow; prefer consult when the request is',
743
+ 'unclear, and do not over-interpret it. Otherwise call only when the user asks to switch or asks which mode is active.',
744
+ ].join(' '),
745
+ parameters: {
746
+ mode: {
747
+ type: 'string',
748
+ enum: [...CODING_MODES],
749
+ description: 'Target mode. Omit to inspect.',
750
+ },
751
+ },
752
+ output: {
753
+ schema: {
754
+ type: 'object',
755
+ additionalProperties: false,
756
+ properties: {
757
+ ok: { type: 'boolean', required: true },
758
+ stage: { type: 'string', required: true },
759
+ mode: { type: 'string', required: true },
760
+ status: { type: 'string', required: true },
761
+ reason: { type: 'string' },
762
+ checkpoint: { type: 'json' },
763
+ },
764
+ },
765
+ render: (_args, value) => [{
766
+ type: 'text',
767
+ text: `mode ${value.mode}; stage ${value.stage}; stages ${stagePath(value.mode)}`,
768
+ }],
769
+ presentationMeta: (_args, value) => value.checkpoint,
770
+ },
771
+ async execute(args, exec) {
772
+ if (exec.agent === undefined)
773
+ throw new Error('coding_mode requires an owning agent session');
774
+ const state = stateOf(exec.agent);
775
+ if (state === undefined)
776
+ throw new Error('coding_mode: this agent is not a Coding lead session');
777
+ if (args?.mode === undefined) {
778
+ return {
779
+ ok: true,
780
+ stage: state.stage,
781
+ mode: state.mode,
782
+ status: statusLine(state),
783
+ checkpoint: checkpointOf(state),
784
+ };
785
+ }
786
+ applyMode(state, args.mode);
787
+ syncTable(exec.agent, state);
788
+ return {
789
+ ok: true,
790
+ stage: state.stage,
791
+ mode: state.mode,
792
+ status: statusLine(state),
793
+ checkpoint: checkpointOf(state),
794
+ };
795
+ },
796
+ })), 'dsh-coding: coding_mode');
797
+ ctx.effect(() => ctx.tools.register(defineTool({
798
+ name: TOOL.reasoning,
799
+ description: [
800
+ 'Inspect the active Coding reasoning level, or set a session override.',
801
+ 'Call with no effort to report the current level and where it came from.',
802
+ 'Set low, high, or max only when the user asks to change it or the task has clearly outgrown the current level;',
803
+ 'ordinary work is classified automatically and needs no call.',
804
+ ].join(' '),
805
+ parameters: {
806
+ effort: {
807
+ type: 'string',
808
+ enum: ['auto', 'low', 'high', 'max'],
809
+ description: 'Omit to inspect; auto clears an override; low/high/max pins this session.',
810
+ },
811
+ },
812
+ output: {
813
+ schema: {
814
+ type: 'object',
815
+ additionalProperties: false,
816
+ properties: {
817
+ ok: { type: 'boolean', required: true },
818
+ reasoning: { type: 'string', required: true },
819
+ source: { type: 'string', required: true },
820
+ effort: { type: 'string', required: true },
821
+ reason: { type: 'string' },
822
+ stage: { type: 'string', required: true },
823
+ mode: { type: 'string', required: true },
824
+ status: { type: 'string', required: true },
825
+ checkpoint: { type: 'json' },
826
+ },
827
+ },
828
+ render: (_args, value) => [{
829
+ type: 'text',
830
+ text: value.ok === true
831
+ ? `reasoning ${value.reasoning} (${value.source}); effort ${value.effort === '' ? 'not applied' : value.effort}`
832
+ : `reasoning not changed: ${String(value.reason ?? '')}`,
833
+ }],
834
+ presentationMeta: (_args, value) => value.checkpoint,
835
+ },
836
+ async execute(args, exec) {
837
+ if (exec.agent === undefined)
838
+ throw new Error('coding_reasoning requires an owning agent session');
839
+ const state = stateOf(exec.agent);
840
+ if (state === undefined)
841
+ throw new Error('coding_reasoning: this agent is not a Coding lead session');
842
+ const report = (ok, extra) => {
843
+ const summary = reasoning.summary(exec.agent);
844
+ return {
845
+ ok,
846
+ reasoning: summary.level ?? '',
847
+ source: summary.source,
848
+ effort: reasoning.describe(exec.agent).effort ?? '',
849
+ ...summary.reason === undefined ? {} : { reason: summary.reason },
850
+ stage: state.stage,
851
+ mode: state.mode,
852
+ status: statusLine(state),
853
+ checkpoint: checkpointOf(state),
854
+ ...extra,
855
+ };
856
+ };
857
+ if (args?.effort === undefined)
858
+ return report(true, {});
859
+ const pinned = config().reasoning;
860
+ if (pinned !== 'auto') {
861
+ return report(false, {
862
+ reason: `reasoning is pinned to ${pinned} by the Coding configuration; `
863
+ + 'set reasoning: auto before using an in-session override',
864
+ });
865
+ }
866
+ reasoning.override(exec.agent, args.effort, state.turn);
867
+ await reasoning.apply(exec.agent, exec.signal, undefined, state.turn);
868
+ return report(true, {});
869
+ },
870
+ })), 'dsh-coding: coding_reasoning');
871
+ // ── Cross-stage handoff ───────────────────────────────────────────────────
872
+ // The record, not the conversation, is what the workers receive: the lead
873
+ // writes it here, the runtime caps it, and every stage reads its own slice.
874
+ ctx.effect(() => ctx.tools.register(defineTool({
875
+ name: TOOL.handoff,
876
+ description: [
877
+ 'Read or update the cross-stage handoff record: the bounded context every worker receives.',
878
+ 'In requirements record the goal, the constraints, and the acceptance criteria; in plan record the',
879
+ 'decisions and the acceptance checks. Any stage may add findings and open questions as evidence.',
880
+ '`goal` replaces the recorded goal; every list field appends (de-duplicated, capped by the plugin).',
881
+ 'Record only what this stage adds or corrects; there is no need to repeat the whole history.',
882
+ 'In deliver write the delivery record back first (`delivered` / `followUps`): the next turn and a',
883
+ 'resumed session read that record, not this turn\'s message.',
884
+ ].join(' '),
885
+ parameters: {
886
+ goal: {
887
+ type: 'string',
888
+ description: 'What the run is for; replaces the recorded goal.',
889
+ },
890
+ constraints: {
891
+ type: 'array',
892
+ items: { type: 'string' },
893
+ description: 'Limits the change must respect; appended.',
894
+ },
895
+ acceptance: {
896
+ type: 'array',
897
+ items: { type: 'string' },
898
+ description: 'Observable checks that define done; appended. codex cannot enter verify without one.',
899
+ },
900
+ findings: {
901
+ type: 'array',
902
+ items: { type: 'string' },
903
+ description: 'Evidence worth carrying to the next stage; appended.',
904
+ },
905
+ decisions: {
906
+ type: 'array',
907
+ items: { type: 'string' },
908
+ description: 'Settled choices later stages must respect; appended.',
909
+ },
910
+ open: {
911
+ type: 'array',
912
+ items: { type: 'string' },
913
+ description: 'Questions still unanswered; appended.',
914
+ },
915
+ delivered: {
916
+ type: 'string',
917
+ description: '一条紧凑的交付记录:交付了什么、改了哪些文件、跑了哪个检查;覆盖已记录的交付。'
918
+ + '在 deliver 阶段写入,下一轮对话与重开会话都读它。',
919
+ },
920
+ followUps: {
921
+ type: 'array',
922
+ items: { type: 'string' },
923
+ description: '残余风险或后续跟进项;追加。',
924
+ },
925
+ reset: {
926
+ type: 'boolean',
927
+ description: 'Reset the verification retry budget; the handoff itself is kept.',
928
+ },
929
+ },
930
+ output: {
931
+ schema: {
932
+ type: 'object',
933
+ additionalProperties: false,
934
+ properties: {
935
+ ok: { type: 'boolean', required: true },
936
+ status: { type: 'string', required: true },
937
+ digest: { type: 'string', required: true },
938
+ checkpoint: { type: 'json' },
939
+ },
940
+ },
941
+ render: (_args, value) => [{
942
+ type: 'text',
943
+ text: value.digest === '' ? value.status : value.digest,
944
+ }],
945
+ presentationMeta: (_args, value) => value.checkpoint,
946
+ },
947
+ async execute(args, exec) {
948
+ if (exec.agent === undefined)
949
+ throw new Error('coding_handoff requires an owning agent session');
950
+ const state = stateOf(exec.agent);
951
+ if (state === undefined)
952
+ throw new Error('coding_handoff: this agent is not a Coding lead session');
953
+ if (args?.reset === true)
954
+ resetVerification(state);
955
+ // A field the model omitted is untouched, and an empty list is "no
956
+ // change": only the fields actually supplied reach the merge.
957
+ const list = (value) => (Array.isArray(value) ? stringList(value) : undefined);
958
+ const goal = typeof args?.goal === 'string' ? args.goal : undefined;
959
+ const constraints = list(args?.constraints);
960
+ const acceptance = list(args?.acceptance);
961
+ const findings = list(args?.findings);
962
+ const decisions = list(args?.decisions);
963
+ const open = list(args?.open);
964
+ const delivered = typeof args?.delivered === 'string' ? args.delivered : undefined;
965
+ const followUps = list(args?.followUps);
966
+ const patch = {
967
+ ...goal === undefined ? {} : { goal },
968
+ ...constraints === undefined ? {} : { constraints },
969
+ ...acceptance === undefined ? {} : { acceptance },
970
+ ...findings === undefined ? {} : { findings },
971
+ ...decisions === undefined ? {} : { decisions },
972
+ ...open === undefined ? {} : { open },
973
+ ...delivered === undefined ? {} : { delivered },
974
+ ...followUps === undefined ? {} : { followUps },
975
+ };
976
+ if (Object.keys(patch).length > 0) {
977
+ try {
978
+ state.handoff = mergeHandoff(state.handoff, patch);
979
+ }
980
+ catch (error) {
981
+ // The record is the workers' only context: a lost merge must reach the
982
+ // lead as a reported failure, not as a silently dropped update.
983
+ fail(state, 'handoff', error);
984
+ throw error;
985
+ }
986
+ state.updatedAt = Date.now();
987
+ }
988
+ return {
989
+ ok: true,
990
+ status: statusLine(state),
991
+ digest: handoffDigest(state.handoff),
992
+ checkpoint: checkpointOf(state),
993
+ };
994
+ },
995
+ })), 'dsh-coding: coding_handoff');
996
+ // ── Delegation: the only way the lead may change a file ───────────────────
997
+ // A subagent name is committed to the parent's catalog and never released, so
998
+ // a fixed name would permit exactly one delegation per session. A per-process
999
+ // ordinal is not enough either: this plugin instance is rebuilt on every Host
1000
+ // restart while the catalog survives, so the ordinal repeats and the first
1001
+ // dispatch after a restart collides with the previous generation's worker.
1002
+ // The name therefore carries a timestamp; the role prefix keeps it readable.
1003
+ let workerSeq = 0;
1004
+ const delegate = async (exec, role, args) => {
1005
+ if (exec.agent === undefined)
1006
+ throw new Error(`delegate_${role} requires an owning agent session`);
1007
+ const state = stateOf(exec.agent);
1008
+ if (state === undefined)
1009
+ throw new Error(`delegate_${role}: this agent is not a Coding lead session`);
1010
+ // One worker at a time: a second dispatch would overwrite the first
1011
+ // worker's record while its result is still in flight.
1012
+ if (state.worker?.status === 'running') {
1013
+ throw new Error(`delegate_${role}: a ${state.worker.role} worker is already running; wait for it to finish`);
1014
+ }
1015
+ const required = role === 'plan' ? 'plan' : role === 'implement' ? 'implement' : 'verify';
1016
+ if (state.stage !== required) {
1017
+ throw new Error(`delegate_${role} runs only in the ${required} stage (current: ${state.stage})`);
1018
+ }
1019
+ if (role === 'implement' && (state.plan === undefined || state.plan.items.length === 0)) {
1020
+ throw new Error('delegate_implement needs the plan stage task list: call todo_write first');
1021
+ }
1022
+ const task = typeof args?.task === 'string' ? args.task.trim() : '';
1023
+ if (task === '')
1024
+ throw new Error(`delegate_${role}: task must be a non-empty self-contained brief`);
1025
+ const files = Array.isArray(args.files) ? args.files.filter((file) => typeof file === 'string') : [];
1026
+ const route = resolveWorkerRoute(config(), role);
1027
+ const workerName = `${role}-${Date.now().toString(36)}-${(workerSeq += 1)}`;
1028
+ const startedAt = Date.now();
1029
+ // Reserve the single worker slot before the model check awaits: a
1030
+ // concurrent dispatch must see the slot taken even while validation is
1031
+ // still in flight, or both calls pass the guard and race for the result.
1032
+ state.worker = { role, status: 'running', startedAt };
1033
+ state.updatedAt = startedAt;
1034
+ // planner 尝试一进入就记为失败:worker 路由不可用时门禁仍然打开,避免一次
1035
+ // 失败的派发锁死整个 codex 流程;派发结束再按实际结果改写。
1036
+ if (role === 'plan')
1037
+ state.planner = { route: route.text, outcome: 'failed', at: startedAt };
1038
+ try {
1039
+ await assertWorkerModel(ctx, route, exec.signal);
1040
+ }
1041
+ catch (error) {
1042
+ fail(state, 'delegate', error);
1043
+ const text = messageOf(error);
1044
+ state.worker = { role, status: 'failed', startedAt, finishedAt: Date.now(), summary: text };
1045
+ state.updatedAt = Date.now();
1046
+ throw new Error(`${text} Fix the route and call delegate_${role} again; retrying the same route will fail identically.`);
1047
+ }
1048
+ // verify 只有在 codex 且任务复杂时才值得付出整份 AGENTS.md 的上下文:
1049
+ // 多子任务意味着跨任务依赖,改动面大意味着需要仓库规则。
1050
+ const taskCount = Math.max(state.handoff?.tasks.length ?? 0, state.plan?.items.length ?? 0);
1051
+ const withInstructions = role === 'verify'
1052
+ && needsWorkspaceInstructions({ mode: state.mode, taskCount, changedFiles: state.files.size });
1053
+ let started;
1054
+ try {
1055
+ started = await ctx.subagents.startActivation({
1056
+ provider: 'spawn',
1057
+ agentPreset: withInstructions ? WORKER_PRESETS.verifyWithInstructions : workerPreset(role),
1058
+ name: workerName,
1059
+ label: workerLabel(role, task),
1060
+ prompt: [{
1061
+ type: 'text',
1062
+ text: role === 'plan'
1063
+ ? plannerPrompt(task, state)
1064
+ : role === 'implement' ? implementPrompt(task, files, args.acceptance, state) : verifyPrompt(task, state, withInstructions),
1065
+ }],
1066
+ parent: exec.agent,
1067
+ signal: exec.signal,
1068
+ delivery: 'caller',
1069
+ agentOptions: { provider: route.provider, model: route.model },
1070
+ outputSchema: role === 'plan' ? PLANNER_REPORT_SCHEMA : role === 'implement' ? IMPLEMENT_REPORT_SCHEMA : VERIFY_REPORT_SCHEMA,
1071
+ });
1072
+ }
1073
+ catch (error) {
1074
+ fail(state, 'delegate', error);
1075
+ state.worker = { role, status: 'failed', startedAt, finishedAt: Date.now(), summary: messageOf(error) };
1076
+ throw new Error(`delegate_${role}: could not start the worker: ${messageOf(error)}`);
1077
+ }
1078
+ state.worker = { ...state.worker, childId: started.childId, startedAt };
1079
+ let result;
1080
+ try {
1081
+ result = await started.result;
1082
+ }
1083
+ catch (error) {
1084
+ fail(state, 'delegate', error);
1085
+ state.worker = { role, status: 'failed', childId: started.childId, startedAt, finishedAt: Date.now(), summary: messageOf(error) };
1086
+ throw new Error(`delegate_${role}: the worker failed: ${messageOf(error)}`);
1087
+ }
1088
+ finally {
1089
+ void Promise.resolve(started.dispose?.()).catch(() => { });
1090
+ }
1091
+ const report = asWorkerReport(result?.structured);
1092
+ const stopReason = String(result?.stopReason ?? 'error');
1093
+ const ok = stopReason === 'completed' && report?.ok === true;
1094
+ state.worker = {
1095
+ role,
1096
+ status: ok ? 'completed' : 'failed',
1097
+ childId: started.childId,
1098
+ startedAt,
1099
+ finishedAt: Date.now(),
1100
+ ...report === undefined
1101
+ ? { summary: outputText(result) ?? `worker ended with ${stopReason}` }
1102
+ : { summary: report.summary, ...report.files.length === 0 ? {} : { files: report.files } },
1103
+ };
1104
+ state.updatedAt = Date.now();
1105
+ if (role === 'plan') {
1106
+ state.planner = { route: route.text, outcome: ok ? 'completed' : 'failed', at: state.updatedAt };
1107
+ }
1108
+ // The dispatch is the failure point either way: a worker that ran but did
1109
+ // not complete is the same interruption, and a completed one clears it.
1110
+ if (ok)
1111
+ clearFailure(state, 'delegate');
1112
+ else
1113
+ fail(state, 'delegate', new Error(state.worker?.summary ?? `the ${role} worker ended with ${stopReason}`));
1114
+ if (role === 'implement' && ok && report !== undefined) {
1115
+ // A new implementation invalidates any earlier verification: the deliver
1116
+ // gate must read evidence produced after the last edit.
1117
+ state.verification = undefined;
1118
+ // A worker re-reports files it already touched, so a dispatch total
1119
+ // overcounts; the card's "files changed" is a session total of paths.
1120
+ for (const file of report.files)
1121
+ state.files.add(file);
1122
+ state.edits = state.baseEdits + state.files.size;
1123
+ // The verifier and the delivery read the handoff, not the worker catalog:
1124
+ // record what this dispatch changed and what the worker noted.
1125
+ const notes = report.notes?.trim() ?? '';
1126
+ state.handoff = mergeHandoff(state.handoff, {
1127
+ changes: report.files.map(file => ({ file, summary: report.summary })),
1128
+ ...notes === '' ? {} : { findings: [notes] },
1129
+ });
1130
+ }
1131
+ if (role === 'plan' && ok && report !== undefined) {
1132
+ // The planner's task list becomes the plan the implement workers receive,
1133
+ // and its summary is the finding the later stages plan against.
1134
+ const summary = report.summary.trim();
1135
+ state.handoff = mergeHandoff(state.handoff, {
1136
+ tasks: report.tasks,
1137
+ ...summary === '' ? {} : { findings: [report.summary] },
1138
+ });
1139
+ }
1140
+ if (role === 'verify') {
1141
+ // A report that contradicts itself (ok, but failing tests) is not
1142
+ // evidence: the deliver gate reads this record, and the lead must see
1143
+ // both the command and the failing names.
1144
+ const command = report?.command?.trim() ?? '';
1145
+ const failedTests = report?.failedTests ?? [];
1146
+ const missingCommand = command === '';
1147
+ const passed = ok && !missingCommand && failedTests.length === 0;
1148
+ const outcome = {
1149
+ passed,
1150
+ kind: report?.kind ?? 'test',
1151
+ scope: report?.scope ?? 'package',
1152
+ source: 'worker',
1153
+ command: missingCommand ? '(verify worker reported no command)' : command,
1154
+ exitCode: passed ? 0 : 1,
1155
+ durationMs: Date.now() - startedAt,
1156
+ failedTests,
1157
+ errors: [
1158
+ ...report?.findings ?? [],
1159
+ ...missingCommand ? ['the verify worker did not report the command it ran'] : [],
1160
+ ...failedTests.length === 0 ? [] : [`the verify worker reported failing tests: ${failedTests.join('; ')}`],
1161
+ ],
1162
+ ranAt: Date.now(),
1163
+ };
1164
+ // The retry budget, not the lead's patience, decides when the loop stops.
1165
+ recordVerification(state, outcome, {
1166
+ maxAttempts: config().maxVerifyAttempts,
1167
+ maxSameFailure: config().maxSameFailure,
1168
+ });
1169
+ const reported = report?.findings ?? [];
1170
+ const findings = reported.length > 0
1171
+ ? reported
1172
+ : report !== undefined && report.summary.trim() !== '' ? [report.summary] : [];
1173
+ if (findings.length > 0)
1174
+ state.handoff = mergeHandoff(state.handoff, { findings });
1175
+ }
1176
+ if (role === 'plan') {
1177
+ return {
1178
+ ok,
1179
+ worker: role,
1180
+ childId: started.childId,
1181
+ stopReason,
1182
+ summary: report?.summary ?? outputText(result) ?? '',
1183
+ tasks: report?.tasks ?? [],
1184
+ checkpoint: checkpointOf(state),
1185
+ };
1186
+ }
1187
+ return {
1188
+ ok,
1189
+ worker: role,
1190
+ childId: started.childId,
1191
+ stopReason,
1192
+ summary: report?.summary ?? outputText(result) ?? '',
1193
+ files: report?.files ?? [],
1194
+ findings: report?.findings ?? [],
1195
+ failedTests: report?.failedTests ?? [],
1196
+ notes: report?.notes ?? '',
1197
+ output: ok ? '' : outputText(result) ?? '',
1198
+ checkpoint: checkpointOf(state),
1199
+ };
1200
+ };
1201
+ const delegationOutput = {
1202
+ schema: {
1203
+ type: 'object',
1204
+ additionalProperties: false,
1205
+ properties: {
1206
+ ok: { type: 'boolean', required: true },
1207
+ worker: { type: 'string', required: true },
1208
+ childId: { type: 'string', required: true },
1209
+ stopReason: { type: 'string', required: true },
1210
+ summary: { type: 'string', required: true },
1211
+ files: { type: 'array', items: { type: 'string' } },
1212
+ findings: { type: 'array', items: { type: 'string' } },
1213
+ failedTests: { type: 'array', items: { type: 'string' } },
1214
+ notes: { type: 'string' },
1215
+ output: { type: 'string' },
1216
+ checkpoint: { type: 'json' },
1217
+ },
1218
+ },
1219
+ render: (_args, value) => [{
1220
+ type: 'text',
1221
+ text: value.ok === true
1222
+ ? `${value.worker} worker completed: ${value.summary}`
1223
+ + (value.files.length === 0 ? '' : `\nFiles changed: ${value.files.join(', ')}`)
1224
+ : `${value.worker} worker did not complete (${value.stopReason}): ${value.summary}`
1225
+ + (value.failedTests.length === 0 ? '' : `\nFailing tests: ${value.failedTests.join('; ')}`)
1226
+ + (value.output === '' ? '' : `\n${value.output}`),
1227
+ }],
1228
+ presentationMeta: (_args, value) => value.checkpoint,
1229
+ };
1230
+ const plannerOutput = {
1231
+ schema: {
1232
+ type: 'object',
1233
+ additionalProperties: false,
1234
+ properties: {
1235
+ ok: { type: 'boolean', required: true },
1236
+ worker: { type: 'string', required: true },
1237
+ childId: { type: 'string', required: true },
1238
+ stopReason: { type: 'string', required: true },
1239
+ summary: { type: 'string', required: true },
1240
+ // The planner's tasks are handoff tasks, so the canonical value keeps
1241
+ // the same shape the handoff and the implement briefs read.
1242
+ tasks: {
1243
+ type: 'array',
1244
+ items: {
1245
+ type: 'object',
1246
+ additionalProperties: false,
1247
+ properties: {
1248
+ goal: { type: 'string', required: true },
1249
+ files: { type: 'array', items: { type: 'string' } },
1250
+ acceptance: { type: 'string' },
1251
+ avoid: { type: 'string' },
1252
+ },
1253
+ },
1254
+ },
1255
+ checkpoint: { type: 'json' },
1256
+ },
1257
+ },
1258
+ render: (_args, value) => [{
1259
+ type: 'text',
1260
+ text: value.ok === true
1261
+ ? `plan worker completed: ${value.summary}\n\nSingle-purpose tasks:\n`
1262
+ + value.tasks.map((task, index) => (`${index + 1}. ${String(task.goal)}`
1263
+ + (Array.isArray(task.files) && task.files.length > 0 ? ` [${task.files.join(', ')}]` : '')
1264
+ + ` — done: ${String(task.acceptance ?? '')}`
1265
+ + (typeof task.avoid === 'string' && task.avoid !== '' ? `; avoid: ${task.avoid}` : ''))).join('\n')
1266
+ + '\n\nNext: call todo_write with one pending item per task, then advance to implement and dispatch each task with delegate_implement.'
1267
+ : `plan worker did not complete (${value.stopReason}): ${value.summary}`,
1268
+ }],
1269
+ presentationMeta: (_args, value) => value.checkpoint,
1270
+ };
1271
+ ctx.effect(() => ctx.tools.register(defineTool({
1272
+ name: TOOL.plan,
1273
+ description: [
1274
+ 'Delegate requirement analysis and sub-task planning to the planner worker (pro model).',
1275
+ 'The worker explores the workspace read-only and returns a list of single-purpose sub-tasks;',
1276
+ 'it cannot edit files, run a shell, or delegate further. Available only in the plan stage.',
1277
+ 'After it returns, call todo_write with one pending item per task, then advance to implement.',
1278
+ ].join(' '),
1279
+ parameters: {
1280
+ task: {
1281
+ type: 'string',
1282
+ required: true,
1283
+ description: 'The requirement to analyse, self-contained; the worker cannot see this conversation.',
1284
+ },
1285
+ },
1286
+ output: plannerOutput,
1287
+ timeoutMs: 3_600_000,
1288
+ async execute(args, exec) {
1289
+ return delegate(exec, 'plan', args);
1290
+ },
1291
+ })), 'dsh-coding: delegate_plan');
1292
+ ctx.effect(() => ctx.tools.register(defineTool({
1293
+ name: TOOL.implement,
1294
+ description: [
1295
+ 'Delegate one implementation task to the implement worker and wait for its structured report.',
1296
+ 'The worker runs in an isolated context with only the editing tools (read, apply_patch, edit, write);',
1297
+ 'the lead keeps no edit permission. The brief must be self-contained: goal, acceptance criteria,',
1298
+ 'exact files, and the excerpts the worker needs. Available only in the implement stage.',
1299
+ ].join(' '),
1300
+ parameters: {
1301
+ task: {
1302
+ type: 'string',
1303
+ required: true,
1304
+ description: 'Complete, self-contained implementation brief; the worker cannot see this conversation.',
1305
+ },
1306
+ files: {
1307
+ type: 'array',
1308
+ items: { type: 'string' },
1309
+ description: 'Files the worker should touch, as repository-relative paths.',
1310
+ },
1311
+ acceptance: {
1312
+ type: 'string',
1313
+ description: 'Observable acceptance criteria the worker must satisfy.',
1314
+ },
1315
+ },
1316
+ output: delegationOutput,
1317
+ timeoutMs: 3_600_000,
1318
+ async execute(args, exec) {
1319
+ return delegate(exec, 'implement', args);
1320
+ },
1321
+ })), 'dsh-coding: delegate_implement');
1322
+ ctx.effect(() => ctx.tools.register(defineTool({
1323
+ name: TOOL.verify,
1324
+ description: [
1325
+ 'Delegate one read-only verification investigation to the verify worker.',
1326
+ 'The worker can read files, search them, and run checks through run_verification; it holds no edit tool.',
1327
+ 'Use it when a failing check needs diagnosis, or when the report should cite reproducible evidence.',
1328
+ 'Available only in the verify stage.',
1329
+ ].join(' '),
1330
+ parameters: {
1331
+ task: {
1332
+ type: 'string',
1333
+ required: true,
1334
+ description: 'What to verify and the failure to investigate, self-contained.',
1335
+ },
1336
+ },
1337
+ output: delegationOutput,
1338
+ timeoutMs: 3_600_000,
1339
+ async execute(args, exec) {
1340
+ return delegate(exec, 'verify', args);
1341
+ },
1342
+ })), 'dsh-coding: delegate_verify');
1343
+ // ── Structured verification ───────────────────────────────────────────────
1344
+ registerVerificationTool(ctx, {
1345
+ config,
1346
+ onRun: (run, exec) => {
1347
+ const state = stateOf(exec.agent);
1348
+ if (state === undefined)
1349
+ return;
1350
+ // Every failed check spends one attempt of the retry budget, whether the
1351
+ // lead ran it or a verify worker reported it.
1352
+ recordVerification(state, {
1353
+ passed: run.passed,
1354
+ kind: run.kind,
1355
+ scope: run.scope,
1356
+ source: 'lead',
1357
+ command: run.command,
1358
+ exitCode: run.exitCode,
1359
+ durationMs: run.durationMs,
1360
+ failedTests: run.failedTests,
1361
+ errors: run.errors,
1362
+ ranAt: run.ranAt,
1363
+ }, {
1364
+ maxAttempts: config().maxVerifyAttempts,
1365
+ maxSameFailure: config().maxSameFailure,
1366
+ });
1367
+ if (run.passed) {
1368
+ clearFailure(state, 'verification');
1369
+ return;
1370
+ }
1371
+ // A normal failing check keeps its own budget/BLOCKED path; only a check
1372
+ // that could not start or timed out is a runtime failure.
1373
+ if (run.command === '' || run.errors.some(error => error.includes('verificationTimeoutMs'))) {
1374
+ fail(state, 'verification', new Error(run.errors.join('; ') || `verification ${run.kind} could not run`));
1375
+ }
1376
+ },
1377
+ decorate: (exec) => {
1378
+ const state = stateOf(exec.agent);
1379
+ return state === undefined ? null : checkpointOf(state);
1380
+ },
1381
+ });
1382
+ // ── Control channel for the UI and the user ──────────────────────────────
1383
+ // The body is extracted so an exception becomes a reported failure with a
1384
+ // next move: `/coding` is the operator's own recovery path.
1385
+ const handleCodingCommand = async ({ agent, rawInput, signal }) => {
1386
+ const state = stateOf(agent);
1387
+ if (state === undefined) {
1388
+ return { kind: 'error', text: 'this session is not running the dsh-coding preset' };
1389
+ }
1390
+ const text = typeof rawInput === 'string' ? rawInput.trim().toLowerCase() : '';
1391
+ if (text === '') {
1392
+ return { kind: 'success', text: `${statusLine(state)}\nstages: ${stagePath(state.mode)}` };
1393
+ }
1394
+ if (text === 'reset') {
1395
+ // The budget belongs to the current fix/verify loop; the handoff and
1396
+ // the recorded verification stay as evidence.
1397
+ resetVerification(state);
1398
+ return { kind: 'success', text: `verification retry budget reset; ${statusLine(state)}` };
1399
+ }
1400
+ if (text === 'memory') {
1401
+ // 交接文档由 Host 写盘:浏览器半只发这一行命令,不直接写文件。
1402
+ const written = await writeMemoryDocument(ctx, agent, state, { signal });
1403
+ if (!written.ok)
1404
+ return { kind: 'error', text: `${written.reason} — ${written.action}` };
1405
+ return {
1406
+ kind: 'success',
1407
+ text: `handoff document written: ${written.displayPath} (session ${state.sessionId})`,
1408
+ };
1409
+ }
1410
+ if (text.startsWith('stage')) {
1411
+ const target = text.slice('stage'.length).trim();
1412
+ if (!CODING_STAGES.includes(target)) {
1413
+ return { kind: 'error', text: `unknown stage "${target}"; use ${CODING_STAGES.join(', ')}` };
1414
+ }
1415
+ const check = checkAdvance(state, target, advanceOptions(agent));
1416
+ if (!check.ok) {
1417
+ // A user-issued move reports the gate but never arms the
1418
+ // step-blocking refusal meant for a model that tried to skip it.
1419
+ return { kind: 'error', text: check.reason ?? 'refused' };
1420
+ }
1421
+ applyStage(state, target, 'user control');
1422
+ // A user-issued exit from an exhausted retry budget is still a
1423
+ // blocked delivery: the report must disclose the failing check.
1424
+ if (check.blocked === true)
1425
+ state.deliveryBlocked = true;
1426
+ syncTable(agent, state);
1427
+ // A stage change takes effect at the next step of the live turn.
1428
+ agent.steer?.(controlMessage(`The user moved this session to the ${target} stage.\n\n${stageContext({
1429
+ mode: state.mode,
1430
+ stage: state.stage,
1431
+ status: statusLine(state),
1432
+ handoff: handoffDigest(state.handoff),
1433
+ })}`, `stage → ${target}`));
1434
+ return { kind: 'success', text: `stage set to ${target}; ${statusLine(state)}` };
1435
+ }
1436
+ if (text.startsWith('set')) {
1437
+ const target = text.slice('set'.length).trim();
1438
+ if (!CODING_MODES.includes(target)) {
1439
+ return { kind: 'error', text: `unknown mode "${target}"; use ${CODING_MODES.join(', ')}` };
1440
+ }
1441
+ applyMode(state, target);
1442
+ syncTable(agent, state);
1443
+ // Silent by design: the pre-Turn picker sets the mode for the first
1444
+ // message and must not start a Turn or inject a control message.
1445
+ return { kind: 'success', text: `mode set to ${target}; ${statusLine(state)}` };
1446
+ }
1447
+ if (!CODING_MODES.includes(text)) {
1448
+ return { kind: 'error', text: `unknown mode "${text}"; use ${CODING_MODES.join(', ')}` };
1449
+ }
1450
+ applyMode(state, text);
1451
+ syncTable(agent, state);
1452
+ // A mode switch changes the plan, so it belongs to a fresh turn.
1453
+ agent.followup?.(controlMessage(`The user switched this session to ${text} mode. Stages: ${stagePath(state.mode)}. `
1454
+ + 'Continue under that mode; re-read the stage contract injected with the next step.', `mode → ${text}`));
1455
+ return { kind: 'success', text: `mode set to ${text}; ${statusLine(state)}` };
1456
+ };
1457
+ ctx.inject(['commands'], (child) => {
1458
+ child.commands.register({
1459
+ name: 'coding',
1460
+ description: 'Show or set this session\'s Coding mode or stage: /coding <auto|consult|review|codex>, /coding set <mode> (silent, no Turn), or /coding stage <name>. /coding memory writes a handoff document for this turn under .agents/memory at the project root.',
1461
+ input: { hint: 'auto | consult | review | codex | set <auto|consult|review|codex> | stage <requirements|plan|implement|verify|deliver> | reset | memory' },
1462
+ handler: async (payload) => {
1463
+ try {
1464
+ return await handleCodingCommand(payload);
1465
+ }
1466
+ catch (error) {
1467
+ const state = stateOf(payload.agent);
1468
+ if (state !== undefined)
1469
+ fail(state, 'command', error);
1470
+ const reason = messageOf(error);
1471
+ const action = state === undefined
1472
+ ? 'Fix the reported error, then retry the command.'
1473
+ : makeFailure('command', error, currentLanguage()).action;
1474
+ return { kind: 'error', text: `${reason} — ${action}` };
1475
+ }
1476
+ },
1477
+ });
1478
+ });
1479
+ }
1480
+ /**
1481
+ * Register the conversation-language section exactly once per agent.
1482
+ * @param ctx - preset context.
1483
+ * @param config - live configuration reader.
1484
+ */
1485
+ function registerLanguage(ctx, config) {
1486
+ const prompt = ctx.get?.('systemPrompt') ?? ctx.systemPrompt;
1487
+ if (typeof prompt?.context !== 'function')
1488
+ return;
1489
+ try {
1490
+ prompt.context({
1491
+ name: 'coding:language',
1492
+ order: 12,
1493
+ text: () => languagePrompt(resolveHostLanguage({
1494
+ mode: config().language,
1495
+ loader: ctx.get?.('loader') ?? ctx.loader,
1496
+ systemLanguages,
1497
+ })),
1498
+ });
1499
+ }
1500
+ catch (error) {
1501
+ ctx.logger?.warn?.(`dsh-coding: could not register the language prompt section: ${messageOf(error)}`);
1502
+ }
1503
+ }
1504
+ /** Render a worker's final text output, capped for a tool result. */
1505
+ function outputText(result) {
1506
+ const content = result?.output;
1507
+ if (!Array.isArray(content))
1508
+ return undefined;
1509
+ const text = content
1510
+ .map((block) => (block?.type === 'text' && typeof block.text === 'string' ? block.text : ''))
1511
+ .join('\n')
1512
+ .trim();
1513
+ return text === '' ? undefined : text.slice(0, 4000);
1514
+ }
1515
+ function messageOf(error) {
1516
+ return error instanceof Error ? error.message : String(error);
1517
+ }
1518
+ /**
1519
+ * Fail the mount when the runtime cannot honour its own gates: a worker route
1520
+ * that could silently fall back to the lead's model, or a subagent backend that
1521
+ * cannot carry the explicit worker preset.
1522
+ * @param ctx - plugin context.
1523
+ * @param config - verified configuration.
1524
+ */
1525
+ async function preflight(ctx, config) {
1526
+ // Every worker route is parsed eagerly, so a malformed field fails the mount
1527
+ // instead of the first dispatch.
1528
+ const routes = WORKER_ROLES.map(role => resolveWorkerRoute(config, role));
1529
+ const provider = ctx.subagents?.getProvider?.('spawn');
1530
+ if (provider === undefined) {
1531
+ throw new Error('dsh-coding: the "spawn" subagent provider is not registered; mount '
1532
+ + '@deepseek-ai/dsh-subagent-spawn-in-process in this composition');
1533
+ }
1534
+ const capabilities = provider.capabilities ?? {};
1535
+ for (const capability of ['agentOptions', 'agentPreset', 'outputSchema']) {
1536
+ if (capabilities[capability] !== true) {
1537
+ throw new Error(`dsh-coding: the "spawn" subagent provider does not support ${capability}, which the worker dispatch requires`);
1538
+ }
1539
+ }
1540
+ // Provider existence is checkable; the model catalog may need credentials, so
1541
+ // an empty or unavailable catalog defers model validation to the dispatch.
1542
+ const providers = describeProviders(ctx);
1543
+ if (providers.length > 0) {
1544
+ for (const route of routes) {
1545
+ if (!providers.includes(route.provider)) {
1546
+ const available = providers.join(', ');
1547
+ throw new Error(`dsh-coding: ${route.field} names LLM provider "${route.provider}", which is not registered; `
1548
+ + `available providers: ${available || '(none)'}`);
1549
+ }
1550
+ }
1551
+ }
1552
+ }