dsh-thinking-levels 0.1.0 → 0.2.0

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/lib/client.js ADDED
@@ -0,0 +1,226 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-thinking-levels",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react = require("react");
8
+ let react_jsx_runtime = require("react/jsx-runtime");
9
+ //#region src/client/locales.ts
10
+ /** `thinking-levels` client dictionaries. */
11
+ /** Dictionary namespace owned by this plugin. */
12
+ const NS = "thinking-levels";
13
+ /** Simplified Chinese dictionary (the key-set source of truth). */
14
+ const zh = {
15
+ "card.title": "思考档位",
16
+ "card.description": "按轮次控制 reasoning_effort:auto 按工具调用历史自动在 low / high / max 间调度,或手动固定档位。",
17
+ "card.level": "档位",
18
+ "card.level.off": "off — 关闭思考(仅手动,永不自动选择)",
19
+ "card.level.low": "low — 低(简单任务,廉价轮保持廉价)",
20
+ "card.level.high": "high — 高(官方默认)",
21
+ "card.level.max": "max — 最大(重任务)",
22
+ "card.level.auto": "auto — 按工具历史自动调度",
23
+ "card.enabled": "启用",
24
+ "card.allowDowngrade": "允许降档(auto 可降至 low)",
25
+ "card.allowUpgrade": "允许升档(auto 可升至 max)",
26
+ "card.unavailable": "设置命名空间不可用:请确认 dsh-thinking-levels 已装配进 profile。",
27
+ "card.readonly": "只读"
28
+ };
29
+ /** English dictionary (keys mirror zh). */
30
+ const en = {
31
+ "card.title": "Thinking Levels",
32
+ "card.description": "Per-round reasoning_effort control: auto schedules between low / high / max from the recent tool-call history, or fix a level manually.",
33
+ "card.level": "Level",
34
+ "card.level.off": "off — disable thinking (manual only, never auto-picked)",
35
+ "card.level.low": "low — cheap rounds stay cheap",
36
+ "card.level.high": "high — the official default",
37
+ "card.level.max": "max — heavy work",
38
+ "card.level.auto": "auto — schedule from tool history",
39
+ "card.enabled": "Enabled",
40
+ "card.allowDowngrade": "Allow downgrade (auto may drop to low)",
41
+ "card.allowUpgrade": "Allow upgrade (auto may lift to max)",
42
+ "card.unavailable": "Settings namespace unavailable: make sure dsh-thinking-levels is assembled into this profile.",
43
+ "card.readonly": "Read-only"
44
+ };
45
+ //#endregion
46
+ //#region src/client/card.tsx
47
+ /**
48
+ * Thinking-levels settings card — the `settings.plugin.item` face of the
49
+ * dsh-thinking-levels plugin.
50
+ *
51
+ * The card binds the `thinking-levels` settings namespace through the
52
+ * `settingsScope` cordis service and renders its four fields: the level picker
53
+ * (off / low / high / max / auto) plus the three scheduler toggles. Every
54
+ * change commits immediately through the scope (no staged form): the decision
55
+ * is read per model request, so a committed change applies to the next request
56
+ * without a restart.
57
+ *
58
+ * Kept dependency-free beyond react: the scope is subscribed with
59
+ * `useSyncExternalStore`, and the controls are plain HTML so the client bundle
60
+ * needs no CSS modules and no primitives value import.
61
+ */
62
+ /** The five user-facing levels, in picker order. */
63
+ const EFFORT_OPTIONS = [
64
+ "off",
65
+ "low",
66
+ "high",
67
+ "max",
68
+ "auto"
69
+ ];
70
+ /** Minimal shared row styling (inline; keeps the client bundle CSS-free). */
71
+ const rowStyle = {
72
+ display: "flex",
73
+ alignItems: "center",
74
+ justifyContent: "space-between",
75
+ gap: "12px",
76
+ padding: "6px 0",
77
+ fontSize: "13px",
78
+ lineHeight: "20px"
79
+ };
80
+ const labelStyle = {
81
+ margin: 0,
82
+ color: "var(--dsw-alias-label-primary)"
83
+ };
84
+ const controlStyle = {
85
+ background: "var(--dsw-alias-bg-surface, #fff)",
86
+ color: "var(--dsw-alias-label-primary)",
87
+ border: "1px solid var(--dsw-alias-border-l2)",
88
+ borderRadius: "4px",
89
+ padding: "3px 8px",
90
+ fontSize: "13px"
91
+ };
92
+ /** One boolean field row (checkbox) bound to the scope. */
93
+ function ToggleRow(props) {
94
+ const { id, label, checked, disabled, onChange } = props;
95
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
96
+ style: rowStyle,
97
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("label", {
98
+ htmlFor: id,
99
+ style: labelStyle,
100
+ children: label
101
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
102
+ id,
103
+ type: "checkbox",
104
+ checked,
105
+ disabled,
106
+ onChange: (event) => onChange(event.currentTarget.checked)
107
+ })]
108
+ });
109
+ }
110
+ /**
111
+ * The card body.
112
+ * @param props - locale copy and the injected settings scope.
113
+ */
114
+ function ThinkingLevelsCard({ t, scope }) {
115
+ const snapshot = (0, react.useSyncExternalStore)((listener) => scope.subscribe(listener), () => scope.getSnapshot());
116
+ const unavailable = snapshot.status === "unavailable";
117
+ const readonly = unavailable || !snapshot.writable;
118
+ const value = snapshot.value ?? {};
119
+ const level = EFFORT_OPTIONS.includes(value.level) ? value.level : "auto";
120
+ if (unavailable) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
121
+ style: {
122
+ padding: "12px 16px",
123
+ fontSize: "13px",
124
+ color: "var(--dsw-alias-label-tertiary)"
125
+ },
126
+ children: t("card.unavailable")
127
+ });
128
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
129
+ style: { padding: "12px 16px" },
130
+ children: [
131
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
132
+ style: rowStyle,
133
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("label", {
134
+ htmlFor: "plugin-config-thinking-levels-level",
135
+ style: labelStyle,
136
+ children: t("card.level")
137
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
138
+ id: "plugin-config-thinking-levels-level",
139
+ value: level,
140
+ disabled: readonly,
141
+ style: controlStyle,
142
+ onChange: (event) => {
143
+ scope.set("level", event.currentTarget.value);
144
+ },
145
+ children: EFFORT_OPTIONS.map((option) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
146
+ value: option,
147
+ children: t(`card.level.${option}`)
148
+ }, option))
149
+ })]
150
+ }),
151
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToggleRow, {
152
+ id: "plugin-config-thinking-levels-enabled",
153
+ label: t("card.enabled"),
154
+ checked: value.enabled ?? true,
155
+ disabled: readonly,
156
+ onChange: (next) => {
157
+ scope.set("enabled", next);
158
+ }
159
+ }),
160
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToggleRow, {
161
+ id: "plugin-config-thinking-levels-downgrade",
162
+ label: t("card.allowDowngrade"),
163
+ checked: value.allowDowngrade ?? true,
164
+ disabled: readonly || value.level !== "auto",
165
+ onChange: (next) => {
166
+ scope.set("allowDowngrade", next);
167
+ }
168
+ }),
169
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToggleRow, {
170
+ id: "plugin-config-thinking-levels-upgrade",
171
+ label: t("card.allowUpgrade"),
172
+ checked: value.allowUpgrade ?? false,
173
+ disabled: readonly || value.level !== "auto",
174
+ onChange: (next) => {
175
+ scope.set("allowUpgrade", next);
176
+ }
177
+ }),
178
+ !snapshot.writable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
179
+ style: {
180
+ margin: "8px 0 0",
181
+ fontSize: "12px",
182
+ color: "var(--dsw-alias-label-tertiary)"
183
+ },
184
+ children: t("card.readonly")
185
+ })
186
+ ]
187
+ });
188
+ }
189
+ //#endregion
190
+ //#region src/client/index.ts
191
+ /** The settings namespace the host half registers (kept in lockstep with src/index.ts). */
192
+ const THINKING_LEVELS_NS = "thinking-levels";
193
+ /** Services required by the browser half. */
194
+ const inject = [
195
+ "slots",
196
+ "locale",
197
+ "settingsScope"
198
+ ];
199
+ /**
200
+ * Client plugin body: dictionaries plus the settings card registration.
201
+ * @param ctx - client root context.
202
+ */
203
+ function apply(ctx) {
204
+ ctx.effect(() => ctx.locale.register(NS, {
205
+ zh,
206
+ en
207
+ }), "dsh-thinking-levels: dictionaries");
208
+ ctx.slots.inject("settings.plugin.item", function* () {
209
+ yield ctx.slots.register({
210
+ name: "settings.plugin.item",
211
+ key: THINKING_LEVELS_NS,
212
+ locale: NS,
213
+ inject: () => {
214
+ return { scope: ctx.settingsScope.bind({ namespace: THINKING_LEVELS_NS }) };
215
+ }
216
+ }, ThinkingLevelsCard);
217
+ });
218
+ }
219
+ //#endregion
220
+ exports.apply = apply;
221
+ exports.inject = inject;
222
+ return module.exports;
223
+ }
224
+ });
225
+
226
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":["useSyncExternalStore"],"sources":["../src/client/locales.ts","../src/client/card.tsx","../src/client/index.ts"],"sourcesContent":["/** `thinking-levels` client dictionaries. */\r\n\r\n/** Dictionary namespace owned by this plugin. */\r\nexport const NS = 'thinking-levels'\r\n\r\n/** Simplified Chinese dictionary (the key-set source of truth). */\r\nexport const zh = {\r\n 'card.title': '思考档位',\r\n 'card.description': '按轮次控制 reasoning_effort:auto 按工具调用历史自动在 low / high / max 间调度,或手动固定档位。',\r\n 'card.level': '档位',\r\n 'card.level.off': 'off — 关闭思考(仅手动,永不自动选择)',\r\n 'card.level.low': 'low — 低(简单任务,廉价轮保持廉价)',\r\n 'card.level.high': 'high — 高(官方默认)',\r\n 'card.level.max': 'max — 最大(重任务)',\r\n 'card.level.auto': 'auto — 按工具历史自动调度',\r\n 'card.enabled': '启用',\r\n 'card.allowDowngrade': '允许降档(auto 可降至 low)',\r\n 'card.allowUpgrade': '允许升档(auto 可升至 max)',\r\n 'card.unavailable': '设置命名空间不可用:请确认 dsh-thinking-levels 已装配进 profile。',\r\n 'card.readonly': '只读',\r\n} satisfies Record<string, string>\r\n\r\n/** English dictionary (keys mirror zh). */\r\nexport const en: Record<keyof typeof zh, string> = {\r\n 'card.title': 'Thinking Levels',\r\n 'card.description': 'Per-round reasoning_effort control: auto schedules between low / high / max from the recent tool-call history, or fix a level manually.',\r\n 'card.level': 'Level',\r\n 'card.level.off': 'off — disable thinking (manual only, never auto-picked)',\r\n 'card.level.low': 'low — cheap rounds stay cheap',\r\n 'card.level.high': 'high — the official default',\r\n 'card.level.max': 'max — heavy work',\r\n 'card.level.auto': 'auto — schedule from tool history',\r\n 'card.enabled': 'Enabled',\r\n 'card.allowDowngrade': 'Allow downgrade (auto may drop to low)',\r\n 'card.allowUpgrade': 'Allow upgrade (auto may lift to max)',\r\n 'card.unavailable': 'Settings namespace unavailable: make sure dsh-thinking-levels is assembled into this profile.',\r\n 'card.readonly': 'Read-only',\r\n}\r\n","/**\r\n * Thinking-levels settings card — the `settings.plugin.item` face of the\r\n * dsh-thinking-levels plugin.\r\n *\r\n * The card binds the `thinking-levels` settings namespace through the\r\n * `settingsScope` cordis service and renders its four fields: the level picker\r\n * (off / low / high / max / auto) plus the three scheduler toggles. Every\r\n * change commits immediately through the scope (no staged form): the decision\r\n * is read per model request, so a committed change applies to the next request\r\n * without a restart.\r\n *\r\n * Kept dependency-free beyond react: the scope is subscribed with\r\n * `useSyncExternalStore`, and the controls are plain HTML so the client bundle\r\n * needs no CSS modules and no primitives value import.\r\n */\r\nimport { useSyncExternalStore } from 'react'\r\nimport type { CSSProperties, JSX } from 'react'\r\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\r\nimport type { SettingsScope } from '@deepseek-ai/dsh-client-ui-settings/client'\r\nimport type { EffortId } from '../thinking-level.ts'\r\nimport type { ThinkingLevelsConfig } from '../index.ts'\r\n\r\n/** One injected face: the bound settings scope for the `thinking-levels` namespace. */\r\nexport interface ThinkingLevelsCardInjected {\r\n scope: SettingsScope<ThinkingLevelsConfig>\r\n}\r\n\r\n/** Full props: locale seat + the injected scope. */\r\nexport type ThinkingLevelsCardProps = PropsLocale<'thinking-levels'> & ThinkingLevelsCardInjected\r\n\r\n/** The five user-facing levels, in picker order. */\r\nconst EFFORT_OPTIONS: readonly EffortId[] = ['off', 'low', 'high', 'max', 'auto']\r\n\r\n/** Minimal shared row styling (inline; keeps the client bundle CSS-free). */\r\nconst rowStyle: CSSProperties = {\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'space-between',\r\n gap: '12px',\r\n padding: '6px 0',\r\n fontSize: '13px',\r\n lineHeight: '20px',\r\n}\r\n\r\nconst labelStyle: CSSProperties = { margin: 0, color: 'var(--dsw-alias-label-primary)' }\r\n\r\nconst controlStyle: CSSProperties = {\r\n background: 'var(--dsw-alias-bg-surface, #fff)',\r\n color: 'var(--dsw-alias-label-primary)',\r\n border: '1px solid var(--dsw-alias-border-l2)',\r\n borderRadius: '4px',\r\n padding: '3px 8px',\r\n fontSize: '13px',\r\n}\r\n\r\n/** One boolean field row (checkbox) bound to the scope. */\r\nfunction ToggleRow(props: {\r\n id: string\r\n label: string\r\n checked: boolean\r\n disabled: boolean\r\n onChange: (next: boolean) => void\r\n}): JSX.Element {\r\n const { id, label, checked, disabled, onChange } = props\r\n return (\r\n <div style={rowStyle}>\r\n <label htmlFor={id} style={labelStyle}>{label}</label>\r\n <input\r\n id={id}\r\n type=\"checkbox\"\r\n checked={checked}\r\n disabled={disabled}\r\n onChange={(event) => onChange(event.currentTarget.checked)}\r\n />\r\n </div>\r\n )\r\n}\r\n\r\n/**\r\n * The card body.\r\n * @param props - locale copy and the injected settings scope.\r\n */\r\nexport function ThinkingLevelsCard({ t, scope }: ThinkingLevelsCardProps): JSX.Element {\r\n const snapshot = useSyncExternalStore(\r\n (listener) => scope.subscribe(listener),\r\n () => scope.getSnapshot(),\r\n )\r\n const unavailable = snapshot.status === 'unavailable'\r\n const readonly = unavailable || !snapshot.writable\r\n const value = (snapshot.value ?? {}) as Partial<ThinkingLevelsConfig>\r\n const level = EFFORT_OPTIONS.includes(value.level as EffortId) ? value.level as EffortId : 'auto'\r\n\r\n if (unavailable) {\r\n return (\r\n <div style={{ padding: '12px 16px', fontSize: '13px', color: 'var(--dsw-alias-label-tertiary)' }}>\r\n {t('card.unavailable')}\r\n </div>\r\n )\r\n }\r\n\r\n return (\r\n <div style={{ padding: '12px 16px' }}>\r\n <div style={rowStyle}>\r\n <label htmlFor=\"plugin-config-thinking-levels-level\" style={labelStyle}>{t('card.level')}</label>\r\n <select\r\n id=\"plugin-config-thinking-levels-level\"\r\n value={level}\r\n disabled={readonly}\r\n style={controlStyle}\r\n onChange={(event) => { void scope.set('level', event.currentTarget.value as EffortId) }}\r\n >\r\n {EFFORT_OPTIONS.map((option) => (\r\n <option key={option} value={option}>{t(`card.level.${option}`)}</option>\r\n ))}\r\n </select>\r\n </div>\r\n <ToggleRow\r\n id=\"plugin-config-thinking-levels-enabled\"\r\n label={t('card.enabled')}\r\n checked={value.enabled ?? true}\r\n disabled={readonly}\r\n onChange={(next) => { void scope.set('enabled', next) }}\r\n />\r\n <ToggleRow\r\n id=\"plugin-config-thinking-levels-downgrade\"\r\n label={t('card.allowDowngrade')}\r\n checked={value.allowDowngrade ?? true}\r\n disabled={readonly || value.level !== 'auto'}\r\n onChange={(next) => { void scope.set('allowDowngrade', next) }}\r\n />\r\n <ToggleRow\r\n id=\"plugin-config-thinking-levels-upgrade\"\r\n label={t('card.allowUpgrade')}\r\n checked={value.allowUpgrade ?? false}\r\n disabled={readonly || value.level !== 'auto'}\r\n onChange={(next) => { void scope.set('allowUpgrade', next) }}\r\n />\r\n {!snapshot.writable && <p style={{ margin: '8px 0 0', fontSize: '12px', color: 'var(--dsw-alias-label-tertiary)' }}>{t('card.readonly')}</p>}\r\n </div>\r\n )\r\n}\r\n","/**\r\n * dsh-thinking-levels — browser half.\r\n *\r\n * Registers the `thinking-levels` dictionaries and one `settings.plugin.item`\r\n * card keyed by the plugin's settings namespace, so the shared Plugins\r\n * settings tab renders an editable card: the level picker (off / low / high /\r\n * max / auto) plus the scheduler toggles.\r\n *\r\n * All @deepseek-ai/* imports are type-only: collaboration happens through\r\n * cordis services (`settingsScope`) and slot registration only (client bundle\r\n * purity).\r\n */\r\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\r\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\r\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\r\nimport type { ThinkingLevelsConfig } from '../index.ts'\r\nimport { NS, en, zh } from './locales.ts'\r\nimport { ThinkingLevelsCard, type ThinkingLevelsCardInjected } from './card.tsx'\r\n\r\n/** The settings namespace the host half registers (kept in lockstep with src/index.ts). */\r\nconst THINKING_LEVELS_NS = 'thinking-levels'\r\n\r\n/** Services required by the browser half. */\r\nexport const inject = ['slots', 'locale', 'settingsScope']\r\n\r\n/**\r\n * Client plugin body: dictionaries plus the settings card registration.\r\n * @param ctx - client root context.\r\n */\r\nexport function apply(ctx: ClientContext): void {\r\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-thinking-levels: dictionaries')\r\n\r\n ctx.slots.inject('settings.plugin.item', function* () {\r\n yield ctx.slots.register({\r\n name: 'settings.plugin.item',\r\n key: THINKING_LEVELS_NS,\r\n locale: NS,\r\n inject: (): ThinkingLevelsCardInjected => {\r\n const scope = ctx.settingsScope.bind<ThinkingLevelsConfig>({ namespace: THINKING_LEVELS_NS })\r\n return { scope }\r\n },\r\n }, ThinkingLevelsCard)\r\n })\r\n}\r\n"],"mappings":"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"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * dsh-thinking-levels host plugin: injects a user-selected or auto-scheduled
3
+ * `reasoning_effort` into every `agent/request` waterfall (levels: off / low /
4
+ * high / max / auto), and records per-tool wall-clock durations for telemetry.
5
+ *
6
+ * Extension points used (verified in deepseek-ai/deepseek-harness):
7
+ * - `agent/request` waterfall (packages/core/agent-loop/src/agent.ts
8
+ * buildRequest): each listener may return a modified GenerateOptions for
9
+ * the next listener — the sanctioned way to adjust request config.
10
+ * - `session.events` (agent.session) carries the step's tool/call records.
11
+ * - settings service namespace (like DSH-better-sidebar's PrefsSchema) for
12
+ * the user toggles.
13
+ */
14
+ import type { Context } from '@deepseek-ai/cordis';
15
+ import z from '@deepseek-ai/schemastery';
16
+ import { type EffortId } from './thinking-level.ts';
17
+ /** Plugin settings. */
18
+ export interface ThinkingLevelsConfig {
19
+ enabled: boolean;
20
+ /** User-selected level: off / low / high / max fix the wire level; `auto` schedules per step. */
21
+ level: EffortId;
22
+ /** Scheduler preference: allow dropping below the `high` hub. */
23
+ allowDowngrade: boolean;
24
+ /** Scheduler preference: allow lifting above the `high` hub to `max`. */
25
+ allowUpgrade: boolean;
26
+ }
27
+ /**
28
+ * Composition-entry schema: what a dsh profile may configure at assembly
29
+ * time (cordis.yml `config:` of the plugin row). The settings namespace
30
+ * reuses the same schema, so a value admitted at one surface is admitted
31
+ * at the other.
32
+ */
33
+ export declare const Config: z<ThinkingLevelsConfig>;
34
+ /** Settings defaults, kept in lockstep with the schema defaults above. */
35
+ export declare const DEFAULT_CONFIG: ThinkingLevelsConfig;
36
+ /** Runtime-adjustable settings namespace: level + scheduler toggles. */
37
+ export declare const THINKING_LEVELS_SETTINGS_NAMESPACE: import("@deepseek-ai/dsh-settings").SettingsNamespace;
38
+ /**
39
+ * Plugin body.
40
+ * @param ctx - host context carrying the agent-event dispatch.
41
+ * @param config - resolved plugin configuration.
42
+ */
43
+ export declare function apply(ctx: Context, config?: ThinkingLevelsConfig): void;
package/lib/index.js ADDED
@@ -0,0 +1,103 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+ import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings';
3
+ import { assertEffortId, decideEffort } from "./thinking-level.js";
4
+ import { recentToolCalls } from "./session-events.js";
5
+ /**
6
+ * Composition-entry schema: what a dsh profile may configure at assembly
7
+ * time (cordis.yml `config:` of the plugin row). The settings namespace
8
+ * reuses the same schema, so a value admitted at one surface is admitted
9
+ * at the other.
10
+ */
11
+ export const Config = z.object({
12
+ enabled: z.boolean().default(true),
13
+ level: z.union(['off', 'low', 'high', 'max', 'auto']).default('auto'),
14
+ allowDowngrade: z.boolean().default(true),
15
+ allowUpgrade: z.boolean().default(false),
16
+ });
17
+ /** Settings defaults, kept in lockstep with the schema defaults above. */
18
+ export const DEFAULT_CONFIG = {
19
+ enabled: true,
20
+ level: 'auto',
21
+ allowDowngrade: true,
22
+ allowUpgrade: false,
23
+ };
24
+ /** Runtime-adjustable settings namespace: level + scheduler toggles. */
25
+ export const THINKING_LEVELS_SETTINGS_NAMESPACE = settingsNamespace('thinking-levels');
26
+ const TOOL_AGE_LIMIT_MS = 10 * 60 * 1000;
27
+ /**
28
+ * Plugin body.
29
+ * @param ctx - host context carrying the agent-event dispatch.
30
+ * @param config - resolved plugin configuration.
31
+ */
32
+ export function apply(ctx, config = DEFAULT_CONFIG) {
33
+ if (!config.enabled)
34
+ return;
35
+ // Fail-loud: a stray config value (e.g. `medium` from an old profile) must
36
+ // not ride through into the model request, where dsh throws
37
+ // UNSUPPORTED_REASONING_EFFORT per request.
38
+ assertEffortId(config.level, 'dsh-thinking-levels config.level');
39
+ // Runtime-adjustable configuration source: the composition entry is the
40
+ // base; the settings namespace layers on top and `current()` always reads
41
+ // the active section (official dsh settings integration pattern).
42
+ let current = () => config;
43
+ installSettingsSection(ctx, THINKING_LEVELS_SETTINGS_NAMESPACE, Config, config, {
44
+ setSource: (source) => {
45
+ current = source;
46
+ },
47
+ // The decision is read per request, so a committed change needs no
48
+ // re-registration.
49
+ onChange: () => { },
50
+ });
51
+ // Inject the level decision into every model request of a step.
52
+ // The 'agent/request' event key is augmented onto cordis Events by the
53
+ // dsh-agent runtime's generated scope types; the npm package does not
54
+ // re-export that augmentation, so the emitter is widened at the boundary.
55
+ const on = ctx.on;
56
+ on('agent/request', async (payload, next) => {
57
+ const seed = await next();
58
+ const cfg = current();
59
+ // `enabled` may flip at runtime through the settings namespace.
60
+ if (!cfg.enabled)
61
+ return seed;
62
+ const calls = recentToolCalls(payload.agent);
63
+ const level = decideEffort({
64
+ recentCalls: calls,
65
+ selected: cfg.level,
66
+ allowDowngrade: cfg.allowDowngrade,
67
+ allowUpgrade: cfg.allowUpgrade,
68
+ });
69
+ // Summary-only log: individual tool names/arg sizes are workflow metadata
70
+ // that need not land in the host log; count and decision suffice.
71
+ ctx.logger?.info?.('[thinking-levels] agent/request: selected=%s calls=%d => level=%s', cfg.level, calls.length, level);
72
+ return { ...seed, reasoningEffort: level };
73
+ });
74
+ // Per-tool wall-clock telemetry: log tool/call -> tool/result durations.
75
+ // Same boundary widening as above (agent/tool is a generated scope event).
76
+ const started = new Map();
77
+ // A tool that never emits `end` (crash, interruption) must not leak its
78
+ // entry forever; sweep stale ones lazily on every new `start`.
79
+ const pruneStale = (now) => {
80
+ for (const [callId, at] of started) {
81
+ if (now - at > TOOL_AGE_LIMIT_MS)
82
+ started.delete(callId);
83
+ }
84
+ };
85
+ on('agent/tool', async (payload) => {
86
+ const callId = payload.callId;
87
+ if (typeof callId !== 'string')
88
+ return;
89
+ if (payload.phase === 'start') {
90
+ const now = Date.now();
91
+ pruneStale(now);
92
+ started.set(callId, now);
93
+ }
94
+ else if (payload.phase === 'end') {
95
+ const from = started.get(callId);
96
+ started.delete(callId);
97
+ if (from !== undefined) {
98
+ const ms = Date.now() - from;
99
+ ctx.logger?.info?.('[thinking-levels] tool %s took %dms', callId, ms);
100
+ }
101
+ }
102
+ });
103
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Session tool-call sampling for dsh-thinking-levels.
3
+ *
4
+ * Pulled out of the plugin body so the extraction logic — the part most
5
+ * exposed to dsh event-shape drift — is unit-testable in isolation, with
6
+ * explicit guards instead of naked type assertions. If a future dsh version
7
+ * reshapes `session.events`, the failure shows up in the tests, not as a
8
+ * silently wrong effort decision.
9
+ */
10
+ import type { ToolCallSample } from './thinking-level.ts';
11
+ /** How many recent tool calls to sample for one decision. */
12
+ export declare const TOOL_SAMPLE_WINDOW = 8;
13
+ /**
14
+ * Recent tool calls of a session's current step, oldest first.
15
+ * Non-tool events and malformed records are skipped; at most
16
+ * {@link TOOL_SAMPLE_WINDOW} samples are returned.
17
+ *
18
+ * @param agent - the `payload.agent` value from the `agent/request` waterfall.
19
+ * @returns the sampled tool calls, or `[]` for a fresh prompt / unknown shape.
20
+ */
21
+ export declare function recentToolCalls(agent: unknown): ToolCallSample[];
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Session tool-call sampling for dsh-thinking-levels.
3
+ *
4
+ * Pulled out of the plugin body so the extraction logic — the part most
5
+ * exposed to dsh event-shape drift — is unit-testable in isolation, with
6
+ * explicit guards instead of naked type assertions. If a future dsh version
7
+ * reshapes `session.events`, the failure shows up in the tests, not as a
8
+ * silently wrong effort decision.
9
+ */
10
+ /** How many recent tool calls to sample for one decision. */
11
+ export const TOOL_SAMPLE_WINDOW = 8;
12
+ function isRecord(value) {
13
+ return typeof value === 'object' && value !== null;
14
+ }
15
+ /** Guard: one session event shaped like a tool/call record. */
16
+ function isToolCallEvent(event) {
17
+ if (!isRecord(event) || event.type !== 'tool/call')
18
+ return false;
19
+ return isRecord(event.data);
20
+ }
21
+ /** Approximate argument size in characters (payload heft); unknown shapes read as 0. */
22
+ function argsSizeOf(argumentsValue) {
23
+ return typeof argumentsValue === 'string' ? argumentsValue.length : 0;
24
+ }
25
+ /**
26
+ * Recent tool calls of a session's current step, oldest first.
27
+ * Non-tool events and malformed records are skipped; at most
28
+ * {@link TOOL_SAMPLE_WINDOW} samples are returned.
29
+ *
30
+ * @param agent - the `payload.agent` value from the `agent/request` waterfall.
31
+ * @returns the sampled tool calls, or `[]` for a fresh prompt / unknown shape.
32
+ */
33
+ export function recentToolCalls(agent) {
34
+ if (!isRecord(agent))
35
+ return [];
36
+ const session = agent.session;
37
+ if (!isRecord(session) || !Array.isArray(session.events))
38
+ return [];
39
+ const samples = [];
40
+ for (let index = session.events.length - 1; index >= 0 && samples.length < TOOL_SAMPLE_WINDOW; index -= 1) {
41
+ const event = session.events[index];
42
+ if (!isToolCallEvent(event))
43
+ continue;
44
+ const data = event.data;
45
+ const name = typeof data.name === 'string' && data.name.length > 0 ? data.name : 'tool';
46
+ samples.push({ name, argsSize: argsSizeOf(data.arguments) });
47
+ }
48
+ return samples.reverse();
49
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Pure thinking-level decision for the dsh-thinking-levels plugin.
3
+ *
4
+ * The measured bottleneck of tool calls in dsh is the model's THINKING phase
5
+ * (~90% of the wall-clock time for simple tasks), not the tool execution
6
+ * itself. DeepSeek's API exposes `reasoning_effort` in three wire levels
7
+ * (low / high / max, plus `off` disables thinking; low shipped 2026-08-13 and
8
+ * maps 1:1 per the official docs — medium/xhigh collapse onto high).
9
+ *
10
+ * The plugin offers FIVE user-facing levels:
11
+ * - `off` : thinking disabled (manual only — never auto-picked).
12
+ * - `low` : manual fix for simple chat tasks (cheap rounds stay cheap).
13
+ * - `high` : manual fix, the official default effort.
14
+ * - `max` : manual fix for heavy work.
15
+ * - `auto` : schedule per step from the recent tool-call history, between
16
+ * `low` / `high` / `max` (never `off`, never `auto` itself).
17
+ *
18
+ * Kept dependency-free (pure inputs -> output) so the policy is unit-testable
19
+ * in isolation; the plugin host feeds it the live session's recent calls.
20
+ */
21
+ /** The five user-facing thinking levels; the wire levels dsh forwards to DeepSeek plus the scheduler sentinel. */
22
+ export type EffortId = 'off' | 'low' | 'high' | 'max' | 'auto';
23
+ /** Wire levels the auto scheduler may pick (never `off`, never `auto`). */
24
+ export type AutoEffort = Exclude<EffortId, 'auto' | 'off'>;
25
+ /** Runtime guard: is this a level the plugin understands? */
26
+ export declare function isEffortId(value: unknown): value is EffortId;
27
+ /**
28
+ * Fail-loud config validation: reject an out-of-band level (e.g. a stray
29
+ * `medium` from an old profile) instead of silently injecting it into the
30
+ * model request, where dsh would throw `UNSUPPORTED_REASONING_EFFORT`.
31
+ */
32
+ export declare function assertEffortId(value: unknown, where: string): asserts value is EffortId;
33
+ /** One observed tool call of the current/last step. */
34
+ export interface ToolCallSample {
35
+ /** Tool name, e.g. 'bash', 'fs_write', 'web_search', 'mcp__...'. */
36
+ name: string;
37
+ /** Approximate argument size in characters (payload heft). */
38
+ argsSize: number;
39
+ }
40
+ /** Everything the policy needs to decide one request's level. */
41
+ export interface EffortDecisionInput {
42
+ /** Recent tool calls of the step (oldest first); empty for a fresh prompt. */
43
+ recentCalls: readonly ToolCallSample[];
44
+ /** The user-selected level: a fixed wire level, or `auto` for scheduling. */
45
+ selected: EffortId;
46
+ /** User preference: allow the scheduler to drop below the hub (`high`). */
47
+ allowDowngrade: boolean;
48
+ /** User preference: allow the scheduler to lift above the hub to `max`. */
49
+ allowUpgrade: boolean;
50
+ }
51
+ /**
52
+ * Map the user's selected level to the level injected into the next
53
+ * `agent/request`. Manual levels (off / low / high / max) pass through
54
+ * unchanged — `low` is the manual pick for simple chat tasks. `auto`
55
+ * delegates to the tool-history scheduler.
56
+ *
57
+ * @param input - recent calls, the selected level and the user's toggles.
58
+ * @returns The level to inject; `auto` is resolved before returning.
59
+ */
60
+ export declare function decideEffort(input: EffortDecisionInput): EffortId;
61
+ /** Wall-clock delta of one tool call, for the timing telemetry. */
62
+ export declare function toolDurationMs(startedAt: number, finishedAt: number): number;
@@ -18,64 +18,31 @@
18
18
  * Kept dependency-free (pure inputs -> output) so the policy is unit-testable
19
19
  * in isolation; the plugin host feeds it the live session's recent calls.
20
20
  */
21
-
22
- /** The five user-facing thinking levels; the wire levels dsh forwards to DeepSeek plus the scheduler sentinel. */
23
- export type EffortId = 'off' | 'low' | 'high' | 'max' | 'auto'
24
-
25
- /** Wire levels the auto scheduler may pick (never `off`, never `auto`). */
26
- export type AutoEffort = Exclude<EffortId, 'auto' | 'off'>
27
-
28
21
  /** Runtime guard: is this a level the plugin understands? */
29
- export function isEffortId(value: unknown): value is EffortId {
30
- return value === 'off' || value === 'low' || value === 'high' || value === 'max' || value === 'auto'
22
+ export function isEffortId(value) {
23
+ return value === 'off' || value === 'low' || value === 'high' || value === 'max' || value === 'auto';
31
24
  }
32
-
33
25
  /**
34
26
  * Fail-loud config validation: reject an out-of-band level (e.g. a stray
35
27
  * `medium` from an old profile) instead of silently injecting it into the
36
28
  * model request, where dsh would throw `UNSUPPORTED_REASONING_EFFORT`.
37
29
  */
38
- export function assertEffortId(value: unknown, where: string): asserts value is EffortId {
39
- if (!isEffortId(value)) {
40
- throw new TypeError(`${where}: invalid thinking level ${JSON.stringify(value)} (expected off | low | high | max | auto)`)
41
- }
30
+ export function assertEffortId(value, where) {
31
+ if (!isEffortId(value)) {
32
+ throw new TypeError(`${where}: invalid thinking level ${JSON.stringify(value)} (expected off | low | high | max | auto)`);
33
+ }
42
34
  }
43
-
44
- /** One observed tool call of the current/last step. */
45
- export interface ToolCallSample {
46
- /** Tool name, e.g. 'bash', 'fs_write', 'web_search', 'mcp__...'. */
47
- name: string
48
- /** Approximate argument size in characters (payload heft). */
49
- argsSize: number
50
- }
51
-
52
- /** Everything the policy needs to decide one request's level. */
53
- export interface EffortDecisionInput {
54
- /** Recent tool calls of the step (oldest first); empty for a fresh prompt. */
55
- recentCalls: readonly ToolCallSample[]
56
- /** The user-selected level: a fixed wire level, or `auto` for scheduling. */
57
- selected: EffortId
58
- /** User preference: allow the scheduler to drop below the hub (`high`). */
59
- allowDowngrade: boolean
60
- /** User preference: allow the scheduler to lift above the hub to `max`. */
61
- allowUpgrade: boolean
62
- }
63
-
64
35
  /** Deterministic tool names that are cheap to reason about (word-boundary anchored). */
65
- const SIMPLE_TOOL_RE = /^(?:fs|bash|terminal|code|text|todo|job|skill|read|list|search|write|grep|glob|edit|ls|cat|rm|mv|cp|touch|mkdir|pwd|head|tail)(?:_|$)/i
66
-
36
+ const SIMPLE_TOOL_RE = /^(?:fs|bash|terminal|code|text|todo|job|skill|read|list|search|write|grep|glob|edit|ls|cat|rm|mv|cp|touch|mkdir|pwd|head|tail)(?:_|$)/i;
67
37
  /** Hefty payloads signal non-trivial work no matter the tool name. */
68
- const HEAVY_ARGS = 800
69
-
38
+ const HEAVY_ARGS = 800;
70
39
  /** Count how many of the recent calls look cheap-and-deterministic. */
71
- function simpleRatio(calls: readonly ToolCallSample[]): number {
72
- if (calls.length === 0) return 1
73
- const simple = calls.filter(call =>
74
- SIMPLE_TOOL_RE.test(call.name) && call.argsSize < HEAVY_ARGS,
75
- ).length
76
- return simple / calls.length
40
+ function simpleRatio(calls) {
41
+ if (calls.length === 0)
42
+ return 1;
43
+ const simple = calls.filter(call => SIMPLE_TOOL_RE.test(call.name) && call.argsSize < HEAVY_ARGS).length;
44
+ return simple / calls.length;
77
45
  }
78
-
79
46
  /**
80
47
  * Auto schedule: map a recent tool-call history to the wire level the NEXT
81
48
  * model request of that step should use.
@@ -91,21 +58,17 @@ function simpleRatio(calls: readonly ToolCallSample[]): number {
91
58
  * @param allowUpgrade - may lift above `high`.
92
59
  * @returns a wire level; never `off` (off is manual-only) and never `auto`.
93
60
  */
94
- function scheduleEffort(
95
- calls: readonly ToolCallSample[],
96
- allowDowngrade: boolean,
97
- allowUpgrade: boolean,
98
- ): AutoEffort {
99
- if (calls.length === 0) return allowDowngrade ? 'low' : 'high'
100
-
101
- const ratio = simpleRatio(calls)
102
- const heaviest = calls.reduce((max, call) => Math.max(max, call.argsSize), 0)
103
-
104
- if (ratio >= 0.75 && allowDowngrade) return 'low'
105
- if (heaviest >= HEAVY_ARGS * 4 && allowUpgrade) return 'max'
106
- return 'high'
61
+ function scheduleEffort(calls, allowDowngrade, allowUpgrade) {
62
+ if (calls.length === 0)
63
+ return allowDowngrade ? 'low' : 'high';
64
+ const ratio = simpleRatio(calls);
65
+ const heaviest = calls.reduce((max, call) => Math.max(max, call.argsSize), 0);
66
+ if (ratio >= 0.75 && allowDowngrade)
67
+ return 'low';
68
+ if (heaviest >= HEAVY_ARGS * 4 && allowUpgrade)
69
+ return 'max';
70
+ return 'high';
107
71
  }
108
-
109
72
  /**
110
73
  * Map the user's selected level to the level injected into the next
111
74
  * `agent/request`. Manual levels (off / low / high / max) pass through
@@ -115,13 +78,13 @@ function scheduleEffort(
115
78
  * @param input - recent calls, the selected level and the user's toggles.
116
79
  * @returns The level to inject; `auto` is resolved before returning.
117
80
  */
118
- export function decideEffort(input: EffortDecisionInput): EffortId {
119
- const { recentCalls, selected, allowDowngrade, allowUpgrade } = input
120
- if (selected !== 'auto') return selected
121
- return scheduleEffort(recentCalls, allowDowngrade, allowUpgrade)
81
+ export function decideEffort(input) {
82
+ const { recentCalls, selected, allowDowngrade, allowUpgrade } = input;
83
+ if (selected !== 'auto')
84
+ return selected;
85
+ return scheduleEffort(recentCalls, allowDowngrade, allowUpgrade);
122
86
  }
123
-
124
87
  /** Wall-clock delta of one tool call, for the timing telemetry. */
125
- export function toolDurationMs(startedAt: number, finishedAt: number): number {
126
- return Math.max(0, finishedAt - startedAt)
88
+ export function toolDurationMs(startedAt, finishedAt) {
89
+ return Math.max(0, finishedAt - startedAt);
127
90
  }
package/package.json CHANGED
@@ -1,22 +1,28 @@
1
1
  {
2
2
  "name": "dsh-thinking-levels",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "DSH host plugin: thinking-level (reasoning_effort) control for dsh — auto-adjust per tool round, with optional manual lock and per-tool timing telemetry.",
5
- "repository": "git+https://github.com/drscrewdriver/dsh-thinking-levels.git",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/drscrewdriver/dsh-thinking-levels.git"
8
+ },
6
9
  "type": "module",
7
10
  "files": [
8
- "src",
9
- "cordis.patch.yml"
11
+ "lib",
12
+ "cordis.patch.yml",
13
+ "README.md",
14
+ "README.zh.md"
10
15
  ],
11
- "main": "src/index.ts",
16
+ "main": "lib/index.js",
17
+ "types": "lib/index.d.ts",
12
18
  "exports": {
13
19
  ".": {
14
- "types": "./src/index.ts",
15
- "default": "./src/index.ts"
20
+ "types": "./lib/index.d.ts",
21
+ "default": "./lib/index.js"
16
22
  },
17
23
  "./thinking-level": {
18
- "types": "./src/thinking-level.ts",
19
- "default": "./src/thinking-level.ts"
24
+ "types": "./lib/thinking-level.d.ts",
25
+ "default": "./lib/thinking-level.js"
20
26
  },
21
27
  "./package.json": "./package.json"
22
28
  },
@@ -35,14 +41,23 @@
35
41
  "@deepseek-ai/cordis": "^4.0.1",
36
42
  "@deepseek-ai/dsh-agent": "^0.1.0-rc.6",
37
43
  "@deepseek-ai/dsh-settings": "^0.1.0-rc.6",
44
+ "@deepseek-ai/dsh-client-locale": "^0.1.0-rc.7",
45
+ "@deepseek-ai/dsh-client-runtime": "^0.1.0-rc.7",
46
+ "@deepseek-ai/dsh-client-ui-settings": "^0.1.0-rc.7",
47
+ "@deepseek-ai/dsh-client-ui-slots": "^0.1.0-rc.7",
38
48
  "@eslint/js": "^10.0.1",
39
49
  "@types/node": "^24.0.0",
50
+ "@types/react": "~18.3.1",
40
51
  "eslint": "^10.8.1",
52
+ "react": "^18.2.0",
53
+ "tsdown": "^0.22.2",
41
54
  "typescript": "^5.6.0",
42
55
  "typescript-eslint": "^8.67.0",
43
56
  "vitest": "^3.0.0"
44
57
  },
45
58
  "scripts": {
59
+ "build": "tsc -p tsconfig.build.json && tsdown",
60
+ "prepublishOnly": "npm run build",
46
61
  "typecheck": "tsc --noEmit",
47
62
  "lint": "eslint src tests",
48
63
  "test": "vitest run"
@@ -51,6 +66,15 @@
51
66
  "dsh": {
52
67
  "bundle": {
53
68
  "patch": "./cordis.patch.yml"
69
+ },
70
+ "client": {
71
+ "inject": [
72
+ "@deepseek-ai/dsh-client-runtime",
73
+ "@deepseek-ai/dsh-client-locale",
74
+ "@deepseek-ai/dsh-client-ui-slots",
75
+ "@deepseek-ai/dsh-client-ui-settings"
76
+ ],
77
+ "platform": "web"
54
78
  }
55
79
  }
56
80
  }
package/src/index.ts DELETED
@@ -1,134 +0,0 @@
1
- /**
2
- * dsh-thinking-levels host plugin: injects a user-selected or auto-scheduled
3
- * `reasoning_effort` into every `agent/request` waterfall (levels: off / low /
4
- * high / max / auto), and records per-tool wall-clock durations for telemetry.
5
- *
6
- * Extension points used (verified in deepseek-ai/deepseek-harness):
7
- * - `agent/request` waterfall (packages/core/agent-loop/src/agent.ts
8
- * buildRequest): each listener may return a modified GenerateOptions for
9
- * the next listener — the sanctioned way to adjust request config.
10
- * - `session.events` (agent.session) carries the step's tool/call records.
11
- * - settings service namespace (like DSH-better-sidebar's PrefsSchema) for
12
- * the user toggles.
13
- */
14
- import type { Context } from '@deepseek-ai/cordis'
15
- import z from '@deepseek-ai/schemastery'
16
- import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings'
17
- import { assertEffortId, decideEffort, type EffortId } from './thinking-level.ts'
18
- import { recentToolCalls } from './session-events.ts'
19
-
20
- /** Plugin settings. */
21
- export interface ThinkingLevelsConfig {
22
- enabled: boolean
23
- /** User-selected level: off / low / high / max fix the wire level; `auto` schedules per step. */
24
- level: EffortId
25
- /** Scheduler preference: allow dropping below the `high` hub. */
26
- allowDowngrade: boolean
27
- /** Scheduler preference: allow lifting above the `high` hub to `max`. */
28
- allowUpgrade: boolean
29
- }
30
-
31
- /**
32
- * Composition-entry schema: what a dsh profile may configure at assembly
33
- * time (cordis.yml `config:` of the plugin row). The settings namespace
34
- * reuses the same schema, so a value admitted at one surface is admitted
35
- * at the other.
36
- */
37
- export const Config: z<ThinkingLevelsConfig> = z.object({
38
- enabled: z.boolean().default(true),
39
- level: z.union(['off', 'low', 'high', 'max', 'auto']).default('auto'),
40
- allowDowngrade: z.boolean().default(true),
41
- allowUpgrade: z.boolean().default(false),
42
- })
43
-
44
- /** Settings defaults, kept in lockstep with the schema defaults above. */
45
- export const DEFAULT_CONFIG: ThinkingLevelsConfig = {
46
- enabled: true,
47
- level: 'auto',
48
- allowDowngrade: true,
49
- allowUpgrade: false,
50
- }
51
-
52
- /** Runtime-adjustable settings namespace: level + scheduler toggles. */
53
- export const THINKING_LEVELS_SETTINGS_NAMESPACE = settingsNamespace('thinking-levels')
54
-
55
- const TOOL_AGE_LIMIT_MS = 10 * 60 * 1000
56
-
57
- /**
58
- * Plugin body.
59
- * @param ctx - host context carrying the agent-event dispatch.
60
- * @param config - resolved plugin configuration.
61
- */
62
- export function apply(ctx: Context, config: ThinkingLevelsConfig = DEFAULT_CONFIG): void {
63
- if (!config.enabled) return
64
- // Fail-loud: a stray config value (e.g. `medium` from an old profile) must
65
- // not ride through into the model request, where dsh throws
66
- // UNSUPPORTED_REASONING_EFFORT per request.
67
- assertEffortId(config.level, 'dsh-thinking-levels config.level')
68
-
69
- // Runtime-adjustable configuration source: the composition entry is the
70
- // base; the settings namespace layers on top and `current()` always reads
71
- // the active section (official dsh settings integration pattern).
72
- let current: () => ThinkingLevelsConfig = () => config
73
- installSettingsSection(ctx, THINKING_LEVELS_SETTINGS_NAMESPACE, Config, config, {
74
- setSource: (source) => {
75
- current = source
76
- },
77
- // The decision is read per request, so a committed change needs no
78
- // re-registration.
79
- onChange: () => {},
80
- })
81
-
82
- // Inject the level decision into every model request of a step.
83
- // The 'agent/request' event key is augmented onto cordis Events by the
84
- // dsh-agent runtime's generated scope types; the npm package does not
85
- // re-export that augmentation, so the emitter is widened at the boundary.
86
- const on = ctx.on as unknown as (
87
- event: string,
88
- handler: (payload: Record<string, unknown>, next: () => unknown) => unknown | Promise<unknown>,
89
- ) => void
90
- on('agent/request', async (payload, next) => {
91
- const seed = await next() as { reasoningEffort?: unknown }
92
- const cfg = current()
93
- // `enabled` may flip at runtime through the settings namespace.
94
- if (!cfg.enabled) return seed
95
- const calls = recentToolCalls(payload.agent)
96
- const level = decideEffort({
97
- recentCalls: calls,
98
- selected: cfg.level,
99
- allowDowngrade: cfg.allowDowngrade,
100
- allowUpgrade: cfg.allowUpgrade,
101
- })
102
- // Summary-only log: individual tool names/arg sizes are workflow metadata
103
- // that need not land in the host log; count and decision suffice.
104
- ctx.logger?.info?.('[thinking-levels] agent/request: selected=%s calls=%d => level=%s', cfg.level, calls.length, level)
105
- return { ...seed, reasoningEffort: level }
106
- })
107
-
108
- // Per-tool wall-clock telemetry: log tool/call -> tool/result durations.
109
- // Same boundary widening as above (agent/tool is a generated scope event).
110
- const started = new Map<string, number>()
111
- // A tool that never emits `end` (crash, interruption) must not leak its
112
- // entry forever; sweep stale ones lazily on every new `start`.
113
- const pruneStale = (now: number): void => {
114
- for (const [callId, at] of started) {
115
- if (now - at > TOOL_AGE_LIMIT_MS) started.delete(callId)
116
- }
117
- }
118
- on('agent/tool', async (payload) => {
119
- const callId = payload.callId
120
- if (typeof callId !== 'string') return
121
- if (payload.phase === 'start') {
122
- const now = Date.now()
123
- pruneStale(now)
124
- started.set(callId, now)
125
- } else if (payload.phase === 'end') {
126
- const from = started.get(callId)
127
- started.delete(callId)
128
- if (from !== undefined) {
129
- const ms = Date.now() - from
130
- ctx.logger?.info?.('[thinking-levels] tool %s took %dms', callId, ms)
131
- }
132
- }
133
- })
134
- }
@@ -1,53 +0,0 @@
1
- /**
2
- * Session tool-call sampling for dsh-thinking-levels.
3
- *
4
- * Pulled out of the plugin body so the extraction logic — the part most
5
- * exposed to dsh event-shape drift — is unit-testable in isolation, with
6
- * explicit guards instead of naked type assertions. If a future dsh version
7
- * reshapes `session.events`, the failure shows up in the tests, not as a
8
- * silently wrong effort decision.
9
- */
10
-
11
- import type { ToolCallSample } from './thinking-level.ts'
12
-
13
- /** How many recent tool calls to sample for one decision. */
14
- export const TOOL_SAMPLE_WINDOW = 8
15
-
16
- function isRecord(value: unknown): value is Record<string, unknown> {
17
- return typeof value === 'object' && value !== null
18
- }
19
-
20
- /** Guard: one session event shaped like a tool/call record. */
21
- function isToolCallEvent(event: unknown): event is { data: Record<string, unknown> } {
22
- if (!isRecord(event) || event.type !== 'tool/call') return false
23
- return isRecord(event.data)
24
- }
25
-
26
- /** Approximate argument size in characters (payload heft); unknown shapes read as 0. */
27
- function argsSizeOf(argumentsValue: unknown): number {
28
- return typeof argumentsValue === 'string' ? argumentsValue.length : 0
29
- }
30
-
31
- /**
32
- * Recent tool calls of a session's current step, oldest first.
33
- * Non-tool events and malformed records are skipped; at most
34
- * {@link TOOL_SAMPLE_WINDOW} samples are returned.
35
- *
36
- * @param agent - the `payload.agent` value from the `agent/request` waterfall.
37
- * @returns the sampled tool calls, or `[]` for a fresh prompt / unknown shape.
38
- */
39
- export function recentToolCalls(agent: unknown): ToolCallSample[] {
40
- if (!isRecord(agent)) return []
41
- const session = agent.session
42
- if (!isRecord(session) || !Array.isArray(session.events)) return []
43
-
44
- const samples: ToolCallSample[] = []
45
- for (let index = session.events.length - 1; index >= 0 && samples.length < TOOL_SAMPLE_WINDOW; index -= 1) {
46
- const event = session.events[index]
47
- if (!isToolCallEvent(event)) continue
48
- const data = event.data
49
- const name = typeof data.name === 'string' && data.name.length > 0 ? data.name : 'tool'
50
- samples.push({ name, argsSize: argsSizeOf(data.arguments) })
51
- }
52
- return samples.reverse()
53
- }