@dsmm/dsmm 0.3.22 → 0.3.23

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.
Files changed (94) hide show
  1. package/agent-presets/dsmm-builder/agent.cordis.yml +1 -7
  2. package/agent-presets/dsmm-clarifier/agent.cordis.yml +1 -7
  3. package/agent-presets/dsmm-code-search/agent.cordis.yml +1 -7
  4. package/agent-presets/dsmm-coding/agent.cordis.yml +1 -7
  5. package/agent-presets/dsmm-complex/agent.cordis.yml +1 -7
  6. package/agent-presets/dsmm-creative/agent.cordis.yml +1 -7
  7. package/agent-presets/dsmm-cross-cutting/agent.cordis.yml +1 -7
  8. package/agent-presets/dsmm-deep/agent.cordis.yml +1 -7
  9. package/agent-presets/dsmm-doc-search/agent.cordis.yml +1 -7
  10. package/agent-presets/dsmm-documenting/agent.cordis.yml +1 -7
  11. package/agent-presets/dsmm-frontend/agent.cordis.yml +1 -7
  12. package/agent-presets/dsmm-hard-reasoning/agent.cordis.yml +1 -7
  13. package/agent-presets/dsmm-media-reader/agent.cordis.yml +1 -7
  14. package/agent-presets/dsmm-normal-task/agent.cordis.yml +1 -7
  15. package/agent-presets/dsmm-oracle/agent.cordis.yml +1 -7
  16. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +1 -7
  17. package/agent-presets/dsmm-orchestrator/agent.cordis.yml +1 -7
  18. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +1 -7
  19. package/agent-presets/dsmm-planner/agent.cordis.yml +1 -7
  20. package/agent-presets/dsmm-quick/agent.cordis.yml +1 -7
  21. package/agent-presets/dsmm-research/agent.cordis.yml +1 -7
  22. package/agent-presets/dsmm-reviewer/agent.cordis.yml +1 -7
  23. package/cordis.patch.yml +3 -0
  24. package/docs/compatibility.md +13 -1
  25. package/docs/maintenance.md +22 -9
  26. package/docs/model-routing.md +25 -3
  27. package/docs/native-permissions.md +20 -4
  28. package/docs/releasing.md +3 -3
  29. package/docs/roadmap.md +33 -11
  30. package/docs/runtime-recovery.md +5 -3
  31. package/docs/testing.md +10 -0
  32. package/docs/web-fetch-fakeip.md +8 -2
  33. package/dsh-plugin.json +1 -1
  34. package/lib/agent-prompt-scope.d.ts +6 -0
  35. package/lib/agent-prompt-scope.js +66 -0
  36. package/lib/client/RoleToolView-data.d.ts +4 -2
  37. package/lib/client/RoleToolView-data.js +18 -4
  38. package/lib/client/RoleToolView-locales.d.ts +4 -0
  39. package/lib/client/RoleToolView-locales.js +2 -0
  40. package/lib/client/RoleToolView.d.ts +9 -3
  41. package/lib/client/RoleToolView.js +27 -8
  42. package/lib/client/children-locales.d.ts +4 -4
  43. package/lib/client/index.js +6 -1
  44. package/lib/client/role-call-observations.d.ts +21 -0
  45. package/lib/client/role-call-observations.js +150 -0
  46. package/lib/client.js +401 -96
  47. package/lib/dsh-types.d.ts +15 -0
  48. package/lib/index.js +4 -1
  49. package/lib/live-pi-ai-owner.d.ts +1 -2
  50. package/lib/live-pi-ai-owner.js +10 -7
  51. package/lib/locale-guidance.d.ts +3 -0
  52. package/lib/locale-guidance.js +12 -0
  53. package/lib/model-family.d.ts +14 -0
  54. package/lib/model-family.js +138 -35
  55. package/lib/model-routing.d.ts +23 -2
  56. package/lib/model-routing.js +145 -7
  57. package/lib/native-admission.d.ts +36 -1
  58. package/lib/native-admission.js +408 -24
  59. package/lib/native-pi-ai-wire.js +17 -4
  60. package/lib/profile-remote.d.ts +2 -0
  61. package/lib/profile-remote.js +12 -3
  62. package/lib/profile-types.d.ts +5 -0
  63. package/lib/prompts.d.ts +3 -2
  64. package/lib/prompts.js +20 -38
  65. package/lib/role-control-remote.d.ts +5 -2
  66. package/lib/role-control-remote.js +84 -4
  67. package/lib/role-control-rpc.d.ts +8 -1
  68. package/lib/role-control-rpc.js +122 -50
  69. package/lib/role-control-types.d.ts +62 -1
  70. package/lib/role-control-types.js +3 -0
  71. package/lib/role-invocation.js +1 -1
  72. package/lib/role-llm-runtime.js +2 -2
  73. package/lib/role-routing.d.ts +27 -7
  74. package/lib/role-routing.js +129 -16
  75. package/lib/role-subagents.js +8 -23
  76. package/lib/runtime-recovery.js +23 -6
  77. package/lib/session-metadata.d.ts +13 -1
  78. package/lib/session-metadata.js +21 -1
  79. package/lib/web-fetch-address-policy.d.ts +6 -2
  80. package/lib/web-fetch-fakeip.d.ts +6 -0
  81. package/lib/web-fetch-fakeip.js +29 -2
  82. package/package.json +2 -2
  83. package/prompts/deepwork.md +0 -1
  84. package/prompts/source/deepwork/claude-opus-5.md +2 -8
  85. package/prompts/source/deepwork/codex.md +2 -8
  86. package/prompts/source/deepwork/gemini-4.md +1 -7
  87. package/prompts/source/deepwork/gemini.md +0 -6
  88. package/prompts/source/deepwork/glm.md +3 -10
  89. package/prompts/source/deepwork/gpt.md +7 -15
  90. package/prompts/source/deepwork/kimi.md +1 -7
  91. package/prompts/source/deepwork/planner.md +0 -4
  92. package/prompts/source/deepwork/swe-2.md +2 -8
  93. package/prompts/source/shared/dsh-host-contract.md +0 -1
  94. package/prompts/source/shared/locale.md +1 -6
@@ -1,6 +1,9 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  export interface DshSessionEvent {
3
3
  type: string;
4
+ seq?: number;
5
+ time?: number;
6
+ ignorable?: true;
4
7
  data?: unknown;
5
8
  }
6
9
  export interface DshSessionHeader {
@@ -36,6 +39,18 @@ export interface DshAgent {
36
39
  };
37
40
  steer?(message: unknown): unknown | Promise<unknown>;
38
41
  inject?(message: unknown): unknown | Promise<unknown>;
42
+ /** DSH 0.2.2+: Agent-owned durable model selection for future steps; absent on 0.2.1 Hosts. */
43
+ readonly model?: DshAgentModel;
44
+ }
45
+ export interface DshModelSelection {
46
+ provider: string;
47
+ model: string;
48
+ reasoningEffort?: string;
49
+ }
50
+ /** Duck-typed 0.2.2 `AgentModel`: `current()` is `pending ?? lastUsed`; `select()` is same-value idempotent. */
51
+ export interface DshAgentModel {
52
+ current(): DshModelSelection | undefined;
53
+ select(selection: DshModelSelection): void;
39
54
  }
40
55
  export interface DshAgentsRegistry {
41
56
  get(id: string): DshAgent | undefined;
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 { registerModelRouting } from "./model-routing.js";
6
+ import { prepareAdmissionModelRoute, registerModelRouting } from "./model-routing.js";
7
7
  import { registerHeadlessRoleTools, registerNativeSubagentControls } from "./role-subagents.js";
8
8
  import { registerRolePresets } from "./preset-registry.js";
9
9
  import { registerRoleProviders } from "./role-providers.js";
@@ -23,6 +23,7 @@ import { registerRoleControlRpc } from "./role-control-rpc.js";
23
23
  import { nativeStandingFullAccess } from "./permission-native-access.js";
24
24
  import { DsmmProfileError } from "./profiles.js";
25
25
  import { registerLspRuntime } from "./lsp.js";
26
+ import { registerAgentPromptScope } from "./agent-prompt-scope.js";
26
27
  export const name = "dsmm";
27
28
  export const inject = ["profileContext", "agents"];
28
29
  export const Config = new Proxy(DSMM_NATIVE_CONFIG_SCHEMA, { apply(_target, _receiver, args) { return DSMM_CONFIG_SCHEMA(args[0] ?? {}); } });
@@ -81,6 +82,7 @@ export async function apply(input, config = {}, startupOptions = {}) {
81
82
  lifetime.signal.throwIfAborted();
82
83
  admission = new NativeAdmission(ctx, profiles, policy, agents => { for (const agent of agents)
83
84
  commandApprovals.clearAgent(agent); });
85
+ admission.bindAdmissionModelSelection((agent, info) => prepareAdmissionModelRoute(ctx, controller, agent, info));
84
86
  ctx.provide("dsmmNativeAdmission", admission);
85
87
  ctx.provide("dsmmProfileRuntime", profiles);
86
88
  ctx.provide("dsmmDeploymentConfig", deployment);
@@ -138,6 +140,7 @@ export async function apply(input, config = {}, startupOptions = {}) {
138
140
  admission.activate(async (agent, candidate) => {
139
141
  candidate.subagentRuntime = () => runtimeAdmissionView(ctx);
140
142
  const scope = agent.ctx;
143
+ registerAgentPromptScope(ctx, controller, candidate, policy, agent, nativeAdmission.lifetime.signal);
141
144
  if (startup.settings.modules.deepwork.enabled) {
142
145
  registerAgentSkills(scope, controller, candidate, agent, admission.lifetime.signal, () => !nativeAdmission.isSelecting(agent));
143
146
  registerDeepworkPrompt(scope, controller, candidate, { section: startup.profile.section ?? startup.global.section }, agent, admission.lifetime.signal);
@@ -5,10 +5,9 @@ import type { DsmmLlmRouteResolver } from "./role-llm.js";
5
5
  type RegistrationHandle = ReturnType<LlmRuntime["registerAdapter"]>;
6
6
  /** Captures public registering-fiber provenance; the native runtime remains the sole registry. */
7
7
  export declare class LivePiAiOwner implements DsmmLlmRouteResolver {
8
- private readonly ctx;
9
8
  private readonly native;
10
9
  private readonly registrations;
11
- constructor(ctx: Context, native: LlmRuntime);
10
+ constructor(_ctx: Context, native: LlmRuntime);
12
11
  supportsNativeStop(provider: string): boolean;
13
12
  requiresRaw(config: DsmmLlmCallConfig): boolean;
14
13
  register(scope: Context, providers: readonly string[], adapter: LlmAdapter, handle: RegistrationHandle): RegistrationHandle;
@@ -9,13 +9,15 @@ import { snapshotDsmmCall } from "./host-llm.js";
9
9
  import { DsmmMissingProviderError, modelRouteToCall } from "./role-llm.js";
10
10
  import { normalizeModelRouteJson } from "./route-json.js";
11
11
  const original = (value) => Reflect.get(value, symbols.original) ?? value;
12
+ const providerConfig = (scope) => {
13
+ const fiber = scope.fiber;
14
+ return "effectiveConfig" in fiber ? fiber.effectiveConfig : fiber.config;
15
+ };
12
16
  /** Captures public registering-fiber provenance; the native runtime remains the sole registry. */
13
17
  export class LivePiAiOwner {
14
- ctx;
15
18
  native;
16
19
  registrations = new Map();
17
- constructor(ctx, native) {
18
- this.ctx = ctx;
20
+ constructor(_ctx, native) {
19
21
  this.native = native;
20
22
  }
21
23
  supportsNativeStop(provider) {
@@ -68,7 +70,7 @@ export class LivePiAiOwner {
68
70
  const { scope, adapter } = record;
69
71
  if (!(adapter instanceof PiAiAdapter) || scope.fiber.entry?.options.name !== "@deepseek-ai/dsh-llm-pi-ai")
70
72
  throw new LlmError("This provider has no raw executor", "UNSUPPORTED_ROUTE_PARAMETERS");
71
- const config = scope.fiber.config;
73
+ const config = providerConfig(scope);
72
74
  if (config === null || typeof config !== "object" || !("providers" in config) || config.providers === null || typeof config.providers !== "object"
73
75
  || !("get" in config.providers) || typeof config.providers.get !== "function")
74
76
  throw new LlmError("Pi-AI live configuration is unavailable", "DSMM_PROVIDER_NOT_READY");
@@ -93,15 +95,16 @@ export class LivePiAiOwner {
93
95
  const signal = AbortSignal.any([record.life.signal, retire.signal]);
94
96
  const assertCurrent = () => {
95
97
  signal.throwIfAborted();
96
- if (this.registrations.get(provider) !== record || scope.fiber.state !== 2 || scope.fiber.entry?.fiber !== scope.fiber
97
- || scope.fiber.config !== config || !isDeepStrictEqual(ref.get()[provider], profile)
98
+ const registeredFiber = scope.fiber.entry?.fiber;
99
+ if (this.registrations.get(provider) !== record || scope.fiber.state !== 2 || registeredFiber === undefined || original(registeredFiber.ctx.fiber) !== original(scope.fiber)
100
+ || providerConfig(scope) !== config || !isDeepStrictEqual(ref.get()[provider], profile)
98
101
  || (credentials === undefined ? scope.get("credentials") !== undefined : scope.get("credentials") === undefined || original(scope.get("credentials")) !== original(credentials))) {
99
102
  retire.abort(new LlmError("Provider configuration or owner changed", "INVALID_PREPARED_CALL"));
100
103
  signal.throwIfAborted();
101
104
  }
102
105
  };
103
106
  assertCurrent();
104
- const owner = createDsmmPiAiProviderOwner(this.ctx, {
107
+ const owner = createDsmmPiAiProviderOwner(scope, {
105
108
  config: { providers: { [provider]: structuredClone(profile) } },
106
109
  settingsNamespace: scope.fiber.entry.options.id,
107
110
  auth: { credentials: new InMemoryCredentialStore(), authContext: {
@@ -0,0 +1,3 @@
1
+ import type { DsmmSettings } from "./settings.js";
2
+ export declare function buildDsmmLocaleGuidance(settings: Pick<DsmmSettings, "locale">): string;
3
+ //# sourceMappingURL=locale-guidance.d.ts.map
@@ -0,0 +1,12 @@
1
+ const localeNames = {
2
+ en: "English", "zh-Hans": "Simplified Chinese", "zh-Hant": "Traditional Chinese", ja: "Japanese", ko: "Korean",
3
+ de: "German", fr: "French", es: "Spanish", "pt-BR": "Brazilian Portuguese", ru: "Russian"
4
+ };
5
+ export function buildDsmmLocaleGuidance(settings) {
6
+ return `<dsmm-visible-output-language>
7
+ ${JSON.stringify({ capturedLocale: settings.locale ?? null, visibleOutputLanguage: settings.locale === undefined ? null : localeNames[settings.locale] })}
8
+ ${settings.locale === undefined ? "No DSMM locale is captured; inherit applicable host/user language guidance, otherwise use the current request and conversation context." : `This Agent's immutable captured locale is ${settings.locale} (${localeNames[settings.locale]}). Use it as the default for visible replies, plans and role/category output.`}
9
+ The current user's explicit output-language request takes precedence. Preserve that instruction in child assignments. A parent's later profile change does not rewrite a child's captured preference. Preserve code, identifiers, commands, paths, protocol fields and exact quotations verbatim. This affects visible output only: it neither promises an internal reasoning language nor changes the host UI/project locale. Do not infer configuration or authority with natural-language matching.
10
+ </dsmm-visible-output-language>`;
11
+ }
12
+ //# sourceMappingURL=locale-guidance.js.map
@@ -1,6 +1,20 @@
1
1
  export type DsmmModelFamily = "gpt" | "codex" | "claude" | "gemini" | "glm" | "kimi" | "deepseek" | "unknown";
2
+ type ModelIdentifier = Exclude<DsmmModelFamily, "unknown"> | "swe-2";
3
+ type ModelSeries = "opus" | "sonnet" | "haiku" | "sol" | "terra" | "astra" | "luna";
4
+ interface ModelNameRecognition {
5
+ identifier: ModelIdentifier;
6
+ family: DsmmModelFamily;
7
+ series: ModelSeries | undefined;
8
+ version: readonly [number, number, number] | undefined;
9
+ versionParts: number | undefined;
10
+ opus5: boolean;
11
+ gemini4: boolean;
12
+ }
13
+ /** Model fields are complete names here; route owners separate provider metadata. */
14
+ export declare function recognizeModelName(model: string): ModelNameRecognition | undefined;
2
15
  export declare function classifyModelFamily(input: {
3
16
  providerID?: string;
4
17
  modelID?: string;
5
18
  }): DsmmModelFamily;
19
+ export {};
6
20
  //# sourceMappingURL=model-family.d.ts.map
@@ -1,48 +1,151 @@
1
- const DOTTED_VENDOR_MODEL_PREFIXES = {
2
- openai: /^(?:gpt-|o\d|chatgpt-|codex-)/,
3
- anthropic: /^claude-/,
4
- google: /^gemini-/,
5
- zhipu: /^glm-/,
6
- deepseek: /^deepseek-/
7
- };
8
- function stripDottedVendorModelPrefix(name) {
9
- const parts = name.split(".");
10
- const vendor = parts[0];
11
- const model = parts.slice(1).join(".");
12
- if (vendor && DOTTED_VENDOR_MODEL_PREFIXES[vendor]?.test(model))
13
- return model;
14
- const region = parts[0];
15
- const regionalVendor = parts[1];
16
- const regionalModel = parts.slice(2).join(".");
17
- if (region
18
- && regionalVendor
19
- && /^(?:[a-z]{2}|[a-z]{2}-[a-z]+-\d+)$/.test(region)
20
- && DOTTED_VENDOR_MODEL_PREFIXES[regionalVendor]?.test(regionalModel)) {
21
- return regionalModel;
1
+ function seriesFamily(series) {
2
+ return series === "opus" || series === "sonnet" || series === "haiku" ? "claude" : "gpt";
3
+ }
4
+ function skipSeparators(name, start) {
5
+ return start + (/^[-_.\s/]+/u.exec(name.slice(start))?.[0].length ?? 0);
6
+ }
7
+ function seriesAt(name, start, family) {
8
+ const series = /^(opus|sonnet|haiku|sol|terra|astra|luna)(?=\d|[^a-z0-9]|$)/u.exec(name.slice(start))?.[1];
9
+ return series !== undefined && (family === undefined || seriesFamily(series) === family) ? series : undefined;
10
+ }
11
+ function suffixNumber(token) {
12
+ return /^(?:(?:19|20)\d{6}|\d+[km])$/u.test(token);
13
+ }
14
+ function versionStartsAt(name, start) {
15
+ const token = /^[a-z0-9]+/u.exec(name.slice(start))?.[0] ?? "";
16
+ return /^\d/u.test(token) && !suffixNumber(token);
17
+ }
18
+ function readVersion(name, start, family) {
19
+ const parts = [];
20
+ let end = start;
21
+ let cursor = start;
22
+ let series;
23
+ let complete = true;
24
+ while (versionStartsAt(name, cursor)) {
25
+ const digits = /^\d+/u.exec(name.slice(cursor))[0];
26
+ const numberEnd = cursor + digits.length;
27
+ parts.push(Number(digits));
28
+ end = numberEnd;
29
+ if (/^[a-z]/u.test(name.slice(numberEnd))) {
30
+ series = seriesAt(name, numberEnd, family);
31
+ if (series === undefined || versionStartsAt(name, skipSeparators(name, numberEnd + series.length))) {
32
+ complete = false;
33
+ series = undefined;
34
+ end += /^[a-z0-9]+/u.exec(name.slice(numberEnd))[0].length;
35
+ }
36
+ else {
37
+ end += series.length;
38
+ }
39
+ break;
40
+ }
41
+ cursor = skipSeparators(name, end);
42
+ if (versionStartsAt(name, cursor))
43
+ continue;
44
+ const trailingSeries = seriesAt(name, cursor, family);
45
+ if (trailingSeries !== undefined && !versionStartsAt(name, skipSeparators(name, cursor + trailingSeries.length))) {
46
+ series = trailingSeries;
47
+ end = cursor + trailingSeries.length;
48
+ }
49
+ break;
22
50
  }
23
- return name;
51
+ const version = complete && parts.length > 0 && parts.length <= 3 && parts.every(Number.isSafeInteger)
52
+ ? [parts[0], parts[1] ?? 0, parts[2] ?? 0] : undefined;
53
+ return { version, versionParts: version === undefined ? undefined : parts.length, series, end };
24
54
  }
25
- function extractModelName(fullID) {
26
- const index = fullID.lastIndexOf("/");
27
- return stripDottedVendorModelPrefix(index >= 0 ? fullID.slice(index + 1) : fullID);
55
+ function identifierFor(marker) {
56
+ if (marker.startsWith("k2"))
57
+ return "kimi";
58
+ if (marker.startsWith("swe"))
59
+ return "swe-2";
60
+ if (marker === "chatgpt")
61
+ return "gpt";
62
+ if (marker === "fable")
63
+ return "claude";
64
+ return marker;
65
+ }
66
+ /** Model fields are complete names here; route owners separate provider metadata. */
67
+ export function recognizeModelName(model) {
68
+ const name = model.trim().toLowerCase();
69
+ const markers = name.matchAll(/(?<![a-z0-9])(?:(?:chatgpt|gpt|codex|claude|fable|gemini|glm|deepseek|kimi|opus|sonnet|haiku|sol|terra|astra|luna)(?=\d|[^a-z0-9]|$)|(?:k2[-_.\s/]*p[5-8]|swe[-_.\s/]+2)(?![a-z0-9])|\d+)/gu);
70
+ let first;
71
+ let consumedEnd = 0;
72
+ for (const marker of markers) {
73
+ if (marker.index < consumedEnd)
74
+ continue;
75
+ let identifier;
76
+ let parsed;
77
+ let wildcardGemini4 = false;
78
+ let series = seriesAt(name, marker.index);
79
+ if (/^\d/u.test(marker[0])) {
80
+ // Numeric spans include malformed segments; never restart at their later digits.
81
+ if (/(?:\d|(?<![a-z0-9])\d[a-z0-9]*)[-_.\s/]+$/u.test(name.slice(consumedEnd, marker.index)))
82
+ continue;
83
+ parsed = readVersion(name, marker.index);
84
+ if (parsed.version === undefined || parsed.series === undefined)
85
+ continue;
86
+ series = parsed.series;
87
+ identifier = seriesFamily(series);
88
+ }
89
+ else if (series !== undefined) {
90
+ const start = skipSeparators(name, marker.index + marker[0].length);
91
+ if (!versionStartsAt(name, start))
92
+ continue;
93
+ identifier = seriesFamily(series);
94
+ parsed = readVersion(name, start, identifier);
95
+ }
96
+ else {
97
+ identifier = identifierFor(marker[0]);
98
+ const markerEnd = marker.index + marker[0].length;
99
+ let start = skipSeparators(name, markerEnd);
100
+ series = start > markerEnd ? seriesAt(name, start, identifier) : undefined;
101
+ if (series !== undefined)
102
+ start = skipSeparators(name, start + series.length);
103
+ if (identifier === "gemini" && /^4\.x/u.test(name.slice(start))) {
104
+ const end = start + 3;
105
+ wildcardGemini4 = /^(?:$|[-_.\s/@:])/u.test(name.slice(end)) && !versionStartsAt(name, skipSeparators(name, end));
106
+ parsed = { version: undefined, versionParts: undefined, series: undefined, end };
107
+ }
108
+ else {
109
+ const compactGemini4 = identifier === "gemini" && /^4(?=[^a-z0-9]|$)/u.test(name.slice(start));
110
+ parsed = start === markerEnd && identifier !== "gpt" && !compactGemini4
111
+ ? { version: undefined, versionParts: undefined, series: undefined, end: markerEnd }
112
+ : readVersion(name, start, identifier);
113
+ }
114
+ series ??= parsed.series;
115
+ }
116
+ if (first !== undefined) {
117
+ if (first.identifier !== "gpt" || first.family !== "gpt" || identifier !== "codex")
118
+ break;
119
+ first.family = "codex";
120
+ consumedEnd = parsed.end;
121
+ continue;
122
+ }
123
+ const family = identifier === "swe-2" || /^k2[-_.\s/]*p8$/u.test(marker[0]) ? "unknown" : identifier;
124
+ first = {
125
+ identifier, family, series, version: parsed.version, versionParts: parsed.versionParts,
126
+ opus5: series === "opus" && parsed.version?.[0] === 5 && (parsed.versionParts === 1 || parsed.versionParts === 2 && parsed.version[1] === 5),
127
+ gemini4: identifier === "gemini" && (wildcardGemini4 || parsed.version?.[0] === 4)
128
+ };
129
+ consumedEnd = parsed.end;
130
+ }
131
+ return first;
28
132
  }
29
133
  export function classifyModelFamily(input) {
30
134
  const providerID = input.providerID?.trim().toLowerCase() ?? "";
31
- const modelID = input.modelID?.trim().toLowerCase() ?? "";
32
- const name = extractModelName(modelID);
33
- if (providerID.includes("codex") || name.includes("codex"))
135
+ const recognized = recognizeModelName(input.modelID ?? "");
136
+ if (recognized !== undefined)
137
+ return recognized.family;
138
+ if (providerID.includes("codex"))
34
139
  return "codex";
35
- if (name.includes("gpt"))
36
- return "gpt";
37
- if (providerID.includes("anthropic") || name.includes("claude"))
140
+ if (providerID.includes("anthropic"))
38
141
  return "claude";
39
- if (providerID === "google" || providerID === "google-vertex" || name.startsWith("gemini-"))
142
+ if (providerID === "google" || providerID === "google-vertex")
40
143
  return "gemini";
41
- if (providerID.includes("zhipu") || name.includes("glm"))
144
+ if (providerID.includes("zhipu"))
42
145
  return "glm";
43
- if (providerID.includes("moonshot") || providerID.includes("kimi") || name.includes("kimi") || /k2[-.]?p[567]/.test(name))
146
+ if (providerID.includes("moonshot") || providerID.includes("kimi"))
44
147
  return "kimi";
45
- if (providerID.includes("deepseek") || name.includes("deepseek"))
148
+ if (providerID.includes("deepseek"))
46
149
  return "deepseek";
47
150
  return "unknown";
48
151
  }
@@ -1,6 +1,27 @@
1
- import type { AgentRequestFrame, DshLlmCallConfig, DshAgent, DshContext } from "./dsh-types.js";
2
- import type { DsmmSettingsGetter } from "./settings.js";
1
+ import type { AgentRequestFrame, DshLlmCallConfig, DshAgent, DshContext, DshModelSelection } from "./dsh-types.js";
2
+ import type { DsmmSettingsGetter, DsmmSettings, DsmmProfileAdmission } from "./settings.js";
3
3
  import type { DeepworkModeController } from "./state.js";
4
+ import type { DsmmRoleId } from "./roles.js";
4
5
  export declare function prepareDsmmRequest(frame: AgentRequestFrame, proposal: DshLlmCallConfig, assertCurrent: () => void): Promise<DshLlmCallConfig>;
5
6
  export declare function registerModelRouting(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, agent?: DshAgent): void;
7
+ export interface DsmmAdmissionRouteInfo {
8
+ readonly settings: DsmmSettings;
9
+ readonly epoch?: string;
10
+ readonly admission?: DsmmProfileAdmission;
11
+ readonly signal: AbortSignal;
12
+ assertCurrent(): void;
13
+ }
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>;
6
27
  //# sourceMappingURL=model-routing.d.ts.map
@@ -1,9 +1,11 @@
1
+ import { LlmError } from "@deepseek-ai/dsh-llm";
1
2
  import { DsmmAwareLlmRuntime } from "./host-llm.js";
2
- import { applyModelRoute, clearRoleRouteLock, effectiveRoleFallbackRoutes, establishRolePolicy, latestNativeModelSelection, nativeModelSelectionWasAccepted, orderedModelRoutes, persistedRoleRoute, pinRoleRoute, roleRouteLock, selectInitialModelRoute, selectInitialModelRouteChoice, sameExactModelRoute, sameModelRoute, takeAdmittedRecoveryRoute } from "./role-routing.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
4
  import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
4
5
  import { isCurrentRecoveryStep } from "./recovery-policy.js";
5
6
  import { capturedRoleInvocation } from "./role-invocation.js";
6
- import { modelRouteFromCall, projectModelRouteParameters } from "./role-llm.js";
7
+ import { resolveAdmittedDsmmRole } from "./role-policy.js";
8
+ import { modelRouteFromCall, modelRouteToCall, projectModelRouteParameters } from "./role-llm.js";
7
9
  import { configuredModelParameterPolicy, resolvedModelParameterPolicy } from "./model-parameter-policy.js";
8
10
  import { registerRuntimeRecovery } from "./runtime-recovery.js";
9
11
  import { captureRequestRouting, captureRequestRoute } from "./request-routing.js";
@@ -23,7 +25,7 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
23
25
  const lockedAgents = new Set();
24
26
  let active = true;
25
27
  const assembledSelections = new WeakMap();
26
- let dispose, disposeAgent, disposeAssembly;
28
+ let dispose, disposeAgent, disposeAssembly, disposeFence;
27
29
  try {
28
30
  const owned = agent !== undefined && readyCtx.get?.("llm") instanceof DsmmAwareLlmRuntime;
29
31
  let recovery;
@@ -47,6 +49,27 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
47
49
  decision.assertCurrent();
48
50
  const { settings, admission, role, configuredRoot } = decision;
49
51
  const parameterPolicy = admission === undefined ? configuredModelParameterPolicy(settings) : resolvedModelParameterPolicy(admission);
52
+ const projectedRoute = (route, effortSource = "dsmm-config") => modelRouteFromCall(projectModelRouteParameters(route, effortSource, parameterPolicy.mode === "passthrough"));
53
+ const assertFixedRoute = (config, route) => {
54
+ if (hostModelSelection(frame.agent) !== undefined
55
+ && (!sameModelRoute(config, route) || config.reasoningEffort !== route.reasoningEffort)) {
56
+ throw new LlmError("The request route differs from the model fixed for this step", "INVALID_PREPARED_CALL");
57
+ }
58
+ };
59
+ const matchingRouteResult = (config, route, effortSource = "dsmm-config") => {
60
+ const projected = projectedRoute(route, effortSource);
61
+ assertFixedRoute(config, projected);
62
+ const { provider: _provider, model: _model, reasoningEffort: _effort, ...requestControls } = config;
63
+ const normalized = modelRouteFromCall({ ...requestControls, provider: projected.provider, model: projected.model,
64
+ ...(projected.reasoningEffort === undefined ? {} : { reasoningEffort: projected.reasoningEffort }) });
65
+ const { provider: _normalizedProvider, model: _normalizedModel, reasoningEffort: _normalizedEffort, ...controls } = normalized;
66
+ return modelRouteToCall({ ...controls, ...projected });
67
+ };
68
+ const replacementRouteResult = (config, route, effortSource) => {
69
+ const projected = projectedRoute(route, effortSource);
70
+ assertFixedRoute(config, projected);
71
+ return applyModelRoute(config, projected);
72
+ };
50
73
  if (!settings.modules.deepwork.enabled) {
51
74
  captureRequestRoute(frame, decision);
52
75
  return downstream;
@@ -98,11 +121,11 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
98
121
  // A consumed explicit selection must not undo an admitted fallback.
99
122
  if (!configuredRoot && lock?.manualSelectionSeq !== undefined) {
100
123
  captureRequestRoute(frame, decision, "native");
101
- return applyModelRoute(downstream, lock.route);
124
+ return lock.candidateIndex > 0 ? replacementRouteResult(downstream, lock.route, "native") : matchingRouteResult(downstream, lock.route, "native");
102
125
  }
103
126
  if (admitted !== undefined) {
104
127
  captureRequestRoute(frame, decision, lock?.effortSource);
105
- return applyModelRoute(downstream, admitted);
128
+ return replacementRouteResult(downstream, admitted, lock?.effortSource);
106
129
  }
107
130
  const accepted = persistedRoleRoute(frame, primary, fallbacks, identity, configuredRoot);
108
131
  if (lock !== undefined && accepted !== undefined && !sameExactModelRoute(accepted, lock.route)) {
@@ -118,7 +141,7 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
118
141
  const candidates = invocation?.candidates ?? orderedModelRoutes([primary ?? inherited, ...fallbacks]);
119
142
  const resolver = parameterPolicy.mode === "passthrough" ? readyCtx.get?.("dsmmLlmRoutes") : undefined;
120
143
  const choice = configuredRoot ? await selectInitialModelRouteChoice(llm ?? {}, candidates, frame.signal, resolver, parameterPolicy.mode === "native-defaults" ? route => modelRouteFromCall(projectModelRouteParameters(route, primary === undefined && sameExactModelRoute(route, inherited) ? "native" : "dsmm-config", false)) : undefined, decision.assertCurrent) : undefined;
121
- const selected = choice?.route ?? accepted ?? invocation?.initialRoute ?? (exactPolicy ? await selectInitialModelRoute(llm ?? {}, candidates, frame.signal, resolver, decision.assertCurrent) : inherited);
144
+ const selected = choice?.proposal ?? accepted ?? invocation?.initialRoute ?? (exactPolicy ? await selectInitialModelRoute(llm ?? {}, candidates, frame.signal, resolver, decision.assertCurrent) : inherited);
122
145
  decision.assertCurrent();
123
146
  frame.signal.throwIfAborted();
124
147
  lock = pinRoleRoute(frame.agent, identity, selected, candidates, { preserveCandidates: parameterPolicy.mode === "native-defaults", initialCandidate: choice?.requestedRoute ?? accepted ?? invocation?.selectedCandidate });
@@ -129,12 +152,27 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
129
152
  lockedAgents.add(frame.agent);
130
153
  }
131
154
  captureRequestRoute(frame, decision, configuredRoot ? lock.effortSource : undefined);
132
- return applyModelRoute(downstream, lock.route);
155
+ return lock.candidateIndex > 0
156
+ ? replacementRouteResult(downstream, lock.route, lock.effortSource)
157
+ : matchingRouteResult(downstream, lock.route, lock.effortSource);
133
158
  };
134
159
  if (owned) {
135
160
  preparations.set(agent, prepare);
136
161
  dispose = () => { if (preparations.get(agent) === prepare)
137
162
  preparations.delete(agent); };
163
+ disposeFence = readyCtx.on("agent/request", async (frame, next) => {
164
+ 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;
169
+ const proposal = await next();
170
+ if (expected !== undefined && (currentRoleRouteLock(frame.agent) !== expected || !sameModelRoute(proposal, expected.route)
171
+ || proposal.reasoningEffort !== expected.route.reasoningEffort)) {
172
+ throw new LlmError("The request route differs from the model fixed for this step", "INVALID_PREPARED_CALL");
173
+ }
174
+ return proposal;
175
+ }, { prepend: true });
138
176
  }
139
177
  else
140
178
  dispose = readyCtx.on("agent/request", async (frame, next) => prepare(frame, await next()), { prepend: true });
@@ -146,6 +184,8 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
146
184
  dispose();
147
185
  if (typeof disposeAssembly === "function")
148
186
  disposeAssembly();
187
+ if (typeof disposeFence === "function")
188
+ disposeFence();
149
189
  throw error;
150
190
  }
151
191
  readyCtx.effect?.(() => () => {
@@ -158,6 +198,8 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
158
198
  disposeAgent();
159
199
  if (typeof disposeAssembly === "function")
160
200
  disposeAssembly();
201
+ if (typeof disposeFence === "function")
202
+ disposeFence();
161
203
  if (typeof dispose === "function")
162
204
  dispose();
163
205
  });
@@ -169,4 +211,100 @@ export function registerModelRouting(ctx, controller, getSettings, agent) {
169
211
  else if (Object.prototype.hasOwnProperty.call(ctx, "llm") && Object.prototype.hasOwnProperty.call(ctx, "on"))
170
212
  install(ctx);
171
213
  }
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;
219
+ 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;
227
+ const parameterPolicy = info.admission === undefined ? configuredModelParameterPolicy(settings) : resolvedModelParameterPolicy(info.admission);
228
+ const invocation = capturedRoleInvocation(agent);
229
+ const fallbacks = effectiveRoleFallbackRoutes(settings, role);
230
+ const primary = invocation?.initialRoute ?? settings.roleRouting[role]?.primary;
231
+ if (configuredRoot && primary === undefined || subagent && invocation === undefined)
232
+ return undefined;
233
+ 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);
243
+ }
244
+ }
245
+ catch (error) {
246
+ if (!configuredRoot || activeRole !== undefined)
247
+ throw error;
248
+ unavailable = error;
249
+ }
250
+ info.assertCurrent();
251
+ 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;
309
+ }
172
310
  //# sourceMappingURL=model-routing.js.map