@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
@@ -40,7 +40,7 @@ import { scopeLifetime } from "./lifetime.js";
40
40
  import { runtimeAdmissionView } from "./runtime-integration.js";
41
41
  import { invocationView } from "./role-invocation.js";
42
42
  import { roleRouteComparison } from "./role-subagents.js";
43
- import { ROLE_CONTROL_HOST, parseChildSessionSnapshot, parseRoleControlDescendants, parseRoleControlPromptRequest, parseRoleControlInterruptRequest, parseRoleControlSessionId } from "./role-control-remote.js";
43
+ import { ROLE_CONTROL_HOST, parseChildSessionSnapshot, parseRoleCallObservationFrame, parseRoleControlDescendants, parseRoleControlPromptRequest, parseRoleControlInterruptRequest, parseRoleControlSessionId } from "./role-control-remote.js";
44
44
  const unavailable = { enabled: false, reason: "unavailable" };
45
45
  class ControlRefusal extends Error {
46
46
  code;
@@ -63,6 +63,7 @@ function boundedLabel(label) {
63
63
  let DsmmChildrenHost = (() => {
64
64
  let _classSuper = TypertRemoteService;
65
65
  let _instanceExtraInitializers = [];
66
+ let _observe_decorators;
66
67
  let _describe_decorators;
67
68
  let _descendants_decorators;
68
69
  let _prompt_decorators;
@@ -70,10 +71,12 @@ let DsmmChildrenHost = (() => {
70
71
  return class DsmmChildrenHost extends _classSuper {
71
72
  static {
72
73
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
74
+ _observe_decorators = [Remote({ mode: "stream" })];
73
75
  _describe_decorators = [Remote];
74
76
  _descendants_decorators = [Remote];
75
77
  _prompt_decorators = [Remote];
76
78
  _interrupt_decorators = [Remote];
79
+ __esDecorate(this, null, _observe_decorators, { kind: "method", name: "observe", static: false, private: false, access: { has: obj => "observe" in obj, get: obj => obj.observe }, metadata: _metadata }, null, _instanceExtraInitializers);
77
80
  __esDecorate(this, null, _describe_decorators, { kind: "method", name: "describe", static: false, private: false, access: { has: obj => "describe" in obj, get: obj => obj.describe }, metadata: _metadata }, null, _instanceExtraInitializers);
78
81
  __esDecorate(this, null, _descendants_decorators, { kind: "method", name: "descendants", static: false, private: false, access: { has: obj => "descendants" in obj, get: obj => obj.descendants }, metadata: _metadata }, null, _instanceExtraInitializers);
79
82
  __esDecorate(this, null, _prompt_decorators, { kind: "method", name: "prompt", static: false, private: false, access: { has: obj => "prompt" in obj, get: obj => obj.prompt }, metadata: _metadata }, null, _instanceExtraInitializers);
@@ -87,59 +90,107 @@ let DsmmChildrenHost = (() => {
87
90
  this.admission = admission;
88
91
  scopeLifetime(ctx, "dsmm: retire child controls", () => this.lifetime.abort());
89
92
  }
93
+ openScope(id, extraSignal) {
94
+ const sessionId = parseRoleControlSessionId(id), invocation = this.ctx.invocation;
95
+ const connection = this.ctx.get("connection");
96
+ if (!invocation?.peer || connection?.browserPeer !== invocation.peer)
97
+ throw new ControlRefusal("not-owned");
98
+ const owner = Reflect.get(connection, symbols.original) ?? connection;
99
+ const agents = this.ctx.get("agents");
100
+ if (!agents)
101
+ throw new ControlRefusal("unavailable");
102
+ const parent = agents.get(SessionId(sessionId));
103
+ if (!parent)
104
+ throw new ControlRefusal("not-found", "sessionId");
105
+ if (!agents.roots().includes(parent) || parent.session.header.origin === "subagent" || parent.session.id !== parent.id)
106
+ throw new ControlRefusal("not-owned", "sessionId");
107
+ const captured = this.admission.assert(parent);
108
+ const signal = AbortSignal.any([invocation.signal, invocation.peer.signal, this.lifetime.signal, this.admission.lifetime.signal,
109
+ ...(extraSignal === undefined ? [] : [extraSignal])]);
110
+ const check = () => {
111
+ signal.throwIfAborted();
112
+ const current = this.ctx.get("connection");
113
+ if (!current || (Reflect.get(current, symbols.original) ?? current) !== owner || current.browserPeer !== invocation.peer
114
+ || this.admission.assert(parent) !== captured || agents.get(parent.id) !== parent)
115
+ throw new ControlRefusal("not-owned", "sessionId");
116
+ };
117
+ check();
118
+ return { parent, admission: captured, epoch: captured.epoch, signal, check };
119
+ }
120
+ observationRoot(target, agents) {
121
+ const roots = agents.roots(), residents = agents.list(), seen = new Set();
122
+ let current = target;
123
+ while (!roots.includes(current)) {
124
+ if (seen.has(current))
125
+ throw new ControlRefusal("not-owned", "sessionId");
126
+ seen.add(current);
127
+ const parents = residents.filter(candidate => candidate !== current && agents.isOwnedBy(current.id, candidate));
128
+ if (parents.length !== 1)
129
+ throw new ControlRefusal("not-owned", "sessionId");
130
+ current = parents[0];
131
+ }
132
+ if (current.session.header.origin === "subagent" || current.session.id !== current.id)
133
+ throw new ControlRefusal("not-owned", "sessionId");
134
+ return current;
135
+ }
136
+ openObservationScope(id, extraSignal) {
137
+ const sessionId = parseRoleControlSessionId(id), invocation = this.ctx.invocation;
138
+ const connection = this.ctx.get("connection");
139
+ if (!invocation?.peer || connection?.browserPeer !== invocation.peer)
140
+ throw new ControlRefusal("not-owned");
141
+ const owner = Reflect.get(connection, symbols.original) ?? connection;
142
+ const agents = this.ctx.get("agents");
143
+ if (!agents)
144
+ throw new ControlRefusal("unavailable");
145
+ const parent = agents.get(SessionId(sessionId));
146
+ if (!parent)
147
+ throw new ControlRefusal("not-found", "sessionId");
148
+ const root = this.observationRoot(parent, agents), captured = this.admission.assert(parent);
149
+ const signal = AbortSignal.any([invocation.signal, invocation.peer.signal, this.lifetime.signal, this.admission.lifetime.signal, extraSignal]);
150
+ const check = () => {
151
+ signal.throwIfAborted();
152
+ const current = this.ctx.get("connection");
153
+ if (!current || (Reflect.get(current, symbols.original) ?? current) !== owner || current.browserPeer !== invocation.peer
154
+ || agents.get(parent.id) !== parent || this.observationRoot(parent, agents) !== root || this.admission.assert(parent) !== captured) {
155
+ throw new ControlRefusal("not-owned", "sessionId");
156
+ }
157
+ };
158
+ check();
159
+ return { parent, admission: captured, epoch: captured.epoch, signal, check };
160
+ }
161
+ refusal(error, operationSignal) {
162
+ let info;
163
+ if (operationSignal?.aborted)
164
+ info = { code: "cancelled" };
165
+ else if (error instanceof ControlRefusal)
166
+ info = { code: error.code, ...(error.field === undefined ? {} : { field: error.field }), ...(error.reason === undefined ? {} : { reason: error.reason }) };
167
+ else if (error instanceof TypeError)
168
+ info = { code: "validation", field: "request" };
169
+ else {
170
+ const code = remoteErrorOf(error)?.code ?? (error instanceof SubagentError ? error.code : undefined);
171
+ if (code === "ABORTED" || code === "gateway/cancelled" || error instanceof Error && error.name === "AbortError")
172
+ info = { code: "cancelled" };
173
+ else if (code === "UNAUTHORIZED" || code === "subagent/unauthorized")
174
+ info = { code: "not-owned" };
175
+ else if (code === "NOT_RESUMABLE" || code === "subagent/not-resumable")
176
+ info = { code: "not-resumable", field: "childSessionId" };
177
+ else if (code === "subagent/attachment-invalid" || code === "gateway/bad-request")
178
+ info = { code: "invalid-content", field: "content" };
179
+ else if (code === "subagent/invalid-time-zone")
180
+ info = { code: "invalid-time-zone", field: "clientTimeZone" };
181
+ else
182
+ info = { code: "unavailable" };
183
+ }
184
+ return new RemoteError("dsmm-children/refused", "The Host refused the native child control operation.", info);
185
+ }
90
186
  async scoped(id, operation) {
91
- let operationSignal;
187
+ let scope;
92
188
  try {
93
- const sessionId = parseRoleControlSessionId(id), invocation = this.ctx.invocation;
94
- const connection = this.ctx.get("connection");
95
- if (!invocation?.peer || connection?.browserPeer !== invocation.peer)
96
- throw new ControlRefusal("not-owned");
97
- const owner = Reflect.get(connection, symbols.original) ?? connection;
98
- const agents = this.ctx.get("agents");
99
- if (!agents)
100
- throw new ControlRefusal("unavailable");
101
- const parent = agents.get(SessionId(sessionId));
102
- if (!parent)
103
- throw new ControlRefusal("not-found", "sessionId");
104
- if (!agents.roots().includes(parent) || parent.session.header.origin === "subagent" || parent.session.id !== parent.id)
105
- throw new ControlRefusal("not-owned", "sessionId");
106
- const captured = this.admission.assert(parent);
107
- const signal = AbortSignal.any([invocation.signal, invocation.peer.signal, this.lifetime.signal, this.admission.lifetime.signal]);
108
- operationSignal = signal;
109
- const check = () => {
110
- signal.throwIfAborted();
111
- const current = this.ctx.get("connection");
112
- if (!current || (Reflect.get(current, symbols.original) ?? current) !== owner || current.browserPeer !== invocation.peer
113
- || this.admission.assert(parent) !== captured || agents.get(parent.id) !== parent)
114
- throw new ControlRefusal("not-owned", "sessionId");
115
- };
116
- check();
117
- return await operation({ parent, epoch: captured.epoch, signal, check });
189
+ scope = this.openScope(id);
190
+ return await operation(scope);
118
191
  }
119
192
  catch (error) {
120
- let info;
121
- if (operationSignal?.aborted)
122
- info = { code: "cancelled" };
123
- else if (error instanceof ControlRefusal)
124
- info = { code: error.code, ...(error.field === undefined ? {} : { field: error.field }), ...(error.reason === undefined ? {} : { reason: error.reason }) };
125
- else if (error instanceof TypeError)
126
- info = { code: "validation", field: "request" };
127
- else {
128
- const code = remoteErrorOf(error)?.code ?? (error instanceof SubagentError ? error.code : undefined);
129
- if (code === "ABORTED" || code === "gateway/cancelled" || error instanceof Error && error.name === "AbortError")
130
- info = { code: "cancelled" };
131
- else if (code === "UNAUTHORIZED" || code === "subagent/unauthorized")
132
- info = { code: "not-owned" };
133
- else if (code === "NOT_RESUMABLE" || code === "subagent/not-resumable")
134
- info = { code: "not-resumable", field: "childSessionId" };
135
- else if (code === "subagent/attachment-invalid" || code === "gateway/bad-request")
136
- info = { code: "invalid-content", field: "content" };
137
- else if (code === "subagent/invalid-time-zone")
138
- info = { code: "invalid-time-zone", field: "clientTimeZone" };
139
- else
140
- info = { code: "unavailable" };
141
- }
142
- throw new RemoteError("dsmm-children/refused", "The Host refused the native child control operation.", info);
193
+ throw this.refusal(error, scope?.signal);
143
194
  }
144
195
  }
145
196
  capabilities(scope) {
@@ -161,6 +212,27 @@ let DsmmChildrenHost = (() => {
161
212
  ...(invocation === undefined ? {} : { invocation: invocationView(invocation, boundedLabel(entry.label ?? invocation.target), "continuable", { childId: entry.id }) }),
162
213
  ...(child === undefined ? {} : { routeComparison: roleRouteComparison(child) }) };
163
214
  }
215
+ observe(sessionId, signal) {
216
+ let scope;
217
+ try {
218
+ scope = this.openObservationScope(sessionId, signal);
219
+ }
220
+ catch (error) {
221
+ throw this.refusal(error, signal);
222
+ }
223
+ return this.followObservedCalls(scope);
224
+ }
225
+ async *followObservedCalls(scope) {
226
+ try {
227
+ for await (const frame of this.admission.observeRoleCalls(scope.parent, scope.admission, scope.signal, scope.check)) {
228
+ scope.check();
229
+ yield parseRoleCallObservationFrame(frame);
230
+ }
231
+ }
232
+ catch (error) {
233
+ throw this.refusal(error, scope.signal);
234
+ }
235
+ }
164
236
  describe(sessionId) {
165
237
  return this.scoped(sessionId, async (scope) => {
166
238
  const rows = await this.ctx.get("subagents").listChildren(scope.parent.id, scope.signal);
@@ -1,7 +1,68 @@
1
1
  /** Browser-safe child control vocabulary; no Host or filesystem authority. */
2
- import type { DsmmInvocationView, DsmmRoleRouteComparison, SubagentRuntimeAdmissionView } from "./profile-types.js";
2
+ import type { DsmmInvocationLevel } from "./settings.js";
3
+ import type { DsmmInvocationView, DsmmRoleRouteComparison, DsmmRouteSource, SubagentRuntimeAdmissionView } from "./profile-types.js";
3
4
  import type { SubagentPromptReceipt, SubagentPromptRequest, SubagentInterruptReceipt } from "@deepseek-ai/dsh-subagent";
4
5
  export type { DsmmInvocationView, DsmmRoleRouteComparison, SubagentPromptRequest, SubagentPromptReceipt, SubagentInterruptReceipt };
6
+ export declare const ROLE_CALL_PHASES: readonly ["reserved", "active", "settled"];
7
+ export declare const ROLE_CALL_DELIVERIES: readonly ["caller", "parent"];
8
+ export declare const ROLE_CALL_STOP_REASONS: readonly ["completed", "aborted", "error", "max-tokens", "refusal"];
9
+ export type RoleCallPhase = typeof ROLE_CALL_PHASES[number];
10
+ export type RoleCallDelivery = typeof ROLE_CALL_DELIVERIES[number];
11
+ export type RoleCallStopReason = typeof ROLE_CALL_STOP_REASONS[number];
12
+ export type RoleCallModelRoute = {
13
+ readonly provider: string;
14
+ readonly model: string;
15
+ readonly reasoningEffort?: string;
16
+ };
17
+ export type RoleCallInitialRoute = {
18
+ readonly status: "known";
19
+ readonly source: "invocation-capture";
20
+ readonly route: RoleCallModelRoute;
21
+ } | {
22
+ readonly status: "unknown";
23
+ readonly reason: "missing-invocation-capture";
24
+ };
25
+ export type RoleCallActualRoute = {
26
+ readonly status: "known";
27
+ readonly source: "own-native-request-header";
28
+ readonly route: RoleCallModelRoute;
29
+ } | {
30
+ readonly status: "unknown";
31
+ readonly reason: "no-own-request-header" | "invalid-own-request-header" | "not-observed";
32
+ };
33
+ export interface RoleCallObservation {
34
+ readonly parentSessionId: string;
35
+ readonly parentAdmissionEpoch: string;
36
+ readonly childAdmissionEpoch?: string;
37
+ readonly callId: string;
38
+ readonly rootCallId: string;
39
+ readonly childId: string;
40
+ readonly runId?: string;
41
+ readonly role: Exclude<import("./roles.js").DsmmRoleId, "dsmm-orchestrator">;
42
+ readonly level: DsmmInvocationLevel;
43
+ readonly routeSource: DsmmRouteSource;
44
+ readonly initialRoute: RoleCallInitialRoute;
45
+ readonly actualRoute: RoleCallActualRoute;
46
+ readonly phase: RoleCallPhase;
47
+ readonly delivery: RoleCallDelivery;
48
+ readonly stopReason?: RoleCallStopReason;
49
+ }
50
+ export type RoleCallObservationFrame = {
51
+ readonly type: "snapshot";
52
+ readonly sessionId: string;
53
+ readonly admissionEpoch: string;
54
+ readonly calls: readonly RoleCallObservation[];
55
+ } | {
56
+ readonly type: "update";
57
+ readonly sessionId: string;
58
+ readonly admissionEpoch: string;
59
+ readonly call: RoleCallObservation;
60
+ } | {
61
+ readonly type: "remove";
62
+ readonly sessionId: string;
63
+ readonly admissionEpoch: string;
64
+ readonly callId: string;
65
+ };
5
66
  export declare const ROLE_CONTROL_DISABLED_REASONS: readonly ["module-off", "role-disabled", "read-only", "one-shot", "unknown-mode", "not-direct-child", "evidence-unavailable", "unavailable"];
6
67
  export type RoleControlDisabledReason = typeof ROLE_CONTROL_DISABLED_REASONS[number];
7
68
  export type RoleControlAvailability = {
@@ -1,3 +1,6 @@
1
+ export const ROLE_CALL_PHASES = ["reserved", "active", "settled"];
2
+ export const ROLE_CALL_DELIVERIES = ["caller", "parent"];
3
+ export const ROLE_CALL_STOP_REASONS = ["completed", "aborted", "error", "max-tokens", "refusal"];
1
4
  export const ROLE_CONTROL_DISABLED_REASONS = [
2
5
  "module-off", "role-disabled", "read-only", "one-shot", "unknown-mode", "not-direct-child",
3
6
  "evidence-unavailable", "unavailable",
@@ -120,7 +120,7 @@ export async function resolveRoleInvocation(parent, target, settings, signal, op
120
120
  const candidates = [project(route, effortSource), ...effectiveFallbacks];
121
121
  const selectedSource = selectedIndex === 0 || candidateEffort !== undefined ? effortSource : "dsmm-config";
122
122
  return freezeSettings({ target, ...(options.level === undefined ? {} : { requestedLevel: options.level }), effectiveLevel: level,
123
- routeSource: source, initialRoute: project(selected.route, selectedSource), selectedCandidate: selected.requestedRoute, requestedRoute: initialCandidates[selectedIndex], candidates, exactEffort,
123
+ routeSource: source, initialRoute: project(selected.proposal, selectedSource), selectedCandidate: selected.requestedRoute, requestedRoute: initialCandidates[selectedIndex], candidates, exactEffort,
124
124
  effortSource: selectedSource, modelParameterPolicy,
125
125
  requestedPolicy: { ...policy, primary: route, fallbackRoutes },
126
126
  policy: { ...policy, primary: project(route, effortSource), fallbackRoutes: effectiveFallbacks } });
@@ -1,7 +1,7 @@
1
1
  import { LlmError } from "@deepseek-ai/dsh-llm";
2
2
  import { captureDsmmEffortSource, requiresDsmmCallAdmission, snapshotDsmmCall } from "./host-llm.js";
3
3
  import { resolvedModelParameterPolicy } from "./model-parameter-policy.js";
4
- import { modelRouteFromCall, projectModelRouteParameters } from "./role-llm.js";
4
+ import { modelRouteFromCall, modelRouteToCall } from "./role-llm.js";
5
5
  import { prepareDsmmRequest } from "./model-routing.js";
6
6
  import { preparedRequestRouting } from "./request-routing.js";
7
7
  import { roleRouteLock } from "./role-routing.js";
@@ -43,7 +43,7 @@ export function createDsmmRoleLlmOwner(ctx, providers) {
43
43
  const originalAdmission = admission;
44
44
  admission = Object.freeze({ ...originalAdmission, assertCurrent() { originalAdmission.assertCurrent(); routing.assertCurrent(); } });
45
45
  const effortSource = routing.effortSource ?? captureDsmmEffortSource(frame.agent);
46
- const config = snapshotDsmmCall(projectModelRouteParameters(modelRouteFromCall(routed), effortSource, policy.mode !== "native-defaults"));
46
+ const config = snapshotDsmmCall(modelRouteToCall(modelRouteFromCall(routed)));
47
47
  admission.assertCurrent();
48
48
  if (routing.decision.configuredRoot && routing.decision.policy !== undefined) {
49
49
  const lock = roleRouteLock(agent, routing.decision.policy);
@@ -1,8 +1,12 @@
1
- import type { AgentRequestFrame, DshAgent, DshContext, DshLlmCallConfig, DshLlmRuntime } from "./dsh-types.js";
1
+ import type { AgentRequestFrame, DshAgent, DshAgentModel, DshContext, DshLlmCallConfig, DshLlmRuntime } from "./dsh-types.js";
2
2
  import type { DsmmRoleId } from "./roles.js";
3
3
  import type { DsmmModelRoute, 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
+ }
6
10
  export declare const DSMM_ROLE_POLICY_EVENT = "dsmm/role-policy";
7
11
  export interface RoleRouteLock {
8
12
  identity: string;
@@ -23,7 +27,18 @@ export interface NativeModelSelectionIntent {
23
27
  seq: number;
24
28
  route: DsmmModelRoute;
25
29
  }
26
- /** Native user selection is authority; inherited headers/default configs are not. */
30
+ /** DSH 0.2.2+ hosts fix the model selection before step preparation; 0.2.1 exposes no such seam. */
31
+ export declare function hostModelSelection(agent: DshAgent): DshAgentModel | undefined;
32
+ export declare function latestModelSelectionSeq(agent: DshAgent): number;
33
+ /** Persist only selections appended during this unpublished activation's trusted setup window. */
34
+ export declare function captureSetupModelSelections(agent: DshAgent, cursor: number): void;
35
+ /**
36
+ * Record a DSMM-owned selection for future steps. On 0.2.1 hosts this is a no-op;
37
+ * callers keep their request-time route binding. Same-value selections append no
38
+ * event and record nothing, matching the native idempotent contract.
39
+ */
40
+ export declare function selectModelRouteForNextStep(agent: DshAgent, route: Pick<DsmmModelRoute, "provider" | "model" | "reasoningEffort">): void;
41
+ /** Native user selection is authority; inherited headers/default configs are not. DSMM's own selections are not manual intent. */
27
42
  export declare function latestNativeModelSelection(agent: DshAgent): NativeModelSelectionIntent | undefined;
28
43
  export declare function sameExactModelRoute(left: Pick<DsmmModelRoute, "provider" | "model" | "reasoningEffort">, right: DsmmModelRoute): boolean;
29
44
  /** Consumed user intent stays explicit on cold resume and profile re-admission. */
@@ -33,16 +48,21 @@ export declare function isUnavailableRouteFailure(error: unknown, nativeRequestF
33
48
  export declare function orderedModelRoutes(candidates: readonly DsmmModelRoute[]): DsmmModelRoute[];
34
49
  /** Exact metadata preparation, never a completion or advisory catalog health check. */
35
50
  export declare function selectInitialModelRoute(llm: DshLlmRuntime, candidates: readonly DsmmModelRoute[], signal?: AbortSignal, resolver?: DsmmLlmRouteResolver, assertCurrent?: () => void): Promise<DsmmModelRoute>;
36
- export declare function selectInitialModelRouteChoice(llm: DshLlmRuntime, candidates: readonly DsmmModelRoute[], signal?: AbortSignal, resolver?: DsmmLlmRouteResolver, project?: (route: DsmmModelRoute) => DsmmModelRoute, assertCurrent?: () => void): Promise<{
37
- route: DsmmModelRoute;
38
- requestedRoute: DsmmModelRoute;
39
- }>;
51
+ export interface InitialModelRouteChoice {
52
+ readonly requestedRoute: DsmmModelRoute;
53
+ readonly proposal: DsmmModelRoute;
54
+ readonly effective: DsmmModelRoute;
55
+ }
56
+ export declare function selectInitialModelRouteChoice(llm: DshLlmRuntime, candidates: readonly DsmmModelRoute[], signal?: AbortSignal, resolver?: DsmmLlmRouteResolver, project?: (route: DsmmModelRoute) => DsmmModelRoute, assertCurrent?: () => void): Promise<InitialModelRouteChoice>;
40
57
  export declare function roleRouteLock(agent: DshAgent, identity: string): RoleRouteLock | undefined;
41
58
  export declare function pinRoleRoute(agent: DshAgent, identity: string, route: DsmmModelRoute, candidates: readonly DsmmModelRoute[], projection?: {
42
59
  preserveCandidates: boolean;
43
60
  initialCandidate?: DsmmModelRoute;
44
61
  }): RoleRouteLock;
45
62
  export declare function clearRoleRouteLock(agent: DshAgent): void;
63
+ 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;
46
66
  export declare function roleRouteRuntimeState(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): DsmmRoleRuntimeState;
47
67
  export declare function liveRolePolicyIdentity(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): string | undefined;
48
68
  /** Native custom events are model-hidden log facts, retained across surface compaction. */
@@ -50,7 +70,7 @@ export declare function establishRolePolicy(frame: AgentRequestFrame, settings:
50
70
  export declare function recordAdmittedRecoveryRoute(frame: AgentRequestFrame, route: DsmmModelRoute): void;
51
71
  export declare function takeAdmittedRecoveryRoute(frame: AgentRequestFrame): DsmmModelRoute | undefined;
52
72
  export declare function effectiveRoleFallbackRoutes(settings: DsmmSettings, role: DsmmRoleId | undefined): readonly DsmmModelRoute[];
53
- export declare function applyModelRoute(config: DshLlmCallConfig, route: DsmmModelRoute): DshLlmCallConfig;
73
+ export declare function applyModelRoute(_config: DshLlmCallConfig, route: DsmmModelRoute): DshLlmCallConfig;
54
74
  export declare function sameModelRoute(left: Pick<DsmmModelRoute, "provider" | "model">, right: Pick<DsmmModelRoute, "provider" | "model">): boolean;
55
75
  /** Accepted post-policy route changes are durable host/recovery ownership, not a new primary request. */
56
76
  export declare function persistedRoleRoute(frame: Pick<AgentRequestFrame, "agent">, primary: DsmmModelRoute | undefined, fallbacks?: readonly DsmmModelRoute[], identity?: string, configuredRoot?: boolean): DsmmModelRoute | undefined;
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { isDeepStrictEqual } from "node:util";
3
3
  import { LlmError } from "@deepseek-ai/dsh-llm";
4
- import { appendRolePolicyRecord } from "./session-metadata.js";
4
+ import { appendModelSelectionRecord, appendRolePolicyRecord, readModelSelectionRecord } from "./session-metadata.js";
5
5
  import { isDsmmRoleId } from "./roles.js";
6
6
  import { isCurrentRecoveryStep } from "./recovery-policy.js";
7
7
  import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
@@ -12,18 +12,113 @@ const admittedRecoveryRoutes = new WeakMap();
12
12
  const routeLocks = new WeakMap();
13
13
  const agentPolicies = new WeakMap();
14
14
  export const DSMM_ROLE_POLICY_EVENT = "dsmm/role-policy";
15
- /** Native user selection is authority; inherited headers/default configs are not. */
16
- export function latestNativeModelSelection(agent) {
17
- let selected;
15
+ /** DSMM's own pre-step selections, excluded from native manual-intent detection. */
16
+ const selfModelSelectionSeqs = new WeakMap();
17
+ const selfSelectionWindows = new WeakMap();
18
+ function selectionRoute(event) {
19
+ if (event.type !== "model/selection" || typeof event.seq !== "number" || !Number.isSafeInteger(event.seq) || !isRecord(event.data))
20
+ return undefined;
21
+ const { provider, model, reasoningEffort } = event.data;
22
+ if (typeof provider !== "string" || provider.trim() === "" || typeof model !== "string" || model.trim() === ""
23
+ || reasoningEffort !== undefined && (typeof reasoningEffort !== "string" || reasoningEffort.trim() === ""))
24
+ return undefined;
25
+ return { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) };
26
+ }
27
+ function nonManualSelections(agent, events) {
28
+ const selected = new Map();
29
+ for (const event of events) {
30
+ const route = selectionRoute(event);
31
+ if (route !== undefined)
32
+ selected.set(Number(event.seq), route);
33
+ }
34
+ const result = new Set(selfModelSelectionSeqs.get(agent));
35
+ for (const event of events) {
36
+ const association = readModelSelectionRecord(event);
37
+ const route = association === undefined ? undefined : selected.get(association.selectionSeq);
38
+ if (association !== undefined && association.recordSeq > association.selectionSeq && route !== undefined
39
+ && sameExactModelRoute(route, association.route))
40
+ result.add(association.selectionSeq);
41
+ }
42
+ const window = selfSelectionWindows.get(agent);
43
+ if (window !== undefined)
44
+ for (const [seq, route] of selected) {
45
+ if (seq > window.afterSeq && sameExactModelRoute(route, window.route))
46
+ result.add(seq);
47
+ }
48
+ return result;
49
+ }
50
+ /** DSH 0.2.2+ hosts fix the model selection before step preparation; 0.2.1 exposes no such seam. */
51
+ export function hostModelSelection(agent) {
52
+ const model = agent.model;
53
+ return typeof model?.select === "function" && typeof model.current === "function" ? model : undefined;
54
+ }
55
+ export function latestModelSelectionSeq(agent) {
56
+ let seq = -1;
18
57
  for (const event of policyEvents({ agent })) {
19
- if (event.type !== "model/selection" || !("seq" in event) || !Number.isSafeInteger(event.seq)
20
- || typeof event.seq !== "number" || event.seq < 0 || !isRecord(event.data))
58
+ if (event.type === "model/selection" && typeof event.seq === "number")
59
+ seq = Math.max(seq, event.seq);
60
+ }
61
+ return seq;
62
+ }
63
+ /** Persist only selections appended during this unpublished activation's trusted setup window. */
64
+ export function captureSetupModelSelections(agent, cursor) {
65
+ if (agent.session.header?.origin !== "subagent" || hostModelSelection(agent) === undefined)
66
+ return;
67
+ const events = policyEvents({ agent });
68
+ const associated = new Set(events.flatMap(event => {
69
+ const record = readModelSelectionRecord(event);
70
+ return record?.source === "activation-setup" ? [record.selectionSeq] : [];
71
+ }));
72
+ for (const event of events) {
73
+ const route = selectionRoute(event);
74
+ if (route === undefined || event.seq <= cursor || associated.has(event.seq))
21
75
  continue;
22
- const { provider, model, reasoningEffort } = event.data;
23
- if (typeof provider !== "string" || provider.trim() === "" || typeof model !== "string" || model.trim() === ""
24
- || (reasoningEffort !== undefined && (typeof reasoningEffort !== "string" || reasoningEffort.trim() === "")))
76
+ appendModelSelectionRecord(agent.session, { version: 1, source: "activation-setup", selectionSeq: event.seq, route });
77
+ }
78
+ }
79
+ /**
80
+ * Record a DSMM-owned selection for future steps. On 0.2.1 hosts this is a no-op;
81
+ * callers keep their request-time route binding. Same-value selections append no
82
+ * event and record nothing, matching the native idempotent contract.
83
+ */
84
+ export function selectModelRouteForNextStep(agent, route) {
85
+ const model = hostModelSelection(agent);
86
+ if (model === undefined)
87
+ return;
88
+ const selected = canonicalRoute(route), cursor = latestModelSelectionSeq(agent);
89
+ selfSelectionWindows.set(agent, { afterSeq: cursor, route: selected });
90
+ try {
91
+ model.select({ provider: selected.provider, model: selected.model,
92
+ ...(selected.reasoningEffort === undefined ? {} : { reasoningEffort: selected.reasoningEffort }) });
93
+ }
94
+ finally {
95
+ selfSelectionWindows.delete(agent);
96
+ }
97
+ const event = policyEvents({ agent }).filter(candidate => {
98
+ const candidateRoute = selectionRoute(candidate);
99
+ return candidateRoute !== undefined && Number(candidate.seq) > cursor && sameExactModelRoute(candidateRoute, selected);
100
+ }).sort((left, right) => Number(left.seq) - Number(right.seq))[0];
101
+ if (event === undefined)
102
+ return;
103
+ const seq = Number(event.seq);
104
+ let seqs = selfModelSelectionSeqs.get(agent);
105
+ if (seqs === undefined) {
106
+ seqs = new Set();
107
+ selfModelSelectionSeqs.set(agent, seqs);
108
+ }
109
+ seqs.add(seq);
110
+ appendModelSelectionRecord(agent.session, { version: 1, source: "dsmm-selection", selectionSeq: seq, route: { provider: selected.provider, model: selected.model,
111
+ ...(selected.reasoningEffort === undefined ? {} : { reasoningEffort: selected.reasoningEffort }) } });
112
+ }
113
+ /** Native user selection is authority; inherited headers/default configs are not. DSMM's own selections are not manual intent. */
114
+ export function latestNativeModelSelection(agent) {
115
+ let selected;
116
+ const events = policyEvents({ agent }), excluded = nonManualSelections(agent, events);
117
+ for (const event of events) {
118
+ const route = selectionRoute(event);
119
+ if (route === undefined || !("seq" in event) || typeof event.seq !== "number" || event.seq < 0 || excluded.has(event.seq))
25
120
  continue;
26
- selected = { seq: event.seq, route: { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) } };
121
+ selected = { seq: event.seq, route };
27
122
  }
28
123
  return selected;
29
124
  }
@@ -52,7 +147,7 @@ export function orderedModelRoutes(candidates) {
52
147
  }
53
148
  /** Exact metadata preparation, never a completion or advisory catalog health check. */
54
149
  export async function selectInitialModelRoute(llm, candidates, signal, resolver, assertCurrent) {
55
- return (await selectInitialModelRouteChoice(llm, candidates, signal, resolver, undefined, assertCurrent)).route;
150
+ return (await selectInitialModelRouteChoice(llm, candidates, signal, resolver, undefined, assertCurrent)).proposal;
56
151
  }
57
152
  export async function selectInitialModelRouteChoice(llm, candidates, signal, resolver, project, assertCurrent) {
58
153
  if (resolver === undefined && llm.resolveCallConfig === undefined)
@@ -64,14 +159,17 @@ export async function selectInitialModelRouteChoice(llm, candidates, signal, res
64
159
  try {
65
160
  if (resolver === undefined && llm.listProviders !== undefined && !llm.listProviders().some(provider => provider.id === route.provider))
66
161
  throw new DsmmMissingProviderError();
67
- const projected = project?.(route) ?? route;
68
- const call = modelRouteToCall(projected);
69
- const prepared = resolver === undefined ? await llm.resolveCallConfig(call, signal) : await resolver.resolveRoute(projected, signal);
162
+ const requestedRoute = canonicalRoute(route), proposal = canonicalRoute(project?.(route) ?? route);
163
+ const call = modelRouteToCall(proposal);
164
+ const prepared = resolver === undefined ? await llm.resolveCallConfig(call, signal) : await resolver.resolveRoute(proposal, signal);
70
165
  assertCurrent?.();
71
166
  if (resolver === undefined && call.customParameters !== undefined)
72
167
  throw new LlmError("Raw route parameters require their declared Host provider owner", "UNSUPPORTED_ROUTE_PARAMETERS");
73
168
  signal?.throwIfAborted();
74
- return { route: canonicalRoute(prepared), requestedRoute: canonicalRoute(route) };
169
+ const effective = canonicalRoute(prepared);
170
+ if (!sameModelRoute(proposal, effective))
171
+ throw new LlmError("Provider resolved another model during route admission", "INVALID_ADAPTER");
172
+ return { requestedRoute, proposal, effective };
75
173
  }
76
174
  catch (error) {
77
175
  assertCurrent?.();
@@ -96,6 +194,21 @@ export function pinRoleRoute(agent, identity, route, candidates, projection) {
96
194
  return lock;
97
195
  }
98
196
  export function clearRoleRouteLock(agent) { routeLocks.delete(agent); }
197
+ export function currentRoleRouteLock(agent) { return routeLocks.get(agent); }
198
+ export function currentRolePolicyState(agent) { return agentPolicies.get(agent); }
199
+ export function restoreRolePolicyAndLock(agent, installedPolicy, installedLock, previousPolicy, previousLock) {
200
+ if (agentPolicies.get(agent) !== installedPolicy || routeLocks.get(agent) !== installedLock)
201
+ return false;
202
+ if (previousPolicy === undefined)
203
+ agentPolicies.delete(agent);
204
+ else
205
+ agentPolicies.set(agent, previousPolicy);
206
+ if (previousLock === undefined)
207
+ routeLocks.delete(agent);
208
+ else
209
+ routeLocks.set(agent, previousLock);
210
+ return true;
211
+ }
99
212
  export function roleRouteRuntimeState(agent, settings, role, epoch) {
100
213
  const resolved = resolveRoleRuntimePolicy(settings, role);
101
214
  const identity = liveRolePolicyIdentity(agent, settings, role, epoch);
@@ -187,7 +300,7 @@ export function takeAdmittedRecoveryRoute(frame) {
187
300
  export function effectiveRoleFallbackRoutes(settings, role) {
188
301
  return resolveRoleRuntimePolicy(settings, role).fallbackRoutes;
189
302
  }
190
- export function applyModelRoute(config, route) {
303
+ export function applyModelRoute(_config, route) {
191
304
  return modelRouteToCall(route);
192
305
  }
193
306
  export function sameModelRoute(left, right) {