dsh-thinking-lang 1.0.7 → 1.0.9

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/core.ts CHANGED
@@ -34,8 +34,10 @@ export interface Language {
34
34
  nativeName: string;
35
35
  /** The rule sentence written in this language. / 用本语言写成的规则句。 */
36
36
  section: string;
37
- /** The short per-turn reminder written in this language. / 用本语言写成的每轮短提醒。 */
37
+ /** The short reminder written in this language for the head of the batch. / 写在批次开头的短提醒。 */
38
38
  reminder: string;
39
+ /** The short reminder written for the last message of the request. / 写在请求末尾的短提醒。 */
40
+ tail: string;
39
41
  }
40
42
 
41
43
  /**
@@ -54,20 +56,23 @@ export const CATALOGUE: readonly Language[] = [
54
56
  {
55
57
  tag: "zh-CN",
56
58
  nativeName: "简体中文",
57
- section: "推理规则:思考、推理与规划一律使用简体中文。回复用户时使用用户所用的语言。",
58
- reminder: "继续用简体中文思考、推理与规划。"
59
+ section: "推理规则:思考、推理与规划一律使用简体中文。",
60
+ reminder: "注意:思考、推理与规划用简体中文,即使上文不是",
61
+ tail: "下文请使用简体中文思考"
59
62
  },
60
63
  {
61
64
  tag: "zh-TW",
62
65
  nativeName: "繁體中文",
63
- section: "推理規則:思考、推理與規劃一律使用繁體中文。回覆使用者時使用使用者所用的語言。",
64
- reminder: "繼續用繁體中文思考、推理與規劃。"
66
+ section: "推理規則:思考、推理與規劃一律使用繁體中文。",
67
+ reminder: "注意:思考、推理與規劃用繁體中文,即使上文不是",
68
+ tail: "下文請使用繁體中文思考"
65
69
  },
66
70
  {
67
71
  tag: "en",
68
72
  nativeName: "English",
69
- section: "Reasoning rules: think, reason, and plan in English. Reply to the user in the language they use.",
70
- reminder: "Keep thinking, reasoning, and planning in English."
73
+ section: "Reasoning rules: think, reason, and plan in English.",
74
+ reminder: "Note: think, reason, and plan in English, even if the text above is not",
75
+ tail: "Think in English from here on"
71
76
  }
72
77
  ];
73
78
 
@@ -86,6 +91,9 @@ export const FIELD_LANGUAGE = "language";
86
91
  /** The reminder field this plugin stores. / 本插件保存的提醒字段。 */
87
92
  export const FIELD_REMINDER = "reminderMinutes";
88
93
 
94
+ /** The extra-injection field this plugin stores. / 本插件保存的额外注入字段。 */
95
+ export const FIELD_EXTRA = "extraInjection";
96
+
89
97
  /** Reminder value that disables the per-turn reminder. / 关闭每轮提醒的取值。 */
90
98
  export const REMINDER_OFF = -1;
91
99
 
@@ -112,10 +120,20 @@ export interface ThinkingSettings {
112
120
  * 注入,1–1440 为最小间隔。
113
121
  */
114
122
  reminderMinutes: number;
123
+ /**
124
+ * Whether the closing rule is also folded into the skill catalogue. It only
125
+ * applies while the reminder is on.
126
+ * 是否把收尾规则同时折进技能目录;仅在提醒开启时生效。
127
+ */
128
+ extraInjection: boolean;
115
129
  }
116
130
 
117
131
  /** Configuration applied when the fields are absent. / 字段缺失时采用的配置。 */
118
- export const DEFAULTS: ThinkingSettings = { language: AUTO, reminderMinutes: DEFAULT_REMINDER_MINUTES };
132
+ export const DEFAULTS: ThinkingSettings = {
133
+ language: AUTO,
134
+ reminderMinutes: DEFAULT_REMINDER_MINUTES,
135
+ extraInjection: true
136
+ };
119
137
 
120
138
  /** A minimal read handle over the host settings service. / 宿主设置服务的最小读取句柄。 */
121
139
  export interface Reader {
@@ -202,8 +220,8 @@ function candidatesOf(locale: Intl.Locale): string[] {
202
220
  * 手写地区对照表。
203
221
  */
204
222
  function chineseTag(locale: Intl.Locale): string {
205
- const maximized = typeof locale.maximize === "function" ? locale.maximize() : undefined;
206
- return maximized?.script === "Hant" ? CHINESE.traditional : CHINESE.simplified;
223
+ const script = locale.script ?? locale.maximize().script;
224
+ return script === "Hant" ? CHINESE.traditional : CHINESE.simplified;
207
225
  }
208
226
 
209
227
  /**
@@ -213,11 +231,12 @@ function chineseTag(locale: Intl.Locale): string {
213
231
  function tagForLocale(raw: unknown): string | undefined {
214
232
  const locale = parseLocale(raw);
215
233
  if (locale === undefined) return undefined;
234
+ if (locale.language === "zh") return chineseTag(locale);
216
235
  for (const candidate of candidatesOf(locale)) {
217
236
  const match = BY_TAG.get(candidate.toLowerCase());
218
237
  if (match !== undefined) return match.tag;
219
238
  }
220
- return locale.language === "zh" ? chineseTag(locale) : undefined;
239
+ return undefined;
221
240
  }
222
241
 
223
242
  /**
@@ -228,9 +247,13 @@ function tagForLocale(raw: unknown): string | undefined {
228
247
  function normalizeReminder(raw: unknown): number {
229
248
  const numeric = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
230
249
  if (!Number.isFinite(numeric)) return DEFAULT_REMINDER_MINUTES;
231
- const rounded = Math.round(numeric);
232
- if (rounded < 0) return REMINDER_OFF;
233
- return rounded > MAX_REMINDER_MINUTES ? MAX_REMINDER_MINUTES : rounded;
250
+ if (numeric < 0) return REMINDER_OFF;
251
+ return Math.max(REMINDER_EVERY_TURN, Math.min(MAX_REMINDER_MINUTES, Math.round(numeric)));
252
+ }
253
+
254
+ /** Coerce one untrusted extra-injection value; only an explicit false turns it off. / 把不可信的额外注入值收敛为布尔;只有明确的 false 视为关闭。 */
255
+ function normalizeExtra(raw: unknown): boolean {
256
+ return raw !== false && raw !== "false";
234
257
  }
235
258
 
236
259
  /**
@@ -251,7 +274,8 @@ export function normalizeSettings(raw: unknown): ThinkingSettings {
251
274
  const stored = section?.[FIELD_LANGUAGE];
252
275
  return {
253
276
  language: typeof stored === "string" && stored !== "" ? stored : DEFAULTS.language,
254
- reminderMinutes: normalizeReminder(section?.[FIELD_REMINDER])
277
+ reminderMinutes: normalizeReminder(section?.[FIELD_REMINDER]),
278
+ extraInjection: normalizeExtra(section?.[FIELD_EXTRA])
255
279
  };
256
280
  }
257
281
 
@@ -297,3 +321,11 @@ export function sectionText(code: string): string {
297
321
  export function reminderText(code: string): string {
298
322
  return languageOf(code)?.reminder ?? "";
299
323
  }
324
+
325
+ /**
326
+ * Build the closing reminder appended as the request's last message.
327
+ * 生成追加在请求最后一条消息里的收尾提醒。
328
+ */
329
+ export function tailText(code: string): string {
330
+ return languageOf(code)?.tail ?? "";
331
+ }
package/src/index.ts CHANGED
@@ -6,10 +6,14 @@
6
6
  * 注入形态(设计理由见 README):
7
7
  *
8
8
  * section order 1 → the authoritative rule, once per session
9
- * pre-step step 1 → a short reminder, at most once per turn (interval configurable, default 30 min)
9
+ * pre-step step 1 → a short reminder at the head of the batch, at most once per turn
10
+ * (interval configurable, default 30 min)
11
+ * pre-step step 1 → the closing rule, folded into the skill catalogue or sent
12
+ * as its own message when extra injection is on
10
13
  *
11
14
  * section order 1 → 权威规则,每会话组装一次
12
- * pre-step step 1 → 短提醒,每轮最多一次(间隔可配置,默认 30 分钟)
15
+ * pre-step step 1 → 批次开头的短提醒,每轮最多一次(间隔可配置,默认 30 分钟)
16
+ * pre-step step 1 → 收尾规则,额外注入开启时折进技能目录,或独立发送
13
17
  *
14
18
  * The host context is described by a local structural interface rather than the
15
19
  * `@deepseek-ai/cordis` type, so this package carries no DSH type dependency.
@@ -21,6 +25,8 @@ import z from "@deepseek-ai/schemastery";
21
25
  import {
22
26
  AUTO,
23
27
  DEFAULT_REMINDER_MINUTES,
28
+ DEFAULTS,
29
+ FIELD_EXTRA,
24
30
  FIELD_LANGUAGE,
25
31
  FIELD_REMINDER,
26
32
  REMINDER_OFF,
@@ -33,6 +39,7 @@ import {
33
39
  normalizeSettings,
34
40
  reminderDelayMs,
35
41
  reminderText,
42
+ tailText,
36
43
  sectionText
37
44
  } from "./core.js";
38
45
 
@@ -121,7 +128,8 @@ function buildSchema(): z<ThinkingSettings> {
121
128
  const choices = [AUTO, ...SELECTABLE_TAGS].map((value) => labelled(z.const(value), nativeNameFor(value)));
122
129
  return z.object({
123
130
  [FIELD_LANGUAGE]: live(z.union(choices).default(AUTO)),
124
- [FIELD_REMINDER]: live(z.number().default(DEFAULT_REMINDER_MINUTES))
131
+ [FIELD_REMINDER]: live(z.number().default(DEFAULT_REMINDER_MINUTES)),
132
+ [FIELD_EXTRA]: live(z.boolean().default(DEFAULTS.extraInjection))
125
133
  });
126
134
  }
127
135
 
@@ -130,12 +138,12 @@ export const Config = buildSchema();
130
138
 
131
139
  /** The slice of the host settings service this plugin uses. / 本插件用到的宿主设置服务切片。 */
132
140
  interface HostSettings {
133
- describe(): unknown;
134
- update(entryId: string, patch: Record<string, unknown>): unknown;
141
+ describe(options: { redactSecrets: boolean }): unknown;
135
142
  }
136
143
 
137
144
  /** One read of the settings document, reusable until its TTL elapses. / 一次设置文档读取,在缓存有效期内可复用。 */
138
145
  interface SettingsSnapshot {
146
+ readonly service: HostSettings;
139
147
  readonly takenAt: number;
140
148
  readonly sections: Map<string, Record<string, unknown>>;
141
149
  }
@@ -143,25 +151,13 @@ interface SettingsSnapshot {
143
151
  /** Handed back while the settings service is unavailable or unreadable. / 设置服务不可用或读不出时交回的空表。 */
144
152
  const NO_SECTIONS: ReadonlyMap<string, Record<string, unknown>> = new Map();
145
153
 
146
- let snapshot: SettingsSnapshot | undefined;
147
-
148
- /**
149
- * Pull every namespace section out of the settings document.
150
- * 从设置文档里取出各个命名空间的段。
151
- *
152
- * A section is a `{ns, value}` entry whose `value` is a plain object; anything
153
- * else in the listing is not something this plugin can read, so it is skipped
154
- * rather than coerced.
155
- * 一个段就是 `value` 为普通对象的 `{ns, value}` 条目;列表里其它形状不是本插件能读
156
- * 的东西,因此跳过而不做强制转换。
157
- */
158
154
  /**
159
155
  * Call `describe()` without letting a throwing host escape.
160
156
  * 调用 `describe()`,不让抛异常的宿主逃逸出去。
161
157
  */
162
158
  function described(settings: HostSettings): unknown {
163
159
  try {
164
- return settings.describe();
160
+ return settings.describe({ redactSecrets: true });
165
161
  } catch {
166
162
  return undefined;
167
163
  }
@@ -182,42 +178,27 @@ function asSection(value: unknown): Record<string, unknown> | undefined {
182
178
  return value as Record<string, unknown>;
183
179
  }
184
180
 
185
- function collect(settings: HostSettings): Map<string, Record<string, unknown>> {
186
- const found = new Map<string, Record<string, unknown>>();
181
+ function collect(settings: HostSettings): Map<string, Record<string, unknown>> | undefined {
187
182
  const listed = described(settings);
188
- if (!Array.isArray(listed)) return found;
183
+ if (!Array.isArray(listed)) return undefined;
184
+ const found = new Map<string, Record<string, unknown>>();
189
185
  for (const item of listed) {
190
- const { ns, value } = item as { ns?: unknown; value?: unknown };
191
- const section = asSection(value);
192
- if (typeof ns === "string" && section !== undefined) found.set(ns, section);
186
+ const entry = asSection(item);
187
+ const ns = entry?.ns;
188
+ if (ns !== SETTINGS_NAMESPACE && ns !== LOCALE_NAMESPACE) continue;
189
+ const section = asSection(entry?.value);
190
+ if (section !== undefined) found.set(ns, section);
193
191
  }
194
192
  return found;
195
193
  }
196
194
 
197
- /**
198
- * Read the namespace sections, reusing one read for a short while.
199
- * 读取各命名空间的段,并在很短的时间内复用同一次读取。
200
- *
201
- * The cache exists because prompt assembly asks on every model step, while
202
- * `describe()` walks the whole settings document each time.
203
- * 缓存的存在是因为提示词组装每一步都会问,而 `describe()` 每次都要遍历整份设置文档。
204
- */
205
- function sectionsOf(settings: HostSettings | undefined | null): ReadonlyMap<string, Record<string, unknown>> {
206
- if (!settings || typeof settings.describe !== "function") return NO_SECTIONS;
207
- const now = Date.now();
208
- if (snapshot === undefined || now - snapshot.takenAt >= SETTINGS_TTL_MS) {
209
- snapshot = { takenAt: now, sections: collect(settings) };
210
- }
211
- return snapshot.sections;
212
- }
213
-
214
195
  /**
215
196
  * Adapt the settings service to the `get()`-style handle the core reads from.
216
197
  * 把设置服务适配成核心代码所用的 `get()` 风格句柄。
217
198
  */
218
- function settingsReader(settings: HostSettings | undefined | null): Reader {
199
+ function settingsReader(sections: ReadonlyMap<string, Record<string, unknown>>): Reader {
219
200
  return {
220
- get: (ns?: string) => sectionsOf(settings).get(typeof ns === "string" ? ns : SETTINGS_NAMESPACE)
201
+ get: (ns = SETTINGS_NAMESPACE) => sections.get(ns)
221
202
  };
222
203
  }
223
204
 
@@ -300,6 +281,8 @@ interface HostContext {
300
281
  listener: (payload: PreStepPayload, next: () => Promise<PreStepDecision>) => Promise<PreStepDecision>,
301
282
  options?: { prepend?: boolean }
302
283
  ): unknown;
284
+ on(event: "agent/created", listener: (payload: unknown) => unknown): unknown;
285
+ on(event: "settings/document-updated", listener: (namespace: string) => void): unknown;
303
286
  systemPrompt: {
304
287
  section(section: { name: string; order?: number; text: () => string }): unknown;
305
288
  };
@@ -322,6 +305,33 @@ function reminderMessage(text: string): Record<string, unknown> {
322
305
  };
323
306
  }
324
307
 
308
+ /**
309
+ * Put the rule in front of the text a message already carries.
310
+ * 把规则放到消息已有文本的前面。
311
+ */
312
+ function prefixPrompt(message: Record<string, unknown>, text: string): Record<string, unknown> {
313
+ const content = Array.isArray(message.content) ? (message.content as Array<Record<string, unknown>>) : [];
314
+ const head = content[0];
315
+ if (head && head.type === "text" && typeof head.text === "string" && head.text.startsWith(text)) return message;
316
+ return { ...message, content: [{ type: "text", text: `${text}\n` }, ...content] };
317
+ }
318
+
319
+ /**
320
+ * Attach the rule to this batch's skill catalogue, or append a plugin-owned message last.
321
+ * 把规则加到当前批次的技能目录;没有目录时在批次末尾追加一条本插件来源的消息。
322
+ *
323
+ * The fallback lands after every other injected message, so the closing rule stays
324
+ * the last thing the model reads even when no catalogue was sent.
325
+ * 回退的那条落在全部注入消息之后,因此没有技能目录时,收尾规则仍是模型最后读到的一句。
326
+ */
327
+ function withClosingReminder(messages: Array<Record<string, unknown>>, text: string): Array<Record<string, unknown>> {
328
+ const index = messages.findIndex((message) => asSection(message.source)?.kind === "skill-catalog");
329
+ if (index < 0) return [...messages, reminderMessage(text)];
330
+ const next = [...messages];
331
+ next[index] = prefixPrompt(messages[index], text);
332
+ return next;
333
+ }
334
+
325
335
  /**
326
336
  * Register the settings consumer, the prompt section, and the per-turn reminder.
327
337
  * 注册设置消费方、提示词段,以及每轮一次的提醒。
@@ -331,7 +341,24 @@ export function apply(ctx: HostContext): void {
331
341
  const lastReminderAt = new Map<string, number>();
332
342
 
333
343
  ctx.inject(["systemPrompt", "settings"], (promptCtx) => {
334
- const reader = () => settingsReader(promptCtx.get("settings") as HostSettings | undefined);
344
+ // A settings write emits this event before acknowledgement. The TTL also
345
+ // refreshes reads when a host change produced no notification.
346
+ // 设置写入在应答前发出此事件。TTL 也会刷新未收到通知的变动。
347
+ let snapshot: SettingsSnapshot | undefined;
348
+ promptCtx.on("settings/document-updated", (namespace) => {
349
+ if (namespace === SETTINGS_NAMESPACE || namespace === LOCALE_NAMESPACE) snapshot = undefined;
350
+ });
351
+ const reader = (): Reader => {
352
+ const service = promptCtx.get("settings") as HostSettings | undefined;
353
+ if (!service || typeof service.describe !== "function") return settingsReader(NO_SECTIONS);
354
+ const now = Date.now();
355
+ if (snapshot?.service === service && now >= snapshot.takenAt && now - snapshot.takenAt < SETTINGS_TTL_MS) {
356
+ return settingsReader(snapshot.sections);
357
+ }
358
+ const sections = collect(service);
359
+ snapshot = sections === undefined ? undefined : { service, takenAt: now, sections };
360
+ return settingsReader(sections ?? NO_SECTIONS);
361
+ };
335
362
 
336
363
  // The text thunk is re-evaluated per assembly, so the section always
337
364
  // reflects the newest setting without re-registering anything.
@@ -342,22 +369,45 @@ export function apply(ctx: HostContext): void {
342
369
  text: () => sectionText(currentSettings(reader()).language)
343
370
  });
344
371
 
345
- // The reminder runs before the other pre-step listeners, so its message is
346
- // appended after theirs and stays closest to the end of the request.
347
- // 该提醒先于其它 pre-step 监听器执行,因此它的消息追加在它们之后,离请求末尾最近。
348
- promptCtx.on("agent/pre-step", async (payload, next) => {
372
+ /**
373
+ * Wrap the batch in two reminders: one before the prompt, one after every injection.
374
+ * 用两条提醒夹住批次:一条在提问之前,一条在全部注入之后。
375
+ */
376
+ const rewrite = async (payload: PreStepPayload, next: () => Promise<PreStepDecision>) => {
349
377
  const decision = await next();
350
- if (decision.kind !== "enter" || payload.signal.aborted || payload.step !== 1) return decision;
378
+ if (decision.kind !== "enter" || payload.signal.aborted || payload.step !== 1 || decision.messages.length === 0) return decision;
351
379
  const settings = currentSettings(reader());
352
380
  const delay = reminderDelayMs(settings.reminderMinutes);
353
381
  if (delay === REMINDER_OFF) return decision;
354
382
  const now = Date.now();
355
383
  const previous = lastReminderAt.get(payload.agent.session.id);
356
384
  if (delay > 0 && previous !== undefined && now - previous < delay) return decision;
357
- const text = reminderText(settings.language);
358
- if (text === "") return decision;
385
+ const head = reminderText(settings.language);
386
+ if (head === "") return decision;
359
387
  lastReminderAt.set(payload.agent.session.id, now);
360
- return { ...decision, messages: [...decision.messages, reminderMessage(text)] };
361
- }, { prepend: true });
388
+ // The closing rule rides on the same switch as the reminder: turning the
389
+ // reminder off skips this whole listener, so both injections stop together.
390
+ // 收尾规则与提醒共用一个开关:提醒关闭时本段不执行,两处注入一起停。
391
+ const tail = settings.extraInjection ? tailText(settings.language) : "";
392
+ const messages = tail === "" ? decision.messages : withClosingReminder(decision.messages, tail);
393
+ return { ...decision, messages: [reminderMessage(head), ...messages] };
394
+ };
395
+
396
+ /**
397
+ * `prepend` unshifts, so the listener prepended last runs first and returns last:
398
+ * only it sees every message the other pre-step listeners appended, including the
399
+ * trailing `time-context` batch.
400
+ * `prepend` 是 unshift:最后 prepend 的监听器最先执行、最后返回,只有它能看见其它
401
+ * pre-step 监听器追加的全部消息,包括压在最后的 `time-context`。
402
+ */
403
+ let disposeStep: (() => void) | undefined;
404
+ const bindOutermost = (): void => {
405
+ disposeStep?.();
406
+ disposeStep = promptCtx.on("agent/pre-step", rewrite, { prepend: true }) as () => void;
407
+ };
408
+ bindOutermost();
409
+ promptCtx.on("agent/created", () => {
410
+ bindOutermost();
411
+ });
362
412
  });
363
413
  }