dsh-thinking-levels 4.4.5 → 4.4.7
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/CHANGELOG.de.md +11 -0
- package/CHANGELOG.es.md +11 -0
- package/CHANGELOG.fr.md +11 -0
- package/CHANGELOG.it.md +11 -0
- package/CHANGELOG.ja.md +11 -0
- package/CHANGELOG.ko.md +11 -0
- package/CHANGELOG.md +11 -0
- package/CHANGELOG.ru.md +11 -0
- package/README.de.md +2 -0
- package/README.es.md +2 -0
- package/README.fr.md +2 -0
- package/README.it.md +2 -0
- package/README.ja.md +2 -0
- package/README.ko.md +2 -0
- package/README.md +2 -0
- package/README.ru.md +2 -0
- package/README.zh.md +2 -0
- package/dsh.plugin.json +16 -16
- package/lib/auto-schedule-projection.d.ts +108 -0
- package/lib/auto-schedule-projection.js +141 -0
- package/lib/billing-projection.d.ts +9 -9
- package/lib/client.js +20 -2
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +12 -10
- package/lib/index.js +26 -4
- package/lib/session-events.d.ts +25 -8
- package/lib/session-events.js +33 -15
- package/lib/thinking-level.d.ts +27 -10
- package/lib/thinking-level.js +22 -19
- package/package.json +6 -6
package/CHANGELOG.de.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
Alle nennenswerten Änderungen an `dsh-thinking-levels` werden hier dokumentiert.
|
|
4
4
|
|
|
5
|
+
## [4.4.7] — 2026-10-27 (auto-Stufe wirkt wirklich — Sampling über eine Projektion + Host-Echo unterbrochen — Issue #6)
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- `auto` fällt nicht mehr dauerhaft auf `low`. Das Werkzeug-Sampling las `agent.session.events`, doch dieses Array-Attribut existiert nur auf Host 0.1.0-rc.8 (ab 0.1.2-rc.1 entfernt); auf 13 der 14 unterstützten Linien blieb die Stichprobe daher `[]` und `high` / `max` waren strukturell unerreichbar. Jetzt registriert das Plugin die Projektion `tlAutoSchedule`: `apply` faltet `tool/call` in einen Ring der Kapazität 8, der Host liest per `stateOf()` in O(1); der erste Lesezugriff faltet das gesamte In-Memory-Log, sodass fortgesetzte und geforkte Sitzungen vollständig sind. Der Host verbietet neue Produktionsaufrufe von `eventAt` / `snapshotEvents` / `ownEvents`, daher keine Rückkehr zu den alten Lesern.
|
|
9
|
+
- `auto` wirkt nicht mehr nur beim ersten Request einer Sitzung. Der Host setzt in jeder Runde das `reasoningEffort` des vorherigen `request/header` (also die eigene Injektion des Plugins) als Seed; die alte Implementierung hielt das für eine manuelle Wahl und reichte es durch, wodurch die Stufe dauerhaft auf der ersten Entscheidung einfror. Jetzt faltet dieselbe Projektion `model/selection`-Ereignisse zur expliziten Sitzungswahl (einziger Produktionsschreiber ist der Auswahlbefehl des Nutzers; Plugin-Injektionen schreiben nie). Der Seed entscheidet nicht mehr über manuell/auto — das Echo verschwindet strukturell, ohne sich die letzte Injektion merken zu müssen, und bleibt nach resume / fork / Kompaktierung korrekt.
|
|
10
|
+
- Stufenpriorität: explizite Sitzungswahl > Plugin-Konfiguration `level` > Scheduler.
|
|
11
|
+
- Bekannte Einschränkung 0.1.0-rc.8: Die Registrierungsoberfläche dieser Linie hat kein `stateOf` (alter Plane-Vertrag), daher wird die Projektion übersprungen und der alte `session.events`-Pfad bleibt — Sampling funktioniert, die Echo-Korrektur greift dort nicht.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
- 215/215: neue Fälle für Projektions-Reducer, Fähigkeits-Gate und Schema-Toleranz; `session-events.spec.ts` wurde zur **Köder-Fixture** (dasselbe Objekt liefert zugleich ein veraltetes `events`-Array und den Projektionszustand; die Assertion verlangt die Projektion), dazu ein Echo-Simulationslauf über vier Requests (erst `low` → schwere Last `max` → explizite Wahl überstimmt den Scheduler).
|
|
15
|
+
|
|
5
16
|
## [4.4.4] — 2026-10-21 (Compat-Felder aus der Oberfläche, Level-Editor überall geöffnet — Issues #7 #8)
|
|
6
17
|
|
|
7
18
|
- Die beiden openai-completions-exklusiven Schalter (`支持 think effort` / `思考格式`) werden auf anderen Protokollen nicht mehr ANGEZEIGT — zuvor waren sie ausgegraut mit einer langen Notiz. Sie erscheinen nur noch, wenn das Modell **als Thinking-Modell deklariert** ist UND die Route `openai-completions` spricht; überall sonst fehlen sie im DOM. Thinking selbst bleibt überall aktiv (protokollneutral `reasoningEfforts`).
|
package/CHANGELOG.es.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
Todos los cambios notables de `dsh-thinking-levels` se documentan aquí.
|
|
4
4
|
|
|
5
|
+
## [4.4.7] — 2026-10-27 (el nivel auto funciona de verdad — muestreo vía proyección + corte del eco del host — issue #6)
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- `auto` ya no cae siempre en `low`. El muestreo de herramientas leía `agent.session.events`, propiedad de tipo array que solo existe en el host 0.1.0-rc.8 (eliminada desde 0.1.2-rc.1); en 13 de las 14 líneas soportadas la muestra quedaba siempre en `[]`, dejando `high` / `max` estructuralmente inalcanzables. Ahora el plugin registra la proyección `tlAutoSchedule`: `apply` pliega los `tool/call` en un anillo de capacidad 8 y el host lee con `stateOf()` en O(1); la primera lectura pliega todo el registro en memoria, así que las sesiones reanudadas y forkeadas quedan completas. El host prohíbe nuevas llamadas de producción a `eventAt` / `snapshotEvents` / `ownEvents`, por lo que no se vuelve a los lectores antiguos.
|
|
9
|
+
- `auto` ya no actúa solo en la primera petición de una sesión. En cada turno el host reutiliza el `reasoningEffort` del `request/header` anterior (es decir, la inyección del propio plugin) como semilla; la implementación antigua lo tomaba por una elección manual y lo dejaba pasar, congelando el nivel en la primera decisión. Ahora la misma proyección pliega los eventos `model/selection` para obtener la elección explícita de la sesión (único escritor en producción: el comando de selección del usuario; la inyección del plugin nunca escribe). La semilla ya no decide entre manual y auto — el eco desaparece por construcción, sin recordar la última inyección, y sigue siendo correcto tras resume / fork / compactación.
|
|
10
|
+
- Prioridad de niveles: elección explícita de la sesión > configuración `level` del plugin > planificador.
|
|
11
|
+
- Límite conocido 0.1.0-rc.8: la superficie de registro de esa línea no tiene `stateOf` (contrato plano antiguo), así que se omite el registro y se mantiene la ruta antigua `session.events` — el muestreo funciona, la corrección del eco no.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
- 215/215: nuevos casos para el reducer de la proyección, el control de capacidad y la tolerancia del esquema; `session-events.spec.ts` pasa a ser una **fixture señuelo** (el mismo objeto ofrece a la vez un array `events` obsoleto y el estado de la proyección, y la aserción exige la proyección), más una simulación del eco en cuatro peticiones (primero `low` → carga pesada `max` → la elección explícita prevalece sobre el planificador).
|
|
15
|
+
|
|
5
16
|
## [4.4.4] — 2026-10-21 (campos de compat fuera de la superficie, editor de niveles abierto en todas partes — issues #7 #8)
|
|
6
17
|
|
|
7
18
|
- Los dos interruptores exclusivos de openai-completions (`支持 think effort` / `思考格式`) ya no se MUESTRAN en otros protocolos — antes aparecían desactivados con una nota larga. Ahora solo aparecen si el modelo está **declarado de thinking** Y la ruta habla `openai-completions`; en el resto no están en el DOM. El thinking en sí sigue activo en todas partes (`reasoningEfforts`, neutral al protocolo).
|
package/CHANGELOG.fr.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
Tous les changements notables de `dsh-thinking-levels` sont documentés ici.
|
|
4
4
|
|
|
5
|
+
## [4.4.7] — 2026-10-27 (le niveau auto fonctionne vraiment — échantillonnage via une projection + coupure de l'écho de l'hôte — issue #6)
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- `auto` ne retombe plus systématiquement sur `low`. L'échantillonnage des outils lisait `agent.session.events`, propriété tableau qui n'existe que sur l'hôte 0.1.0-rc.8 (retirée depuis 0.1.2-rc.1) ; sur 13 des 14 lignes prises en charge l'échantillon restait `[]`, rendant `high` / `max` structurellement inatteignables. Le plugin enregistre désormais la projection `tlAutoSchedule` : `apply` replie les `tool/call` dans un anneau de capacité 8, l'hôte lit via `stateOf()` en O(1) ; la première lecture replie tout le journal en mémoire, donc les sessions reprises et forkées sont complètes. L'hôte interdit tout nouvel appel de production à `eventAt` / `snapshotEvents` / `ownEvents`, d'où le refus de revenir aux anciens lecteurs.
|
|
9
|
+
- `auto` ne s'applique plus uniquement à la première requête d'une session. À chaque tour, l'hôte reprend le `reasoningEffort` du `request/header` précédent (donc l'injection du plugin) comme graine ; l'ancienne implémentation y voyait un choix manuel et le laissait passer, figeant le niveau sur la première décision. Désormais la même projection replie les événements `model/selection` pour obtenir le choix explicite de la session (unique écrivain en production : la commande de sélection de l'utilisateur ; l'injection du plugin n'écrit jamais). La graine ne décide plus du mode manuel/auto — l'écho disparaît structurellement, sans mémoriser la dernière injection, et reste correct après resume / fork / compaction.
|
|
10
|
+
- Priorité des niveaux : choix explicite de la session > configuration `level` du plugin > ordonnanceur.
|
|
11
|
+
- Limite connue 0.1.0-rc.8 : la surface d'enregistrement de cette ligne n'a pas `stateOf` (ancien contrat plan), l'enregistrement est donc ignoré et l'ancien chemin `session.events` subsiste — l'échantillonnage fonctionne, la correction de l'écho non.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
- 215/215 : nouveaux cas pour le reducer de projection, le verrou de capacité et la tolérance du schéma ; `session-events.spec.ts` devient une **fixture leurre** (le même objet fournit à la fois un tableau `events` périmé et l'état de projection, l'assertion exige la projection), plus une simulation d'écho sur quatre requêtes (d'abord `low` → charge lourde `max` → choix explicite qui prime sur l'ordonnanceur).
|
|
15
|
+
|
|
5
16
|
## [4.4.4] — 2026-10-21 (champs de compat retirés de la surface, éditeur de niveaux ouvert partout — issues #7 #8)
|
|
6
17
|
|
|
7
18
|
- Les deux interrupteurs propres à openai-completions (`支持 think effort` / `思考格式`) ne sont plus AFFICHÉS sur les autres protocoles — ils étaient grisés avec une longue note. Ils n'apparaissent plus que si le modèle est **déclaré réflexif** ET que la route parle `openai-completions` ; ailleurs ils sont absents du DOM. La réflexion elle-même reste active partout (`reasoningEfforts`, neutre au protocole).
|
package/CHANGELOG.it.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
Tutte le modifiche notevoli a `dsh-thinking-levels` sono documentate qui.
|
|
4
4
|
|
|
5
|
+
## [4.4.7] — 2026-10-27 (il livello auto funziona davvero — campionamento via projection + taglio dell'eco dell'host — issue #6)
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- `auto` non ricade più sempre su `low`. Il campionamento degli strumenti leggeva `agent.session.events`, proprietà array che esiste solo sull'host 0.1.0-rc.8 (rimossa da 0.1.2-rc.1); su 13 delle 14 linee supportate il campione restava `[]`, rendendo `high` / `max` strutturalmente irraggiungibili. Ora il plugin registra la projection `tlAutoSchedule`: `apply` ripiega i `tool/call` in un anello di capacità 8, l'host legge via `stateOf()` in O(1); la prima lettura ripiega l'intero log in memoria, quindi le sessioni riprese e forkate sono complete. L'host vieta nuove chiamate di produzione a `eventAt` / `snapshotEvents` / `ownEvents`, quindi nessun ritorno ai vecchi lettori.
|
|
9
|
+
- `auto` non vale più solo per la prima richiesta di una sessione. A ogni turno l'host riusa il `reasoningEffort` del `request/header` precedente (cioè l'iniezione del plugin) come seme; la vecchia implementazione lo leggeva come scelta manuale e lo lasciava passare, congelando il livello sulla prima decisione. Ora la stessa projection ripiega gli eventi `model/selection` per ottenere la scelta esplicita della sessione (unico scrittore in produzione: il comando di selezione dell'utente; l'iniezione del plugin non scrive mai). Il seme non decide più fra manuale e auto — l'eco scompare per costruzione, senza dover ricordare l'ultima iniezione, e resta corretto dopo resume / fork / compattazione.
|
|
10
|
+
- Priorità dei livelli: scelta esplicita della sessione > configurazione `level` del plugin > scheduler.
|
|
11
|
+
- Limite noto 0.1.0-rc.8: la superficie di registrazione di quella linea non ha `stateOf` (vecchio contratto plan), quindi la registrazione viene saltata e resta il vecchio percorso `session.events` — il campionamento funziona, la correzione dell'eco no.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
- 215/215: nuovi casi per reducer della projection, gate di capacità e tolleranza dello schema; `session-events.spec.ts` diventa una **fixture esca** (lo stesso oggetto espone sia un array `events` obsoleto sia lo stato della projection, e l'assert richiede la projection), più una simulazione dell'eco su quattro richieste (prima `low` → carico pesante `max` → scelta esplicita che prevale sullo scheduler).
|
|
15
|
+
|
|
5
16
|
## [4.4.4] — 2026-10-21 (campi di compat tolti dalla superficie, editor dei livelli aperto ovunque — issue #7 #8)
|
|
6
17
|
|
|
7
18
|
- I due interruttori esclusivi di openai-completions (`支持 think effort` / `思考格式`) non vengono più MOSTRATI sugli altri protocolli — prima erano disabilitati con una nota lunga. Ora compaiono solo se il modello è **dichiarato thinking** E la rotta parla `openai-completions`; altrove sono assenti dal DOM. Il thinking stesso resta attivo ovunque (`reasoningEfforts`, neutro rispetto al protocollo).
|
package/CHANGELOG.ja.md
CHANGED
|
@@ -11,6 +11,17 @@
|
|
|
11
11
|
- [Список изменений на русском](./CHANGELOG.ru.md)
|
|
12
12
|
- [Changelog en español](./CHANGELOG.es.md)
|
|
13
13
|
|
|
14
|
+
## [4.4.7] — 2026-10-27(auto レベルが実際に機能 — サンプリングを projection に変更 + ホストのエコーを遮断 — issue #6)
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
- `auto` が常に `low` に落ちることがなくなりました。ツールサンプリングは `agent.session.events` を読んでいましたが、この配列プロパティはホスト 0.1.0-rc.8 にのみ存在し(0.1.2-rc.1 で削除)、対応する 14 ライン中 13 ラインでサンプルが常に `[]` となり `high` / `max` が構造的に到達不能でした。`tlAutoSchedule` projection を登録し、`apply` が `tool/call` を容量 8 のリングに畳み込み、ホストは `stateOf()` で O(1) 読み出します。初回読み出しでメモリ上のログ全体を fold するため、再開・分岐セッションでも完全です。ホストは `eventAt` / `snapshotEvents` / `ownEvents` の新規プロダクション呼び出しを禁じているため、旧読み出しには戻しません。
|
|
18
|
+
- `auto` がセッション最初のリクエストだけで効く問題を修正しました。ホストは毎回、直前の `request/header` の `reasoningEffort`(= このプラグイン自身の注入値)を次リクエストのシードにします。旧実装はそれを「手動選択」とみなして素通ししたため、レベルが初回の決定に固定されていました。同じ projection が `model/selection` イベントを畳み込んでセッションの明示選択を取得します(このイベントの唯一のプロダクション書き込み元はユーザーの選択コマンドであり、プラグインの注入は書き込みません)。シードは手動/自動の判定に一切関与しません — エコーが構造的に消え、前回の注入値を覚える必要もなく、resume / fork / 圧縮後も正しく動作します。
|
|
19
|
+
- レベルの優先順位:セッション内の明示選択 > プラグイン設定 `level` > スケジューラ。
|
|
20
|
+
- 0.1.0-rc.8 の既知の制限:このラインの登録面には `stateOf` がない(旧プレーン契約)ため projection 登録をスキップし、`session.events` の旧経路を維持します — サンプリングは正常ですがエコー修正は適用されません。
|
|
21
|
+
|
|
22
|
+
### Tests
|
|
23
|
+
- 215/215:projection reducer・能力ゲート・schema 寛容性のケースを追加。`session-events.spec.ts` を**デコイ固定具**に書き換え(同一オブジェクトに旧 `events` 配列と projection 状態を同時に与え、projection が優先されることを断言)、4 リクエストのエコーシミュレーションを追加(初回 `low` → 高負荷 `max` → 明示選択がスケジューリングを抑止)。
|
|
24
|
+
|
|
14
25
|
## [4.4.4] — 2026-10-21(互換フィールドを画面から外す・レベル表は全プロトコルで編集可 — issue #7 #8)
|
|
15
26
|
|
|
16
27
|
- `支持 think effort` / `思考格式` の 2 スイッチは、他のプロトコルでは「無効化して長文の注記を出す」のをやめ、画面に出さないようにしました。表示条件は「思考モデルと宣言済み」かつ「ルートが openai-completions」の 2 つだけです。思考スイッチ自体は全プロトコルで有効のまま(protocol 非依存の `reasoningEfforts`)。
|
package/CHANGELOG.ko.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
`dsh-thinking-levels`의 주요 변경 사항을 기록합니다.
|
|
4
4
|
|
|
5
|
+
## [4.4.7] — 2026-10-27 (auto 레벨이 실제로 동작 — 샘플링을 프로젝션으로 교체 + 호스트 에코 차단 — issue #6)
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- `auto`가 더 이상 항상 `low`로 떨어지지 않습니다. 도구 샘플링은 `agent.session.events`를 읽었으나 이 배열 속성은 호스트 0.1.0-rc.8에만 존재하고(0.1.2-rc.1부터 제거), 지원하는 14개 라인 중 13개에서 샘플이 항상 `[]`여서 `high` / `max`가 구조적으로 도달 불가능했습니다. 이제 `tlAutoSchedule` 프로젝션을 등록해 `apply`가 `tool/call`을 용량 8의 링에 적재하고 호스트는 `stateOf()`로 O(1) 읽습니다. 첫 읽기에서 메모리 로그 전체를 fold하므로 재개/분기 세션도 완전합니다. 호스트는 `eventAt` / `snapshotEvents` / `ownEvents`의 신규 프로덕션 호출을 금지하므로 옛 읽기 방식으로 되돌리지 않습니다.
|
|
9
|
+
- `auto`가 더 이상 세션의 첫 요청에서만 동작하지 않습니다. 호스트가 매 단계 이전 `request/header`의 `reasoningEffort`(즉 이 플러그인의 주입값)를 다음 요청의 시드로 넣고, 구 구현은 이를 “수동 선택”으로 보고 그대로 통과시켜 레벨이 첫 결정에 영구히 고정되었습니다. 이제 같은 프로젝션이 `model/selection` 이벤트를 fold해 세션의 명시적 선택을 읽습니다(이 이벤트의 유일한 프로덕션 기록자는 사용자 선택 명령이며 플러그인 주입은 기록하지 않습니다). 시드는 더 이상 수동/자동 판정에 관여하지 않습니다 — 에코가 구조적으로 사라져 이전 주입값을 기억할 필요가 없고 resume / fork / 압축 후에도 올바릅니다.
|
|
10
|
+
- 레벨 우선순위: 세션 내 명시적 선택 > 플러그인 설정 `level` > 스케줄러.
|
|
11
|
+
- 0.1.0-rc.8 알려진 제한: 해당 라인의 등록면에는 `stateOf`가 없어(구 평면 계약) 프로젝션 등록을 건너뛰고 `session.events` 구 경로를 유지합니다 — 샘플링은 정상이나 에코 수정은 적용되지 않습니다.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
- 215/215: 프로젝션 reducer·능력 게이트·schema 내성 케이스 추가; `session-events.spec.ts`를 **미끼 픽스처**로 재작성(같은 객체에 구식 `events` 배열과 프로젝션 상태를 동시에 주고 프로젝션이 우선인지 단언)했으며, 4회 요청 에코 시뮬레이션을 추가했습니다(1회 `low` → 고부하 `max` → 명시적 선택이 스케줄링을 억제).
|
|
15
|
+
|
|
5
16
|
## [4.4.4] — 2026-10-21 (호환 필드를 화면에서 제거·레벨 표는 모든 프로토콜에서 편집 — issue #7 #8)
|
|
6
17
|
|
|
7
18
|
- `支持 think effort` / `思考格式` 두 스위치는 다른 프로토콜에서 "비활성화 + 긴 안내문" 대신 화면에 아예 표시하지 않습니다. 표시 조건은 "사고 모델로 선언됨" 그리고 "라우트가 openai-completions" 두 가지뿐입니다. 사고 스위치 자체는 모든 프로토콜에서 계속 사용 가능합니다(protocol 중립적 `reasoningEfforts`).
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
4.4.5: host enumeration addendum for DSH 0.2.1-rc.3 (declaration-only bump; contract plane zero diff).
|
|
3
3
|
|
|
4
4
|
|
|
5
|
+
## [4.4.7] — 2026-10-27 (auto 档真正生效:采样改投影 + 打断宿主回灌 — issue #6)
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- `auto` 档不再恒落 `low`。工具采样原先读 `agent.session.events`,而该数组属性只在宿主 0.1.0-rc.8 存在(0.1.2-rc.1 起移除),因此在 14 条支持线中的 13 条上采样恒为 `[]`、`high` / `max` 结构性不可达。现改为注册 `tlAutoSchedule` 投影单元:`apply` 把 `tool/call` 折进容量 8 的环形,宿主侧 `stateOf()` O(1) 读取;首次读会自动 fold 整条内存日志,恢复 / 分叉会话同样完整。宿主已明令禁止新增 `eventAt` / `snapshotEvents` / `ownEvents` 生产调用,故不回绑旧读法。
|
|
9
|
+
- `auto` 档不再只在会话首个请求生效。宿主每轮把上一轮 `request/header` 的 `reasoningEffort`(即本插件自己的注入值)当作下一轮种子,旧实现视其为“手动选档”直接透传,档位由此被首轮决定永久锁死。现改为同一投影折入 `model/selection` 事件取会话内的显式选择(该事件唯一生产写点即用户选档命令,插件注入永不写入),种子不再参与手动 / 自动判定 —— 回灌在结构上消失,无需记忆上一轮注入值,resume / fork / 压缩后同样正确。
|
|
10
|
+
- 档位来源优先级:会话内显式选择 > 插件配置 `level` > 调度器。
|
|
11
|
+
- 0.1.0-rc.8 已知限制:该线注册面无 `stateOf`(旧平面契约),跳过投影注册并继续走 `session.events` 老读法 —— 采样照常,但“回灌”修正不生效。
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
- 215/215:新增投影 reducer、能力门控与 schema 容错用例;`session-events.spec.ts` 改为**诱饵夹具**(同一对象同时提供过期 `events` 数组与投影状态,断言优先取投影),并新增跨四轮会话的回灌仿真(首轮 `low` → 重负载 `max` → 显式选档压住调度)。
|
|
15
|
+
|
|
5
16
|
## [4.4.5] — 2026-10-21 (toggle fold is openai-completions-only — issue #9)
|
|
6
17
|
|
|
7
18
|
### Fixed
|
package/CHANGELOG.ru.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
Все заметные изменения `dsh-thinking-levels` документируются здесь.
|
|
4
4
|
|
|
5
|
+
## [4.4.7] — 2026-10-27 (уровень auto действительно работает — выборка через projection + обрыв эха хоста — issue #6)
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- `auto` больше не сваливается постоянно в `low`. Выборка вызовов инструментов читала `agent.session.events`, но это свойство-массив есть только на хосте 0.1.0-rc.8 (убрано с 0.1.2-rc.1), поэтому на 13 из 14 поддерживаемых линий выборка всегда оставалась `[]`, а `high` / `max` были структурно недостижимы. Теперь плагин регистрирует projection `tlAutoSchedule`: `apply` складывает `tool/call` в кольцо ёмкостью 8, хост читает через `stateOf()` за O(1); первое чтение сворачивает весь журнал в памяти, поэтому возобновлённые и форкнутые сессии полны. Хост запрещает новые production-вызовы `eventAt` / `snapshotEvents` / `ownEvents`, поэтому возврата к старым читателям нет.
|
|
9
|
+
- `auto` больше не действует только на первом запросе сессии. Хост каждый раунд подставляет `reasoningEffort` из предыдущего `request/header` (то есть собственную инъекцию плагина) как seed; старая реализация считала это ручным выбором и пропускала насквозь, из-за чего уровень навсегда фиксировался на первом решении. Теперь та же projection сворачивает события `model/selection`, давая явный выбор сессии (единственный production-писатель — команда выбора пользователя; инъекция плагина не пишет никогда). Seed больше не участвует в различении ручного и auto — эхо исчезает структурно, без запоминания последней инъекции, и остаётся корректным после resume / fork / сжатия.
|
|
10
|
+
- Приоритет уровней: явный выбор сессии > конфигурация плагина `level` > планировщик.
|
|
11
|
+
- Известное ограничение 0.1.0-rc.8: в поверхности регистрации этой линии нет `stateOf` (старый plane-контракт), поэтому регистрация пропускается и остаётся старый путь `session.events` — выборка работает, исправление эха — нет.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
- 215/215: добавлены случаи для reducer-projection, capability-гейта и терпимости схемы; `session-events.spec.ts` переделан в **фикстуру-приманку** (один объект одновременно даёт устаревший массив `events` и состояние projection, ассерт требует projection), плюс сценарий эха на четыре запроса (сначала `low` → тяжёлая нагрузка `max` → явный выбор подавляет планировщик).
|
|
15
|
+
|
|
5
16
|
## [4.4.4] — 2026-10-21 (поля совместимости убраны с экрана, редактор уровней открыт везде — issue #7 #8)
|
|
6
17
|
|
|
7
18
|
- Два переключателя, доступные только на openai-completions (`支持 think effort` / `思考格式`), больше не ОТОБРАЖАЮТСЯ на других протоколах — раньше они были неактивны с длинной подсказкой. Теперь они появляются только если модель **объявлена thinking** И маршрут использует `openai-completions`; в остальных случаях их нет в DOM. Сам thinking остаётся доступным везде (протоколонезависимый `reasoningEfforts`).
|
package/README.de.md
CHANGED
|
@@ -130,6 +130,8 @@ Der Hub ist `high` (der offizielle Standard). `auto` plant zwischen `low` / `hig
|
|
|
130
130
|
|
|
131
131
|
Die Planungspolitik stammt aus derselben Quelle wie [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) (dieselbe Simple-Tool-Whitelist / dieselben Payload-Schwellen / dieselbe 75-%-Regel).
|
|
132
132
|
|
|
133
|
+
**Woher die Stichproben kommen (4.4.7+):** Der Scheduler faltet `tool/call`-Ereignisse in eine Session-Projektion (`tlAutoSchedule`) und sieht damit auf jedem Host ab 0.1.2-rc.1 echte Werkzeughistorie; das frühere `session.events`-Lesen lieferte nur auf 0.1.0-rc.8 Stichproben. Die explizite Sitzungswahl wird aus `model/selection`-Ereignissen gefaltet, sodass ein vom Host zurückgespiegeltes Level nie als manuelle Wahl gilt. Bekannte Einschränkung: Host `0.1.0-rc.8` hat kein `stateOf` an seiner Registrierungsoberfläche (alter Plane-Vertrag); diese Linie behält das alte Array-Lesen — Scheduling funktioniert dort, die Echo-Korrektur nicht.
|
|
134
|
+
|
|
133
135
|
## Installation
|
|
134
136
|
|
|
135
137
|
Siehe [INSTALL.md](./INSTALL.de.md) für die vollständige Anleitung der offiziellen CLI (Profil-Erkennung, Upgrade, Migration, Verifikation, Fehlerbehebung). Schnellstart:
|
package/README.es.md
CHANGED
|
@@ -130,6 +130,8 @@ El eje es `high` (el oficial predeterminado). `auto` programa entre `low` / `hig
|
|
|
130
130
|
|
|
131
131
|
La política de programación comparte la misma fuente que [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) (la misma lista blanca de herramientas simples / los mismos umbrales de carga / la misma regla del 75 %).
|
|
132
132
|
|
|
133
|
+
**De dónde salen las muestras (4.4.7+).** El planificador pliega los eventos `tool/call` en una proyección de Session (`tlAutoSchedule`) y por tanto ve el historial real de herramientas en cualquier host desde 0.1.2-rc.1; la lectura `session.events` anterior a 4.4.7 solo producía muestras en 0.1.0-rc.8. La elección explícita de la sesión se pliega desde eventos `model/selection`, así que un nivel devuelto en eco por el host nunca puede confundirse con una elección manual. Límite conocido: el host `0.1.0-rc.8` no expone `stateOf` en su superficie de registro (contrato plano antiguo); esa línea mantiene la lectura antigua del array — la planificación funciona, la corrección del eco no.
|
|
134
|
+
|
|
133
135
|
## Instalación
|
|
134
136
|
|
|
135
137
|
Consulta [INSTALL.md](./INSTALL.es.md) para la guía completa de la CLI oficial (descubrimiento del perfil, actualización, migración, verificación, resolución de problemas). Inicio rápido:
|
package/README.fr.md
CHANGED
|
@@ -130,6 +130,8 @@ Le pivot est `high` (l'officiel par défaut). `auto` planifie entre `low` / `hig
|
|
|
130
130
|
|
|
131
131
|
La politique de planification partage la même source que [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) (même liste blanche d'outils simples / mêmes seuils de charge / même règle des 75 %).
|
|
132
132
|
|
|
133
|
+
**D'où viennent les échantillons (4.4.7+).** L'ordonnanceur replie les événements `tool/call` dans une projection de Session (`tlAutoSchedule`) et voit donc l'historique réel des outils sur tout hôte depuis 0.1.2-rc.1 ; la lecture `session.events` antérieure à 4.4.7 ne produisait des échantillons que sur 0.1.0-rc.8. Le choix explicite de la session est replié depuis les événements `model/selection`, si bien qu'un niveau renvoyé en écho par l'hôte ne peut jamais passer pour une sélection manuelle. Limite connue : l'hôte `0.1.0-rc.8` n'expose pas `stateOf` sur sa surface d'enregistrement (ancien contrat plan) ; cette ligne conserve l'ancienne lecture de tableau — l'ordonnancement y fonctionne, la correction de l'écho non.
|
|
134
|
+
|
|
133
135
|
## Installation
|
|
134
136
|
|
|
135
137
|
Voir [INSTALL.md](./INSTALL.fr.md) pour le guide complet de la CLI officielle (découverte du profil, mise à niveau, migration, vérification, dépannage). Démarrage rapide :
|
package/README.it.md
CHANGED
|
@@ -129,6 +129,8 @@ Il perno è `high` (il predefinito ufficiale). `auto` pianifica tra `low` / `hig
|
|
|
129
129
|
|
|
130
130
|
La politica di pianificazione condivide la stessa origine di [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) (stessa whitelist di strumenti semplici / stesse soglie di payload / stessa regola del 75%).
|
|
131
131
|
|
|
132
|
+
**Da dove vengono i campioni (4.4.7+).** Lo scheduler ripiega gli eventi `tool/call` in una projection di Session (`tlAutoSchedule`) e vede quindi la cronologia reale degli strumenti su ogni host da 0.1.2-rc.1 in poi; la lettura `session.events` precedente alla 4.4.7 produceva campioni solo su 0.1.0-rc.8. La scelta esplicita della sessione viene ripiegata dagli eventi `model/selection`, così un livello restituito in eco dall'host non può mai passare per una scelta manuale. Limite noto: l'host `0.1.0-rc.8` non espone `stateOf` sulla superficie di registrazione (vecchio contratto plan); quella linea mantiene la vecchia lettura ad array — lo scheduling funziona, la correzione dell'eco no.
|
|
133
|
+
|
|
132
134
|
## Installazione
|
|
133
135
|
|
|
134
136
|
Vedi [INSTALL.md](./INSTALL.it.md) per la guida completa alla CLI ufficiale (scoperta del profilo, aggiornamento, migrazione, verifica, risoluzione dei problemi). Avvio rapido:
|
package/README.ja.md
CHANGED
|
@@ -98,6 +98,8 @@ auto スケジューラーは対応モデルで `low` を選ぶことがあり
|
|
|
98
98
|
|
|
99
99
|
スケジュールポリシーは [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) と同源です(同じシンプルツールのホワイトリスト / ペイロード閾値 / 75% 比率ルール)。
|
|
100
100
|
|
|
101
|
+
**サンプリング元(4.4.7+)**:スケジューラは `tool/call` イベントを Session projection(`tlAutoSchedule`)に畳み込むため、0.1.2-rc.1 以降のすべてのホストで実際のツール履歴を参照できます。4.4.7 以前が読んでいた `session.events` は 0.1.0-rc.8 でのみサンプルを返していました。セッション内の明示選択は `model/selection` イベントから畳み込むので、ホストが返すエコーを手動選択と誤認しません。既知の制限:ホスト `0.1.0-rc.8` の登録面には `stateOf` がない(旧プレーン契約)ため、そのラインは旧来の配列読み出しを維持します — スケジューリングは動作しますが、エコー修正は適用されません。
|
|
102
|
+
|
|
101
103
|
## インストール
|
|
102
104
|
|
|
103
105
|
完全な手順(profile の確認、アップグレード、移行、検証、トラブルシューティング)は [INSTALL.ja.md](./INSTALL.ja.md) を参照してください。クイックスタート:
|
package/README.ko.md
CHANGED
|
@@ -98,6 +98,8 @@ auto 스케줄러는 지원 모델에서 `low`를 선택할 수 있습니다—
|
|
|
98
98
|
|
|
99
99
|
스케줄링 정책은 [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo)와 동일한 소스입니다(같은 단순 도구 화이트리스트 / 페이로드 임계값 / 75% 비율 규칙).
|
|
100
100
|
|
|
101
|
+
**샘플 출처(4.4.7+)** — 스케줄러는 `tool/call` 이벤트를 Session 프로젝션(`tlAutoSchedule`)으로 fold하므로 0.1.2-rc.1 이후 모든 호스트에서 실제 도구 이력을 봅니다. 4.4.7 이전의 `session.events` 읽기는 0.1.0-rc.8에서만 샘플을 만들었습니다. 세션의 명시적 선택은 `model/selection` 이벤트에서 fold하므로 호스트가 되돌려주는 에코를 수동 선택으로 오인하지 않습니다. 알려진 제한: 호스트 `0.1.0-rc.8`의 등록면에는 `stateOf`가 없어(구 평면 계약) 해당 라인은 구 배열 읽기를 유지합니다 — 스케줄링은 동작하지만 에코 보정은 적용되지 않습니다.
|
|
102
|
+
|
|
101
103
|
## 설치
|
|
102
104
|
|
|
103
105
|
전체 절차(profile 확인, 업그레이드, 마이그레이션, 검증, 트러블슈팅)는 [INSTALL.ko.md](./INSTALL.ko.md)를 참조하세요. 빠른 시작:
|
package/README.md
CHANGED
|
@@ -158,6 +158,8 @@ The hub is `high` (the official default). `auto` schedules between `low` / `high
|
|
|
158
158
|
|
|
159
159
|
The scheduling policy is the same source as [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) (same simple-tool whitelist / payload thresholds / 75% ratio rule).
|
|
160
160
|
|
|
161
|
+
**Where the samples come from (4.4.7+).** The scheduler folds `tool/call` events into a Session projection (`tlAutoSchedule`), so it sees real tool history on every host from 0.1.2-rc.1 on; the pre-4.4.7 `session.events` read only ever produced samples on 0.1.0-rc.8. The session's explicit pick is folded from `model/selection` events, so a level the host echoes back can never be mistaken for a manual choice. Known limitation: host `0.1.0-rc.8` exposes no `stateOf` on its projection registry (legacy plane contract), so that one line keeps the old array read — scheduling works there, the echo correction does not.
|
|
162
|
+
|
|
161
163
|
## Install
|
|
162
164
|
|
|
163
165
|
See [INSTALL.md](./INSTALL.md) for the full official-CLI guide (profile discovery, upgrade, migration, verification, troubleshooting). Quick start:
|
package/README.ru.md
CHANGED
|
@@ -130,6 +130,8 @@ openai-completions-маршруты (например, локальный Qwen3.
|
|
|
130
130
|
|
|
131
131
|
Политика планирования ведёт происхождение от [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) (тот же белый список простых инструментов / те же пороги нагрузки / то же правило 75%).
|
|
132
132
|
|
|
133
|
+
**Откуда берутся выборки (4.4.7+).** Планировщик сворачивает события `tool/call` в projection сессии (`tlAutoSchedule`) и потому видит реальную историю инструментов на любом хосте начиная с 0.1.2-rc.1; прежнее чтение `session.events` давало выборки только на 0.1.0-rc.8. Явный выбор сессии сворачивается из событий `model/selection`, поэтому уровень, возвращённый хостом (эхо), никогда не принимается за ручной выбор. Известное ограничение: на хосте `0.1.0-rc.8` в поверхности регистрации нет `stateOf` (старый plane-контракт); эта линия сохраняет старое чтение массива — планирование работает, исправление эха — нет.
|
|
134
|
+
|
|
133
135
|
## Установка
|
|
134
136
|
|
|
135
137
|
Полное руководство по официальному CLI (обнаружение профиля, обновление, миграция, проверка, устранение неполадок) — см. [INSTALL.md](./INSTALL.ru.md). Быстрый старт:
|
package/README.zh.md
CHANGED
|
@@ -116,6 +116,8 @@ auto 调度对支持的模型仍可选出 `low`——由上面的能力守卫负
|
|
|
116
116
|
|
|
117
117
|
调度策略与 [dsh-tool-turbo](https://github.com/drscrewdriver/dsh-tool-turbo) 同源(同一套简单工具白名单 / 载荷阈值 / 75% 比例规则)。
|
|
118
118
|
|
|
119
|
+
**采样来源(4.4.7+)**:调度器把 `tool/call` 事件折入 Session 投影(`tlAutoSchedule`),因此在 0.1.2-rc.1 起的宿主上都能看到真实工具历史;4.4.7 之前读的 `session.events` 只在 0.1.0-rc.8 上产出过样本。会话内的显式选档由 `model/selection` 事件折入,宿主回灌的档位不会被误判为手动选择。已知限制:宿主 `0.1.0-rc.8` 的投影注册面没有 `stateOf`(旧平面契约),该线继续走旧的数组读法 —— 调度照常,回灌修正不生效。
|
|
120
|
+
|
|
119
121
|
## 安装
|
|
120
122
|
|
|
121
123
|
完整流程(profile 确认、升级、迁移、验证、排查)见 [INSTALL.zh.md](./INSTALL.zh.md)。快速开始:
|
package/dsh.plugin.json
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
{
|
|
2
|
-
"id": "dsh-external/dsh-thinking-levels",
|
|
3
|
-
"version": "4.4.
|
|
4
|
-
"main": "./lib/index.js",
|
|
5
|
-
"description": "thinking-level (reasoning_effort) control — auto-adjust per tool round, with optional manual lock and per-tool timing telemetry.",
|
|
6
|
-
"engines": {
|
|
7
|
-
"dsh": "0.1.0-rc.8 || 0.1.1-rc.1 || 0.1.1-rc.2 || 0.1.2-rc.1 || 0.1.5-rc.1 || 0.1.5-rc.2 || 0.1.5-rc.3 || 0.1.7-rc.1 || 0.1.7-rc.2 || 0.2.0-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.1 || 0.2.1-rc.2 || 0.2.1-rc.3"
|
|
8
|
-
},
|
|
9
|
-
"contributes": {
|
|
10
|
-
"tools": [],
|
|
11
|
-
"skills": []
|
|
12
|
-
},
|
|
13
|
-
"client": {
|
|
14
|
-
"main": "./lib/client.js"
|
|
15
|
-
}
|
|
16
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"id": "dsh-external/dsh-thinking-levels",
|
|
3
|
+
"version": "4.4.6",
|
|
4
|
+
"main": "./lib/index.js",
|
|
5
|
+
"description": "thinking-level (reasoning_effort) control — auto-adjust per tool round, with optional manual lock and per-tool timing telemetry.",
|
|
6
|
+
"engines": {
|
|
7
|
+
"dsh": "0.1.0-rc.8 || 0.1.1-rc.1 || 0.1.1-rc.2 || 0.1.2-rc.1 || 0.1.5-rc.1 || 0.1.5-rc.2 || 0.1.5-rc.3 || 0.1.7-rc.1 || 0.1.7-rc.2 || 0.2.0-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.1 || 0.2.1-rc.2 || 0.2.1-rc.3"
|
|
8
|
+
},
|
|
9
|
+
"contributes": {
|
|
10
|
+
"tools": [],
|
|
11
|
+
"skills": []
|
|
12
|
+
},
|
|
13
|
+
"client": {
|
|
14
|
+
"main": "./lib/client.js"
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TL auto-schedule projection unit (`tlAutoSchedule`).
|
|
3
|
+
*
|
|
4
|
+
* Issue #6 background — the two defects this unit exists to fix:
|
|
5
|
+
* - The scheduler sampled tool calls from `agent.session.events`, an array
|
|
6
|
+
* property that only existed on 0.1.0-rc.8. From 0.1.2-rc.1 onward the host
|
|
7
|
+
* exposes `eventAt()/snapshotEvents()/ownEvents()` instead, so the sampler
|
|
8
|
+
* returned `[]` on 13 of the 14 supported host lines and `auto` silently
|
|
9
|
+
* collapsed to `low`. Those three readers are now `@deprecated` with an
|
|
10
|
+
* explicit "new production calls are prohibited" policy
|
|
11
|
+
* (`packages/core/session/README.md:62`), so re-binding to them is not an
|
|
12
|
+
* option either.
|
|
13
|
+
* - The host seeds every request's `reasoningEffort` from the previous
|
|
14
|
+
* `request/header`, i.e. from THIS plugin's own output
|
|
15
|
+
* (`core/agent-loop/src/agent.ts:573-581`), so treating a concrete seed as a
|
|
16
|
+
* manual pick froze `auto` after the first request of a session.
|
|
17
|
+
*
|
|
18
|
+
* Both are solved by reading/writing a Session projection instead of the log:
|
|
19
|
+
* - `apply` folds `tool/call` events into a bounded ring → `samples`.
|
|
20
|
+
* - `apply` folds `model/selection` events into `userEffort`. That event has
|
|
21
|
+
* exactly one production writer, the user-facing selection command
|
|
22
|
+
* (`api/session-controller/src/agent.ts:340` ← `commands.ts:176`), so the
|
|
23
|
+
* plugin's own injection can never pollute it — the echo disappears by
|
|
24
|
+
* construction and needs no "remember what I injected" side table.
|
|
25
|
+
*
|
|
26
|
+
* Projections are the sanctioned read path ("reads the projection"), are
|
|
27
|
+
* folded lazily over the in-memory log on first read (so resumed/forked
|
|
28
|
+
* sessions are complete), and cost O(1) per request afterwards.
|
|
29
|
+
*
|
|
30
|
+
* Explicitly NOT used: the host's `modelSelection` projection. Its `lastUsed`
|
|
31
|
+
* is rewritten on every `request/header` (i.e. it holds this plugin's own
|
|
32
|
+
* output) and `pending` is cleared once a matching header commits
|
|
33
|
+
* (`api/session-controller/src/model-selection-projection.ts:39-58`), so
|
|
34
|
+
* neither field carries a durable user intent.
|
|
35
|
+
* @module dsh-thinking-levels/auto-schedule-projection
|
|
36
|
+
*/
|
|
37
|
+
import { z } from 'zod';
|
|
38
|
+
import { type EffortId, type ToolCallSample } from './thinking-level.ts';
|
|
39
|
+
/** Projection key. `tl` matches the plugin's other unit (`tlCacheBilling`). */
|
|
40
|
+
export declare const AUTO_SCHEDULE_KEY = "tlAutoSchedule";
|
|
41
|
+
/** Folded state: recent tool samples plus the session's explicit pick. */
|
|
42
|
+
export interface AutoScheduleState {
|
|
43
|
+
/** Recent `tool/call` samples, oldest first, at most {@link TOOL_SAMPLE_WINDOW}. */
|
|
44
|
+
samples: readonly ToolCallSample[];
|
|
45
|
+
/** Effort explicitly picked in this session, or null when never picked. */
|
|
46
|
+
userEffort: string | null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Fold one committed Session event into the auto-schedule state.
|
|
50
|
+
*
|
|
51
|
+
* Unrelated events return the SAME reference — the projection registry gates
|
|
52
|
+
* its change feed on `Object.is`, so rebuilding state for every message would
|
|
53
|
+
* wake every client-visible unit on each append.
|
|
54
|
+
*
|
|
55
|
+
* @param state - state before the event.
|
|
56
|
+
* @param event - next committed Session event (raw wire shape; narrowed below).
|
|
57
|
+
* @returns the original or advanced state.
|
|
58
|
+
*/
|
|
59
|
+
export declare function applyAutoSchedule(state: AutoScheduleState, event: unknown): AutoScheduleState;
|
|
60
|
+
/**
|
|
61
|
+
* Build the `tlAutoSchedule` projection definition. Registered soft-coupled
|
|
62
|
+
* (runtime inject), exactly like `tlCacheBilling`: hosts whose registry cannot
|
|
63
|
+
* serve `stateOf` simply never register it and the scheduler falls back to the
|
|
64
|
+
* legacy array read.
|
|
65
|
+
*/
|
|
66
|
+
export declare function buildAutoScheduleDefinition(): {
|
|
67
|
+
key: string;
|
|
68
|
+
stateVersion: number;
|
|
69
|
+
stateSchema: z.ZodObject<{
|
|
70
|
+
samples: z.ZodArray<z.ZodObject<{
|
|
71
|
+
name: z.ZodString;
|
|
72
|
+
argsSize: z.ZodNumber;
|
|
73
|
+
}, z.core.$strip>>;
|
|
74
|
+
userEffort: z.ZodNullable<z.ZodString>;
|
|
75
|
+
}, z.core.$strip>;
|
|
76
|
+
init: () => AutoScheduleState;
|
|
77
|
+
apply: typeof applyAutoSchedule;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Read the folded auto-schedule state for a session.
|
|
81
|
+
*
|
|
82
|
+
* Returns `undefined` — never throws — when the host cannot serve it: the
|
|
83
|
+
* service is absent, or the registry predates `stateOf` (0.1.0-rc.8 is the
|
|
84
|
+
* legacy plane-contract registry with `schema`/`view` and no `stateOf`). A
|
|
85
|
+
* thrown error here would take down the whole turn
|
|
86
|
+
* (`agent-loop/README.md:128`: "plugin failure ends the turn").
|
|
87
|
+
*
|
|
88
|
+
* @param ctx - plugin context (only `get` is used).
|
|
89
|
+
* @param session - the live session owning the state.
|
|
90
|
+
* @returns the folded state, or undefined when unavailable.
|
|
91
|
+
*/
|
|
92
|
+
export declare function readAutoSchedule(ctx: {
|
|
93
|
+
get?: (name: string) => unknown;
|
|
94
|
+
}, session: unknown): AutoScheduleState | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* The level this request was asked for: the session's explicit pick when it is
|
|
97
|
+
* a level the plugin understands, else the plugin-configured default.
|
|
98
|
+
*
|
|
99
|
+
* Note the `isEffortId` gate is deliberate and matches the pre-existing
|
|
100
|
+
* behaviour: a gateway-specific wire value (e.g. `ultra`) inside a concrete
|
|
101
|
+
* pick already fell through to the scheduler before this change, because
|
|
102
|
+
* `resolveEffortInjection` only passes through known effort ids.
|
|
103
|
+
*
|
|
104
|
+
* @param state - folded state, when the host could serve it.
|
|
105
|
+
* @param fallback - configured default level.
|
|
106
|
+
* @returns the requested level.
|
|
107
|
+
*/
|
|
108
|
+
export declare function requestedEffortOf(state: AutoScheduleState | undefined, fallback: EffortId): EffortId;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TL auto-schedule projection unit (`tlAutoSchedule`).
|
|
3
|
+
*
|
|
4
|
+
* Issue #6 background — the two defects this unit exists to fix:
|
|
5
|
+
* - The scheduler sampled tool calls from `agent.session.events`, an array
|
|
6
|
+
* property that only existed on 0.1.0-rc.8. From 0.1.2-rc.1 onward the host
|
|
7
|
+
* exposes `eventAt()/snapshotEvents()/ownEvents()` instead, so the sampler
|
|
8
|
+
* returned `[]` on 13 of the 14 supported host lines and `auto` silently
|
|
9
|
+
* collapsed to `low`. Those three readers are now `@deprecated` with an
|
|
10
|
+
* explicit "new production calls are prohibited" policy
|
|
11
|
+
* (`packages/core/session/README.md:62`), so re-binding to them is not an
|
|
12
|
+
* option either.
|
|
13
|
+
* - The host seeds every request's `reasoningEffort` from the previous
|
|
14
|
+
* `request/header`, i.e. from THIS plugin's own output
|
|
15
|
+
* (`core/agent-loop/src/agent.ts:573-581`), so treating a concrete seed as a
|
|
16
|
+
* manual pick froze `auto` after the first request of a session.
|
|
17
|
+
*
|
|
18
|
+
* Both are solved by reading/writing a Session projection instead of the log:
|
|
19
|
+
* - `apply` folds `tool/call` events into a bounded ring → `samples`.
|
|
20
|
+
* - `apply` folds `model/selection` events into `userEffort`. That event has
|
|
21
|
+
* exactly one production writer, the user-facing selection command
|
|
22
|
+
* (`api/session-controller/src/agent.ts:340` ← `commands.ts:176`), so the
|
|
23
|
+
* plugin's own injection can never pollute it — the echo disappears by
|
|
24
|
+
* construction and needs no "remember what I injected" side table.
|
|
25
|
+
*
|
|
26
|
+
* Projections are the sanctioned read path ("reads the projection"), are
|
|
27
|
+
* folded lazily over the in-memory log on first read (so resumed/forked
|
|
28
|
+
* sessions are complete), and cost O(1) per request afterwards.
|
|
29
|
+
*
|
|
30
|
+
* Explicitly NOT used: the host's `modelSelection` projection. Its `lastUsed`
|
|
31
|
+
* is rewritten on every `request/header` (i.e. it holds this plugin's own
|
|
32
|
+
* output) and `pending` is cleared once a matching header commits
|
|
33
|
+
* (`api/session-controller/src/model-selection-projection.ts:39-58`), so
|
|
34
|
+
* neither field carries a durable user intent.
|
|
35
|
+
* @module dsh-thinking-levels/auto-schedule-projection
|
|
36
|
+
*/
|
|
37
|
+
import { z } from 'zod';
|
|
38
|
+
import { TOOL_SAMPLE_WINDOW, toolSampleOf } from "./session-events.js";
|
|
39
|
+
import { isEffortId } from "./thinking-level.js";
|
|
40
|
+
/** Projection key. `tl` matches the plugin's other unit (`tlCacheBilling`). */
|
|
41
|
+
export const AUTO_SCHEDULE_KEY = 'tlAutoSchedule';
|
|
42
|
+
const stateSchema = z.object({
|
|
43
|
+
samples: z.array(z.object({ name: z.string(), argsSize: z.number() })),
|
|
44
|
+
userEffort: z.string().nullable(),
|
|
45
|
+
});
|
|
46
|
+
/** Initial folded state (also the shape every cold read starts from). */
|
|
47
|
+
const initAutoSchedule = () => ({ samples: [], userEffort: null });
|
|
48
|
+
/**
|
|
49
|
+
* Fold one committed Session event into the auto-schedule state.
|
|
50
|
+
*
|
|
51
|
+
* Unrelated events return the SAME reference — the projection registry gates
|
|
52
|
+
* its change feed on `Object.is`, so rebuilding state for every message would
|
|
53
|
+
* wake every client-visible unit on each append.
|
|
54
|
+
*
|
|
55
|
+
* @param state - state before the event.
|
|
56
|
+
* @param event - next committed Session event (raw wire shape; narrowed below).
|
|
57
|
+
* @returns the original or advanced state.
|
|
58
|
+
*/
|
|
59
|
+
export function applyAutoSchedule(state, event) {
|
|
60
|
+
if (typeof event !== 'object' || event === null)
|
|
61
|
+
return state;
|
|
62
|
+
const type = event.type;
|
|
63
|
+
if (type === 'tool/call') {
|
|
64
|
+
const sample = toolSampleOf(event);
|
|
65
|
+
if (sample === undefined)
|
|
66
|
+
return state;
|
|
67
|
+
const grown = [...state.samples, sample];
|
|
68
|
+
const samples = grown.length > TOOL_SAMPLE_WINDOW
|
|
69
|
+
? grown.slice(grown.length - TOOL_SAMPLE_WINDOW)
|
|
70
|
+
: grown;
|
|
71
|
+
return { ...state, samples };
|
|
72
|
+
}
|
|
73
|
+
if (type === 'model/selection') {
|
|
74
|
+
const data = event.data;
|
|
75
|
+
const raw = typeof data === 'object' && data !== null
|
|
76
|
+
? data.reasoningEffort
|
|
77
|
+
: undefined;
|
|
78
|
+
const userEffort = typeof raw === 'string' && raw.length > 0 ? raw : null;
|
|
79
|
+
return userEffort === state.userEffort ? state : { ...state, userEffort };
|
|
80
|
+
}
|
|
81
|
+
return state;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Build the `tlAutoSchedule` projection definition. Registered soft-coupled
|
|
85
|
+
* (runtime inject), exactly like `tlCacheBilling`: hosts whose registry cannot
|
|
86
|
+
* serve `stateOf` simply never register it and the scheduler falls back to the
|
|
87
|
+
* legacy array read.
|
|
88
|
+
*/
|
|
89
|
+
export function buildAutoScheduleDefinition() {
|
|
90
|
+
return {
|
|
91
|
+
key: AUTO_SCHEDULE_KEY,
|
|
92
|
+
stateVersion: 1,
|
|
93
|
+
stateSchema,
|
|
94
|
+
init: initAutoSchedule,
|
|
95
|
+
apply: applyAutoSchedule,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Read the folded auto-schedule state for a session.
|
|
100
|
+
*
|
|
101
|
+
* Returns `undefined` — never throws — when the host cannot serve it: the
|
|
102
|
+
* service is absent, or the registry predates `stateOf` (0.1.0-rc.8 is the
|
|
103
|
+
* legacy plane-contract registry with `schema`/`view` and no `stateOf`). A
|
|
104
|
+
* thrown error here would take down the whole turn
|
|
105
|
+
* (`agent-loop/README.md:128`: "plugin failure ends the turn").
|
|
106
|
+
*
|
|
107
|
+
* @param ctx - plugin context (only `get` is used).
|
|
108
|
+
* @param session - the live session owning the state.
|
|
109
|
+
* @returns the folded state, or undefined when unavailable.
|
|
110
|
+
*/
|
|
111
|
+
export function readAutoSchedule(ctx, session) {
|
|
112
|
+
if (typeof session !== 'object' || session === null)
|
|
113
|
+
return undefined;
|
|
114
|
+
try {
|
|
115
|
+
const service = ctx.get?.('sessionProjections');
|
|
116
|
+
if (typeof service?.stateOf !== 'function')
|
|
117
|
+
return undefined;
|
|
118
|
+
const state = service.stateOf(session, AUTO_SCHEDULE_KEY);
|
|
119
|
+
return typeof state === 'object' && state !== null ? state : undefined;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The level this request was asked for: the session's explicit pick when it is
|
|
127
|
+
* a level the plugin understands, else the plugin-configured default.
|
|
128
|
+
*
|
|
129
|
+
* Note the `isEffortId` gate is deliberate and matches the pre-existing
|
|
130
|
+
* behaviour: a gateway-specific wire value (e.g. `ultra`) inside a concrete
|
|
131
|
+
* pick already fell through to the scheduler before this change, because
|
|
132
|
+
* `resolveEffortInjection` only passes through known effort ids.
|
|
133
|
+
*
|
|
134
|
+
* @param state - folded state, when the host could serve it.
|
|
135
|
+
* @param fallback - configured default level.
|
|
136
|
+
* @returns the requested level.
|
|
137
|
+
*/
|
|
138
|
+
export function requestedEffortOf(state, fallback) {
|
|
139
|
+
const user = state?.userEffort;
|
|
140
|
+
return isEffortId(user) ? user : fallback;
|
|
141
|
+
}
|