@dsmm/dsmm 0.3.40 → 0.3.41

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/README.md CHANGED
@@ -4,14 +4,14 @@ DSMM 是 DeepSeek Harness(DSH)的插件。它让不同 Agent 分工处理任
4
4
 
5
5
  比如,让 Planner 拆解任务、Coding 写代码、Reviewer 检查结果,再由 Orchestrator 协调。各个角色可以用不同的模型,不必共用一套配置。
6
6
 
7
- 当前发布版本为 `@dsmm/dsmm@0.3.40`,支持 DSH `>=0.2.1-rc.2 <0.2.2-0 || >=0.2.2-rc.1 <0.3.0`。安装前请确认客户端版本;范围外的 DSH 版本不受支持。Desktop 使用自带运行时,独立命令行环境需要 Node.js 22 或更高版本。
7
+ 当前发布版本为 `@dsmm/dsmm@0.3.41`,支持 DSH `>=0.2.1-rc.2 <0.2.2-0 || >=0.2.2-rc.1 <0.3.0`。安装前请确认客户端版本;范围外的 DSH 版本不受支持。Desktop 使用自带运行时,独立命令行环境需要 Node.js 22 或更高版本。
8
8
 
9
9
  官方 DSH rc.3 以 `engines.dsh` 优先于 peer ranges 判定兼容性;锁文件保留 `0.2.1-rc.2` 作为开发基线。
10
10
 
11
11
  历史会话仅保守支持已有的原生读取和已验证的受限恢复路径,不承诺补齐旧版本行为或自动迁移。继续执行须满足当前身份与权限检查,历史批准不会恢复为当前授权。
12
12
 
13
13
  - 源码仓库:[hugefiver/dsmm](https://github.com/hugefiver/dsmm)
14
- - 安装来源:[npm (@dsmm/dsmm)](https://www.npmjs.com/package/@dsmm/dsmm);发布资产:[GitHub Releases (v0.3.40)](https://github.com/hugefiver/dsmm/releases/tag/v0.3.40)
14
+ - 安装来源:[npm (@dsmm/dsmm)](https://www.npmjs.com/package/@dsmm/dsmm);发布资产:[GitHub Releases (v0.3.41)](https://github.com/hugefiver/dsmm/releases/tag/v0.3.41)
15
15
 
16
16
  ---
17
17
 
@@ -22,7 +22,7 @@ DSMM 是 DeepSeek Harness(DSH)的插件。它让不同 Agent 分工处理任
22
22
  ### 初次安装
23
23
 
24
24
  1. 打开 DeepSeek Harness Desktop,进入 **插件(Plugins)** 页面。
25
- 2. 点击 **添加插件(Add plugin)**,输入 `@dsmm/dsmm@0.3.40` 并确认。
25
+ 2. 点击 **添加插件(Add plugin)**,输入 `@dsmm/dsmm@0.3.41` 并确认。
26
26
  3. 安装完成后,检查插件是否处于启用状态。如果界面提示需要重启,请按提示重启客户端。
27
27
 
28
28
  Desktop 的插件由客户端自己管理。全局 npm 安装和独立 npm 版 `dsh` 命令不能替代这一步。
@@ -34,7 +34,7 @@ DSH Desktop 当前不支持在界面中用同名版本原位覆盖更新插件
34
34
  1. 保存好正在进行的任务,**正常退出并完全关闭 DSH Desktop**。
35
35
  2. 使用 Desktop 安装自带的命令行工具更新配置。以下示例适用于 Windows 默认安装路径(`%LOCALAPPDATA%\Programs\DeepSeek Harness\`):
36
36
  ```powershell
37
- & "$env:LOCALAPPDATA\Programs\DeepSeek Harness\resources\runtime\cli\bin\dsh.cmd" plugin --profile desktop add @dsmm/dsmm@0.3.40 --save-exact --ignore-scripts --registry=https://registry.npmjs.org
37
+ & "$env:LOCALAPPDATA\Programs\DeepSeek Harness\resources\runtime\cli\bin\dsh.cmd" plugin --profile desktop add @dsmm/dsmm@0.3.41 --save-exact --ignore-scripts --registry=https://registry.npmjs.org
38
38
  ```
39
39
  *若安装在自定义路径,请替换为对应的实际位置;非 Windows 系统请参考 Desktop 自身菜单或官方指引,不要混用非 Desktop 的独立 CLI 命令。*
40
40
  3. 重新打开 DSH Desktop 即可加载新版本。
@@ -86,7 +86,7 @@ DSMM 包含两处相互独立的配置区域:
86
86
  - 会话必须处于真正空闲状态:无正在生成的回复、无排队输入、无待处理审批且无运行中的子任务。界面单独显示 `idle` 状态并不代表没有后台活动,需等待所有操作完全结束。
87
87
  - 切换成功后,已存在的旧子任务继续保留启动时的原配置与限制,后续新委派的子任务才会使用新方案。
88
88
  - 已停止并完成收尾、或自然完成的会话可以直接切换。切换以当前会话及已加载子会话的实际状态为准;若仍有任务或其他操作进行中,结束后重试。保存方案和原生模型选择保持独立。
89
- - **使用方案模型(Use profile model)**:对于有对应 DSMM 角色主模型的会话,把原生模型选择切换为方案中配置的主模型。默认的 `rootModelPolicy: native` 下,保存或切换方案不会自动改模型;要一起换模型,需要明确点击这个操作。操作期间如果又手动选择了模型,以较新的选择为准。
89
+ - **使用方案模型(Use profile model)**:对于有对应 DSMM 角色主模型的会话,把原生模型选择切换为方案中配置的主模型。保存或应用方案默认保留当前主模型。需要切换时,明确选择使用方案模型;之后仍可手动改选。操作期间如果又手动选择了模型,以较新的选择为准。
90
90
 
91
91
  ### 配置角色模型与参数
92
92
 
@@ -100,7 +100,7 @@ DSMM 包含两处相互独立的配置区域:
100
100
 
101
101
  终端适配提供 `/dsmm` 操作菜单、简单设置和已保存方案的选择,不另做复杂配置编辑器。DSMM 必须加载在 TUI 实际使用的 profile 中,Desktop 中已安装的插件不会自动共用。
102
102
 
103
- 如果希望显式 DSMM 根预设按配置中的主模型和备用路由运行,可在 TUI 的部署配置中将 `rootModelPolicy` 设为 `configured`。它影响同一部署中的所有客户端,具名方案不能覆盖这个策略;其他独立部署默认仍使用原生模型选择。具体版本要求、配置范围和联调限制见 [TUI 使用说明](docs/tui.md)。
103
+ 在 `/dsmm profiles` 中应用方案默认保留当前主模型。要一起切换,请选择使用方案模型;之后仍可用 `/model` 改选。若希望新根会话从角色配置的主模型启动,可将部署的 `rootModelPolicy` 设为 `configured`。具体版本要求、配置范围和联调限制见 [TUI 使用说明](docs/tui.md)。
104
104
 
105
105
  ---
106
106
 
@@ -24,7 +24,7 @@ Core configuration and native permissions work without a session or active Deepw
24
24
 
25
25
  Global and exact native-profile saves are independent. Native form identity/revision and base/user provenance are required; no fallback Global write or cross-layer transaction is implied. Named documents, future-default pointers and actual admission remain separate. Desired saves don't change mounted capability or a running Agent's policy. Without a session, actual admission is unknown.
26
26
 
27
- Save and future-default selection remain available under their own authority. Native **Use profile model** and **Deepwork mode** have independent capabilities. Use profile model consumes the admitted configuration and respects newer native manual model/effort intent, including same-value reselection. With the default `rootModelPolicy: "native"`, root requests retain native assembled selection/defaults; refreshing an admission does not implicitly apply its profile primary or authorize a root fallback channel. Explicit deployment policy `configured` instead gives eligible admitted roots configuration-led primary/fallback routing. It applies equally to Web and TUI roots in that deployment, not by detecting a client; named profiles cannot override the policy. See [model routing](model-routing.md), [Profiles](profiles.md) and [settings/status](settings-status.md).
27
+ Save and future-default selection remain available under their own authority. Native **Use profile model** and **Deepwork mode** have independent capabilities. Use profile model consumes the admitted configuration and respects newer native manual model/effort intent, including same-value reselection. With the default `rootModelPolicy: "native"`, root requests retain native assembled selection/defaults; refreshing an admission does not implicitly apply its profile primary or authorize a root fallback channel. Explicit deployment policy `configured` gives eligible roots an initial primary/fallback route until the user selects a model. It applies equally to Web and TUI roots in that deployment, not by detecting a client; named profiles cannot override the policy. See [model routing](model-routing.md), [Profiles](profiles.md) and [settings/status](settings-status.md).
28
28
 
29
29
  Stores use separate CAS and atomic-write boundaries. Committed saves aren't rolled back in the response because observation/notification failed: report refresh-required or unsynchronized status. An unconfirmed native mutation requires authoritative reread before retry. Operator, connection and owner lifetime remain valid through precommit; client claims or loopback-looking URLs don't authorize writes.
30
30
 
@@ -34,7 +34,7 @@ Stores use separate CAS and atomic-write boundaries. Committed saves aren't roll
34
34
 
35
35
  DSMM runs identically on 0.2.1 and 0.2.2 Hosts except where 0.2.2 changed public contracts. Runtime capability detection (`agent.model.select` presence, provider-constructor shape) routes each surface; version strings are never consulted.
36
36
 
37
- - **Model selection is fixed before step preparation.** DSMM prepares the selection and request proposal together during admission and maintenance, keeping adapter defaults separate from explicit effort. Configured roots with an explicit primary reassert their admitted selection at public running/inbox boundaries; native roots retain native selection authority. A request that conflicts with its step's fixed provider/model/effort is rejected before dispatch, without scheduling another selection or dropping parameters. A picker change racing a running step can therefore produce a refusal; change models while idle for the next-turn boundary. Plugin metadata associates DSMM-written selections and child setup selections observed between native Session and Agent announcements with their exact events. These remain distinguishable on cold activation without treating setup as new manual intent. The records convey no authority, and same-value selections create no synthetic intent.
37
+ - **Model selection is fixed before step preparation.** A configured root can start on its profile primary. Applying another profile keeps the effective model, and a later native picker choice takes effect on the next step under either policy. A request that conflicts with its step's fixed provider/model/effort is rejected before dispatch, without scheduling another selection or dropping parameters. A picker change racing a running step can therefore produce a refusal; change models while idle for the next-turn boundary. Plugin metadata associates DSMM-written selections and child setup selections observed between native Session and Agent announcements with their exact events. These remain distinguishable on cold activation without treating setup as new manual intent. The records convey no authority, and same-value selections create no synthetic intent.
38
38
  - **Cross-route model fallback is unavailable on 0.2.2** (blocked): the request-error contract only allows same-selection retries, so `rate-limit-fallback` route switching degrades to a bounded same-route retry with a one-time diagnostic, and unavailable-route switching refuses outright. 0.2.1 behavior is unchanged. The native `dsh-llm-retry` extension coexists with DSMM's retry ownership.
39
39
  - **Idle session configuration switching uses current activity.** Completed or stopped roots can select a saved profile or the deployment baseline through native maintenance, including on Hosts without `subagents.list()`. Running resident descendants, observed pending work, queued input and conflicting maintenance still prevent switching. Provider registration alone does not disable the action. Existing children retain their captured configuration; the root's next request and new delegations use the selected configuration.
40
40
  - **Native tree publication precedes child admission on newer Hosts.** Child requests and tools wait for verified native publication. New delegation requires its exact live creator. Existing members keep the durable creator distinct from the live root that owns admission lifetime. A supported cold member with a complete own restriction ceiling can resume while its creator is absent; native catalog/provider identity, current configuration and captured limits remain required. Legacy records without this evidence retain exact-live-creator recovery.
@@ -9,13 +9,13 @@ DSMM supports the Host range declared in [compatibility](compatibility.md), incl
9
9
  `rootModelPolicy` is a deployment setting with two values:
10
10
 
11
11
  - **`native` (default):** roots retain native assembled provider/model/effort, including implicit defaults before the first `model/selection` event. Activating Deepwork, choosing a preset, saving/selecting a profile or refreshing a cold admission does not implicitly apply a root primary. **Use profile model** is the explicit native selection action against admitted configuration; later manual choices remain authoritative. Root retry preserves the native downstream configuration and does not automatically select a profile fallback channel.
12
- - **`configured`:** admitted roots with Deepwork enabled and an effective DSMM role use that role's configured primary and ordered fallback routes. Without an explicit primary, the initial route inherits the native baseline. Ordinary sessions with Deepwork mode off and no effective DSMM role retain native routing. Configuration does not grant a role, enable a disabled module or bypass native capability checks.
12
+ - **`configured`:** eligible roots with Deepwork enabled and an effective DSMM role can start on that role's configured primary and ordered fallback routes. Without an explicit primary, the initial route inherits the native baseline. Ordinary sessions with Deepwork mode off and no effective DSMM role retain native routing. Configuration does not grant a role, enable a disabled module or bypass native capability checks.
13
13
 
14
14
  Global and native-profile configuration may set this policy; named profiles cannot override it. Clearing a native-profile override restores inheritance from Global. The policy applies to the deployment, not to a detected client: a Web session in the same configured deployment follows it too. A separate Desktop deployment retains the default `native` behavior. Saving desired configuration does not replace an existing Agent's immutable admission; use the existing admission lifecycle to adopt changes.
15
15
 
16
- An explicit primary takes precedence over a picker selection; inherited routing still uses the native baseline. On DSH 0.2.1, configured routing changes the request without writing the picker. On DSH 0.2.2, the public `agent.model.select()` boundary makes the admitted route visible as the pending selection before preparation. Neither path writes the saved native model preference. Status distinguishes the admitted policy and actual route from a declared model.
16
+ Both policies respect subsequent native model and effort choices. Applying a profile to the current session or clearing its override preserves the effective model. To switch to the profile's primary, explicitly choose **Use profile model**. This selects it once; later turns follow the native picker. Selecting a future default leaves the current session unchanged.
17
17
 
18
- On 0.2.2, admission and maintenance prepare the selection before a request. Configured roots also bind their cached route on running/inbox boundaries, including the next turn after an idle picker change or mode activation. A running picker can race the next snapshot; a conflicting request then fails before dispatch rather than using an incorrect route. Request-time routing never schedules a deferred correction or removes route parameters to satisfy the Host check. Native roots continue to follow native selection.
18
+ On DSH 0.2.1, a configured initial route can differ from the native picker. On DSH 0.2.2 the initial route is visible through `agent.model.current()`. A step already in progress keeps its captured selection. On resume, a new selection supplied by the Host takes precedence over the saved session model. Status distinguishes a fresh native selection or the most recent request route from the profile's declared model.
19
19
 
20
20
  Selection/proposal effort is distinct from the effective adapter default. With passthrough OFF, a configured effort does not override defaults: the proposal can omit effort while `prepareCall` resolves the adapter's default for HTTP. Explicit native effort remains explicit. DSMM's plugin metadata associates only its own newly appended selection events with their exact routes; it is not admission or delegation authority.
21
21
 
package/docs/profiles.md CHANGED
@@ -21,7 +21,7 @@ The root and its resident descendants must have no running work, open turn, queu
21
21
 
22
22
  The compact Conversation header menu shows the current admission separately from the future default. **Use profile model** asks native model selection to use the admitted immutable configuration's declared main model, not a later saved draft. It doesn't write an overlay pointer or increment the admission epoch. Native model-default persistence follows the Models tab; newer manual model or effort intent, including same-value reselection, wins. `canSelectModel`, `canToggleMode` and `canApplyOverlay` have independent reasons: unavailable live Apply doesn't disable ordinary model selection or mode switching.
23
23
 
24
- `rootModelPolicy` is a separate deployment setting, not a named-profile field. The default `native` keeps the native model choice authoritative. With `configured`, an eligible root's requests use the effective role routing from its admitted configuration; applying a named profile can therefore change the next request's primary/fallback routes without changing the native model picker. Named profiles cannot turn this deployment policy on or off. A Web session and a TUI session in the same deployment follow the same policy. See [root routing policy](model-routing.md#root-policy-and-child-defaults).
24
+ `rootModelPolicy` is a separate deployment setting, not a named-profile field. The default `native` keeps the native model choice authoritative. With `configured`, eligible roots can start on the role's configured primary or a permitted fallback. Applying a profile keeps the current model unless the user explicitly selects the profile model. A later native model selection takes precedence under either policy. Named profiles cannot turn this deployment policy on or off. A Web session and a TUI session in the same deployment follow the same policy. See [root routing policy](model-routing.md#root-policy-and-child-defaults).
25
25
 
26
26
  Without a current session, choose a workspace and a saved profile or deployment defaults in the header menu or Settings session scope. Choosing a profile first keeps that choice pending until a workspace is explicitly selected. Browsing, refreshing and editing profiles do not create sessions, and the first workspace is never selected automatically. On explicit selection, the native workspace service creates or reuses a blank session; DSMM retains it, blocks sending while configuration is unconfirmed, completes the existing selection transaction and only then opens the confirmed session. This does not change the future default or native model.
27
27
 
@@ -35,7 +35,7 @@ Fallback decisions stay in the native request loop. DSMM doesn't create another
35
35
 
36
36
  An abortable middleware delay can honor valid `providerRetryAfterMs` only within per-delay and total budgets. Cancellation, owner/provider retirement, closed turn/step boundaries or superseded intent invalidate pending work before another dispatch. Duplicate errors can't reserve a second fallback.
37
37
 
38
- For native-root routing and child selection, native model selection, including same-value reselection, is new intent. Assembly captures that intent for the request; a concurrently newer selection belongs to the next assembly, not a retrofit. Child initial routes are defaults, not every-turn overrides of accepted native intent or valid fallback. A configured root's native picker intent does not override its explicit primary, expand configured fallback candidates or reset retry budgets. Existing Agents consume admitted policy, not later saved desired configuration. The same request decision captures admission, role, mode revision and policy before recovery preparation, and remains checked through provider awaits and retries. See [model routing](model-routing.md).
38
+ A new native model-selection event supersedes a pending retry on the old selection, including for roots with a configured startup route. The next step uses the new choice; a step already in flight keeps its captured model. Child initial routes remain defaults. Existing Agents consume admitted policy, not later saved desired configuration. The same request decision captures admission, role, mode revision and policy before recovery preparation, and remains checked through provider awaits and retries. See [model routing](model-routing.md).
39
39
 
40
40
  ## Live continuation and activation
41
41
 
@@ -36,7 +36,7 @@ On a mounted Host, desired-off affects new root admissions and cold role continu
36
36
 
37
37
  The inspector separates merged desired, startup-mounted/captured, next-root preview, and current-session admission. Without an actual session, current admission is unknown. Host bundle enablement also remains unknown when the public interface can't observe it. Sources, capture origins, global file version, native descriptor version and named snapshot reference aren't one acknowledgment.
38
38
 
39
- `rootModelPolicy` is deployment-only: Global and native-profile accept `native` (default) or `configured`; named overlays reject it. An explicit native-profile value overrides Global, and Unset restores inheritance. The policy is captured with admission rather than startup-pinned: saving changes desired configuration, not an existing Agent's captured policy. `configured` enables configuration-led routing for admitted roots with an effective DSMM role and Deepwork module enabled, regardless of whether their client is Web or TUI. It does not enable a module or grant a role. Status reports the captured value and its source only when admission is known; see [root routing policy](model-routing.md#root-policy-and-child-defaults).
39
+ `rootModelPolicy` is deployment-only: Global and native-profile accept `native` (default) or `configured`; named overlays reject it. An explicit native-profile value overrides Global, and Unset restores inheritance. The policy is captured with admission rather than startup-pinned: saving changes desired configuration, not an existing Agent's captured policy. `configured` supplies the initial role route for eligible roots on both Web and TUI. Applying a profile keeps the current model by default; both policies respect native model changes. It does not enable a module or grant a role. Status reports the captured value and its source only when admission is known; see [root routing policy](model-routing.md#root-policy-and-child-defaults).
40
40
 
41
41
  `presets` only carries materialization settings (`materialize`, optional `root`). The dispatcher is the only standing root; there is no per-role root switch, and named overlays cannot configure presets. See [roles and composition](agent-presets.md#roles-and-composition) for the selection roster, forced creation/resume and read-only boundaries.
42
42
 
package/docs/tui.md CHANGED
@@ -38,11 +38,13 @@ TUI 使用单一 `/dsmm` 入口,命令权限整体启用或撤销,不分别
38
38
  在 **TUI 的原生 profile** 中把 `rootModelPolicy` 设为 `configured`,并为有效角色配置 `primary` 和 `fallbackRoutes`。普通会话还需开启 Deepwork;配置本身不会打开已关闭的模块或赋予角色权限。
39
39
 
40
40
  - `native` 是默认值,保留 DSH 原生模型选择。
41
- - `configured` 让符合条件的根会话按已捕获配置路由,不需要在终端再调整模型。未设置 primary 时继承原生基础路由,不生成一个默认模型。
41
+ - `configured` 让符合条件的新根会话从角色的 `primary` 启动;未设置时沿用原生模型。两种策略都允许用 `/model` 改选,后续请求使用新选择。
42
42
  - 这是**部署策略**。同一部署中的 Web 会话也遵循它;独立 Desktop 部署保持默认值时不受影响。具名方案可以提供角色路由,但不能改变该策略。
43
43
  - 备用模型不是遇到任何错误都切换。仅允许既有规则认可的模型/服务商缺失或无输出限流等情况,并受重试预算限制。取消、凭据/权限/配额错误和已经产生部分输出的请求不会借此换模型重试。
44
44
 
45
- 路由不会修改原生模型选择器或 `Agent.options`。DSH 在请求路由前进行的历史图片能力检查等限制仍然存在;详见[模型路由](model-routing.md)和[兼容性说明](compatibility.md)。
45
+ 在 `/dsmm profiles` 中选择 **Apply to current session** 时,默认只应用方案并保留当前主模型。若要同时切换,请选择使用方案模型。切换只针对本次会话;后续仍可用 `/model` 改选。若 Host 未提供会话级选模接口,可先应用方案,再通过 `/model` 选模型。恢复部署基线及设置未来默认方案都不会切换当前模型。
46
+
47
+ DSH 在请求路由前进行的历史图片能力检查等限制仍然存在;详见[模型路由](model-routing.md)和[兼容性说明](compatibility.md)。
46
48
 
47
49
  ## 权限与验证边界
48
50
 
package/dsh-plugin.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifestVersion": "0.15",
4
4
  "id": "com.hugefiver.dsmm",
5
5
  "name": "DSMM",
6
- "version": "0.3.40",
6
+ "version": "0.3.41",
7
7
  "facets": {
8
8
  "host": {
9
9
  "entry": "lib/index.js",
@@ -91,7 +91,7 @@ export const deploymentZh = {
91
91
  };
92
92
  /** Stable public field names stay visible alongside localized context. */
93
93
  export const deploymentFieldLabels = {
94
- rootModelPolicy: ["Root model policy (native: user model; configured: admitted routes, all clients)", "根模型策略(native:用户模型;configured:准入路由,所有客户端)"],
94
+ rootModelPolicy: ["Initial root model (native: Host default; configured: role default)", "初始主模型(native:Host 默认;configured:角色默认)"],
95
95
  modelParameters: ["Model parameters", "模型参数"], passthrough: ["Model parameter passthrough", "模型参数透传"], locale: ["Agent business language", "Agent 业务语言"],
96
96
  permissionControl: ["Permission-control module", "权限控制子模块"],
97
97
  modules: ["Modules", "子模块"], skills: ["Skills", "技能"], roles: ["Agent roles", "Agent 角色"],
package/lib/client.js CHANGED
@@ -7016,7 +7016,7 @@ var deploymentZh = {
7016
7016
  namedIndependent: "设置中的 Deepwork Profiles 是独立的具名 JSONC 运行时资源编辑器。在此保存不会应用具名配置或选择其模型。"
7017
7017
  };
7018
7018
  var deploymentFieldLabels = {
7019
- rootModelPolicy: ["Root model policy (native: user model; configured: admitted routes, all clients)", "根模型策略(native:用户模型;configured:准入路由,所有客户端)"],
7019
+ rootModelPolicy: ["Initial root model (native: Host default; configured: role default)", "初始主模型(native:Host 默认;configured:角色默认)"],
7020
7020
  modelParameters: ["Model parameters", "模型参数"],
7021
7021
  passthrough: ["Model parameter passthrough", "模型参数透传"],
7022
7022
  locale: ["Agent business language", "Agent 业务语言"],
package/lib/index.js CHANGED
@@ -3,7 +3,7 @@ import { registerDsmmTuiAdapter } from "./tui-adapter.js";
3
3
  import { hasShellGuardConstraint, registerSafetyGuards } from "./guards.js";
4
4
  import { registerDeepworkPrompt } from "./mode.js";
5
5
  import { registerAgentSkills } from "./preset-skills.js";
6
- import { prepareAdmissionModelRoute, registerModelRouting } from "./model-routing.js";
6
+ import { installAdmissionModelRoute, registerModelRouting } from "./model-routing.js";
7
7
  import { bindCoreLlmAdmission } from "./role-llm-runtime.js";
8
8
  import { registerHeadlessRoleTools, registerNativeSubagentControls } from "./role-subagents.js";
9
9
  import { registerRolePresets } from "./preset-registry.js";
@@ -83,7 +83,7 @@ export async function apply(input, config = {}, startupOptions = {}) {
83
83
  lifetime.signal.throwIfAborted();
84
84
  admission = new NativeAdmission(ctx, profiles, policy, agents => { for (const agent of agents)
85
85
  commandApprovals.clearAgent(agent); });
86
- admission.bindAdmissionModelSelection((agent, info) => prepareAdmissionModelRoute(ctx, controller, agent, info));
86
+ admission.bindAdmissionModelSelection((agent, info) => installAdmissionModelRoute(ctx, controller, agent, info));
87
87
  ctx.provide("dsmmNativeAdmission", admission);
88
88
  ctx.provide("dsmmProfileRuntime", profiles);
89
89
  ctx.provide("dsmmDeploymentConfig", deployment);
@@ -1,7 +1,6 @@
1
- import type { AgentRequestFrame, DshLlmCallConfig, DshAgent, DshContext, DshModelSelection } from "./dsh-types.js";
1
+ import type { AgentRequestFrame, DshLlmCallConfig, DshAgent, DshContext } from "./dsh-types.js";
2
2
  import type { DsmmSettingsGetter, DsmmSettings, DsmmProfileAdmission } from "./settings.js";
3
3
  import type { DeepworkModeController } from "./state.js";
4
- import type { DsmmRoleId } from "./roles.js";
5
4
  export declare function prepareDsmmRequest(frame: AgentRequestFrame, proposal: DshLlmCallConfig, assertCurrent: () => void): Promise<DshLlmCallConfig>;
6
5
  export declare function registerModelRouting(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, agent?: DshAgent): void;
7
6
  export interface DsmmAdmissionRouteInfo {
@@ -11,17 +10,6 @@ export interface DsmmAdmissionRouteInfo {
11
10
  readonly signal: AbortSignal;
12
11
  assertCurrent(): void;
13
12
  }
14
- export interface DsmmAdmissionRouteInstallation {
15
- readonly selection: DshModelSelection;
16
- rollback(): void;
17
- }
18
- export interface DsmmPreparedAdmissionRoute {
19
- readonly admission?: DsmmProfileAdmission;
20
- readonly role: DsmmRoleId;
21
- readonly restoresConfiguredPrimary: boolean;
22
- readonly preflightFailure?: unknown;
23
- install(currentAdmission?: DsmmProfileAdmission): DsmmAdmissionRouteInstallation | undefined;
24
- }
25
- /** Preflight immutable route metadata without materializing adapter defaults as Agent selection. */
26
- export declare function prepareAdmissionModelRoute(ctx: DshContext, controller: DeepworkModeController, agent: DshAgent, info: DsmmAdmissionRouteInfo): Promise<DsmmPreparedAdmissionRoute | undefined>;
13
+ /** Fixed-step Hosts need the admitted initial selection before their first assembly. */
14
+ export declare function installAdmissionModelRoute(ctx: DshContext, controller: DeepworkModeController, agent: DshAgent, info: DsmmAdmissionRouteInfo): Promise<void>;
27
15
  //# sourceMappingURL=model-routing.d.ts.map
@@ -1,11 +1,11 @@
1
1
  import { LlmError } from "@deepseek-ai/dsh-llm";
2
2
  import { isDsmmAwareLlmRuntime } from "./host-llm.js";
3
- import { applyModelRoute, clearRoleRouteLock, currentRolePolicyState, currentRoleRouteLock, effectiveRoleFallbackRoutes, establishRolePolicy, hostModelSelection, latestModelSelectionSeq, latestNativeModelSelection, liveRolePolicyIdentity, nativeModelSelectionWasAccepted, orderedModelRoutes, persistedRoleRoute, pinRoleRoute, restoreRolePolicyAndLock, roleRouteLock, selectInitialModelRoute, selectInitialModelRouteChoice, selectModelRouteForNextStep, sameExactModelRoute, sameModelRoute, takeAdmittedRecoveryRoute } from "./role-routing.js";
3
+ import { applyModelRoute, clearRoleRouteLock, currentRoleRouteLock, effectiveRoleFallbackRoutes, establishRolePolicy, hasRecordedRolePolicy, hostModelSelection, latestNativeModelSelection, liveRolePolicyIdentity, nativeModelSelectionWasAccepted, orderedModelRoutes, persistedRoleRoute, pinRoleRoute, usesConfiguredRootRoute, roleRouteLock, selectInitialModelRoute, selectInitialModelRouteChoice, selectModelRouteForNextStep, sameExactModelRoute, sameModelRoute, takeAdmittedRecoveryRoute } from "./role-routing.js";
4
4
  import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
5
5
  import { isCurrentRecoveryStep } from "./recovery-policy.js";
6
6
  import { capturedRoleInvocation } from "./role-invocation.js";
7
7
  import { resolveAdmittedDsmmRole } from "./role-policy.js";
8
- import { modelRouteFromCall, modelRouteToCall, projectModelRouteParameters } from "./role-llm.js";
8
+ import { modelRouteFromCall, modelRouteFromHeader, modelRouteToCall, projectModelRouteParameters } from "./role-llm.js";
9
9
  import { configuredModelParameterPolicy, resolvedModelParameterPolicy } from "./model-parameter-policy.js";
10
10
  import { registerRuntimeRecovery } from "./runtime-recovery.js";
11
11
  import { captureRequestRouting, captureRequestRoute } from "./request-routing.js";
@@ -35,15 +35,20 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
35
35
  assembledSelections.set(context.agent, { signal: context.signal, intent: latestNativeModelSelection(context.agent) });
36
36
  return next();
37
37
  }, { prepend: true });
38
+ const stepSelection = (frame) => {
39
+ const captured = assembledSelections.get(frame.agent);
40
+ return captured?.signal === frame.signal ? captured.intent : frame.agent.session.header?.origin === "subagent" ? undefined : latestNativeModelSelection(frame.agent);
41
+ };
38
42
  const prepare = async (frame, proposal, assertCurrent = () => frame.signal.throwIfAborted()) => {
39
43
  if (frame.signal.aborted)
40
44
  return proposal;
41
- const decision = captureRequestRouting(frame, readyCtx, controller, getSettings, () => {
45
+ const manual = stepSelection(frame);
46
+ const decision = captureRequestRouting(frame, readyCtx, controller, getSettings, manual, () => {
42
47
  if (!active)
43
48
  throw new Error("DSMM routing owner retired");
44
49
  assertCurrent();
45
50
  });
46
- const downstream = recovery === undefined ? proposal : await recovery(frame, proposal);
51
+ let downstream = recovery === undefined ? proposal : await recovery(frame, proposal);
47
52
  if (frame.signal.aborted)
48
53
  return downstream;
49
54
  decision.assertCurrent();
@@ -70,16 +75,32 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
70
75
  assertFixedRoute(config, projected);
71
76
  return applyModelRoute(config, projected);
72
77
  };
78
+ const ordinaryRoot = frame.agent.session.header?.origin !== "subagent";
79
+ const requestTimeRoot = ordinaryRoot && hostModelSelection(frame.agent) === undefined;
80
+ let nativeBaseline;
81
+ // A request-time configured route leaves the Host baseline unchanged. Retain the
82
+ // actual header only while that baseline still owns assembly after Apply.
83
+ if (requestTimeRoot && admission !== undefined && admission.scope !== "global-default" && manual === undefined) {
84
+ const previous = currentRoleRouteLock(frame.agent), baseline = previous?.nativeBaseline;
85
+ const retainedPolicy = previous === undefined ? hasRecordedRolePolicy(frame.agent)
86
+ : baseline !== undefined && sameModelRoute(downstream, baseline) && downstream.reasoningEffort === baseline.reasoningEffort;
87
+ const header = retainedPolicy ? frame.agent.session.requestHeader?.() : undefined;
88
+ if (header !== undefined) {
89
+ nativeBaseline = { provider: downstream.provider, model: downstream.model, reasoningEffort: downstream.reasoningEffort };
90
+ const { provider, model, reasoningEffort } = modelRouteFromHeader(header);
91
+ const retained = { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) };
92
+ downstream = matchingRouteResult(downstream, retained, "native");
93
+ }
94
+ }
73
95
  if (!settings.modules.deepwork.enabled) {
74
96
  captureRequestRoute(frame, decision);
75
97
  return downstream;
76
98
  }
77
- const ordinaryRoot = frame.agent.session.header?.origin !== "subagent";
78
99
  const admitted = takeAdmittedRecoveryRoute(frame);
79
100
  const policy = role === undefined ? undefined : settings.roleRouting[role];
80
101
  const invocation = capturedRoleInvocation(frame.agent);
81
102
  const primary = invocation?.initialRoute ?? policy?.primary;
82
- const identity = await establishRolePolicy(frame, settings, role, readyCtx, admission?.epoch);
103
+ const identity = await establishRolePolicy(frame, settings, role, readyCtx, admission?.epoch, requestTimeRoot ? configuredRoot || nativeBaseline !== undefined : undefined);
83
104
  decision.assertCurrent();
84
105
  frame.signal.throwIfAborted();
85
106
  const fallbacks = effectiveRoleFallbackRoutes(settings, role);
@@ -93,8 +114,6 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
93
114
  let lock = roleRouteLock(frame.agent, identity);
94
115
  const exactPolicy = invocation === undefined ? primary !== undefined || policy?.fallbackRoutes !== undefined || fallbacks.length > 0
95
116
  : invocation.routeSource !== "inherited" || invocation.exactEffort || fallbacks.length > 0;
96
- const captured = assembledSelections.get(frame.agent);
97
- const manual = captured?.signal === frame.signal ? captured.intent : undefined;
98
117
  if (ordinaryRoot && !configuredRoot) {
99
118
  const selected = modelRouteFromCall(downstream);
100
119
  if (lock === undefined || !sameExactModelRoute(lock.route, selected) || lock.manualSelectionSeq !== manual?.seq) {
@@ -104,6 +123,7 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
104
123
  lock.generation = generation;
105
124
  lockedAgents.add(frame.agent);
106
125
  }
126
+ lock.nativeBaseline = nativeBaseline;
107
127
  captureRequestRoute(frame, decision, "native");
108
128
  return downstream;
109
129
  }
@@ -151,6 +171,8 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
151
171
  lock.startupSettled = true;
152
172
  lockedAgents.add(frame.agent);
153
173
  }
174
+ if (requestTimeRoot && configuredRoot)
175
+ lock.nativeBaseline = { provider: downstream.provider, model: downstream.model, reasoningEffort: downstream.reasoningEffort };
154
176
  captureRequestRoute(frame, decision, configuredRoot ? lock.effortSource : undefined);
155
177
  return lock.candidateIndex > 0
156
178
  ? replacementRouteResult(downstream, lock.route, lock.effortSource)
@@ -162,10 +184,9 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
162
184
  preparations.delete(agent); };
163
185
  disposeFence = readyCtx.on("agent/request", async (frame, next) => {
164
186
  const settings = getSettings(frame.agent), admission = getSettings.admission?.(frame.agent);
165
- const configuredRoot = admission !== undefined && frame.agent.session.header?.origin !== "subagent"
166
- && settings.modules.deepwork.enabled && settings.rootModelPolicy === "configured"
167
- && resolveAdmittedDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive)) !== undefined;
168
- const expected = configuredRoot && hostModelSelection(frame.agent) !== undefined ? currentRoleRouteLock(frame.agent) : undefined;
187
+ const role = resolveAdmittedDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive));
188
+ const expected = hostModelSelection(frame.agent) !== undefined && usesConfiguredRootRoute(frame.agent, settings, admission, role, stepSelection(frame))
189
+ ? currentRoleRouteLock(frame.agent) : undefined;
169
190
  const proposal = await next();
170
191
  if (expected !== undefined && (currentRoleRouteLock(frame.agent) !== expected || !sameModelRoute(proposal, expected.route)
171
192
  || proposal.reasoningEffort !== expected.route.reasoningEffort)) {
@@ -211,100 +232,47 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
211
232
  else if (Object.prototype.hasOwnProperty.call(ctx, "llm") && Object.prototype.hasOwnProperty.call(ctx, "on"))
212
233
  install(ctx);
213
234
  }
214
- /** Preflight immutable route metadata without materializing adapter defaults as Agent selection. */
215
- export async function prepareAdmissionModelRoute(ctx, controller, agent, info) {
216
- const model = hostModelSelection(agent), { settings } = info;
217
- if (model === undefined || !settings.modules.deepwork.enabled)
218
- return undefined;
235
+ /** Fixed-step Hosts need the admitted initial selection before their first assembly. */
236
+ export async function installAdmissionModelRoute(ctx, controller, agent, info) {
237
+ const { settings, admission } = info;
238
+ if (hostModelSelection(agent) === undefined || !settings.modules.deepwork.enabled)
239
+ return;
219
240
  const subagent = agent.session.header?.origin === "subagent";
220
- const configuredRoot = !subagent && settings.rootModelPolicy === "configured";
221
- if (!subagent && !configuredRoot)
222
- return undefined;
223
- const activeRole = resolveAdmittedDsmmRole(agent, settings, controller.active(agent, settings.defaultActive));
224
- const role = activeRole ?? (configuredRoot ? resolveAdmittedDsmmRole(agent, settings, true) : undefined);
225
- if (role === undefined)
226
- return undefined;
241
+ const role = resolveAdmittedDsmmRole(agent, settings, controller.active(agent, settings.defaultActive));
242
+ if (role === undefined || !subagent && !usesConfiguredRootRoute(agent, settings, admission, role, latestNativeModelSelection(agent)))
243
+ return;
227
244
  const parameterPolicy = info.admission === undefined ? configuredModelParameterPolicy(settings) : resolvedModelParameterPolicy(info.admission);
228
245
  const invocation = capturedRoleInvocation(agent);
229
246
  const fallbacks = effectiveRoleFallbackRoutes(settings, role);
230
247
  const primary = invocation?.initialRoute ?? settings.roleRouting[role]?.primary;
231
- if (configuredRoot && primary === undefined || subagent && invocation === undefined)
232
- return undefined;
248
+ if (primary === undefined || subagent && invocation === undefined)
249
+ return;
233
250
  const candidates = invocation?.candidates ?? orderedModelRoutes([primary, ...fallbacks]);
234
- let choice;
235
- let unavailable;
236
- try {
237
- if (configuredRoot) {
238
- const llm = agent.ctx?.get?.("llm") ?? ctx.get?.("llm") ?? ctx.llm;
239
- const resolver = parameterPolicy.mode === "passthrough" ? ctx.get?.("dsmmLlmRoutes") : undefined;
240
- choice = await selectInitialModelRouteChoice(llm ?? {}, candidates, info.signal, resolver, configuredRoot && parameterPolicy.mode === "native-defaults"
241
- ? route => modelRouteFromCall(projectModelRouteParameters(route, "dsmm-config", false))
242
- : undefined, info.assertCurrent);
251
+ let proposal = primary, requested = invocation?.selectedCandidate;
252
+ if (!subagent) {
253
+ const llm = agent.ctx?.get?.("llm") ?? ctx.get?.("llm") ?? ctx.llm;
254
+ const resolver = parameterPolicy.mode === "passthrough" ? ctx.get?.("dsmmLlmRoutes") : undefined;
255
+ try {
256
+ const choice = await selectInitialModelRouteChoice(llm ?? {}, candidates, info.signal, resolver, parameterPolicy.mode === "native-defaults" ? route => modelRouteFromCall(projectModelRouteParameters(route, "dsmm-config", false)) : undefined, info.assertCurrent);
257
+ proposal = choice.proposal;
258
+ requested = choice.requestedRoute;
243
259
  }
244
- }
245
- catch (error) {
246
- if (!configuredRoot || activeRole !== undefined)
260
+ catch (error) {
261
+ info.assertCurrent();
262
+ info.signal.throwIfAborted();
263
+ if (latestNativeModelSelection(agent) !== undefined)
264
+ return;
247
265
  throw error;
248
- unavailable = error;
266
+ }
267
+ if (latestNativeModelSelection(agent) !== undefined)
268
+ return;
249
269
  }
250
270
  info.assertCurrent();
251
271
  info.signal.throwIfAborted();
252
- const proposal = choice?.proposal ?? invocation?.initialRoute;
253
- const requested = choice?.requestedRoute ?? invocation?.selectedCandidate;
254
- const effortSource = configuredRoot ? "dsmm-config" : invocation?.effortSource ?? "dsmm-config";
255
- const prepared = Object.freeze({ admission: info.admission, role,
256
- restoresConfiguredPrimary: configuredRoot && primary !== undefined,
257
- ...(unavailable === undefined ? {} : { preflightFailure: unavailable }),
258
- install(currentAdmission) {
259
- if (currentAdmission !== info.admission)
260
- return undefined;
261
- const currentRole = resolveAdmittedDsmmRole(agent, settings, controller.active(agent, settings.defaultActive));
262
- if (currentRole !== role)
263
- return undefined;
264
- if (unavailable !== undefined)
265
- throw unavailable;
266
- if (proposal === undefined)
267
- return undefined;
268
- const previousPolicy = currentRolePolicyState(agent), previousLock = currentRoleRouteLock(agent), previousSelection = model.current();
269
- const identity = liveRolePolicyIdentity(agent, settings, role, info.epoch);
270
- if (identity === undefined)
271
- return undefined;
272
- const installedPolicy = currentRolePolicyState(agent);
273
- let lock = roleRouteLock(agent, identity);
274
- if (lock === undefined || !sameExactModelRoute(lock.route, proposal)) {
275
- lock = pinRoleRoute(agent, identity, proposal, candidates, { preserveCandidates: parameterPolicy.mode === "native-defaults",
276
- initialCandidate: requested });
277
- }
278
- lock.effortSource = effortSource;
279
- const selection = { provider: proposal.provider, model: proposal.model,
280
- ...(proposal.reasoningEffort === undefined ? {} : { reasoningEffort: proposal.reasoningEffort }) };
281
- selectModelRouteForNextStep(agent, selection);
282
- const installedSelectionSeq = latestModelSelectionSeq(agent);
283
- let rolledBack = false;
284
- return Object.freeze({ selection, rollback() {
285
- if (rolledBack)
286
- return;
287
- rolledBack = true;
288
- const current = model.current();
289
- let selectionFailure;
290
- try {
291
- if (current !== undefined && latestModelSelectionSeq(agent) === installedSelectionSeq && sameExactModelRoute(current, selection)) {
292
- if (previousSelection === undefined)
293
- throw new LlmError("The prior model selection cannot be restored", "INVALID_PREPARED_CALL");
294
- selectModelRouteForNextStep(agent, previousSelection);
295
- }
296
- }
297
- catch (error) {
298
- selectionFailure = error;
299
- }
300
- finally {
301
- restoreRolePolicyAndLock(agent, installedPolicy, lock, previousPolicy, previousLock);
302
- }
303
- if (selectionFailure !== undefined)
304
- throw selectionFailure;
305
- } });
306
- },
307
- });
308
- return prepared;
272
+ const identity = liveRolePolicyIdentity(agent, settings, role, info.epoch);
273
+ const lock = pinRoleRoute(agent, identity, proposal, candidates, { preserveCandidates: parameterPolicy.mode === "native-defaults", initialCandidate: requested });
274
+ lock.effortSource = invocation?.effortSource ?? "dsmm-config";
275
+ selectModelRouteForNextStep(agent, { provider: proposal.provider, model: proposal.model,
276
+ ...(proposal.reasoningEffort === undefined ? {} : { reasoningEffort: proposal.reasoningEffort }) });
309
277
  }
310
278
  //# sourceMappingURL=model-routing.js.map
@@ -3,7 +3,7 @@ import type { Agent } from "@deepseek-ai/dsh-agent";
3
3
  import { SessionId } from "@deepseek-ai/dsh-session";
4
4
  import type { SubagentProvider, SubagentActivation, ContinuableCreateRequest } from "@deepseek-ai/dsh-subagent";
5
5
  import type { ToolExecution } from "@deepseek-ai/dsh-tools";
6
- import type { DsmmAdmissionRouteInfo, DsmmPreparedAdmissionRoute } from "./model-routing.js";
6
+ import type { DsmmAdmissionRouteInfo } from "./model-routing.js";
7
7
  import type { DsmmProfileRuntime } from "./profile-runtime.js";
8
8
  import type { DsmmProfileAdmission } from "./settings.js";
9
9
  import type { ResolvedRoleInvocation } from "./role-invocation.js";
@@ -52,8 +52,6 @@ export declare class NativeAdmission {
52
52
  private readonly nativeToolExecution;
53
53
  private readonly observedCallRuns;
54
54
  private readonly callSubscribers;
55
- private readonly admissionRoutes;
56
- private readonly admissionRouteFailures;
57
55
  private readonly setupSelectionCursors;
58
56
  private ready;
59
57
  private readonly scopes;
@@ -62,8 +60,7 @@ export declare class NativeAdmission {
62
60
  constructor(ctx: Context, profiles: DsmmProfileRuntime, policy: DsmmRolePolicy, configurationCommitted?: (agents: readonly Agent[]) => void);
63
61
  activate(install: NonNullable<NativeAdmission["install"]>): void;
64
62
  restoreResidentRoots(): Promise<void>;
65
- /** Bind asynchronous metadata preparation; later lifecycle callbacks only install its immutable result. */
66
- bindAdmissionModelSelection(hook: (agent: Agent, info: DsmmAdmissionRouteInfo) => Promise<DsmmPreparedAdmissionRoute | undefined>): void;
63
+ bindAdmissionModelSelection(hook: (agent: Agent, info: DsmmAdmissionRouteInfo) => Promise<void>): void;
67
64
  private callsFor;
68
65
  private recordsFor;
69
66
  private observationRoute;
@@ -85,8 +82,6 @@ export declare class NativeAdmission {
85
82
  private retireObservedParent;
86
83
  observeRoleCalls(parent: Agent, admission: DsmmProfileAdmission, signal: AbortSignal, check: () => void): AsyncIterable<RoleCallObservationFrame>;
87
84
  private notifyObservedParent;
88
- private installCachedAdmissionRoute;
89
- private installCachedAdmissionRouteSafely;
90
85
  get isReady(): boolean;
91
86
  /** Exact process-local capture, retained after retirement so stale objects never become native. */
92
87
  owns(agent: Agent): boolean;
@@ -95,8 +95,6 @@ export class NativeAdmission {
95
95
  nativeToolExecution = new AsyncLocalStorage();
96
96
  observedCallRuns = new Map();
97
97
  callSubscribers = new Set();
98
- admissionRoutes = new WeakMap();
99
- admissionRouteFailures = new WeakMap();
100
98
  setupSelectionCursors = new WeakMap();
101
99
  ready = false;
102
100
  scopes = new Map();
@@ -141,37 +139,15 @@ export class NativeAdmission {
141
139
  else
142
140
  await this.created(frame.agent, frame.source, frame.signal);
143
141
  }, { global: true, prepend: true });
144
- ctx.on("agent/status", ({ agent, status }) => { if (status === "running")
145
- this.installCachedAdmissionRouteSafely(agent); }, { global: true });
146
- ctx.on("agent/inbox/claimed", ({ agent }) => { this.installCachedAdmissionRouteSafely(agent); }, { global: true });
147
142
  ctx.on("session/event", (session, event) => {
148
143
  if (event.type === "request/header")
149
144
  this.observeCallRequestHeader(session, event.data.header.config);
150
- if (event.type !== "model/selection")
151
- return;
152
- const agent = this.ctx.agents.get(session.id), cache = agent === undefined ? undefined : this.admissionRoutes.get(agent);
153
- if (agent === undefined || agent.session !== session || cache?.candidate?.restoresConfiguredPrimary !== true)
154
- return;
155
- queueMicrotask(() => {
156
- try {
157
- if (this.lifetime.signal.aborted || this.agentLifetimes.get(agent)?.signal.aborted || this.selecting.has(agent)
158
- || this.admissionRoutes.get(agent) !== cache)
159
- return;
160
- this.installCachedAdmissionRouteSafely(agent, cache);
161
- }
162
- catch (error) {
163
- if (this.admissionRoutes.get(agent) === cache)
164
- this.admissionRouteFailures.set(agent, { cache, error });
165
- }
166
- });
167
145
  }, { global: true });
168
146
  ctx.on("agent/disposed", ({ agent }) => {
169
147
  void this.retireAgent(agent).catch(() => { });
170
148
  this.retireObservedParent(agent);
171
149
  this.live.delete(agent);
172
150
  this.candidates.delete(agent);
173
- this.admissionRoutes.delete(agent);
174
- this.admissionRouteFailures.delete(agent);
175
151
  this.agents.delete(agent);
176
152
  for (const activation of this.activations)
177
153
  if (activation.childId === agent.id)
@@ -251,7 +227,6 @@ export class NativeAdmission {
251
227
  }
252
228
  }));
253
229
  }
254
- /** Bind asynchronous metadata preparation; later lifecycle callbacks only install its immutable result. */
255
230
  bindAdmissionModelSelection(hook) {
256
231
  this.admissionModelSelection = hook;
257
232
  }
@@ -593,25 +568,6 @@ export class NativeAdmission {
593
568
  if (subscriber.parent === parent)
594
569
  subscriber.notify();
595
570
  }
596
- installCachedAdmissionRoute(agent, expected) {
597
- const cache = expected ?? this.admissionRoutes.get(agent), live = this.live.get(agent);
598
- if (cache === undefined || cache !== this.admissionRoutes.get(agent) || live === undefined || this.failedInstallations.has(agent)
599
- || !this.isReady || this.ctx.agents.get(agent.id) !== agent || this.agentLifetimes.get(agent)?.signal.aborted)
600
- return undefined;
601
- return cache.candidate?.install(live.admission);
602
- }
603
- installCachedAdmissionRouteSafely(agent, expected) {
604
- const cache = expected ?? this.admissionRoutes.get(agent);
605
- if (cache?.candidate?.restoresConfiguredPrimary !== true || this.admissionRouteFailures.get(agent)?.cache === cache)
606
- return;
607
- try {
608
- this.installCachedAdmissionRoute(agent, cache);
609
- }
610
- catch (error) {
611
- if (this.admissionRoutes.get(agent) === cache)
612
- this.admissionRouteFailures.set(agent, { cache, error });
613
- }
614
- }
615
571
  get isReady() {
616
572
  const current = this.ctx.get("dsmmNativeAdmission");
617
573
  return this.ready && !this.lifetime.signal.aborted && current !== undefined && original(current) === original(this);
@@ -674,10 +630,6 @@ export class NativeAdmission {
674
630
  throw new SubagentError("Session configuration maintenance is in progress", "UNAUTHORIZED");
675
631
  if (!this.isReady || !live || this.ctx.agents.get(agent.id) !== agent)
676
632
  throw new SubagentError("No trusted live admission; create a new session", "UNAUTHORIZED");
677
- const routeFailure = this.admissionRouteFailures.get(agent);
678
- if (routeFailure !== undefined && routeFailure.cache === this.admissionRoutes.get(agent)) {
679
- throw new SubagentError("Configured model selection installation failed; create a new session", "UNAUTHORIZED");
680
- }
681
633
  if (this.ctx.get("sessions")?.get(agent.id) !== agent.session || agent.session.id !== agent.id || agent.session.header.id !== agent.id
682
634
  || scopeOf(agent.ctx) !== agent || original(agent.ctx.get("agents")) !== original(this.ctx.agents)
683
635
  || live.dependencies && this.dependencies(agent).some((value, index) => value !== live.dependencies[index])
@@ -766,8 +718,6 @@ export class NativeAdmission {
766
718
  }
767
719
  let prepared = false, committed = false;
768
720
  let publication;
769
- const previousRouteCache = this.admissionRoutes.get(agent), previousRouteFailure = this.admissionRouteFailures.get(agent);
770
- let installedRouteCache, routeInstallation;
771
721
  let providers = new Map();
772
722
  const assertCurrent = () => {
773
723
  assertAuthority();
@@ -802,21 +752,7 @@ export class NativeAdmission {
802
752
  }));
803
753
  });
804
754
  assertCurrent();
805
- const candidate = await this.admissionModelSelection?.(agent, { settings: admission.settings, epoch: admission.epoch,
806
- admission, signal: preparationSignal, assertCurrent });
807
- assertCurrent();
808
755
  prepared = true;
809
- installedRouteCache = Object.freeze({ candidate });
810
- this.admissionRoutes.set(agent, installedRouteCache);
811
- this.admissionRouteFailures.delete(agent);
812
- try {
813
- routeInstallation = candidate?.install(admission);
814
- }
815
- catch (error) {
816
- if (candidate?.preflightFailure !== error)
817
- this.failedInstallations.add(agent);
818
- throw error;
819
- }
820
756
  await install(admission);
821
757
  assertCurrent();
822
758
  this.installing.run({ agent, admission }, describe);
@@ -826,38 +762,16 @@ export class NativeAdmission {
826
762
  close: async () => {
827
763
  try {
828
764
  if (prepared && !committed) {
829
- const errors = [];
830
- const canRestore = this.ctx.agents.get(agent.id) === agent && !this.lifetime.signal.aborted;
831
- if (canRestore) {
765
+ if (this.ctx.agents.get(agent.id) === agent && !this.lifetime.signal.aborted)
832
766
  try {
833
767
  await install(previous.admission);
834
768
  }
835
769
  catch (error) {
836
- errors.push(error);
770
+ this.failedInstallations.add(agent);
771
+ const refusal = new DsmmProfileError("activation", "Session configuration restoration failed. Execution is disabled; create a new session.");
772
+ refusal.cause = error;
773
+ throw refusal;
837
774
  }
838
- try {
839
- routeInstallation?.rollback();
840
- }
841
- catch (error) {
842
- errors.push(error);
843
- }
844
- }
845
- if (installedRouteCache !== undefined && this.admissionRoutes.get(agent) === installedRouteCache) {
846
- if (previousRouteCache === undefined)
847
- this.admissionRoutes.delete(agent);
848
- else
849
- this.admissionRoutes.set(agent, previousRouteCache);
850
- if (previousRouteFailure !== undefined && previousRouteFailure.cache === previousRouteCache)
851
- this.admissionRouteFailures.set(agent, previousRouteFailure);
852
- else
853
- this.admissionRouteFailures.delete(agent);
854
- }
855
- if (errors.length > 0) {
856
- this.failedInstallations.add(agent);
857
- const refusal = new DsmmProfileError("activation", "Session configuration restoration failed. Execution is disabled; create a new session.");
858
- refusal.cause = errors.length === 1 ? errors[0] : new AggregateError(errors, "Session configuration restoration failed");
859
- throw refusal;
860
- }
861
775
  }
862
776
  }
863
777
  finally {
@@ -1110,8 +1024,6 @@ export class NativeAdmission {
1110
1024
  this.scopes.delete(agent);
1111
1025
  this.live.delete(agent);
1112
1026
  this.candidates.delete(agent);
1113
- this.admissionRoutes.delete(agent);
1114
- this.admissionRouteFailures.delete(agent);
1115
1027
  this.agents.delete(agent);
1116
1028
  this.profiles.release(agent);
1117
1029
  this.policy.release(agent);
@@ -1279,15 +1191,10 @@ export class NativeAdmission {
1279
1191
  this.check(pending);
1280
1192
  if (continuationProvider && this.ctx.get("subagents").getProvider(continuationProvider.name) !== continuationProvider)
1281
1193
  throw new SubagentError("Role provider changed", "UNAUTHORIZED");
1282
- const routeCandidate = await this.admissionModelSelection?.(agent, {
1194
+ await this.admissionModelSelection?.(agent, {
1283
1195
  settings: admission.settings, epoch: admission.epoch, admission, signal, assertCurrent: check,
1284
1196
  });
1285
1197
  check();
1286
- const routeCache = Object.freeze({ candidate: routeCandidate });
1287
- this.admissionRoutes.set(agent, routeCache);
1288
- this.admissionRouteFailures.delete(agent);
1289
- routeCandidate?.install(admission);
1290
- check();
1291
1198
  this.profiles.publish(agent, admission);
1292
1199
  const published = this.profiles.admission(agent);
1293
1200
  this.live.set(agent, Object.freeze({ admission: published, preset, scopeParent: scopeParentOf(agent), parent, owner, creatorId: agent.session.header.parentSession,
@@ -1300,8 +1207,6 @@ export class NativeAdmission {
1300
1207
  }
1301
1208
  catch (error) {
1302
1209
  this.failedInstallations.add(agent);
1303
- this.admissionRoutes.delete(agent);
1304
- this.admissionRouteFailures.delete(agent);
1305
1210
  this.policy.release(agent);
1306
1211
  await scope.fiber.dispose();
1307
1212
  throw error;
@@ -208,7 +208,7 @@ export class DsmmProfileRuntime {
208
208
  const profileModel = role === undefined ? undefined : admitted.settings.roleRouting[role]?.primary;
209
209
  const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
210
210
  return { sessionId: agent.id, globalDefault: this.observedSelection(this.current), selection: selectionState(disk), admittedSelection: this.observedSelection(admitted), scope: admitted.scope,
211
- rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), deepwork,
211
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted)), deepwork,
212
212
  modules: projectDsmmModules(this.baseline, admitted.deployment, admitted, false, this.options.getMountedPermission), configuration: deploymentAdmissionView(admitted),
213
213
  warnings: structuredClone(admitted.warnings ?? []), roles: structuredClone(admitted.roleAvailability ?? []), subagentRuntime: this.runtimeView(),
214
214
  ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }), admissionEpoch: admitted.epoch,
@@ -247,7 +247,7 @@ export class DsmmProfileRuntime {
247
247
  const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
248
248
  const { profileModel: _previous, selectModelUnavailableReason: _modelReason, toggleModeUnavailableReason: _modeReason, applyOverlayUnavailableReason: _overlayReason, ...snapshot } = before;
249
249
  return { ...snapshot, deepwork, ...this.sessionActions(agent, admitted, deepwork, profileModel !== undefined),
250
- rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }) };
250
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted)), ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }) };
251
251
  });
252
252
  }
253
253
  catch (error) {
@@ -3,6 +3,7 @@ import type { DsmmSettingsGetter } from "./settings.js";
3
3
  import type { DeepworkModeController } from "./state.js";
4
4
  import type { DsmmEffortSource } from "./host-llm.js";
5
5
  import { resolveAdmittedDsmmRole } from "./role-policy.js";
6
+ import { type NativeModelSelectionIntent } from "./role-routing.js";
6
7
  /** Shared by selection, recovery and the native prepared-call owner. */
7
8
  export interface DsmmRequestRoutingDecision {
8
9
  readonly frame: AgentRequestFrame;
@@ -21,7 +22,7 @@ declare const results: WeakMap<AgentRequestFrame, {
21
22
  }>;
22
23
  export declare function currentRequestRouting(agent: DshAgent): DsmmRequestRoutingDecision | undefined;
23
24
  export declare function preparedRequestRouting(frame: AgentRequestFrame): ReturnType<typeof results.get>;
24
- export declare function captureRequestRouting(frame: AgentRequestFrame, ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, assertOwner: () => void): DsmmRequestRoutingDecision;
25
+ export declare function captureRequestRouting(frame: AgentRequestFrame, ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, manual: NativeModelSelectionIntent | undefined, assertOwner: () => void): DsmmRequestRoutingDecision;
25
26
  export declare function captureRequestRoute(frame: AgentRequestFrame, decision: DsmmRequestRoutingDecision, effortSource?: DsmmEffortSource): void;
26
27
  export {};
27
28
  //# sourceMappingURL=request-routing.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { resolveAdmittedDsmmRole } from "./role-policy.js";
2
- import { liveRolePolicyIdentity, roleRouteLock } from "./role-routing.js";
2
+ import { liveRolePolicyIdentity, roleRouteLock, usesConfiguredRootRoute } from "./role-routing.js";
3
3
  import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
4
4
  import { isCurrentRecoveryStep } from "./recovery-policy.js";
5
5
  const decisions = new WeakMap();
@@ -7,7 +7,7 @@ const routeAssertions = new WeakMap();
7
7
  const results = new WeakMap();
8
8
  export function currentRequestRouting(agent) { return decisions.get(agent); }
9
9
  export function preparedRequestRouting(frame) { return results.get(frame); }
10
- export function captureRequestRouting(frame, ctx, controller, getSettings, assertOwner) {
10
+ export function captureRequestRouting(frame, ctx, controller, getSettings, manual, assertOwner) {
11
11
  const settings = getSettings(frame.agent), admission = getSettings.admission?.(frame.agent);
12
12
  const role = settings.modules.deepwork.enabled
13
13
  ? resolveAdmittedDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive)) : undefined;
@@ -19,8 +19,7 @@ export function captureRequestRouting(frame, ctx, controller, getSettings, asser
19
19
  const events = () => captured.agent.session.header?.origin === "subagent" ? childOwnedSessionEvents(captured.agent.session) : sessionEvents(captured.agent.session);
20
20
  const currentStep = isCurrentRecoveryStep(events(), captured.turn, captured.step);
21
21
  const decision = Object.freeze({ frame: captured, settings, admission, role, policy,
22
- configuredRoot: captured.agent.session.header?.origin !== "subagent" && admission !== undefined
23
- && admission.settings === settings && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined,
22
+ configuredRoot: usesConfiguredRootRoute(captured.agent, settings, admission, role, manual),
24
23
  assertPolicyCurrent() {
25
24
  assertOwner();
26
25
  captured.signal.throwIfAborted();
@@ -1,12 +1,8 @@
1
- import type { AgentRequestFrame, DshAgent, DshAgentModel, DshContext, DshLlmCallConfig, DshLlmRuntime } from "./dsh-types.js";
1
+ import type { AgentRequestFrame, DshAgent, DshAgentModel, DshContext, DshLlmCallConfig, DshLlmRuntime, DshModelSelection } from "./dsh-types.js";
2
2
  import type { DsmmRoleId } from "./roles.js";
3
- import type { DsmmModelRoute, DsmmSettings } from "./settings.js";
3
+ import type { DsmmModelRoute, DsmmProfileAdmission, DsmmSettings } from "./settings.js";
4
4
  import type { DsmmRoleRuntimeState } from "./profile-types.js";
5
5
  import type { DsmmLlmRouteResolver } from "./role-llm.js";
6
- export interface RolePolicyState {
7
- readonly fields: unknown;
8
- readonly identity: string;
9
- }
10
6
  export declare const DSMM_ROLE_POLICY_EVENT = "dsmm/role-policy";
11
7
  export interface RoleRouteLock {
12
8
  identity: string;
@@ -21,6 +17,7 @@ export interface RoleRouteLock {
21
17
  switches: number;
22
18
  totalDelayMs: number;
23
19
  manualSelectionSeq?: number;
20
+ nativeBaseline?: DshModelSelection;
24
21
  effortSource?: "native" | "dsmm-config";
25
22
  }
26
23
  export interface NativeModelSelectionIntent {
@@ -61,12 +58,13 @@ export declare function pinRoleRoute(agent: DshAgent, identity: string, route: D
61
58
  }): RoleRouteLock;
62
59
  export declare function clearRoleRouteLock(agent: DshAgent): void;
63
60
  export declare function currentRoleRouteLock(agent: DshAgent): RoleRouteLock | undefined;
64
- export declare function currentRolePolicyState(agent: DshAgent): RolePolicyState | undefined;
65
- export declare function restoreRolePolicyAndLock(agent: DshAgent, installedPolicy: RolePolicyState, installedLock: RoleRouteLock, previousPolicy: RolePolicyState | undefined, previousLock: RoleRouteLock | undefined): boolean;
66
- export declare function roleRouteRuntimeState(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): DsmmRoleRuntimeState;
61
+ export declare function usesConfiguredRootRoute(agent: DshAgent, settings: DsmmSettings, admission: DsmmProfileAdmission | undefined, role: DsmmRoleId | undefined, manual: NativeModelSelectionIntent | undefined): boolean;
62
+ export declare function observedRootModel(agent: DshAgent, manual: NativeModelSelectionIntent | undefined): DsmmModelRoute | undefined;
63
+ export declare function roleRouteRuntimeState(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, admission?: DsmmProfileAdmission): DsmmRoleRuntimeState;
67
64
  export declare function liveRolePolicyIdentity(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): string | undefined;
65
+ export declare function hasRecordedRolePolicy(agent: DshAgent): boolean;
68
66
  /** Native custom events are model-hidden log facts, retained across surface compaction. */
69
- export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined, _ctx?: DshContext, epoch?: string): Promise<string | undefined>;
67
+ export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined, _ctx?: DshContext, epoch?: string, ownsRoute?: boolean): Promise<string | undefined>;
70
68
  export declare function recordAdmittedRecoveryRoute(frame: AgentRequestFrame, route: DsmmModelRoute): void;
71
69
  export declare function takeAdmittedRecoveryRoute(frame: AgentRequestFrame): DsmmModelRoute | undefined;
72
70
  export declare function effectiveRoleFallbackRoutes(settings: DsmmSettings, role: DsmmRoleId | undefined): readonly DsmmModelRoute[];
@@ -196,26 +196,35 @@ export function pinRoleRoute(agent, identity, route, candidates, projection) {
196
196
  }
197
197
  export function clearRoleRouteLock(agent) { routeLocks.delete(agent); }
198
198
  export function currentRoleRouteLock(agent) { return routeLocks.get(agent); }
199
- export function currentRolePolicyState(agent) { return agentPolicies.get(agent); }
200
- export function restoreRolePolicyAndLock(agent, installedPolicy, installedLock, previousPolicy, previousLock) {
201
- if (agentPolicies.get(agent) !== installedPolicy || routeLocks.get(agent) !== installedLock)
202
- return false;
203
- if (previousPolicy === undefined)
204
- agentPolicies.delete(agent);
205
- else
206
- agentPolicies.set(agent, previousPolicy);
207
- if (previousLock === undefined)
208
- routeLocks.delete(agent);
209
- else
210
- routeLocks.set(agent, previousLock);
211
- return true;
212
- }
213
- export function roleRouteRuntimeState(agent, settings, role, epoch) {
199
+ export function usesConfiguredRootRoute(agent, settings, admission, role, manual) {
200
+ return agent.session.header?.origin !== "subagent" && admission?.scope === "global-default" && admission.settings === settings
201
+ && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined && manual === undefined;
202
+ }
203
+ export function observedRootModel(agent, manual) {
204
+ const header = agent.session.requestHeader?.();
205
+ if (manual !== undefined && !sessionEvents(agent.session).some(event => event.type === "request/header" && Number(event.seq) > manual.seq))
206
+ return manual.route;
207
+ if (header !== undefined) {
208
+ const config = header.config;
209
+ if (typeof config?.provider !== "string" || typeof config.model !== "string")
210
+ return undefined;
211
+ return { provider: config.provider, model: config.model,
212
+ ...(typeof config.reasoningEffort === "string" ? { reasoningEffort: config.reasoningEffort } : {}) };
213
+ }
214
+ const current = hostModelSelection(agent)?.current();
215
+ return current === undefined ? undefined : { ...current };
216
+ }
217
+ export function roleRouteRuntimeState(agent, settings, role, admission) {
214
218
  const resolved = resolveRoleRuntimePolicy(settings, role);
215
- const identity = liveRolePolicyIdentity(agent, settings, role, epoch);
216
- const lock = identity === undefined ? undefined : roleRouteLock(agent, identity);
217
- return { ...(role === undefined ? {} : { role }), strategy: agent.session.header?.origin === "subagent" || epoch !== undefined && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined ? resolved.strategy : "startup-lock", rateLimit: { ...resolved.rateLimit },
218
- ...(lock === undefined ? {} : { route: { ...lock.route } }), retries: lock?.retries ?? 0,
219
+ const policy = agentPolicies.get(agent);
220
+ const current = policy !== undefined && policy.fields.role === role && policy.fields.epoch === admission?.epoch ? roleRouteLock(agent, policy.identity) : undefined;
221
+ const child = agent.session.header?.origin === "subagent";
222
+ const manual = child ? undefined : latestNativeModelSelection(agent);
223
+ const lock = !child && manual?.seq !== current?.manualSelectionSeq ? undefined : current;
224
+ const configured = usesConfiguredRootRoute(agent, settings, admission, role, manual);
225
+ const route = child || configured ? lock?.route : observedRootModel(agent, manual) ?? lock?.route;
226
+ return { ...(role === undefined ? {} : { role }), strategy: child || configured ? resolved.strategy : "startup-lock", rateLimit: { ...resolved.rateLimit },
227
+ ...(route === undefined ? {} : { route: { ...route } }), retries: lock?.retries ?? 0,
219
228
  rateLimitFailures: lock?.rateLimits ?? 0, switches: lock?.switches ?? 0, totalDelayMs: lock?.totalDelayMs ?? 0 };
220
229
  }
221
230
  export function liveRolePolicyIdentity(agent, settings, role, epoch) {
@@ -263,10 +272,21 @@ function readPolicyMarker(event) {
263
272
  }
264
273
  return { role: data.role, policy: data.policy };
265
274
  }
275
+ export function hasRecordedRolePolicy(agent) {
276
+ const events = policyEvents({ agent });
277
+ for (let index = events.length - 1; index >= 0; index--) {
278
+ const event = events[index];
279
+ if (isPresetBoundary({ agent }, event))
280
+ return false;
281
+ if (event.type === DSMM_ROLE_POLICY_EVENT)
282
+ return readPolicyMarker(event)?.policy != null;
283
+ }
284
+ return false;
285
+ }
266
286
  /** Native custom events are model-hidden log facts, retained across surface compaction. */
267
- export async function establishRolePolicy(frame, settings, role, _ctx, epoch) {
287
+ export async function establishRolePolicy(frame, settings, role, _ctx, epoch, ownsRoute) {
268
288
  const identity = liveRolePolicyIdentity(frame.agent, settings, role, epoch);
269
- const declared = role !== undefined && (Object.keys(settings.roleRouting[role] ?? {}).length > 0 || settings.runtimeRecovery.fallbackRoutes.length > 0);
289
+ const declared = ownsRoute ?? (role !== undefined && (Object.keys(settings.roleRouting[role] ?? {}).length > 0 || settings.runtimeRecovery.fallbackRoutes.length > 0));
270
290
  if (frame.signal.aborted)
271
291
  return identity;
272
292
  let latest;
@@ -48,7 +48,7 @@ export function roleInvocationObservation(invocation, label, mode, getSettings,
48
48
  const actual = latestOwnRoleRoute(child);
49
49
  if (actual.status === "known")
50
50
  return { view: { ...view, route: actual.route }, routeKind: "actual" };
51
- const route = roleRouteRuntimeState(child, getSettings(child), invocation.target, getSettings.admission?.(child).epoch).route;
51
+ const route = roleRouteRuntimeState(child, getSettings(child), invocation.target, getSettings.admission?.(child)).route;
52
52
  return { view: route === undefined ? view : { ...view, route: { ...route } }, routeKind: "initial" };
53
53
  }
54
54
  function latestOwnRoleRoute(child) {
@@ -184,7 +184,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings, bindReques
184
184
  pendingByAgent.delete(frame.agent);
185
185
  throw new Error("DSMM retry routing capture changed");
186
186
  }
187
- if (!decision?.configuredRoot && latestNativeModelSelection(frame.agent)?.seq !== pending.manualSelectionSeq) {
187
+ if (latestNativeModelSelection(frame.agent)?.seq !== pending.manualSelectionSeq) {
188
188
  pendingByAgent.delete(frame.agent);
189
189
  throw new Error("dsmm retry was superseded by an explicit native model selection");
190
190
  }
@@ -254,7 +254,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings, bindReques
254
254
  if (!active || frame.signal.aborted || lock === undefined || headerRoute === undefined
255
255
  || headerRoute.provider !== frame.provider || !sameModelRoute(headerRoute, lock.route) || headerRoute.reasoningEffort !== lock.route.reasoningEffort
256
256
  || attempt === undefined || attempt.policy !== policy || attempt.generation !== lock.generation
257
- || !decision?.configuredRoot && latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
257
+ || latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
258
258
  || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step) || !positiveNoOutput(frame, attempt))
259
259
  return undefined;
260
260
  const expectedGeneration = lock.generation;
@@ -346,7 +346,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings, bindReques
346
346
  || liveRolePolicyIdentity(frame.agent, currentSettings, currentRole, getSettings.admission?.(frame.agent).epoch) !== policy
347
347
  || roleRouteLock(frame.agent, policy) !== lock || lock.generation !== expectedGeneration
348
348
  || attemptsByAgent.get(frame.agent) !== attempt || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step)
349
- || !decision?.configuredRoot && latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
349
+ || latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
350
350
  || !positiveNoOutput(frame, attempt, true)
351
351
  || !sameExactModelRoute(modelRouteFromHeader(frame.agent.session.requestHeader?.()), attempt.route))
352
352
  return undefined;
package/lib/status.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { classifyModelFamily } from "./model-family.js";
2
2
  import { DSMM_ROLES, isDsmmRoleId } from "./roles.js";
3
- import { roleRouteRuntimeState } from "./role-routing.js";
3
+ import { latestNativeModelSelection, observedRootModel, roleRouteRuntimeState, usesConfiguredRootRoute } from "./role-routing.js";
4
4
  import { resolveSelectedAgentPreset } from "./session-scope.js";
5
5
  import { resolveAdmittedDsmmRole as resolveEffectiveDsmmRole } from "./role-policy.js";
6
6
  import { resolveRoleRuntimePolicy } from "./routing-policy.js";
@@ -20,14 +20,14 @@ export function createDsmmStatusSnapshot(input) {
20
20
  invalidDescriptor = true;
21
21
  }
22
22
  const inScope = modeActive || role !== undefined;
23
- const nativeRoot = ordinaryRoot && !(input.admission?.settings === settings
24
- && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined && !invalidDescriptor);
23
+ const manual = ordinaryRoot ? latestNativeModelSelection(agent) : undefined;
24
+ const nativeRoot = ordinaryRoot && !usesConfiguredRootRoute(agent, settings, input.admission, role, manual);
25
25
  const policy = nativeRoot || role === undefined ? undefined : settings.roleRouting[role];
26
26
  const runtimePolicy = resolveRoleRuntimePolicy(settings, role);
27
27
  const roleRuntimeState = input.roleRuntimeState ?? (input.admission === undefined || invalidDescriptor ? undefined
28
- : roleRouteRuntimeState(agent, settings, role, input.admission.epoch));
28
+ : roleRouteRuntimeState(agent, settings, role, input.admission));
29
29
  const fallbacks = nativeRoot || invalidDescriptor ? [] : runtimePolicy.fallbackRoutes;
30
- const selectedRoute = resolveRoute(agent, !ordinaryRoot || nativeRoot);
30
+ const selectedRoute = (ordinaryRoot && nativeRoot ? observedRootModel(agent, manual) : undefined) ?? resolveRoute(agent, !ordinaryRoot || nativeRoot);
31
31
  const family = classifyModelFamily({
32
32
  providerID: selectedRoute.provider,
33
33
  modelID: selectedRoute.model
@@ -1,3 +1,5 @@
1
+ import { symbols } from "@deepseek-ai/cordis";
2
+ import { hostModelSelection, latestModelSelectionSeq } from "./role-routing.js";
1
3
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
2
4
  import { createDsmmStatusSnapshot, formatDsmmStatus } from "./status.js";
3
5
  import { handleDsmmStatusCommand, parseDeepworkCommandInput } from "./commands.js";
@@ -183,6 +185,7 @@ async function manageGlobal(deps, authority) {
183
185
  return success(`Saved Global ${field.path.join(".")}=${after}; desired revision is ${saved.revision}.${saved.refreshRequired ? " Refresh is required before another edit." : ""}`);
184
186
  }
185
187
  async function manageProfiles(deps, invocation, authority) {
188
+ const choiceCursor = latestModelSelectionSeq(invocation.agent);
186
189
  const operation = await authority.select("Named profiles", [
187
190
  { id: "browse", label: "Browse", description: "Show saved profile IDs, diagnostics and revisions" },
188
191
  { id: "future", label: "Select future default", description: "Set or clear the default for new sessions" },
@@ -212,9 +215,22 @@ async function manageProfiles(deps, invocation, authority) {
212
215
  ...(revision === undefined ? {} : { expectedRevision: revision }) }, () => authority.assertCurrent());
213
216
  return success(`Future named-profile default is ${selected.selectedId ?? "deployment baseline"}; current sessions were not changed.${selected.refreshRequired ? " The commit succeeded, but refresh is required before another profile action." : ""}`);
214
217
  }
218
+ const chooseModel = id === null ? undefined : captureProfileModelChoice(invocation.agent, choiceCursor);
215
219
  const session = await deps.profiles.getSession(invocation.agent);
216
220
  authority.assertCurrent();
217
- const message = `Apply ${id ?? "deployment baseline"} to live root session ${session.sessionId}; admission ${session.admissionEpoch}; selection revision ${session.selection.selectionRevision}${revision === undefined ? "" : `; profile revision ${revision}`}.`;
221
+ let useModel = false;
222
+ if (chooseModel !== undefined) {
223
+ const action = await authority.select(`Apply ${id} to this session`, [
224
+ { id: "apply-only", label: "Apply profile only", description: "Keep the current session model" },
225
+ { id: "apply-model", label: "Apply and use profile model", description: "Select the admitted profile’s model for this session" }
226
+ ]);
227
+ if (action === undefined)
228
+ return error("Session profile action cancelled; no maintenance was started.");
229
+ useModel = action === "apply-model";
230
+ }
231
+ const modelNotice = useModel ? " Also select the admitted profile’s model for this session."
232
+ : chooseModel === undefined && id !== null ? " Keep the current model. Use /model to select a model on this Host." : " Keep the current model.";
233
+ const message = `Apply ${id ?? "deployment baseline"} to live root session ${session.sessionId}; admission ${session.admissionEpoch}; selection revision ${session.selection.selectionRevision}${revision === undefined ? "" : `; profile revision ${revision}`}.${modelNotice}`;
218
234
  if (await authority.confirm("Confirm session profile", message, "Apply") !== true)
219
235
  return error("Session profile action cancelled; no maintenance was started.");
220
236
  authority.assertCurrent();
@@ -222,7 +238,54 @@ async function manageProfiles(deps, invocation, authority) {
222
238
  expectedSelectionRevision: session.selection.selectionRevision, expectedAdmissionEpoch: session.admissionEpoch,
223
239
  ...(revision === undefined ? {} : { expectedRevision: revision }) }, invocation.agent, authority.signal, () => authority.assertCurrent());
224
240
  const refreshRequired = selected.refreshRequired === true || selected.selection.refreshRequired === true;
225
- return success(`Session ${selected.sessionId} now admits ${selected.admittedSelection?.selectedId ?? "deployment baseline"}; admission epoch ${selected.admissionEpoch}.${refreshRequired ? " The commit succeeded, but refresh is required before another profile action." : ""}`);
241
+ const applied = `Applied ${id ?? "deployment baseline"} to session ${session.sessionId}; admission epoch ${selected.admissionEpoch}.`;
242
+ if (refreshRequired)
243
+ return success(`${applied} Refresh is required before another profile action.${useModel ? " The profile model was not selected." : ""}`);
244
+ if (!useModel || chooseModel === undefined)
245
+ return success(`${applied}${id !== null && chooseModel === undefined ? " Use /model to change the session model." : ""}`);
246
+ if (selected.sessionId !== session.sessionId || selected.canSelectModel !== true || selected.profileModel === undefined) {
247
+ return success(`${applied} The profile model is unavailable; use /model to choose a session model.`);
248
+ }
249
+ try {
250
+ const outcome = await chooseModel(selected.profileModel, authority, selected.admissionEpoch);
251
+ return success(`${applied} ${outcome}`);
252
+ }
253
+ catch {
254
+ return success(`${applied} Model selection was not confirmed; check /model.`);
255
+ }
256
+ }
257
+ function captureProfileModelChoice(agent, cursor) {
258
+ const selector = hostModelSelection(agent);
259
+ const llm = agent.ctx?.get?.("llm");
260
+ if (selector === undefined || typeof llm?.resolveCallConfig !== "function" || (!agent.session.snapshotEvents && !agent.session.events))
261
+ return undefined;
262
+ const resolve = llm.resolveCallConfig.bind(llm);
263
+ const current = selector.current();
264
+ const before = current === undefined ? undefined : { ...current };
265
+ const llmOwner = Reflect.get(llm, symbols.original) ?? llm;
266
+ return async ({ provider, model, reasoningEffort }, authority, epoch) => {
267
+ const choiceUnchanged = () => {
268
+ authority.assertApplied(epoch);
269
+ const liveLlm = agent.ctx?.get?.("llm");
270
+ if (hostModelSelection(agent) !== selector || !liveLlm || (Reflect.get(liveLlm, symbols.original) ?? liveLlm) !== llmOwner) {
271
+ throw new Error("The session model service changed.");
272
+ }
273
+ const now = selector.current();
274
+ return latestModelSelectionSeq(agent) === cursor && before?.provider === now?.provider && before?.model === now?.model && before?.reasoningEffort === now?.reasoningEffort;
275
+ };
276
+ const newerChoice = "Kept the newer session model choice.";
277
+ if (!choiceUnchanged())
278
+ return newerChoice;
279
+ const route = { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) };
280
+ const resolved = await resolve({ ...route }, authority.signal);
281
+ if (!choiceUnchanged())
282
+ return newerChoice;
283
+ if (resolved.provider !== provider || resolved.model !== model || (reasoningEffort !== undefined && resolved.reasoningEffort !== reasoningEffort)) {
284
+ return "The Host could not resolve the exact profile model and effort; use /model to choose a session model.";
285
+ }
286
+ selector.select(route);
287
+ return `Selected ${provider}/${model} for this session.`;
288
+ };
226
289
  }
227
290
  async function chooseProfile(authority, inventory) {
228
291
  const available = inventory.profiles.filter(profile => profile.error === undefined && typeof profile.revision === "string");
@@ -1,6 +1,7 @@
1
1
  import { symbols } from "@deepseek-ai/cordis";
2
2
  import { createDeepworkCommandDefinition, createDsmmStatusCommandDefinition } from "./commands.js";
3
3
  import { DSMM_LOCALES } from "./settings.js";
4
+ import { validateAdmissionEpoch } from "./profiles.js";
4
5
  import { createDsmmManagementCommandDefinition, DIALOG_TIMEOUT_MS, DSMM_TUI_CONTRIBUTIONS } from "./tui-actions.js";
5
6
  const INHERIT = "inherit";
6
7
  const ACTION_TIMEOUT_MS = 120_000;
@@ -277,7 +278,7 @@ class DsmmTuiAdapter {
277
278
  const signal = invocation.signal === undefined
278
279
  ? AbortSignal.any([local.signal, deadline.signal])
279
280
  : AbortSignal.any([local.signal, deadline.signal, invocation.signal]);
280
- const assertCurrent = () => {
281
+ const assertOwner = () => {
281
282
  if (signal.aborted || this.disposed)
282
283
  throw abortError();
283
284
  if (this.mediated !== mounted || !this.currentHost(mounted.owner, mounted.generationId)
@@ -286,17 +287,17 @@ class DsmmTuiAdapter {
286
287
  const currentAgents = softGet(this.ctx, "agents");
287
288
  if (currentAgents === undefined || original(currentAgents) !== agentsOwner || currentAgents.get(id) !== agent)
288
289
  throw new Error("The exact live Agent changed.");
289
- if (admission !== undefined) {
290
- const current = this.options.getSettings.admission?.(agent);
291
- if (current !== admission || current?.epoch !== admission.epoch)
292
- throw new Error("The DSMM admission changed.");
293
- }
294
290
  if (dialogsOwner !== undefined) {
295
291
  const currentDialogs = softGet(this.ctx, "tuiDialogs");
296
292
  if (currentDialogs === undefined || original(currentDialogs) !== dialogsOwner)
297
293
  throw new Error("The managed dialog owner changed.");
298
294
  }
299
295
  };
296
+ const assertCurrent = () => {
297
+ assertOwner();
298
+ if (admission !== undefined && this.options.getSettings.admission?.(agent) !== admission)
299
+ throw new Error("The DSMM admission changed.");
300
+ };
300
301
  const checked = async (operation) => {
301
302
  assertCurrent();
302
303
  const result = await operation();
@@ -308,7 +309,18 @@ class DsmmTuiAdapter {
308
309
  signal,
309
310
  agent,
310
311
  assertCurrent,
311
- select: (title, options) => checked(() => dialogs.select({ title, options, signal, timeoutMs: DIALOG_TIMEOUT_MS })),
312
+ assertApplied: epoch => {
313
+ assertOwner();
314
+ validateAdmissionEpoch(epoch);
315
+ if (admission === undefined || epoch === admission.epoch || this.options.getSettings.admission?.(agent)?.epoch !== epoch) {
316
+ throw new Error("The applied session admission is no longer current.");
317
+ }
318
+ },
319
+ select: (title, options) => checked(async () => {
320
+ const offered = options.map(option => option.id);
321
+ const answer = await dialogs.select({ title, options, signal, timeoutMs: DIALOG_TIMEOUT_MS });
322
+ return answer !== undefined && offered.includes(answer) ? answer : undefined;
323
+ }),
312
324
  confirm: (title, message, confirmLabel) => checked(() => dialogs.confirm({ title, message,
313
325
  ...(confirmLabel === undefined ? {} : { confirmLabel }), cancelLabel: "Cancel", signal, timeoutMs: DIALOG_TIMEOUT_MS })),
314
326
  input: (title, placeholder) => checked(() => dialogs.input({ title, ...(placeholder === undefined ? {} : { placeholder }), signal, timeoutMs: DIALOG_TIMEOUT_MS })),
@@ -88,6 +88,7 @@ export interface DsmmTuiActionAuthority {
88
88
  readonly signal: AbortSignal;
89
89
  readonly agent: DshCommandInvocation["agent"];
90
90
  assertCurrent(): void;
91
+ assertApplied(epoch: string): void;
91
92
  select(title: string, options: readonly TuiDialogOption[]): Promise<string | undefined>;
92
93
  confirm(title: string, message: string, confirmLabel?: string): Promise<boolean>;
93
94
  input(title: string, placeholder?: string): Promise<string | undefined>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsmm/dsmm",
3
- "version": "0.3.40",
3
+ "version": "0.3.41",
4
4
  "description": "Native Deepwork roles, routing, profiles, and permission controls for DeepSeek Harness.",
5
5
  "author": "Hugefiver",
6
6
  "license": "LicenseRef-AAAPL",