dsh-thinking-levels 4.5.0 → 4.7.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/index.d.ts CHANGED
@@ -77,6 +77,14 @@ export interface ThinkingLevelsConfig {
77
77
  * namespace strip, exactly like a built-in token.
78
78
  */
79
79
  simpleTools: string[] | Volatile<string[]>;
80
+ /**
81
+ * Extra RAW REGEX patterns with the same cheap-and-deterministic role
82
+ * (issue #12): each entry compiles as written (`i` flag, no auto-anchoring —
83
+ * anchor with `^` yourself), and the matcher tests BOTH the full tool name
84
+ * and the namespace-stripped bare name, so `ops_.*` covers the whole family.
85
+ * Invalid patterns are skipped with a one-time warning.
86
+ */
87
+ simpleToolsRegex: string[] | Volatile<string[]>;
80
88
  /**
81
89
  * Master takeover switch: mirrored into the openai-completions transport's
82
90
  * own section (`llm-openai-completions.enabled`) when it flips. The
@@ -114,6 +122,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
114
122
  allowDowngrade: z<boolean, boolean, "volatile-defined">;
115
123
  allowUpgrade: z<boolean, boolean, "volatile-defined">;
116
124
  simpleTools: z<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
125
+ simpleToolsRegex: z<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
117
126
  takeover: z<boolean, boolean, "volatile-defined">;
118
127
  takeoverUi: z<boolean, boolean, "volatile-defined">;
119
128
  defaultPricing: z<"off" | "custom" | "estimate" | "cn" | "global", "off" | "custom" | "estimate" | "cn" | "global", "volatile-defined">;
@@ -134,6 +143,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
134
143
  allowDowngrade: z<boolean, boolean, "volatile-defined">;
135
144
  allowUpgrade: z<boolean, boolean, "volatile-defined">;
136
145
  simpleTools: z<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
146
+ simpleToolsRegex: z<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
137
147
  takeover: z<boolean, boolean, "volatile-defined">;
138
148
  takeoverUi: z<boolean, boolean, "volatile-defined">;
139
149
  defaultPricing: z<"off" | "custom" | "estimate" | "cn" | "global", "off" | "custom" | "estimate" | "cn" | "global", "volatile-defined">;
@@ -162,6 +172,7 @@ export declare const LegacyConfig: z<Schemastery.ObjectS<NoInfer<{
162
172
  allowDowngrade: z<boolean, boolean, "defined">;
163
173
  allowUpgrade: z<boolean, boolean, "defined">;
164
174
  simpleTools: z<string[], string[], "defined">;
175
+ simpleToolsRegex: z<string[], string[], "defined">;
165
176
  takeover: z<boolean, boolean, "defined">;
166
177
  takeoverUi: z<boolean, boolean, "defined">;
167
178
  defaultPricing: z<"off" | "custom" | "estimate" | "cn" | "global", "off" | "custom" | "estimate" | "cn" | "global", "defined">;
@@ -182,6 +193,7 @@ export declare const LegacyConfig: z<Schemastery.ObjectS<NoInfer<{
182
193
  allowDowngrade: z<boolean, boolean, "defined">;
183
194
  allowUpgrade: z<boolean, boolean, "defined">;
184
195
  simpleTools: z<string[], string[], "defined">;
196
+ simpleToolsRegex: z<string[], string[], "defined">;
185
197
  takeover: z<boolean, boolean, "defined">;
186
198
  takeoverUi: z<boolean, boolean, "defined">;
187
199
  defaultPricing: z<"off" | "custom" | "estimate" | "cn" | "global", "off" | "custom" | "estimate" | "cn" | "global", "defined">;
package/lib/index.js CHANGED
@@ -4,6 +4,7 @@ import { buildBillingDefinition } from "./billing-projection.js";
4
4
  import { recentToolCalls } from "./session-events.js";
5
5
  import { buildAutoScheduleDefinition, readAutoSchedule, requestedEffortOf } from "./auto-schedule-projection.js";
6
6
  import { effortOfSelection, planStrictStep, } from "./strict-step-schedule.js";
7
+ import { markSchedulerWrite } from "./plugin-records.js";
7
8
  import { CONTEXT_WINDOW_MAX, CONTEXT_WINDOW_MIN } from "./context-window.js";
8
9
  import { PI_AI_NAMESPACE, TAKEOVER_NAMESPACE_CANDIDATES, takeoverPatch, takeoverRoutesOf, withOfficialCompatFixes, } from "./takeover-sync.js";
9
10
  import { describeSettings, readSection, readSectionOf, resolveNamespaceOf } from "./settings-read.js";
@@ -33,6 +34,7 @@ export const Config = z.object({
33
34
  allowDowngrade: z.boolean().default(true).volatile(),
34
35
  allowUpgrade: z.boolean().default(false).volatile(),
35
36
  simpleTools: z.array(z.string()).default([]).volatile(),
37
+ simpleToolsRegex: z.array(z.string()).default([]).volatile(),
36
38
  takeover: z.boolean().default(false).volatile(),
37
39
  takeoverUi: z.boolean().default(false).volatile(),
38
40
  defaultPricing: defaultPricingSchema.volatile(),
@@ -51,6 +53,7 @@ export const LegacyConfig = z.object({
51
53
  allowDowngrade: z.boolean().default(true),
52
54
  allowUpgrade: z.boolean().default(false),
53
55
  simpleTools: z.array(z.string()).default([]),
56
+ simpleToolsRegex: z.array(z.string()).default([]),
54
57
  takeover: z.boolean().default(false),
55
58
  takeoverUi: z.boolean().default(false),
56
59
  defaultPricing: defaultPricingSchema,
@@ -63,6 +66,7 @@ export const DEFAULT_CONFIG = {
63
66
  allowDowngrade: true,
64
67
  allowUpgrade: false,
65
68
  simpleTools: [],
69
+ simpleToolsRegex: [],
66
70
  takeover: false,
67
71
  takeoverUi: false,
68
72
  defaultPricing: 'estimate',
@@ -93,6 +97,7 @@ function resolveLiveConfig(config) {
93
97
  allowDowngrade: readVolatile(config.allowDowngrade, true),
94
98
  allowUpgrade: readVolatile(config.allowUpgrade, false),
95
99
  simpleTools: readVolatile(config.simpleTools, []),
100
+ simpleToolsRegex: readVolatile(config.simpleToolsRegex, []),
96
101
  takeover: readVolatile(config.takeover, false),
97
102
  takeoverUi: readVolatile(config.takeoverUi, false),
98
103
  defaultPricing: readVolatile(config.defaultPricing, 'estimate'),
@@ -453,6 +458,7 @@ export function installLegacySection(ctx, config, hooks) {
453
458
  allowDowngrade: readVolatile(config.allowDowngrade, true),
454
459
  allowUpgrade: readVolatile(config.allowUpgrade, false),
455
460
  simpleTools: readVolatile(config.simpleTools, []),
461
+ simpleToolsRegex: readVolatile(config.simpleToolsRegex, []),
456
462
  takeover: readVolatile(config.takeover, false),
457
463
  takeoverUi: readVolatile(config.takeoverUi, false),
458
464
  models: config.models,
@@ -659,6 +665,7 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
659
665
  allowDowngrade: cfg.allowDowngrade,
660
666
  allowUpgrade: cfg.allowUpgrade,
661
667
  extraSimpleTools: cfg.simpleTools,
668
+ extraSimpleRegex: cfg.simpleToolsRegex,
662
669
  supportsReasoning: capabilityFor.supportsReasoning,
663
670
  efforts: capabilityFor.efforts,
664
671
  toggleOnly: capabilityFor.toggleOnly,
@@ -708,6 +715,27 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
708
715
  }
709
716
  return strictSelectNext(agent, provider, model, write) ? 'next' : 'none';
710
717
  };
718
+ /**
719
+ * Record a scheduler write into the session log so the trace can attribute it.
720
+ *
721
+ * Fire-and-forget on purpose: `agent/pre-step` must not wait on a log append,
722
+ * and a missing channel must never fail the step. The mark is an `ignorable`
723
+ * `plugin:` record, so readers that do not know it skip it rather than refuse
724
+ * the session (see plugin-records.ts).
725
+ * @param agent - the agent whose session receives the mark.
726
+ * @param write - the level written (or the clear).
727
+ * @param applied - whether it landed on this step or is deferred to the next.
728
+ */
729
+ const markStrictWrite = (agent, provider, model, write, applied, intent) => {
730
+ const session = agent.session;
731
+ void markSchedulerWrite(session, {
732
+ ...write.clear ? { clear: true } : { level: String(write.level) },
733
+ provider,
734
+ model,
735
+ applied,
736
+ intent,
737
+ }, ctx.logger).catch(() => { });
738
+ };
711
739
  /**
712
740
  * Schedule the step the host just fixed.
713
741
  */
@@ -733,6 +761,11 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
733
761
  const plan = await strictPlanFor(agent, provider, model, selection.reasoningEffort);
734
762
  const applied = strictApplyStep(agent, provider, model, selection, plan);
735
763
  const write = plan.select;
764
+ // Mark the write in the log: without it the trace cannot tell a scheduler
765
+ // choice from a user pick (the host never logs plugin-side selections).
766
+ if (write !== undefined && applied !== 'none') {
767
+ markStrictWrite(agent, provider, model, write, applied, plan.intent);
768
+ }
736
769
  ctx.logger?.info?.('[thinking-levels] agent/pre-step: model=%s/%s fixed=%s intent=%s => %s=%s', provider, model, fixed ?? 'adapter default', plan.intent, applied === 'step' ? 'applied' : applied === 'next' ? 'deferred-next-step' : 'unchanged', write === undefined ? '-' : write.clear ? 'clear' : String(write.level));
737
770
  }
738
771
  catch (error) {
@@ -812,6 +845,7 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
812
845
  allowDowngrade: cfg.allowDowngrade,
813
846
  allowUpgrade: cfg.allowUpgrade,
814
847
  extraSimpleTools: cfg.simpleTools,
848
+ extraSimpleRegex: cfg.simpleToolsRegex,
815
849
  efforts: capabilityFor.efforts,
816
850
  toggleOnly: capabilityFor.toggleOnly,
817
851
  });
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Durable marks for the scheduler's OWN `model/selection` writes.
3
+ *
4
+ * ## The problem this solves
5
+ *
6
+ * On the 0.2.2+ strict line this plugin is itself a `model/selection` writer:
7
+ * it fixes the next step's level through `agent.model.select()` (or by rewriting
8
+ * the step's captured selection). Those writes do NOT reach the session log —
9
+ * the host only appends `model/selection` for an explicit user pick
10
+ * (`api/session-controller/src/commands.ts:176` → `selectForNextRequest`).
11
+ *
12
+ * Measured live (session `7f321902`): ONE `model/selection` event against THIRTY
13
+ * `request/header` events alternating high/low. A projection folded over the log
14
+ * alone therefore cannot tell "the user chose low" from "the scheduler chose
15
+ * low", and the first honest answer was `unknown` — truthful, but useless: it
16
+ * cannot distinguish scheduler output from a genuinely unexplained change.
17
+ *
18
+ * ## The mechanism
19
+ *
20
+ * `@deepseek-ai/dsh-session` exposes `appendPluginRecord(session, type, data)`
21
+ * for exactly this: an `ignorable` event under a `plugin:`-namespaced type that
22
+ * never enters the model-visible surface, is retained across fork/resume, and is
23
+ * skipped (not refused) by readers that do not know it. We append one record per
24
+ * scheduler write, so the projection can attribute the following
25
+ * `request/header` to the scheduler.
26
+ *
27
+ * ## Coupling rules
28
+ *
29
+ * - **Soft**: the host package is resolved with a dynamic `import()` at call
30
+ * time and every failure degrades to "no mark" (the projection then keeps its
31
+ * `unknown` attribution). A plugin must never take a turn down because an
32
+ * optional telemetry channel is missing (`agent-loop/README.md:128`).
33
+ * - **Never throws**: the caller is mid-turn; a rejected append would abort the
34
+ * step. All paths are wrapped.
35
+ * - **Probed once**: the first attempt logs whether the API was reachable, so a
36
+ * silent degradation is diagnosable from the host log instead of by guessing.
37
+ * @module dsh-thinking-levels/plugin-records
38
+ */
39
+ /**
40
+ * The record type. `plugin:` + slash-separated lowercase segments, per the
41
+ * host grammar (`PluginRecordType` in `dsh-session/types`).
42
+ */
43
+ export declare const SCHEDULER_WRITE_RECORD = "plugin:dsh-thinking-levels/scheduler-write";
44
+ /** Payload of one scheduler-write mark. */
45
+ export interface SchedulerWriteRecord {
46
+ /** The level this plugin wrote (absent when it cleared the effort). */
47
+ level?: string;
48
+ /** `true` when the write removed the effort instead of setting one. */
49
+ clear?: boolean;
50
+ /** The intent the scheduler resolved for this step, for diagnosis. */
51
+ intent?: string;
52
+ /** Provider/model route the write targeted. */
53
+ provider?: string;
54
+ model?: string;
55
+ /** `step` when the write landed on the current step, `next` when deferred. */
56
+ applied?: 'step' | 'next';
57
+ }
58
+ /**
59
+ * Append one scheduler-write mark to the session log.
60
+ *
61
+ * Best-effort by construction: an absent API, a non-appendable session, a
62
+ * rejected payload or a throwing host all resolve to `false` — never a
63
+ * rejection — because the caller is in the middle of a turn.
64
+ * @param session - the live Session the write applies to (`agent.session`).
65
+ * @param record - what was written.
66
+ * @param logger - optional host logger, used once for the capability probe.
67
+ * @returns whether the mark was committed.
68
+ */
69
+ export declare function markSchedulerWrite(session: unknown, record: SchedulerWriteRecord, logger?: {
70
+ info?: (message: string, ...args: unknown[]) => void;
71
+ warn?: (message: string, ...args: unknown[]) => void;
72
+ }): Promise<boolean>;
73
+ /**
74
+ * Read one committed event as a scheduler-write mark.
75
+ *
76
+ * Duck-typed on purpose: the projection folds raw events and must recognize the
77
+ * mark on any host line without importing host types.
78
+ * @param event - any committed session event.
79
+ * @returns the record payload, or undefined for any other event.
80
+ */
81
+ export declare function schedulerWriteOf(event: unknown): SchedulerWriteRecord | undefined;
82
+ /** Whether the capability probe has run and what it found (diagnostics/tests). */
83
+ export declare function schedulerMarkChannel(): 'ready' | 'unavailable' | 'unprobed';
84
+ /** Test seam: forget the cached module and probe state. */
85
+ export declare function resetSchedulerMarkChannel(): void;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Durable marks for the scheduler's OWN `model/selection` writes.
3
+ *
4
+ * ## The problem this solves
5
+ *
6
+ * On the 0.2.2+ strict line this plugin is itself a `model/selection` writer:
7
+ * it fixes the next step's level through `agent.model.select()` (or by rewriting
8
+ * the step's captured selection). Those writes do NOT reach the session log —
9
+ * the host only appends `model/selection` for an explicit user pick
10
+ * (`api/session-controller/src/commands.ts:176` → `selectForNextRequest`).
11
+ *
12
+ * Measured live (session `7f321902`): ONE `model/selection` event against THIRTY
13
+ * `request/header` events alternating high/low. A projection folded over the log
14
+ * alone therefore cannot tell "the user chose low" from "the scheduler chose
15
+ * low", and the first honest answer was `unknown` — truthful, but useless: it
16
+ * cannot distinguish scheduler output from a genuinely unexplained change.
17
+ *
18
+ * ## The mechanism
19
+ *
20
+ * `@deepseek-ai/dsh-session` exposes `appendPluginRecord(session, type, data)`
21
+ * for exactly this: an `ignorable` event under a `plugin:`-namespaced type that
22
+ * never enters the model-visible surface, is retained across fork/resume, and is
23
+ * skipped (not refused) by readers that do not know it. We append one record per
24
+ * scheduler write, so the projection can attribute the following
25
+ * `request/header` to the scheduler.
26
+ *
27
+ * ## Coupling rules
28
+ *
29
+ * - **Soft**: the host package is resolved with a dynamic `import()` at call
30
+ * time and every failure degrades to "no mark" (the projection then keeps its
31
+ * `unknown` attribution). A plugin must never take a turn down because an
32
+ * optional telemetry channel is missing (`agent-loop/README.md:128`).
33
+ * - **Never throws**: the caller is mid-turn; a rejected append would abort the
34
+ * step. All paths are wrapped.
35
+ * - **Probed once**: the first attempt logs whether the API was reachable, so a
36
+ * silent degradation is diagnosable from the host log instead of by guessing.
37
+ * @module dsh-thinking-levels/plugin-records
38
+ */
39
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
40
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
41
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
42
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
43
+ });
44
+ }
45
+ return path;
46
+ };
47
+ /**
48
+ * The record type. `plugin:` + slash-separated lowercase segments, per the
49
+ * host grammar (`PluginRecordType` in `dsh-session/types`).
50
+ */
51
+ export const SCHEDULER_WRITE_RECORD = 'plugin:dsh-thinking-levels/scheduler-write';
52
+ /** Cached module namespace, so the dynamic import runs at most once per process. */
53
+ let recordsModule;
54
+ /** Whether the capability probe already ran (log once, not per request). */
55
+ let probed = false;
56
+ /** Whether the API is reachable; `undefined` until the first probe settles. */
57
+ let available;
58
+ /**
59
+ * Resolve the host session package and its `appendPluginRecord` export.
60
+ *
61
+ * The package is installation-scoped, so the host's runtime resolution answers
62
+ * it for any profile plugin (the plugin does not need it in its own
63
+ * `node_modules`, and does not declare it as a hard peer).
64
+ *
65
+ * The specifier is held in a variable on purpose: a literal
66
+ * `import('@deepseek-ai/dsh-session')` would make the package a hard
67
+ * compile-time dependency of this plugin, and it is deliberately optional —
68
+ * older hosts do not export the API at all, and the plugin must still install
69
+ * there. `tsc` therefore never type-checks the module's shape; the narrow
70
+ * structural interface below is the contract.
71
+ * @returns the append function, or undefined when unreachable.
72
+ */
73
+ async function loadAppendPluginRecord() {
74
+ if (recordsModule !== undefined)
75
+ return recordsModule.appendPluginRecord;
76
+ try {
77
+ const specifier = '@deepseek-ai/dsh-session';
78
+ const namespace = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ specifier));
79
+ recordsModule = namespace;
80
+ return typeof namespace.appendPluginRecord === 'function' ? namespace.appendPluginRecord : undefined;
81
+ }
82
+ catch {
83
+ // Unreachable on this host line: remember the miss so every later write
84
+ // short-circuits instead of retrying the import per step.
85
+ recordsModule = {};
86
+ return undefined;
87
+ }
88
+ }
89
+ /**
90
+ * Append one scheduler-write mark to the session log.
91
+ *
92
+ * Best-effort by construction: an absent API, a non-appendable session, a
93
+ * rejected payload or a throwing host all resolve to `false` — never a
94
+ * rejection — because the caller is in the middle of a turn.
95
+ * @param session - the live Session the write applies to (`agent.session`).
96
+ * @param record - what was written.
97
+ * @param logger - optional host logger, used once for the capability probe.
98
+ * @returns whether the mark was committed.
99
+ */
100
+ export async function markSchedulerWrite(session, record, logger) {
101
+ if (typeof session !== 'object' || session === null)
102
+ return false;
103
+ const append = await loadAppendPluginRecord();
104
+ if (!probed) {
105
+ probed = true;
106
+ available = append !== undefined;
107
+ // One line, at the first write: a silently unmarked trace is otherwise
108
+ // indistinguishable from a scheduler that never wrote anything. The log
109
+ // call is guarded — a hostile/throwing logger must not turn a best-effort
110
+ // mark into a rejected step.
111
+ const line = '[thinking-levels] plugin-record channel %s (scheduler-write marks)';
112
+ try {
113
+ if (append === undefined)
114
+ logger?.warn?.(line, 'unavailable — scheduler writes stay unmarked');
115
+ else
116
+ logger?.info?.(line, 'ready');
117
+ }
118
+ catch { /* diagnostics only */ }
119
+ }
120
+ if (append === undefined)
121
+ return false;
122
+ try {
123
+ append(session, SCHEDULER_WRITE_RECORD, {
124
+ ...record.level === undefined ? {} : { level: record.level },
125
+ ...record.clear === true ? { clear: true } : {},
126
+ ...record.intent === undefined ? {} : { intent: record.intent },
127
+ ...record.provider === undefined ? {} : { provider: record.provider },
128
+ ...record.model === undefined ? {} : { model: record.model },
129
+ ...record.applied === undefined ? {} : { applied: record.applied },
130
+ });
131
+ return true;
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ }
137
+ /**
138
+ * Read one committed event as a scheduler-write mark.
139
+ *
140
+ * Duck-typed on purpose: the projection folds raw events and must recognize the
141
+ * mark on any host line without importing host types.
142
+ * @param event - any committed session event.
143
+ * @returns the record payload, or undefined for any other event.
144
+ */
145
+ export function schedulerWriteOf(event) {
146
+ if (typeof event !== 'object' || event === null)
147
+ return undefined;
148
+ const candidate = event;
149
+ if (candidate.type !== SCHEDULER_WRITE_RECORD)
150
+ return undefined;
151
+ const data = candidate.data;
152
+ if (typeof data !== 'object' || data === null)
153
+ return undefined;
154
+ const record = data;
155
+ const level = record['level'];
156
+ const clear = record['clear'];
157
+ const intent = record['intent'];
158
+ const provider = record['provider'];
159
+ const model = record['model'];
160
+ const applied = record['applied'];
161
+ return {
162
+ ...typeof level === 'string' && level.length > 0 ? { level } : {},
163
+ ...clear === true ? { clear: true } : {},
164
+ ...typeof intent === 'string' ? { intent } : {},
165
+ ...typeof provider === 'string' ? { provider } : {},
166
+ ...typeof model === 'string' ? { model } : {},
167
+ ...applied === 'step' || applied === 'next' ? { applied } : {},
168
+ };
169
+ }
170
+ /** Whether the capability probe has run and what it found (diagnostics/tests). */
171
+ export function schedulerMarkChannel() {
172
+ if (available === undefined)
173
+ return 'unprobed';
174
+ return available ? 'ready' : 'unavailable';
175
+ }
176
+ /** Test seam: forget the cached module and probe state. */
177
+ export function resetSchedulerMarkChannel() {
178
+ recordsModule = undefined;
179
+ probed = false;
180
+ available = undefined;
181
+ }
@@ -66,6 +66,8 @@ export interface StrictStepInput {
66
66
  allowUpgrade: boolean;
67
67
  /** Extra tool names merged into the built-in cheap-and-deterministic set (issue #8 `Config.simpleTools`). */
68
68
  extraSimpleTools?: readonly string[];
69
+ /** Extra raw regex patterns for the same set (issue #12 `Config.simpleToolsRegex`). */
70
+ extraSimpleRegex?: readonly string[];
69
71
  /** Whether the target model advertises reasoning-effort support at all. */
70
72
  supportsReasoning: boolean;
71
73
  /** The model's advertised effort ids (including plugin masks like `auto`). */
@@ -81,6 +81,7 @@ export function planStrictStep(input) {
81
81
  allowDowngrade: input.allowDowngrade,
82
82
  allowUpgrade: input.allowUpgrade,
83
83
  extraSimpleTools: input.extraSimpleTools,
84
+ extraSimpleRegex: input.extraSimpleRegex,
84
85
  efforts: input.efforts,
85
86
  toggleOnly: input.toggleOnly,
86
87
  });
@@ -69,7 +69,40 @@ export interface EffortDecisionInput {
69
69
  * leaves the built-in classification untouched (issue #8 `Config.simpleTools`).
70
70
  */
71
71
  extraSimpleTools?: readonly string[];
72
+ /**
73
+ * Extra RAW REGEX patterns treated as cheap-and-deterministic, merged with
74
+ * the literal list and the built-in set (issue #12 `Config.simpleToolsRegex`).
75
+ * Each entry compiles as written (`i` flag, no auto-anchoring — the hint
76
+ * suggests `^`); invalid entries are skipped with a one-time warning. The
77
+ * matcher tests the full name and the bare name, so a family pattern like
78
+ * `ops_.*` hits the whole namespace.
79
+ */
80
+ extraSimpleRegex?: readonly string[];
81
+ }
82
+ /**
83
+ * The merged cheap-and-deterministic classifier over both extra lists
84
+ * (issue #12): literal entries (`Config.simpleTools`, anchored exactly as
85
+ * before) plus raw regex entries (`Config.simpleToolsRegex`, compiled as
86
+ * written — invalid ones skipped with a one-time warning, never thrown).
87
+ *
88
+ * `test` matches the FULL tool name AND the namespace-stripped bare name: a
89
+ * family pattern like `ops_.*` can only ever hit the full name (the bare name
90
+ * carries no `ops_` prefix), while a literal entry like `ops_bash` used to be
91
+ * dead on arrival against the bare name alone — the dual face repairs it as a
92
+ * side effect. The BUILT-IN table keeps its bare-name-only semantics (the
93
+ * issue #8 contract); only the extra lists gained the second face.
94
+ */
95
+ export interface SimpleToolMatcher {
96
+ test(name: string): boolean;
72
97
  }
98
+ /**
99
+ * Compile the two extra lists into one classifier, or `null` when both are
100
+ * empty (the built-in classification then stands alone). A compile is pure
101
+ * apart from the one-time `console.warn` for invalid regex entries — the
102
+ * cache keys on content, so the warning fires once per configuration, not
103
+ * once per request.
104
+ */
105
+ export declare function compileSimpleToolsMatcher(literal: readonly string[] | undefined, regex: readonly string[] | undefined): SimpleToolMatcher | null;
73
106
  /**
74
107
  * Map the user's selected level to the level injected into the next
75
108
  * `agent/request`. Manual levels (off / low / high / max) pass through
@@ -123,6 +156,11 @@ export interface EffortInjectionInput {
123
156
  * the `auto` scheduler (issue #8 `Config.simpleTools`).
124
157
  */
125
158
  extraSimpleTools?: readonly string[];
159
+ /**
160
+ * Extra raw regex patterns for the same set (issue #12
161
+ * `Config.simpleToolsRegex`), compiled as written, invalid ones skipped.
162
+ */
163
+ extraSimpleRegex?: readonly string[];
126
164
  /** The model's advertised effort ids (including plugin masks like `auto`). */
127
165
  efforts: readonly string[];
128
166
  /**
@@ -75,27 +75,68 @@ function escapeRe(source) {
75
75
  return source.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
76
76
  }
77
77
  /**
78
- * Compiled `extraSimpleTools` matchers, memoised by content. The config array
79
- * may be a fresh reference on every read (volatile `.get()`), so key on the
80
- * joined names rather than identity to avoid recompiling per request.
78
+ * Compiled matchers, memoised by content. The config arrays may be fresh
79
+ * references on every read (volatile `.get()`), so key on the joined contents
80
+ * rather than identity to avoid recompiling per request.
81
81
  */
82
- const EXTRA_SIMPLE_RE_CACHE = new Map();
83
- function compileExtraSimpleTools(tokens) {
84
- if (tokens === undefined || tokens.length === 0)
82
+ const SIMPLE_MATCHER_CACHE = new Map();
83
+ /**
84
+ * Compile the two extra lists into one classifier, or `null` when both are
85
+ * empty (the built-in classification then stands alone). A compile is pure
86
+ * apart from the one-time `console.warn` for invalid regex entries — the
87
+ * cache keys on content, so the warning fires once per configuration, not
88
+ * once per request.
89
+ */
90
+ export function compileSimpleToolsMatcher(literal, regex) {
91
+ const literalKey = (literal ?? []).join('\u0000');
92
+ const regexKey = (regex ?? []).join('\u0000');
93
+ if (literalKey === '' && regexKey === '')
85
94
  return null;
86
- const key = tokens.join('\u0000');
87
- const hit = EXTRA_SIMPLE_RE_CACHE.get(key);
95
+ const key = `${literalKey}\u0001${regexKey}`;
96
+ const hit = SIMPLE_MATCHER_CACHE.get(key);
88
97
  if (hit !== undefined)
89
98
  return hit;
90
- const cleaned = tokens.map(token => token.trim()).filter(token => token !== '');
91
- const re = cleaned.length === 0 ? null : new RegExp(`^(?:${cleaned.map(escapeRe).join('|')})(?:_|$)`, 'i');
92
- EXTRA_SIMPLE_RE_CACHE.set(key, re);
93
- return re;
99
+ const matcher = buildSimpleToolsMatcher(literal ?? [], regex ?? []);
100
+ SIMPLE_MATCHER_CACHE.set(key, matcher);
101
+ return matcher;
102
+ }
103
+ function buildSimpleToolsMatcher(literal, regex) {
104
+ const cleaned = literal.map(token => token.trim()).filter(token => token !== '');
105
+ const literalRe = cleaned.length === 0
106
+ ? null
107
+ : new RegExp(`^(?:${cleaned.map(escapeRe).join('|')})(?:_|$)`, 'i');
108
+ const rawRes = [];
109
+ const failed = [];
110
+ for (const pattern of regex) {
111
+ const trimmed = pattern.trim();
112
+ if (trimmed === '')
113
+ continue;
114
+ try {
115
+ rawRes.push(new RegExp(trimmed, 'i'));
116
+ }
117
+ catch {
118
+ failed.push(trimmed);
119
+ }
120
+ }
121
+ if (failed.length > 0) {
122
+ console.warn(`[dsh-thinking-levels] Config.simpleToolsRegex: skipped invalid pattern(s) (they must compile as JavaScript RegExp): ${failed.map(p => `/${p}/`).join(', ')}`);
123
+ }
124
+ if (literalRe === null && rawRes.length === 0)
125
+ return null;
126
+ return {
127
+ test(name) {
128
+ const bare = name.replace(TOOL_NAMESPACE_RE, '');
129
+ return (literalRe !== null && (literalRe.test(name) || literalRe.test(bare)))
130
+ || rawRes.some(re => re.test(name) || re.test(bare));
131
+ },
132
+ };
94
133
  }
95
- /** Whether a tool name (namespace prefix removed) looks cheap-and-deterministic. */
134
+ /** Whether a tool name looks cheap-and-deterministic: the built-in table reads
135
+ * the namespace-stripped bare name (issue #8 semantics, untouched); the extra
136
+ * matcher carries its own dual face (full name ∥ bare name, issue #12). */
96
137
  function isSimpleToolName(name, extra) {
97
138
  const bare = name.replace(TOOL_NAMESPACE_RE, '');
98
- return SIMPLE_TOOL_RE.test(bare) || (extra !== undefined && extra !== null && extra.test(bare));
139
+ return SIMPLE_TOOL_RE.test(bare) || (extra !== undefined && extra !== null && extra.test(name));
99
140
  }
100
141
  /** Count how many of the recent calls look cheap-and-deterministic. */
101
142
  function simpleRatio(calls, extra) {
@@ -155,10 +196,10 @@ function scheduleEffort(calls, allowDowngrade, allowUpgrade, extra) {
155
196
  * @returns The level to inject; `auto` is resolved before returning.
156
197
  */
157
198
  export function decideEffort(input) {
158
- const { recentCalls, selected, allowDowngrade, allowUpgrade, extraSimpleTools } = input;
199
+ const { recentCalls, selected, allowDowngrade, allowUpgrade, extraSimpleTools, extraSimpleRegex } = input;
159
200
  if (selected !== 'auto')
160
201
  return selected;
161
- return scheduleEffort(recentCalls, allowDowngrade, allowUpgrade, compileExtraSimpleTools(extraSimpleTools));
202
+ return scheduleEffort(recentCalls, allowDowngrade, allowUpgrade, compileSimpleToolsMatcher(extraSimpleTools, extraSimpleRegex));
162
203
  }
163
204
  /**
164
205
  * Whether a model's resolved metadata advertises reasoning-effort support.
@@ -252,6 +293,7 @@ export function resolveEffortInjection(input) {
252
293
  allowDowngrade: input.allowDowngrade,
253
294
  allowUpgrade: input.allowUpgrade,
254
295
  extraSimpleTools: input.extraSimpleTools,
296
+ extraSimpleRegex: input.extraSimpleRegex,
255
297
  });
256
298
  const clamped = clampToEfforts(level, efforts);
257
299
  return clamped === undefined ? { inject: false } : { inject: true, level: clamped };