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/index.js CHANGED
@@ -1,13 +1,116 @@
1
+ /**
2
+ * Host-side settings service of the `dsh-coding` bundle.
3
+ *
4
+ * This row is the bundle's only Host contribution: it owns the verified
5
+ * configuration the Coding preset and its four worker presets read, and it
6
+ * performs no agent work by itself. Installing the bundle therefore changes no
7
+ * existing session; only a session that selects the Coding preset runs the
8
+ * enforced runtime.
9
+ *
10
+ * It also filters this bundle's four internal worker presets out of the exported
11
+ * preset roster: no client offers them, while the Host roster keeps resolving
12
+ * the compositions `delegate_implement` and `delegate_verify` dispatch to.
13
+ *
14
+ * The configuration is validated twice on purpose: {@link Config} (Schemastery)
15
+ * rejects a malformed row at activation, and {@link normalizeConfig} parses both
16
+ * worker routes so a missing model fails the mount instead of silently
17
+ * inheriting the lead's own model at dispatch.
18
+ *
19
+ * @module dsh-coding
20
+ */
1
21
  import { Service } from '@deepseek-ai/cordis';
22
+ import { Config as CodingConfigSchema, configJsonSchema, normalizeConfig, } from './config.js';
23
+ import { WORKER_PRESETS } from './stages.js';
24
+ // `Config` carries both meanings: the Schemastery schema (value) and the
25
+ // configuration type (interface) it validates.
26
+ export { Config, configJsonSchema, parseWorkerRoute } from './config.js';
27
+ /** The same JSON Schema under the name non-Loader consumers expect. */
28
+ export const configSchema = configJsonSchema;
29
+ /** Cordis plugin name used by loader diagnostics. */
30
+ export const name = 'dsh-coding';
31
+ /** Preset ids this bundle reserves for its subagents, never offered to a user. */
32
+ const WORKER_PRESET_IDS = [
33
+ WORKER_PRESETS.planner,
34
+ WORKER_PRESETS.implement,
35
+ WORKER_PRESETS.verify,
36
+ WORKER_PRESETS.verifyWithInstructions,
37
+ ];
38
+ /**
39
+ * The client-facing roster without this bundle's worker presets. The Host
40
+ * roster keeps them: `delegate_implement` / `delegate_verify` resolve their
41
+ * compositions from it, and only the exported list is a user-facing surface.
42
+ * @param roster - `remoteExportList()` result.
43
+ * @returns the same roster minus the worker rows.
44
+ */
45
+ export function filterWorkerPresets(roster) {
46
+ return { ...roster, presets: roster.presets.filter(row => !WORKER_PRESET_IDS.includes(row.id)) };
47
+ }
2
48
  /**
3
- * Inert Host entry for the `dsh-coding` bundle.
49
+ * Filter the preset registry's client-facing export for this deployment.
4
50
  *
5
- * It registers the `dshCoding` service and does nothing else: the package
6
- * reserves the npm name and proves that the bundle installs and composes. It
7
- * adds no tools, prompts, presets, client code, or settings.
51
+ * DSH has no hidden-preset flag, and a browser-side replacement of the shipped
52
+ * picker costs the product's own chip, copy, and interaction. The registry
53
+ * exports its roster through one Remote method, and the gateway resolves that
54
+ * method per call, so wrapping it here hides the workers from every client
55
+ * surface while the Host keeps dispatching to them.
56
+ * @param ctx - owning host context.
8
57
  */
9
- export default class DshCodingService extends Service {
10
- constructor(ctx) {
11
- super(ctx, 'dshCoding');
58
+ export function installWorkerPresetFilter(ctx) {
59
+ ctx.inject(['agentPresets'], (child) => {
60
+ child.effect(() => {
61
+ const registry = child.agentPresets;
62
+ const original = registry?.remoteExportList;
63
+ if (registry === undefined || typeof original !== 'function')
64
+ return;
65
+ const wrapped = async (...args) => filterWorkerPresets(await original.apply(registry, args));
66
+ registry.remoteExportList = wrapped;
67
+ return () => {
68
+ // Only undo our own wrapper: a later generation may have re-wrapped it.
69
+ if (registry.remoteExportList === wrapped)
70
+ registry.remoteExportList = original;
71
+ };
72
+ }, 'dsh-coding: preset roster filter');
73
+ });
74
+ }
75
+ /**
76
+ * Bundle settings surface (`ctx.dshCodingRuntime`).
77
+ *
78
+ * The service exposes only immutable, already-verified options: consumers never
79
+ * re-validate, and no agent behavior depends on an unvalidated value.
80
+ */
81
+ export default class DshCodingSettings extends Service {
82
+ /** Schemastery schema the Loader validates the bundle row's `config` with. */
83
+ static Config = CodingConfigSchema;
84
+ raw;
85
+ /**
86
+ * @param ctx - owning host context.
87
+ * @param config - Loader-validated row configuration. The page-editable fields
88
+ * arrive as Schemastery volatile accessors, so every read below observes the
89
+ * value currently saved on the plugin page.
90
+ * @throws when a worker route is absent or not a `provider/model` pair.
91
+ */
92
+ constructor(ctx, config) {
93
+ super(ctx, 'dshCodingRuntime');
94
+ this.raw = config;
95
+ // Validate once at activation so a bad row fails loudly; later edits are
96
+ // validated again on every read. `normalizeConfig` reads every field through
97
+ // `volatileValue`, so the row must be passed through unchanged: a hand-copied
98
+ // field map drops any route added later (a missing `plannerWorkerModel` threw
99
+ // here and took the whole bundle's presets down with it).
100
+ normalizeConfig(this.raw);
101
+ // The plugin manager page renders our own configuration form, so the
102
+ // automatic settings page is switched off for this entry.
103
+ ctx.inject(['settings'], (child) => {
104
+ child.effect(() => child.settings.configure({ auto: false }, ctx.fiber));
105
+ });
106
+ // Hide this bundle's internal worker presets from the exported roster.
107
+ installWorkerPresetFilter(ctx);
108
+ }
109
+ /**
110
+ * Verified configuration, re-read from the volatile fields on every access.
111
+ * @throws when a page-edited worker route is not a usable `provider/model` pair.
112
+ */
113
+ get options() {
114
+ return normalizeConfig(this.raw);
12
115
  }
13
116
  }
@@ -0,0 +1,136 @@
1
+ /** Values accepted by the settings surface. */
2
+ export const LANGUAGE_MODES = ['auto', 'zh', 'en'];
3
+ /** Malformed or unknown values fall back to automatic resolution. */
4
+ export function normalizeLanguageMode(value) {
5
+ return value === 'zh' || value === 'en' || value === 'auto' ? value : 'auto';
6
+ }
7
+ /** Lowercased primary language tag, ignoring the codeset and `@modifier`. */
8
+ function primaryTag(tag) {
9
+ if (typeof tag !== 'string')
10
+ return '';
11
+ return tag.trim().toLowerCase().replace(/_/g, '-').split('.')[0] ?? '';
12
+ }
13
+ /**
14
+ * Map one BCP 47-style tag (or a POSIX `LANG` value) onto a shipped language.
15
+ * Chinese is the only match that selects Chinese; every other tag is English.
16
+ */
17
+ export function languageOf(tag) {
18
+ const normalized = primaryTag(tag);
19
+ if (normalized === 'zh' || normalized.startsWith('zh-'))
20
+ return 'zh';
21
+ return 'en';
22
+ }
23
+ /**
24
+ * The shipped language of one tag, or `undefined` when this package ships
25
+ * neither. A desktop language list is consulted in order, so an unsupported
26
+ * entry (`ja-JP`) must be skipped rather than folded into English.
27
+ */
28
+ function shippedLanguageOf(tag) {
29
+ const normalized = primaryTag(tag);
30
+ if (normalized === 'zh' || normalized.startsWith('zh-'))
31
+ return 'zh';
32
+ if (normalized === 'en' || normalized.startsWith('en-'))
33
+ return 'en';
34
+ return undefined;
35
+ }
36
+ /**
37
+ * A POSIX locale that states no language preference at all. `C.UTF-8` is a
38
+ * codeset variant of `C`, and it is the value a macOS login shell commonly
39
+ * exports — treating it as "English" is what made a Chinese desktop answer in
40
+ * English.
41
+ */
42
+ export function isNeutralLocale(value) {
43
+ const base = primaryTag(value);
44
+ return base === '' || base === 'c' || base === 'posix';
45
+ }
46
+ /**
47
+ * The DSH interface preference, read from the locale plugin's loader entry.
48
+ * `loader.entries()` covers the whole composition, so a nested row is found
49
+ * too; an unavailable loader simply means "no explicit preference".
50
+ */
51
+ export function localePreferenceOf(loader) {
52
+ let entries;
53
+ try {
54
+ entries = typeof loader?.entries === 'function' ? [...loader.entries()] : [];
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ if (!Array.isArray(entries))
60
+ return undefined;
61
+ for (const entry of entries) {
62
+ const options = entry?.options ?? entry;
63
+ const name = options?.name;
64
+ if (typeof name !== 'string' || !name.includes('client-locale'))
65
+ continue;
66
+ const preference = options?.config?.preference;
67
+ if (typeof preference === 'string' && preference.trim() !== '')
68
+ return preference;
69
+ }
70
+ return undefined;
71
+ }
72
+ /** The host locale: POSIX locale variables first, then the OS default. */
73
+ export function hostLocaleOf(env = process.env) {
74
+ for (const name of ['LC_ALL', 'LC_MESSAGES', 'LANG']) {
75
+ const value = env[name];
76
+ if (typeof value !== 'string')
77
+ continue;
78
+ const trimmed = value.trim();
79
+ if (isNeutralLocale(trimmed))
80
+ continue;
81
+ return trimmed;
82
+ }
83
+ try {
84
+ return Intl.DateTimeFormat().resolvedOptions().locale;
85
+ }
86
+ catch {
87
+ return 'en';
88
+ }
89
+ }
90
+ /** Read the OS language list, tolerating a thunk that throws. */
91
+ function readSystemLanguages(input) {
92
+ if (typeof input === 'function') {
93
+ try {
94
+ const value = input();
95
+ return Array.isArray(value) ? value : [];
96
+ }
97
+ catch {
98
+ return [];
99
+ }
100
+ }
101
+ return Array.isArray(input) ? input : [];
102
+ }
103
+ /** Resolve the language used by prompts, tool text, and todo items. */
104
+ export function resolveHostLanguage(inputs = {}) {
105
+ const mode = normalizeLanguageMode(inputs.mode);
106
+ if (mode !== 'auto')
107
+ return mode;
108
+ const preference = localePreferenceOf(inputs.loader);
109
+ if (preference !== undefined)
110
+ return languageOf(preference);
111
+ // The desktop decides its own interface language from this list, and the
112
+ // POSIX variables it inherits from a login shell carry no language at all.
113
+ for (const tag of readSystemLanguages(inputs.systemLanguages)) {
114
+ const language = shippedLanguageOf(tag);
115
+ if (language !== undefined)
116
+ return language;
117
+ }
118
+ return languageOf(inputs.locale !== undefined ? inputs.locale : hostLocaleOf());
119
+ }
120
+ /** Prompt section that fixes the conversation language for the session. */
121
+ export function languagePrompt(language) {
122
+ if (language === 'zh') {
123
+ return [
124
+ 'Language: 本会话使用中文。',
125
+ '用中文回复用户,编写 todo 条目及其状态说明、计划摘要、澄清提问和交付说明。',
126
+ '代码、标识符、文件路径、命令与引用的报错原文保持原样,不做翻译。',
127
+ '只有用户切换 DSH 界面语言后,才改用对应语言。',
128
+ ].join('\n');
129
+ }
130
+ return [
131
+ 'Language: use English for this session.',
132
+ 'Write chat replies, todo items and their status notes, plan summaries, clarifying questions, and delivery notes in English.',
133
+ 'Keep code, identifiers, file paths, command lines, and quoted errors in their original form.',
134
+ 'Switch language only when the user changes the DSH interface language.',
135
+ ].join('\n');
136
+ }
package/lib/memory.js ADDED
@@ -0,0 +1,336 @@
1
+ /**
2
+ * 任务交接文档:把一轮 Coding 结束时的有界状态写成一篇 Markdown,落到
3
+ * `<会话 cwd>/.agents/memory/<sessionId>-<YYYYMMDD-HHmmss>.md`。
4
+ *
5
+ * 文档只由状态机与 coding_handoff 记录({@link CodingHandoff})拼出,不回读对话正文,
6
+ * 也不新增 Session 事件:它是本轮状态机与交接记录的存档快照,下一轮继续时仍以
7
+ * coding_handoff 的实时记录为准。拼装部分是纯函数({@link composeMemoryDocument}),
8
+ * 便于单测;写盘只走注入的 fs 服务(`resolve` + `writeText`),从不使用 `node:fs`。
9
+ *
10
+ * 本模块只在 Host 侧使用(依赖 `node:path`),客户端不导入它。
11
+ *
12
+ * @module dsh-coding/memory
13
+ */
14
+ import { join } from 'node:path';
15
+ /** 文档最大字符数;超出后截断到最后一个完整行。 */
16
+ export const MEMORY_LIMIT = 20000;
17
+ /** 交接文档在项目根下的目录。 */
18
+ export const MEMORY_DIR = join('.agents', 'memory');
19
+ /** 文件名里保留的 sessionId 字符;其余一律替换成 `-`。 */
20
+ const SAFE_ID = /[^A-Za-z0-9._-]/gu;
21
+ /**
22
+ * 生成一篇交接文档的文件名:`<清洗后的 sessionId>-<YYYYMMDD-HHmmss>.md`。
23
+ *
24
+ * sessionId 只保留 `[A-Za-z0-9._-]`,其余字符换成 `-`,清洗后为空则退回 `session`;
25
+ * 时间戳取 UTC,非法 `at` 按 epoch 处理而不抛错。
26
+ * @param sessionId - 会话 id。
27
+ * @param at - 时间戳(毫秒)。
28
+ * @returns 文件名,不含目录。
29
+ */
30
+ export function memoryFileName(sessionId, at) {
31
+ const cleaned = sessionId.replace(SAFE_ID, '-');
32
+ const stem = cleaned === '' ? 'session' : cleaned;
33
+ return `${stem}-${utcStamp(at)}.md`;
34
+ }
35
+ /**
36
+ * 组装整篇交接文档。
37
+ *
38
+ * 纯字符串拼接:不读文件、不取时钟(时间来自 {@link MemoryInput.now}),因此可以直接单测。
39
+ * 空数组与缺失字段对应的整节省略,不输出「无」。
40
+ * @param input - 状态机与 handoff 的有界快照。
41
+ * @returns 文档正文,超过 {@link MEMORY_LIMIT} 时截断并标注。
42
+ */
43
+ export function composeMemoryDocument(input) {
44
+ const handoff = input.handoff;
45
+ const cwd = textOf(input.cwd);
46
+ const lines = [
47
+ '# Coding 任务交接文档',
48
+ '',
49
+ `- 会话: ${input.sessionId}`,
50
+ `- 生成时间: ${isoStamp(input.now)}(UTC)`,
51
+ `- 工作目录: ${cwd === '' ? '(unknown)' : cwd}`,
52
+ `- 模式 / 阶段: ${input.mode} / ${input.stage}`,
53
+ `- 轮次: turn ${input.turn}`,
54
+ `- 状态: ${input.blocked ? '阻塞交付(BLOCKED)' : '正常交付'}`,
55
+ ];
56
+ pushText(lines, '目标', handoff?.goal);
57
+ pushList(lines, '约束', handoff?.constraints ?? []);
58
+ pushList(lines, '验收标准', handoff?.acceptance ?? []);
59
+ pushText(lines, '交付记录', handoff?.delivered);
60
+ pushList(lines, '后续跟进', handoff?.followUps ?? []);
61
+ pushList(lines, '决策', handoff?.decisions ?? []);
62
+ pushList(lines, '发现', handoff?.findings ?? []);
63
+ pushList(lines, '待答问题', handoff?.open ?? []);
64
+ pushPlan(lines, input.plan);
65
+ pushTasks(lines, handoff?.tasks ?? []);
66
+ pushChanges(lines, handoff?.changes ?? []);
67
+ pushUnlisted(lines, input.files, handoff?.changes ?? []);
68
+ pushVerification(lines, input.verification);
69
+ pushTransitions(lines, input.transitions);
70
+ pushNextRound(lines);
71
+ return truncateDocument(lines.join('\n'));
72
+ }
73
+ /**
74
+ * 写出本轮的任务交接文档,返回一条可回报给用户的收据。
75
+ *
76
+ * 写盘只走注入的 fs 服务:`resolve` 解析 `.agents/memory` 下的目标,`writeText` 以
77
+ * `createIfAbsent` 语义写入,因此重复点击生成新文件而不覆盖旧文档;目录缺失由 Host 的
78
+ * 原子写入自动创建。任何一步抛错都收成 `{ ok:false, … }` 收据,绝不外泄异常。
79
+ * @param ctx - 插件作用域。
80
+ * @param agent - 触发写入的 lead agent(`agent.ctx` 的作用域优先级更高)。
81
+ * @param state - 本轮结束时的状态机快照。
82
+ * @param options - 取消信号。
83
+ * @returns 成功时给出文件名与展示路径,失败时给出原因与处理办法。
84
+ */
85
+ export async function writeMemoryDocument(ctx, agent, state, options) {
86
+ const signal = options?.signal;
87
+ try {
88
+ const fs = serviceOf(agent?.ctx, ctx, 'fs');
89
+ if (fs === undefined) {
90
+ return {
91
+ ok: false,
92
+ reason: 'this Host does not expose the fs service',
93
+ action: 'keep the Coding preset mounted in a DSH host that provides the filesystem service, '
94
+ + 'then retry /coding memory',
95
+ };
96
+ }
97
+ const cwd = agent?.session?.header?.cwd;
98
+ if (typeof cwd !== 'string' || cwd === '') {
99
+ return {
100
+ ok: false,
101
+ reason: 'the session has no working directory',
102
+ action: 'set a working directory for this session, then retry /coding memory',
103
+ };
104
+ }
105
+ const policy = await sandboxPolicyOf(agent?.ctx, ctx, agent);
106
+ const now = Date.now();
107
+ const name = memoryFileName(state.sessionId, now);
108
+ const display = join(MEMORY_DIR, name);
109
+ const target = await fs.resolve(display, { cwd, signal });
110
+ await fs.writeText(target, composeMemoryDocument({
111
+ sessionId: state.sessionId,
112
+ cwd,
113
+ mode: state.mode,
114
+ stage: state.stage,
115
+ turn: state.turn,
116
+ blocked: state.deliveryBlocked === true,
117
+ ...(state.handoff === undefined ? {} : { handoff: state.handoff }),
118
+ plan: state.plan?.items ?? [],
119
+ ...(state.verification === undefined ? {} : { verification: state.verification }),
120
+ files: [...state.files].sort(),
121
+ transitions: state.transitions,
122
+ now,
123
+ }), { kind: 'createIfAbsent' }, signal, policy);
124
+ const shown = target?.displayPath;
125
+ return {
126
+ ok: true,
127
+ name,
128
+ displayPath: typeof shown === 'string' && shown !== '' ? shown : display,
129
+ };
130
+ }
131
+ catch (error) {
132
+ const raw = (error instanceof Error ? error.message : String(error)).trim();
133
+ return {
134
+ ok: false,
135
+ reason: (raw === '' ? 'unknown error' : raw).slice(0, 600),
136
+ action: 'fix the reported filesystem problem, then retry /coding memory',
137
+ };
138
+ }
139
+ }
140
+ /**
141
+ * 依次在 agent 作用域与插件作用域里找一个宿主服务。
142
+ * agent 作用域在上:预设子作用域看到的服务比插件作用域更全。
143
+ * @param primary - 优先作用域(通常是 `agent?.ctx`)。
144
+ * @param fallback - 兜底作用域(插件 ctx)。
145
+ * @param name - 服务名。
146
+ * @returns 找到的服务,或 undefined。
147
+ */
148
+ function serviceOf(primary, fallback, name) {
149
+ for (const scope of [primary, fallback]) {
150
+ if (scope === undefined || scope === null)
151
+ continue;
152
+ try {
153
+ const service = scope.get?.(name) ?? scope[name];
154
+ if (service !== undefined)
155
+ return service;
156
+ }
157
+ catch {
158
+ // 这个作用域读不到,换下一个。
159
+ }
160
+ }
161
+ return undefined;
162
+ }
163
+ /**
164
+ * 解析沙箱策略。沙箱是可选服务:没有它的宿主照常写盘,解析失败一律当作「没有策略」。
165
+ * @param primary - 优先作用域(通常是 `agent?.ctx`)。
166
+ * @param fallback - 兜底作用域(插件 ctx)。
167
+ * @param agent - 触发写入的 lead agent。
168
+ * @returns 策略值,或 undefined。
169
+ */
170
+ async function sandboxPolicyOf(primary, fallback, agent) {
171
+ const service = serviceOf(primary, fallback, 'sandboxPolicy');
172
+ if (typeof service?.resolve !== 'function')
173
+ return undefined;
174
+ try {
175
+ return await service.resolve(agent === undefined ? {} : { session: agent.session });
176
+ }
177
+ catch {
178
+ return undefined;
179
+ }
180
+ }
181
+ /** UTC 时间戳,格式 `YYYYMMDD-HHmmss`;非法数值按 epoch 处理。 */
182
+ function utcStamp(at) {
183
+ const iso = new Date(Number.isFinite(at) ? at : 0).toISOString();
184
+ return `${iso.slice(0, 10).replace(/-/gu, '')}-${iso.slice(11, 19).replace(/:/gu, '')}`;
185
+ }
186
+ /** 头部时间戳,ISO 8601(UTC);非法数值按 epoch 处理。 */
187
+ function isoStamp(at) {
188
+ return new Date(Number.isFinite(at) ? at : 0).toISOString();
189
+ }
190
+ /** 把一个值修剪成单段文本;非字符串与空白读作空串。 */
191
+ function textOf(value) {
192
+ return typeof value === 'string' ? value.trim() : '';
193
+ }
194
+ /** 一组列表项:修剪、去空、去重(保序)。 */
195
+ function cleanItems(values) {
196
+ const items = [];
197
+ for (const value of values) {
198
+ const item = textOf(value);
199
+ if (item !== '' && !items.includes(item))
200
+ items.push(item);
201
+ }
202
+ return items;
203
+ }
204
+ /** 任务清单的状态标记:`[x]` 已完成、`[~]` 进行中、`[ ]` 待办。 */
205
+ function markOf(status) {
206
+ if (status === 'completed')
207
+ return '[x]';
208
+ if (status === 'in_progress')
209
+ return '[~]';
210
+ return '[ ]';
211
+ }
212
+ /** 追加一个多行文本章节;空内容整节省略,不写「无」。 */
213
+ function pushText(lines, title, body) {
214
+ const value = textOf(body);
215
+ if (value === '')
216
+ return;
217
+ lines.push('', `## ${title}`, value);
218
+ }
219
+ /** 追加一个列表章节;空列表整节省略。 */
220
+ function pushList(lines, title, values) {
221
+ const items = cleanItems(values);
222
+ if (items.length === 0)
223
+ return;
224
+ lines.push('', `## ${title}`, ...items.map(item => `- ${item}`));
225
+ }
226
+ /** 追加任务清单(来自 `todo_write` 的 plan 快照)。 */
227
+ function pushPlan(lines, plan) {
228
+ const rows = [];
229
+ for (const item of plan) {
230
+ const content = textOf(item.content);
231
+ if (content === '')
232
+ continue;
233
+ rows.push(`- ${markOf(item.status)} ${content}`);
234
+ }
235
+ if (rows.length === 0)
236
+ return;
237
+ lines.push('', '## 任务清单', ...rows);
238
+ }
239
+ /** 追加 planner 交接任务:目标、涉及文件、验收标准与避让说明。 */
240
+ function pushTasks(lines, tasks) {
241
+ const rows = [];
242
+ for (const task of tasks) {
243
+ const goal = textOf(task.goal);
244
+ if (goal === '')
245
+ continue;
246
+ const files = cleanItems(task.files);
247
+ const done = textOf(task.acceptance);
248
+ const avoid = textOf(task.avoid);
249
+ rows.push(`- ${goal} — files: ${files.length === 0 ? '(none)' : files.join(', ')}`
250
+ + `;done: ${done === '' ? '(none)' : done}`
251
+ + (avoid === '' ? '' : `;avoid: ${avoid}`));
252
+ }
253
+ if (rows.length === 0)
254
+ return;
255
+ lines.push('', '## 交接任务(planner)', ...rows);
256
+ }
257
+ /** 追加改动文件:每条 `- <path> — <summary>`,空摘要只留路径。 */
258
+ function pushChanges(lines, changes) {
259
+ const rows = [];
260
+ for (const change of changes) {
261
+ const file = textOf(change.file);
262
+ if (file === '')
263
+ continue;
264
+ const summary = textOf(change.summary);
265
+ rows.push(summary === '' ? `- ${file}` : `- ${file} — ${summary}`);
266
+ }
267
+ if (rows.length === 0)
268
+ return;
269
+ lines.push('', '## 改动文件', ...rows);
270
+ }
271
+ /** 追加未并表路径:implement worker 报过的文件里,handoff 的 changes 没覆盖到的部分。 */
272
+ function pushUnlisted(lines, files, changes) {
273
+ const listed = new Set();
274
+ for (const change of changes) {
275
+ const file = textOf(change.file);
276
+ if (file !== '')
277
+ listed.add(file);
278
+ }
279
+ const rows = [];
280
+ for (const file of files) {
281
+ const path = textOf(file);
282
+ if (path === '' || listed.has(path))
283
+ continue;
284
+ rows.push(`- ${path}`);
285
+ }
286
+ if (rows.length === 0)
287
+ return;
288
+ lines.push('', '## 未并表的改动路径', ...rows);
289
+ }
290
+ /** 追加验证结果:结论、类型/范围、命令、退出码、耗时,以及失败测试与错误。 */
291
+ function pushVerification(lines, outcome) {
292
+ if (outcome === undefined)
293
+ return;
294
+ const section = [
295
+ '',
296
+ '## 验证',
297
+ `- 结果: ${outcome.passed ? 'passed' : 'FAILED'}`,
298
+ `- 类型 / 范围: ${outcome.kind} / ${outcome.scope}`,
299
+ `- 命令: \`${outcome.command}\``,
300
+ `- 退出码: ${outcome.exitCode === null ? '(none)' : outcome.exitCode}`,
301
+ `- 耗时: ${outcome.durationMs}ms`,
302
+ ];
303
+ const failed = cleanItems(outcome.failedTests);
304
+ if (failed.length > 0)
305
+ section.push(`- 失败测试: ${failed.join(', ')}`);
306
+ for (const error of cleanItems(outcome.errors))
307
+ section.push(`- 错误: ${error}`);
308
+ lines.push(...section);
309
+ }
310
+ /** 追加阶段轨迹:每条 `- <from> → <to>(<reason>)`,无原因时省略括号。 */
311
+ function pushTransitions(lines, transitions) {
312
+ const rows = [];
313
+ for (const transition of transitions) {
314
+ const from = textOf(transition.from);
315
+ const to = textOf(transition.to);
316
+ if (from === '' || to === '')
317
+ continue;
318
+ const reason = textOf(transition.reason);
319
+ rows.push(reason === '' ? `- ${from} → ${to}` : `- ${from} → ${to}(${reason})`);
320
+ }
321
+ if (rows.length === 0)
322
+ return;
323
+ lines.push('', '## 阶段轨迹', ...rows);
324
+ }
325
+ /** 固定尾节:说明这份文档与 coding_handoff 实时记录的关系,以及续接顺序。 */
326
+ function pushNextRound(lines) {
327
+ lines.push('', '## 下一轮怎么接', '- 这份文档是本轮状态机与 coding_handoff 记录的存档快照;下一轮继续时以 coding_handoff 的实时记录为准。', '- 续接轮请先读「目标 / 验收标准 / 交付记录 / 后续跟进」四节,再决定是否重做上一轮。');
328
+ }
329
+ /** 截断到 {@link MEMORY_LIMIT}:优先切在最后一个完整行,并标注文档已截断。 */
330
+ function truncateDocument(text) {
331
+ if (text.length <= MEMORY_LIMIT)
332
+ return text;
333
+ const cut = text.slice(0, MEMORY_LIMIT);
334
+ const lastBreak = cut.lastIndexOf('\n');
335
+ return `${lastBreak > 0 ? cut.slice(0, lastBreak) : cut}\n…(文档已截断)`;
336
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Message sources and constructors this plugin contributes to the model-visible
3
+ * surface. Declaring the source kinds here (rather than inventing a user prompt)
4
+ * is what keeps an injected stage fragment and a control notice distinguishable
5
+ * from a real human message in derived history.
6
+ *
7
+ * @module dsh-coding/messages
8
+ */
9
+ import { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm';
10
+ /** The one-line summary bound of a context notice. */
11
+ const SUMMARY_MAX = 120;
12
+ /**
13
+ * Build the per-step stage context message.
14
+ * @param text - complete stage fragment.
15
+ * @param summary - one-line account shown without expanding the row.
16
+ * @returns an immutable user-role context message.
17
+ */
18
+ export function stageMessage(text, summary) {
19
+ return createUserMessage({
20
+ content: [{ type: 'text', text }],
21
+ source: {
22
+ kind: 'dsh-coding-stage',
23
+ form: 'notice',
24
+ summary: boundContextSummary(summary.slice(0, SUMMARY_MAX)),
25
+ },
26
+ });
27
+ }
28
+ /**
29
+ * Build a control notice delivered by `agent.followup()` or `agent.steer()`.
30
+ * @param text - what the runtime decided and what the model should do.
31
+ * @param summary - one-line account for the conversation row.
32
+ * @returns an immutable user-role context message.
33
+ */
34
+ export function controlMessage(text, summary) {
35
+ return createUserMessage({
36
+ content: [{ type: 'text', text }],
37
+ source: {
38
+ kind: 'dsh-coding-control',
39
+ form: 'notice',
40
+ summary: boundContextSummary(summary.slice(0, SUMMARY_MAX)),
41
+ },
42
+ });
43
+ }