dsh-thinking-lang 0.0.0-stage → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,353 @@
1
+ /**
2
+ * Host entry: the settings namespace, the prompt section, and the language line.
3
+ * 宿主入口:设置命名空间、提示词段、以及每步注入的语言行。
4
+ *
5
+ * Injection shape (see README for the reasoning):
6
+ * 注入形态(设计理由见 README):
7
+ *
8
+ * section order 1 → the authoritative rule, once per session
9
+ * pre-step step 1 → a short reminder, at most once per turn (10 min apart)
10
+ *
11
+ * section order 1 → 权威规则,每会话组装一次
12
+ * pre-step step 1 → 短提醒,每轮最多一次(间隔 10 分钟)
13
+ *
14
+ * The host context is described by a local structural interface rather than the
15
+ * `@deepseek-ai/cordis` type, so this package carries no DSH type dependency.
16
+ * 宿主上下文用本文件内的结构化接口描述,而不引用 `@deepseek-ai/cordis` 的类型,
17
+ * 因此本包不依赖任何 DSH 类型包。
18
+ */
19
+ import { randomUUID } from "node:crypto";
20
+ import z from "@deepseek-ai/schemastery";
21
+ import {
22
+ AUTO,
23
+ FIELD_LANGUAGE,
24
+ SELECTABLE_TAGS,
25
+ SETTINGS_NAMESPACE,
26
+ type Reader,
27
+ type ThinkingSettings,
28
+ effectiveCode,
29
+ nativeNameFor,
30
+ normalizeSettings,
31
+ reminderText,
32
+ sectionText
33
+ } from "./core.js";
34
+
35
+ /** Stable Cordis plugin name. / 稳定的 Cordis 插件名。 */
36
+ export const name = "ay-dsh-tk-lang";
37
+
38
+ /** Plugin-level service requirements; services are acquired per branch below. / 插件级服务声明;服务在下方逐分支获取。 */
39
+ export const inject: string[] = [];
40
+
41
+ /**
42
+ * Section order. The host's own table (dsh-system-prompt) puts the harness
43
+ * identity at -1000, the deployment persona prefix at 0 and the first policy
44
+ * section at 500, so 1 lands immediately after the persona line.
45
+ * 段的顺序。宿主自己的分段表(dsh-system-prompt)把身份声明放在 -1000、部署
46
+ * persona 前缀放在 0、第一个策略段放在 500,因此取 1 就紧跟在 persona 那行之后。
47
+ */
48
+ const SECTION_ORDER = 1;
49
+
50
+ /** Minimum milliseconds between two per-turn reminders in one session. / 同一会话中两次每轮提醒之间的最小毫秒数。 */
51
+ const REMINDER_INTERVAL_MS = 600_000;
52
+
53
+ /** Settings namespace holding the desktop UI locale. / 保存桌面 UI 语言的设置命名空间。 */
54
+ const LOCALE_NAMESPACE = "locale";
55
+
56
+ /** Field of {@link LOCALE_NAMESPACE} holding the UI locale. / {@link LOCALE_NAMESPACE} 中保存 UI 语言的字段。 */
57
+ const LOCALE_FIELD = "preference";
58
+
59
+ /** How long one settings read is reused; prompt assembly reads it every step. / 一次设置读取的复用时长;提示词组装每步都会读。 */
60
+ const SETTINGS_TTL_MS = 1000;
61
+
62
+ /** The shape a schemastery node must expose for {@link live} to mark it. / {@link live} 标记节点时,该节点需要暴露的形状。 */
63
+ interface LiveCapable {
64
+ volatile?: () => unknown;
65
+ extra?: (key: string, value: boolean) => unknown;
66
+ }
67
+
68
+ /**
69
+ * The two spellings schemastery accepts for the "live field" flag.
70
+ * schemastery 接受「实时字段」标记的两种写法。
71
+ *
72
+ * Each probe returns nothing when the node does not implement that spelling, so
73
+ * {@link live} can simply try them in turn.
74
+ * 节点未实现某种写法时,对应的探测返回空,{@link live} 因此可以按顺序逐个尝试。
75
+ */
76
+ const LIVE_MARKERS: ReadonlyArray<(field: LiveCapable) => unknown> = [
77
+ (field) => (typeof field.volatile === "function" ? field.volatile() : undefined),
78
+ (field) => (typeof field.extra === "function" ? field.extra("volatile", true) : undefined)
79
+ ];
80
+
81
+ /**
82
+ * Declare a schema field live, so the settings service accepts writes to it.
83
+ * 把 schema 字段声明为「可实时修改」,使设置服务接受对它的写入。
84
+ *
85
+ * A namespace whose fields carry neither marker is refused as having no volatile
86
+ * fields at all, which would leave the whole namespace read-only.
87
+ * 字段两种标记都不带的命名空间会被以「没有可实时修改的字段」为由拒绝,导致整个
88
+ * 命名空间变成只读。
89
+ */
90
+ function live<T>(field: z<T>): z<T> {
91
+ const probe = field as unknown as LiveCapable;
92
+ for (const mark of LIVE_MARKERS) {
93
+ const marked = mark(probe);
94
+ if (marked !== undefined && marked !== null) return marked as z<T>;
95
+ }
96
+ return field;
97
+ }
98
+
99
+ /**
100
+ * Attach a picker label to a schema node, when the node takes descriptions.
101
+ * 在 schema 节点接受描述时,为它挂上选择器标签。
102
+ */
103
+ function labelled<T>(node: z<T>, label: string | undefined): z<T> {
104
+ const probe = node as unknown as { description?: (text: string) => z<T> };
105
+ const describe = probe.description;
106
+ if (label === undefined || typeof describe !== "function") return node;
107
+ return describe.call(node, label);
108
+ }
109
+
110
+ /**
111
+ * Build the durable settings schema for the single language field.
112
+ * 为唯一的语言字段构建持久化设置 schema。
113
+ *
114
+ * Language options carry the native name as their schema description, so the
115
+ * picker can be rendered from the registered schema instead of a second copy.
116
+ * 语言选项把本族语名作为 schema 描述携带,使选择器可以依据已注册的 schema 渲染,
117
+ * 而不必再维护一份副本。
118
+ */
119
+ function buildSchema(): z<ThinkingSettings> {
120
+ const choices = [AUTO, ...SELECTABLE_TAGS].map((value) => labelled(z.const(value), nativeNameFor(value)));
121
+ return z.object({ [FIELD_LANGUAGE]: live(z.union(choices).default(AUTO)) });
122
+ }
123
+
124
+ /** Durable settings schema; the field defaults to {@link AUTO}. / 持久化设置 schema;字段默认为 {@link AUTO}。 */
125
+ export const Config = buildSchema();
126
+
127
+ /** The slice of the host settings service this plugin uses. / 本插件用到的宿主设置服务切片。 */
128
+ interface HostSettings {
129
+ describe(): unknown;
130
+ update(entryId: string, patch: Record<string, unknown>): unknown;
131
+ }
132
+
133
+ /** One read of the settings document, reusable until its TTL elapses. / 一次设置文档读取,在缓存有效期内可复用。 */
134
+ interface SettingsSnapshot {
135
+ readonly takenAt: number;
136
+ readonly sections: Map<string, Record<string, unknown>>;
137
+ }
138
+
139
+ /** Handed back while the settings service is unavailable or unreadable. / 设置服务不可用或读不出时交回的空表。 */
140
+ const NO_SECTIONS: ReadonlyMap<string, Record<string, unknown>> = new Map();
141
+
142
+ let snapshot: SettingsSnapshot | undefined;
143
+
144
+ /**
145
+ * Pull every namespace section out of the settings document.
146
+ * 从设置文档里取出各个命名空间的段。
147
+ *
148
+ * A section is a `{ns, value}` entry whose `value` is a plain object; anything
149
+ * else in the listing is not something this plugin can read, so it is skipped
150
+ * rather than coerced.
151
+ * 一个段就是 `value` 为普通对象的 `{ns, value}` 条目;列表里其它形状不是本插件能读
152
+ * 的东西,因此跳过而不做强制转换。
153
+ */
154
+ /**
155
+ * Call `describe()` without letting a throwing host escape.
156
+ * 调用 `describe()`,不让抛异常的宿主逃逸出去。
157
+ */
158
+ function described(settings: HostSettings): unknown {
159
+ try {
160
+ return settings.describe();
161
+ } catch {
162
+ return undefined;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Coerce an untrusted value into a settings section, or nothing.
168
+ * 把不可信的值强制转换为设置段;不是段则为空。
169
+ *
170
+ * A section is a plain object keyed by field name. Arrays and primitives are
171
+ * refused rather than coerced, so a malformed document reads as "no settings"
172
+ * instead of producing nonsense.
173
+ * 设置段就是以字段名为键的普通对象。数组与原始值一律拒绝而不做转换,使格式错误的
174
+ * 文档读作「没有设置」,而不是产生无意义的结果。
175
+ */
176
+ function asSection(value: unknown): Record<string, unknown> | undefined {
177
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
178
+ return value as Record<string, unknown>;
179
+ }
180
+
181
+ function collect(settings: HostSettings): Map<string, Record<string, unknown>> {
182
+ const found = new Map<string, Record<string, unknown>>();
183
+ const listed = described(settings);
184
+ if (!Array.isArray(listed)) return found;
185
+ for (const item of listed) {
186
+ const { ns, value } = item as { ns?: unknown; value?: unknown };
187
+ const section = asSection(value);
188
+ if (typeof ns === "string" && section !== undefined) found.set(ns, section);
189
+ }
190
+ return found;
191
+ }
192
+
193
+ /**
194
+ * Read the namespace sections, reusing one read for a short while.
195
+ * 读取各命名空间的段,并在很短的时间内复用同一次读取。
196
+ *
197
+ * The cache exists because prompt assembly asks on every model step, while
198
+ * `describe()` walks the whole settings document each time.
199
+ * 缓存的存在是因为提示词组装每一步都会问,而 `describe()` 每次都要遍历整份设置文档。
200
+ */
201
+ function sectionsOf(settings: HostSettings | undefined | null): ReadonlyMap<string, Record<string, unknown>> {
202
+ if (!settings || typeof settings.describe !== "function") return NO_SECTIONS;
203
+ const now = Date.now();
204
+ if (snapshot === undefined || now - snapshot.takenAt >= SETTINGS_TTL_MS) {
205
+ snapshot = { takenAt: now, sections: collect(settings) };
206
+ }
207
+ return snapshot.sections;
208
+ }
209
+
210
+ /**
211
+ * Adapt the settings service to the `get()`-style handle the core reads from.
212
+ * 把设置服务适配成核心代码所用的 `get()` 风格句柄。
213
+ */
214
+ function settingsReader(settings: HostSettings | undefined | null): Reader {
215
+ return {
216
+ get: (ns?: string) => sectionsOf(settings).get(typeof ns === "string" ? ns : SETTINGS_NAMESPACE)
217
+ };
218
+ }
219
+
220
+ /**
221
+ * Read one namespace section, or undefined when it is absent or malformed.
222
+ * 读取一个命名空间的段;缺失或格式不对时返回 undefined。
223
+ */
224
+ function sectionOf(reader: Reader, ns: string): Record<string, unknown> | undefined {
225
+ return asSection(reader.get(ns));
226
+ }
227
+
228
+ /**
229
+ * Cached operating-system locale; the wrapper distinguishes "not probed yet"
230
+ * from "probed, and the runtime had nothing to report".
231
+ * 缓存的操作系统语言;用包装对象区分「尚未探测」与「已探测但运行时拿不到」。
232
+ */
233
+ let osLocaleCache: { value: string | undefined } | undefined;
234
+
235
+ /**
236
+ * Read the operating-system locale, preferring the POSIX environment variables.
237
+ * 读取操作系统语言,优先使用 POSIX 环境变量。
238
+ *
239
+ * The environment wins where it is set (Linux/macOS). On Windows it is normally
240
+ * absent, so `Intl` — which follows the OS regional settings there — stands in.
241
+ * The result is cached because prompt assembly asks on every model step.
242
+ * 在设置了环境变量的平台(Linux/macOS)环境变量优先;Windows 上通常没有,改由
243
+ * `Intl` 顶上(它会跟随系统的区域设置)。结果会被缓存,因为提示词组装每一步都问。
244
+ */
245
+ function osLocale(): string | undefined {
246
+ if (osLocaleCache) return osLocaleCache.value;
247
+ let value: string | undefined;
248
+ const env = process.env.LC_ALL ?? process.env.LC_MESSAGES ?? process.env.LANG;
249
+ if (typeof env === "string" && env !== "") {
250
+ value = env;
251
+ } else {
252
+ try {
253
+ const resolved = new Intl.DateTimeFormat().resolvedOptions().locale;
254
+ if (typeof resolved === "string" && resolved !== "") value = resolved;
255
+ } catch {
256
+ /* Intl is unavailable in this runtime */
257
+ }
258
+ }
259
+ osLocaleCache = { value };
260
+ return value;
261
+ }
262
+
263
+ /**
264
+ * Resolve the effective language for one prompt build.
265
+ * 为一次提示词构建解析出生效语言。
266
+ */
267
+ function currentLanguage(reader: Reader): string {
268
+ const settings = normalizeSettings(sectionOf(reader, SETTINGS_NAMESPACE));
269
+ const desktop = sectionOf(reader, LOCALE_NAMESPACE)?.[LOCALE_FIELD];
270
+ return effectiveCode(settings, osLocale(), typeof desktop === "string" ? desktop : undefined);
271
+ }
272
+
273
+ /** One pre-step payload slice this entry reads. / 本入口读取的 pre-step 载荷切片。 */
274
+ interface PreStepPayload {
275
+ agent: { session: { id: string } };
276
+ turn: number;
277
+ step: number;
278
+ signal: AbortSignal;
279
+ }
280
+
281
+ /** The pre-step decision this entry appends a reminder to. / 本入口追加提醒的 pre-step 决策。 */
282
+ interface PreStepDecision {
283
+ kind: "enter" | "reject";
284
+ messages: Array<Record<string, unknown>>;
285
+ }
286
+
287
+ /** The host plugin context shape this entry relies on. / 本入口依赖的宿主插件上下文形状。 */
288
+ interface HostContext {
289
+ get(name: string): unknown;
290
+ inject(names: string[], callback: (ctx: HostContext) => void): unknown;
291
+ on(
292
+ event: "agent/pre-step",
293
+ listener: (payload: PreStepPayload, next: () => Promise<PreStepDecision>) => Promise<PreStepDecision>,
294
+ options?: { prepend?: boolean }
295
+ ): unknown;
296
+ systemPrompt: {
297
+ section(section: { name: string; order?: number; text: () => string }): unknown;
298
+ };
299
+ }
300
+
301
+ /**
302
+ * Build the durable user message carrying one reminder.
303
+ * 生成携带一条提醒的持久用户消息。
304
+ *
305
+ * The message keeps the plugin as its source, so the session log can attribute
306
+ * the injection and the host restores it like any other user message.
307
+ * 消息以本插件为来源,会话日志因此能归属这次注入,宿主也像普通用户消息一样恢复它。
308
+ */
309
+ function reminderMessage(text: string): Record<string, unknown> {
310
+ return {
311
+ id: randomUUID(),
312
+ role: "user",
313
+ content: [{ type: "text", text }],
314
+ source: { kind: name, form: "snapshot", sections: [{ name, text }] }
315
+ };
316
+ }
317
+
318
+ /**
319
+ * Register the settings consumer, the prompt section, and the per-turn reminder.
320
+ * 注册设置消费方、提示词段,以及每轮一次的提醒。
321
+ */
322
+ export function apply(ctx: HostContext): void {
323
+ /** Latest reminder time per session, in process memory. / 每个会话最近一次提醒时间,存于进程内存。 */
324
+ const lastReminderAt = new Map<string, number>();
325
+
326
+ ctx.inject(["systemPrompt", "settings"], (promptCtx) => {
327
+ const reader = () => settingsReader(promptCtx.get("settings") as HostSettings | undefined);
328
+
329
+ // The text thunk is re-evaluated per assembly, so the section always
330
+ // reflects the newest setting without re-registering anything.
331
+ // 文本 thunk 每次组装都会重新求值,因此该段始终反映最新设置,无需重新注册。
332
+ promptCtx.systemPrompt.section({
333
+ name: "app:tk-lang",
334
+ order: SECTION_ORDER,
335
+ text: () => sectionText(currentLanguage(reader()))
336
+ });
337
+
338
+ // The reminder runs before the other pre-step listeners, so its message is
339
+ // appended after theirs and stays closest to the end of the request.
340
+ // 该提醒先于其它 pre-step 监听器执行,因此它的消息追加在它们之后,离请求末尾最近。
341
+ promptCtx.on("agent/pre-step", async (payload, next) => {
342
+ const decision = await next();
343
+ if (decision.kind !== "enter" || payload.signal.aborted || payload.step !== 1) return decision;
344
+ const now = Date.now();
345
+ const previous = lastReminderAt.get(payload.agent.session.id);
346
+ if (previous !== undefined && now - previous < REMINDER_INTERVAL_MS) return decision;
347
+ const text = reminderText(currentLanguage(reader()));
348
+ if (text === "") return decision;
349
+ lastReminderAt.set(payload.agent.session.id, now);
350
+ return { ...decision, messages: [...decision.messages, reminderMessage(text)] };
351
+ }, { prepend: true });
352
+ });
353
+ }