dsh-thinking-levels 0.1.0 → 0.1.1

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/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.1.1",
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
  },
@@ -43,6 +49,8 @@
43
49
  "vitest": "^3.0.0"
44
50
  },
45
51
  "scripts": {
52
+ "build": "tsc -p tsconfig.build.json",
53
+ "prepublishOnly": "npm run build",
46
54
  "typecheck": "tsc --noEmit",
47
55
  "lint": "eslint src tests",
48
56
  "test": "vitest run"
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
- }