dsh-thinking-levels 4.4.11 → 4.4.12

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.js CHANGED
@@ -3,6 +3,7 @@ import { assertEffortId, reasoningEffortSupported, resolveEffortInjection } from
3
3
  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
+ import { effortOfSelection, planStrictStep, } from "./strict-step-schedule.js";
6
7
  import { CONTEXT_WINDOW_MAX, CONTEXT_WINDOW_MIN } from "./context-window.js";
7
8
  import { PI_AI_NAMESPACE, TAKEOVER_NAMESPACE_CANDIDATES, takeoverPatch, takeoverRoutesOf, withOfficialCompatFixes, } from "./takeover-sync.js";
8
9
  import { describeSettings, readSection, readSectionOf, resolveNamespaceOf } from "./settings-read.js";
@@ -493,7 +494,148 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
493
494
  // Model capability snapshots, cached per provider/model and cleared whenever
494
495
  // the adapter registry changes (a route's reasoning metadata can move).
495
496
  const capability = capabilityResolver(ctx);
497
+ const strictAgents = new WeakSet();
498
+ const strictMemory = new WeakMap();
499
+ const onEvent = ctx.on;
500
+ /** Resolve the route's capability, then plan the step's level. */
501
+ const strictPlanFor = async (agent, provider, model, selectionEffort) => {
502
+ const capabilityFor = await capability.resolve(provider, model);
503
+ const state = readAutoSchedule(ctx, agent.session);
504
+ const cfg = current();
505
+ return planStrictStep({
506
+ selectionEffort,
507
+ memory: strictMemory.get(agent),
508
+ cfgLevel: cfg.level,
509
+ samples: state?.samples ?? [],
510
+ allowDowngrade: cfg.allowDowngrade,
511
+ allowUpgrade: cfg.allowUpgrade,
512
+ supportsReasoning: capabilityFor.supportsReasoning,
513
+ efforts: capabilityFor.efforts,
514
+ toggleOnly: capabilityFor.toggleOnly,
515
+ });
516
+ };
517
+ /** Write the NEXT step's level through the documented API (one-step lag). */
518
+ const strictSelectNext = (agent, provider, model, write) => {
519
+ const select = agent.model?.select;
520
+ if (typeof select !== 'function')
521
+ return false;
522
+ select.call(agent.model, write.clear ? { provider, model } : { provider, model, reasoningEffort: write.level });
523
+ return true;
524
+ };
525
+ /**
526
+ * Apply the plan to the step the host ALREADY fixed.
527
+ *
528
+ * `payload.modelSelection` is the very object the loop captured and will hand
529
+ * to `prepareRequest` (`core/agent-loop/src/agent.ts`: the payload field and
530
+ * `decision.selection` are one reference), so writing its `reasoningEffort`
531
+ * takes effect on THIS step. That matters for more than latency: on the
532
+ * strict line a plugin mask (`auto`, `on`) is not a wire level, and nothing
533
+ * may rewrite it at request time any more — it has to be resolved before the
534
+ * adapter binds or the request fails downstream.
535
+ *
536
+ * `agent.model.select()` stays the FALLBACK and the durable record. If a host
537
+ * copies the selection instead of passing it through (or freezes it), the
538
+ * write cannot land on this step and the documented API takes over one step
539
+ * later — the accepted lag.
540
+ *
541
+ * @returns how the plan was applied, for the runtime log.
542
+ */
543
+ const strictApplyStep = (agent, provider, model, selection, plan) => {
544
+ strictMemory.set(agent, plan.memory);
545
+ const write = plan.select;
546
+ if (write === undefined)
547
+ return 'none';
548
+ try {
549
+ if (write.clear)
550
+ delete selection.reasoningEffort;
551
+ else
552
+ selection.reasoningEffort = write.level;
553
+ if (effortOfSelection(selection.reasoningEffort) === (write.clear ? null : write.level))
554
+ return 'step';
555
+ }
556
+ catch {
557
+ // Frozen or otherwise non-writable selection: fall back below.
558
+ }
559
+ return strictSelectNext(agent, provider, model, write) ? 'next' : 'none';
560
+ };
561
+ /**
562
+ * Schedule the step the host just fixed.
563
+ */
564
+ onEvent('agent/pre-step', async (payload, next) => {
565
+ const decision = await next?.();
566
+ const agent = payload.agent;
567
+ const selection = payload.modelSelection;
568
+ if (agent === undefined || selection === undefined)
569
+ return decision;
570
+ if (typeof agent.model?.select !== 'function')
571
+ return decision;
572
+ const provider = selection.provider;
573
+ const model = selection.model;
574
+ if (typeof provider !== 'string' || typeof model !== 'string')
575
+ return decision;
576
+ // Marked even when disabled: the request hook must keep hands off on this
577
+ // line regardless, or a stale injection throws the turn.
578
+ strictAgents.add(agent);
579
+ if (!current().enabled)
580
+ return decision;
581
+ try {
582
+ const fixed = effortOfSelection(selection.reasoningEffort);
583
+ const plan = await strictPlanFor(agent, provider, model, selection.reasoningEffort);
584
+ const applied = strictApplyStep(agent, provider, model, selection, plan);
585
+ const write = plan.select;
586
+ 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));
587
+ }
588
+ catch (error) {
589
+ ctx.logger?.warn?.('[thinking-levels] agent/pre-step schedule skipped: %s', String(error));
590
+ }
591
+ return decision;
592
+ });
593
+ /**
594
+ * Step 1: the host fixed the selection before any step could observe it, and
595
+ * `agent/created` is a SERIAL dispatch (`dsh-agent`: `ctx.serial(...,
596
+ * 'agent/created', ...)`) awaited before the Agent becomes live, so a write
597
+ * here is in place before the first request — deterministically, not by
598
+ * racing.
599
+ *
600
+ * Only a route with NO effort at all is touched: a resumed or forked session
601
+ * keeps its recorded choice, which is also what seeds the baseline so it
602
+ * never reads back as a user change. One `model/selection` write is retired
603
+ * by the first `request/header`, so the recorded pick does not linger.
604
+ */
605
+ onEvent('agent/created', async (payload) => {
606
+ const agent = payload.agent;
607
+ if (agent === undefined || typeof agent.model?.select !== 'function')
608
+ return;
609
+ try {
610
+ if (!current().enabled)
611
+ return;
612
+ const opening = agent.model?.current?.();
613
+ if (opening === undefined)
614
+ return;
615
+ if (effortOfSelection(opening.reasoningEffort) !== null)
616
+ return;
617
+ const provider = opening.provider;
618
+ const model = opening.model;
619
+ if (typeof provider !== 'string' || typeof model !== 'string')
620
+ return;
621
+ strictAgents.add(agent);
622
+ const plan = await strictPlanFor(agent, provider, model, opening.reasoningEffort);
623
+ strictMemory.set(agent, plan.memory);
624
+ const write = plan.select;
625
+ const applied = write !== undefined && strictSelectNext(agent, provider, model, write);
626
+ ctx.logger?.info?.('[thinking-levels] agent/created: model=%s/%s opening step at %s', provider, model, applied && write !== undefined ? String(write.level) : 'adapter default');
627
+ }
628
+ catch (error) {
629
+ ctx.logger?.warn?.('[thinking-levels] agent/created schedule skipped: %s', String(error));
630
+ }
631
+ });
496
632
  on('agent/request', async (payload, next) => {
633
+ // Strict line: the selection was fixed before this waterfall and the host
634
+ // rejects any change here; `agent/pre-step` already recorded the next
635
+ // step's level through `agent.model.select()`. Pass the seed through.
636
+ const gatedAgent = payload.agent;
637
+ if (gatedAgent !== undefined && strictAgents.has(gatedAgent))
638
+ return next();
497
639
  const seed = await next();
498
640
  const cfg = current();
499
641
  // `enabled` may flip at runtime through the settings namespace.
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Strict-line step scheduler (dsh 0.2.2+).
3
+ *
4
+ * From `dsh-v0.2.2-alpha.2` the host fixes the step's provider / model /
5
+ * `reasoningEffort` during step preparation and REJECTS any `agent/request`
6
+ * listener that changes one of the three:
7
+ *
8
+ * ```
9
+ * agent "${id}": agent/request proposed reasoning effort "low" after step
10
+ * preparation fixed "adapter default"; use agent.model.select() before step
11
+ * preparation
12
+ * ```
13
+ *
14
+ * (`packages/core/agent-loop/src/agent.ts`, `prepareRequest`.) The official
15
+ * migration guide (`docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection`)
16
+ * names the replacement: `agent.model.select(selection)` before the prompt is
17
+ * assembled. So on that line the plugin stops rewriting the request and
18
+ * schedules one step AHEAD instead:
19
+ *
20
+ * - `agent/pre-step` observes the selection the host just fixed for THIS step,
21
+ * computes the level the NEXT step should be fixed at, and records it with
22
+ * `agent.model.select()`. The already-captured selection is untouched (the
23
+ * loop reads `model.current()` before the waterfall), so the change applies
24
+ * to the next step — the accepted lag.
25
+ * - `agent/request` returns the seed unchanged. Any change there is a throw.
26
+ *
27
+ * ## Why a baseline instead of the session pick
28
+ *
29
+ * The plugin is now itself a writer of `model/selection`, so the folded
30
+ * `userEffort` of `tlAutoSchedule` can no longer distinguish "the user picked
31
+ * `auto`" from "the scheduler wrote `low` last step". The strict line therefore
32
+ * diffs the observed selection against the value it last observed/wrote
33
+ * (`baseline`): a change that the plugin did not make is a user change and
34
+ * becomes the new intent; otherwise the carried intent stands.
35
+ *
36
+ * `baseline` lives in a WeakMap per live Agent. That is correct across
37
+ * resume/fork without extra persistence: a resumed Agent's first observation IS
38
+ * the last value this plugin (or the user) left in the log, so it seeds the
39
+ * baseline rather than registering as a change.
40
+ * @module dsh-thinking-levels/strict-step-schedule
41
+ */
42
+ import { type EffortId, type ToolCallSample } from './thinking-level.ts';
43
+ /** Per-Agent memory carried between steps of the strict line. */
44
+ export interface StrictStepMemory {
45
+ /** The effort the host fixed for the previous step (null = the step had none). */
46
+ baseline: string | null;
47
+ /** The user intent carried to the next step when nothing changed externally. */
48
+ intent: EffortId;
49
+ }
50
+ /** One strict-line step observation. */
51
+ export interface StrictStepInput {
52
+ /** `payload.modelSelection.reasoningEffort` — the value the host fixed for this step. */
53
+ selectionEffort: unknown;
54
+ /**
55
+ * What the plugin last observed or wrote for this Agent, or undefined on the
56
+ * first strict-line step of the Agent (a fresh, resumed, or forked session).
57
+ */
58
+ memory: StrictStepMemory | undefined;
59
+ /** The configured level, used as the intent whenever the session carries none. */
60
+ cfgLevel: EffortId;
61
+ /** Recent tool-call samples folded by `tlAutoSchedule`. */
62
+ samples: readonly ToolCallSample[];
63
+ /** Scheduler preference: may drop to `low` once tool evidence exists. */
64
+ allowDowngrade: boolean;
65
+ /** Scheduler preference: may lift above the hub to `max`. */
66
+ allowUpgrade: boolean;
67
+ /** Whether the target model advertises reasoning-effort support at all. */
68
+ supportsReasoning: boolean;
69
+ /** The model's advertised effort ids (including plugin masks like `auto`). */
70
+ efforts: readonly string[];
71
+ /** The model takes only an on/off thinking toggle (Qwen3.6-style). */
72
+ toggleOnly: boolean;
73
+ }
74
+ /** The change to record on the Session for the NEXT step. */
75
+ export interface StrictSelectionWrite {
76
+ /** The level to fix; absent when the effort must be cleared. */
77
+ level?: EffortId;
78
+ /** Clear the effort entirely (a model that takes none). */
79
+ clear: boolean;
80
+ }
81
+ /** One step's plan: what to remember and what (if anything) to write. */
82
+ export interface StrictStepPlan {
83
+ /** Memory for the next step. */
84
+ memory: StrictStepMemory;
85
+ /** The selection change for the next step, or undefined to leave it alone. */
86
+ select: StrictSelectionWrite | undefined;
87
+ /** The intent this step resolved, for the runtime log. */
88
+ intent: EffortId;
89
+ }
90
+ /** Read the effort a host selection carries; absent / non-string reads as null. */
91
+ export declare function effortOfSelection(value: unknown): string | null;
92
+ /**
93
+ * Plan one strict-line step.
94
+ *
95
+ * Pure: the caller owns the WeakMap, the capability lookup and the append. The
96
+ * returned `select` is a request for `agent.model.select()`, which takes effect
97
+ * on the NEXT step's preparation (the current step's selection was captured
98
+ * before `agent/pre-step` ran).
99
+ *
100
+ * @param input - the observed step selection plus the scheduler inputs.
101
+ * @returns the memory to keep and the selection change to record.
102
+ */
103
+ export declare function planStrictStep(input: StrictStepInput): StrictStepPlan;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Strict-line step scheduler (dsh 0.2.2+).
3
+ *
4
+ * From `dsh-v0.2.2-alpha.2` the host fixes the step's provider / model /
5
+ * `reasoningEffort` during step preparation and REJECTS any `agent/request`
6
+ * listener that changes one of the three:
7
+ *
8
+ * ```
9
+ * agent "${id}": agent/request proposed reasoning effort "low" after step
10
+ * preparation fixed "adapter default"; use agent.model.select() before step
11
+ * preparation
12
+ * ```
13
+ *
14
+ * (`packages/core/agent-loop/src/agent.ts`, `prepareRequest`.) The official
15
+ * migration guide (`docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection`)
16
+ * names the replacement: `agent.model.select(selection)` before the prompt is
17
+ * assembled. So on that line the plugin stops rewriting the request and
18
+ * schedules one step AHEAD instead:
19
+ *
20
+ * - `agent/pre-step` observes the selection the host just fixed for THIS step,
21
+ * computes the level the NEXT step should be fixed at, and records it with
22
+ * `agent.model.select()`. The already-captured selection is untouched (the
23
+ * loop reads `model.current()` before the waterfall), so the change applies
24
+ * to the next step — the accepted lag.
25
+ * - `agent/request` returns the seed unchanged. Any change there is a throw.
26
+ *
27
+ * ## Why a baseline instead of the session pick
28
+ *
29
+ * The plugin is now itself a writer of `model/selection`, so the folded
30
+ * `userEffort` of `tlAutoSchedule` can no longer distinguish "the user picked
31
+ * `auto`" from "the scheduler wrote `low` last step". The strict line therefore
32
+ * diffs the observed selection against the value it last observed/wrote
33
+ * (`baseline`): a change that the plugin did not make is a user change and
34
+ * becomes the new intent; otherwise the carried intent stands.
35
+ *
36
+ * `baseline` lives in a WeakMap per live Agent. That is correct across
37
+ * resume/fork without extra persistence: a resumed Agent's first observation IS
38
+ * the last value this plugin (or the user) left in the log, so it seeds the
39
+ * baseline rather than registering as a change.
40
+ * @module dsh-thinking-levels/strict-step-schedule
41
+ */
42
+ import { isEffortId, resolveEffortInjection } from "./thinking-level.js";
43
+ /** Read the effort a host selection carries; absent / non-string reads as null. */
44
+ export function effortOfSelection(value) {
45
+ return typeof value === 'string' && value.length > 0 ? value : null;
46
+ }
47
+ /**
48
+ * Plan one strict-line step.
49
+ *
50
+ * Pure: the caller owns the WeakMap, the capability lookup and the append. The
51
+ * returned `select` is a request for `agent.model.select()`, which takes effect
52
+ * on the NEXT step's preparation (the current step's selection was captured
53
+ * before `agent/pre-step` ran).
54
+ *
55
+ * @param input - the observed step selection plus the scheduler inputs.
56
+ * @returns the memory to keep and the selection change to record.
57
+ */
58
+ export function planStrictStep(input) {
59
+ const observed = effortOfSelection(input.selectionEffort);
60
+ const memory = input.memory;
61
+ let intent;
62
+ if (memory === undefined) {
63
+ // First observation of this Agent. The value may be an adapter default, a
64
+ // resumed `lastUsed`, or a user pick made before the plugin attached —
65
+ // indistinguishable, so it seeds the baseline and the configured level
66
+ // supplies the intent.
67
+ intent = input.cfgLevel;
68
+ }
69
+ else if (observed !== memory.baseline) {
70
+ // The selection moved without this plugin writing it: a user change.
71
+ intent = isEffortId(observed) ? observed : input.cfgLevel;
72
+ }
73
+ else {
74
+ intent = memory.intent;
75
+ }
76
+ const decision = resolveEffortInjection({
77
+ supportsReasoning: input.supportsReasoning,
78
+ requested: intent,
79
+ seedEffort: input.selectionEffort,
80
+ recentCalls: input.samples,
81
+ allowDowngrade: input.allowDowngrade,
82
+ allowUpgrade: input.allowUpgrade,
83
+ efforts: input.efforts,
84
+ toggleOnly: input.toggleOnly,
85
+ });
86
+ let select;
87
+ let baseline = observed;
88
+ if (!decision.inject) {
89
+ // The model takes no effort: clear whatever the step inherited. `clear` is
90
+ // only needed when the host currently fixes one.
91
+ if (observed !== null) {
92
+ select = { clear: true };
93
+ baseline = null;
94
+ }
95
+ }
96
+ else if (decision.level !== observed && decision.level !== undefined) {
97
+ select = { level: decision.level, clear: false };
98
+ baseline = decision.level;
99
+ }
100
+ return { memory: { baseline, intent }, select, intent };
101
+ }
@@ -65,23 +65,34 @@ function simpleRatio(calls) {
65
65
  * model request of that step should use.
66
66
  *
67
67
  * Hub is `high` (the official default). Rules:
68
- * - No tool calls yet (fresh prompt, pure chat) -> `low` (simple chat tasks).
69
- * - All/mostly simple tools -> `low` (when downgrades are allowed).
68
+ * - No tool calls yet (the session's FIRST request) -> `high`, ALWAYS.
69
+ * - All/mostly simple tools -> `low` (when downgrades are allowed) — `low` is
70
+ * the floor the scheduler may ever reach.
70
71
  * - Mixed or heavy tools -> `high` (the hub).
71
72
  * - Very heavy context (huge args) -> `max` (when upgrades are allowed).
72
73
  *
74
+ * Why the first request sits on the hub instead of the old `low`: the first
75
+ * step has no tool history to justify a downgrade, and it is the step that
76
+ * decides the plan — tool choice, payload shape, decomposition. An
77
+ * under-thought first step produces a plan the rest of the turn inherits, and
78
+ * the measured saving of one cheap step does not pay for a re-plan. Downgrades
79
+ * therefore require evidence: `low` needs at least one observed simple tool
80
+ * call, so `allowDowngrade` no longer moves the no-sample branch.
81
+ *
73
82
  * The scheduler MAY pick `low`: the request-level capability guard strips any
74
83
  * effort from models that do not support it, so a scheduled `low` only ever
75
84
  * reaches models that advertise the level.
76
85
  *
77
86
  * @param calls - recent tool calls of the step.
78
- * @param allowDowngrade - may drop below `high`.
87
+ * @param allowDowngrade - may drop below `high` once tool evidence exists.
79
88
  * @param allowUpgrade - may lift above `high`.
80
89
  * @returns a wire level; never `off` (off is manual-only) and never `auto`.
81
90
  */
82
91
  function scheduleEffort(calls, allowDowngrade, allowUpgrade) {
92
+ // The no-sample branch is the first request of the session: start at the hub
93
+ // regardless of `allowDowngrade` (see the rationale above).
83
94
  if (calls.length === 0)
84
- return allowDowngrade ? 'low' : 'high';
95
+ return 'high';
85
96
  const ratio = simpleRatio(calls);
86
97
  const heaviest = calls.reduce((max, call) => Math.max(max, call.argsSize), 0);
87
98
  if (ratio >= 0.75 && allowDowngrade)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-thinking-levels",
3
- "version": "4.4.11",
3
+ "version": "4.4.12",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org",
6
6
  "access": "public",