@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
@@ -3,11 +3,14 @@ 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
7
  import type { DsmmProfileRuntime } from "./profile-runtime.js";
7
8
  import type { DsmmProfileAdmission } from "./settings.js";
8
9
  import type { ResolvedRoleInvocation } from "./role-invocation.js";
9
10
  import type { DsmmRolePolicy } from "./role-policy.js";
10
11
  import type { SessionActionUnavailableReason } from "./profile-types.js";
12
+ import type { DsmmInvocationView } from "./profile-types.js";
13
+ import type { RoleCallDelivery, RoleCallObservationFrame } from "./role-control-types.js";
11
14
  declare module "@deepseek-ai/cordis" {
12
15
  interface Context {
13
16
  dsmmNativeAdmission: NativeAdmission;
@@ -39,12 +42,43 @@ export declare class NativeAdmission {
39
42
  private readonly blankUpdates;
40
43
  private readonly getters;
41
44
  private readonly executions;
45
+ private readonly observedCalls;
46
+ private readonly observedCallRecords;
47
+ private readonly ambiguousCallIds;
48
+ private readonly observedCallTokens;
49
+ private readonly observedCallChildren;
50
+ private readonly observedCallRuns;
51
+ private readonly callSubscribers;
42
52
  private readonly providerScopes;
43
53
  private readonly opaqueAgents;
54
+ private readonly admissionRoutes;
55
+ private readonly admissionRouteFailures;
56
+ private readonly setupSelectionCursors;
44
57
  private ready;
45
58
  private install?;
59
+ private admissionModelSelection?;
46
60
  constructor(ctx: Context, profiles: DsmmProfileRuntime, policy: DsmmRolePolicy, configurationCommitted?: (agents: readonly Agent[]) => void);
47
61
  activate(install: NonNullable<NativeAdmission["install"]>): void;
62
+ /** Bind asynchronous metadata preparation; later lifecycle callbacks only install its immutable result. */
63
+ bindAdmissionModelSelection(hook: (agent: Agent, info: DsmmAdmissionRouteInfo) => Promise<DsmmPreparedAdmissionRoute | undefined>): void;
64
+ private callsFor;
65
+ private recordsFor;
66
+ private observationRoute;
67
+ private observedCall;
68
+ private publishObservedCall;
69
+ private publishObservedRemoval;
70
+ private observedInvocation;
71
+ private startObservedActivation;
72
+ private endObservedActivation;
73
+ private settleObservedActivation;
74
+ private bindObservedChild;
75
+ private observeCallRequestHeader;
76
+ private finishObservedTool;
77
+ private retireObservedParent;
78
+ observeRoleCalls(parent: Agent, admission: DsmmProfileAdmission, signal: AbortSignal, check: () => void): AsyncIterable<RoleCallObservationFrame>;
79
+ private notifyObservedParent;
80
+ private installCachedAdmissionRoute;
81
+ private installCachedAdmissionRouteSafely;
48
82
  get isReady(): boolean;
49
83
  /** Exact process-local capture, retained after retirement so stale objects never become native. */
50
84
  owns(agent: Agent): boolean;
@@ -69,10 +103,11 @@ export declare class NativeAdmission {
69
103
  close(): Promise<void>;
70
104
  }>;
71
105
  private trackExecution;
72
- reserve(exec: Readonly<ToolExecution>, invocation: ResolvedRoleInvocation, provider: SubagentProvider, maxDepth?: number): Promise<{
106
+ reserve(exec: Readonly<ToolExecution>, invocation: ResolvedRoleInvocation, provider: SubagentProvider, label: string, delivery: RoleCallDelivery, maxDepth?: number): Promise<{
73
107
  childId: SessionId;
74
108
  release(): Promise<void>;
75
109
  signal: AbortSignal;
110
+ view(): DsmmInvocationView;
76
111
  }>;
77
112
  duringCall<T>(agent: Agent, signal: AbortSignal, operation: (signal: AbortSignal) => Promise<T>): Promise<T>;
78
113
  prepare(request: ContinuableCreateRequest, provider: SubagentProvider): void;
@@ -5,6 +5,7 @@ import { SessionId } from "@deepseek-ai/dsh-session";
5
5
  import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
6
6
  import { SubagentError, delegationDepthOf, foldSubagentDescriptor } from "@deepseek-ai/dsh-subagent";
7
7
  import { freezeSettings } from "./settings.js";
8
+ import { invocationView } from "./role-invocation.js";
8
9
  import { scopeLifetime } from "./lifetime.js";
9
10
  import { sessionEvents, childOwnedSessionEvents } from "./session-scope.js";
10
11
  import { scopeParentOf, scopeOf } from "./native-scope.js";
@@ -14,8 +15,46 @@ import { resolveRoleInvocation } from "./role-invocation.js";
14
15
  import { resolvedModelParameterPolicy } from "./model-parameter-policy.js";
15
16
  import { roleFromProviderName } from "./role-providers.js";
16
17
  import { isDsmmRoleId } from "./roles.js";
17
- import { latestNativeModelSelection } from "./role-routing.js";
18
+ import { captureSetupModelSelections, latestModelSelectionSeq, latestNativeModelSelection } from "./role-routing.js";
18
19
  import { hasOpenTurn } from "./state.js";
20
+ import { modelRouteFromCall } from "./role-llm.js";
21
+ import { ROLE_CALL_STOP_REASONS } from "./role-control-types.js";
22
+ class RoleCallSubscriber {
23
+ parent;
24
+ admission;
25
+ pending = new Map();
26
+ wake;
27
+ constructor(parent, admission) {
28
+ this.parent = parent;
29
+ this.admission = admission;
30
+ }
31
+ push(call) {
32
+ this.pending.set(call.callId, { type: "update", call });
33
+ this.wake?.();
34
+ }
35
+ remove(callId) {
36
+ this.pending.set(callId, { type: "remove", callId });
37
+ this.wake?.();
38
+ }
39
+ take() {
40
+ const changes = [...this.pending.values()];
41
+ this.pending.clear();
42
+ return changes;
43
+ }
44
+ async changed(signal) {
45
+ if (this.pending.size > 0)
46
+ return;
47
+ await new Promise(resolve => {
48
+ const wake = () => { signal.removeEventListener("abort", wake); if (this.wake === wake)
49
+ this.wake = undefined; resolve(); };
50
+ this.wake = wake;
51
+ signal.addEventListener("abort", wake, { once: true });
52
+ if (signal.aborted || this.pending.size > 0)
53
+ wake();
54
+ });
55
+ }
56
+ notify() { this.wake?.(); }
57
+ }
19
58
  /** Short-lived creation correlations and exact live bindings, never an execution queue. */
20
59
  export class NativeAdmission {
21
60
  ctx;
@@ -42,10 +81,21 @@ export class NativeAdmission {
42
81
  blankUpdates = new WeakMap();
43
82
  getters = new WeakMap();
44
83
  executions = new WeakMap();
84
+ observedCalls = new WeakMap();
85
+ observedCallRecords = new WeakMap();
86
+ ambiguousCallIds = new WeakMap();
87
+ observedCallTokens = new Map();
88
+ observedCallChildren = new Map();
89
+ observedCallRuns = new Map();
90
+ callSubscribers = new Set();
45
91
  providerScopes = new Map();
46
92
  opaqueAgents = new WeakSet();
93
+ admissionRoutes = new WeakMap();
94
+ admissionRouteFailures = new WeakMap();
95
+ setupSelectionCursors = new WeakMap();
47
96
  ready = false;
48
97
  install;
98
+ admissionModelSelection;
49
99
  constructor(ctx, profiles, policy, configurationCommitted = () => { }) {
50
100
  this.ctx = ctx;
51
101
  this.profiles = profiles;
@@ -54,6 +104,11 @@ export class NativeAdmission {
54
104
  scopeLifetime(ctx, "dsmm: close admission before owner teardown", () => {
55
105
  this.lifetime.abort();
56
106
  this.pending.clear();
107
+ for (const subscriber of this.callSubscribers)
108
+ subscriber.notify();
109
+ this.observedCallTokens.clear();
110
+ this.observedCallChildren.clear();
111
+ this.observedCallRuns.clear();
57
112
  for (const agent of this.agents)
58
113
  agent.cancel({ kind: "disposed" });
59
114
  });
@@ -79,11 +134,44 @@ export class NativeAdmission {
79
134
  for (const agent of ctx.agents.list())
80
135
  this.opaqueAgents.add(agent);
81
136
  observeProviders();
137
+ ctx.on("subagent/start", info => { this.startObservedActivation(info); }, { global: true });
138
+ ctx.on("subagent/end", info => { this.endObservedActivation(info); }, { global: true });
139
+ ctx.on("session/created", session => {
140
+ this.setupSelectionCursors.set(session, latestModelSelectionSeq({ session }));
141
+ }, { global: true });
142
+ ctx.on("session/disposed", session => { this.setupSelectionCursors.delete(session); }, { global: true });
82
143
  ctx.on("agent/created", async (frame) => { await this.created(frame.agent, frame.source, frame.signal); }, { 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
+ ctx.on("session/event", (session, event) => {
148
+ if (event.type === "request/header")
149
+ 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
+ }, { global: true });
83
168
  ctx.on("agent/disposed", ({ agent }) => {
84
169
  void this.retireAgent(agent).catch(() => { });
170
+ this.retireObservedParent(agent);
85
171
  this.live.delete(agent);
86
172
  this.candidates.delete(agent);
173
+ this.admissionRoutes.delete(agent);
174
+ this.admissionRouteFailures.delete(agent);
87
175
  this.agents.delete(agent);
88
176
  for (const activation of this.activations)
89
177
  if (activation.childId === agent.id)
@@ -107,8 +195,11 @@ export class NativeAdmission {
107
195
  }
108
196
  return next();
109
197
  }, { global: true, prepend: true });
110
- ctx.on("tools/result", exec => { if (exec.agent)
111
- this.executions.get(exec.agent)?.delete(exec.token); }, { global: true });
198
+ ctx.on("tools/result", (exec, result) => {
199
+ if (exec.agent)
200
+ this.executions.get(exec.agent)?.delete(exec.token);
201
+ this.finishObservedTool(exec, result);
202
+ }, { global: true });
112
203
  ctx.on("agent-preset/selected", id => {
113
204
  const agent = ctx.agents.get(id);
114
205
  if (!agent || !this.live.has(agent))
@@ -123,6 +214,204 @@ export class NativeAdmission {
123
214
  this.install = install;
124
215
  this.ready = true;
125
216
  }
217
+ /** Bind asynchronous metadata preparation; later lifecycle callbacks only install its immutable result. */
218
+ bindAdmissionModelSelection(hook) {
219
+ this.admissionModelSelection = hook;
220
+ }
221
+ callsFor(parent) {
222
+ let calls = this.observedCalls.get(parent);
223
+ if (calls === undefined) {
224
+ calls = new Map();
225
+ this.observedCalls.set(parent, calls);
226
+ }
227
+ return calls;
228
+ }
229
+ recordsFor(parent) {
230
+ let records = this.observedCallRecords.get(parent);
231
+ if (records === undefined) {
232
+ records = new Set();
233
+ this.observedCallRecords.set(parent, records);
234
+ }
235
+ return records;
236
+ }
237
+ observationRoute(route) {
238
+ return Object.freeze({ provider: route.provider, model: route.model,
239
+ ...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }) });
240
+ }
241
+ observedCall(record) {
242
+ return Object.freeze({ parentSessionId: record.parent.id, parentAdmissionEpoch: record.parentAdmission.epoch,
243
+ ...(record.childAdmission === undefined ? {} : { childAdmissionEpoch: record.childAdmission.epoch }),
244
+ callId: record.callId, rootCallId: record.rootCallId, childId: record.childId,
245
+ ...(record.runId === undefined ? {} : { runId: record.runId }), role: record.role,
246
+ level: record.invocation.effectiveLevel, routeSource: record.invocation.routeSource,
247
+ initialRoute: Object.freeze({ status: "known", source: "invocation-capture", route: this.observationRoute(record.invocation.initialRoute) }),
248
+ actualRoute: record.actualRoute, phase: record.phase, delivery: record.delivery,
249
+ ...(record.stopReason === undefined ? {} : { stopReason: record.stopReason }) });
250
+ }
251
+ publishObservedCall(record) {
252
+ if (this.observedCalls.get(record.parent)?.get(record.callId) !== record || this.ambiguousCallIds.get(record.parent)?.has(record.callId))
253
+ return;
254
+ const call = this.observedCall(record);
255
+ for (const subscriber of this.callSubscribers) {
256
+ if (subscriber.parent === record.parent && subscriber.admission === record.parentAdmission)
257
+ subscriber.push(call);
258
+ }
259
+ }
260
+ publishObservedRemoval(parent, admission, callId) {
261
+ for (const subscriber of this.callSubscribers) {
262
+ if (subscriber.parent === parent && subscriber.admission === admission)
263
+ subscriber.remove(callId);
264
+ }
265
+ }
266
+ observedInvocation(record) {
267
+ const call = this.observedCall(record);
268
+ return { ...invocationView(record.invocation, record.label, "continuable", { childId: record.childId, ...(record.runId === undefined ? {} : { runId: record.runId }) }),
269
+ role: record.role, route: this.observationRoute(record.invocation.initialRoute),
270
+ routeComparison: { childId: record.childId, initialRoute: call.initialRoute, liveRoute: call.actualRoute },
271
+ delivery: record.delivery, phase: record.phase, ...(record.stopReason === undefined ? {} : { stopReason: record.stopReason }) };
272
+ }
273
+ startObservedActivation(info) {
274
+ const record = this.observedCallChildren.get(info.id);
275
+ if (record === undefined || info.provider !== record.provider || !info.local || record.phase === "settled")
276
+ return;
277
+ if (record.runId !== undefined && record.runId !== info.runId)
278
+ return;
279
+ record.runId = info.runId;
280
+ record.phase = "active";
281
+ this.observedCallRuns.set(info.runId, record);
282
+ this.publishObservedCall(record);
283
+ }
284
+ endObservedActivation(info) {
285
+ const record = this.observedCallRuns.get(info.runId);
286
+ if (record === undefined || record.childId !== info.id || record.provider !== info.provider || !info.local)
287
+ return;
288
+ this.settleObservedActivation(record, info.stopReason);
289
+ }
290
+ settleObservedActivation(record, stopReason) {
291
+ if (record.phase === "settled")
292
+ return;
293
+ record.phase = "settled";
294
+ if (ROLE_CALL_STOP_REASONS.includes(stopReason ?? ""))
295
+ record.stopReason = stopReason;
296
+ if (record.runId !== undefined && this.observedCallRuns.get(record.runId) === record)
297
+ this.observedCallRuns.delete(record.runId);
298
+ if (this.observedCallChildren.get(record.childId) === record)
299
+ this.observedCallChildren.delete(record.childId);
300
+ this.publishObservedCall(record);
301
+ }
302
+ bindObservedChild(record, child, admission) {
303
+ if (record.phase === "settled" || record.parentAdmission !== this.get(record.parent)
304
+ || this.observedCallChildren.get(record.childId) !== record || child.id !== record.childId)
305
+ return;
306
+ record.child = child;
307
+ record.childAdmission = admission;
308
+ if (record.actualRoute.status === "unknown" && record.actualRoute.reason === "not-observed")
309
+ record.actualRoute = Object.freeze({ status: "unknown", reason: "no-own-request-header" });
310
+ this.publishObservedCall(record);
311
+ }
312
+ observeCallRequestHeader(session, value) {
313
+ const record = this.observedCallChildren.get(session.id), child = this.ctx.agents.get(session.id);
314
+ if (record === undefined || child === undefined || child !== record.child || child.session !== session
315
+ || record.parentAdmission !== this.get(record.parent) || record.childAdmission !== this.get(child) || record.phase === "settled")
316
+ return;
317
+ const config = typeof value === "object" && value !== null ? value : undefined;
318
+ if (typeof config?.provider !== "string" || typeof config.model !== "string"
319
+ || config.reasoningEffort !== undefined && typeof config.reasoningEffort !== "string") {
320
+ record.actualRoute = Object.freeze({ status: "unknown", reason: "invalid-own-request-header" });
321
+ }
322
+ else {
323
+ try {
324
+ const route = modelRouteFromCall({ provider: config.provider, model: config.model,
325
+ ...(config.reasoningEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(config.reasoningEffort) }) });
326
+ record.actualRoute = Object.freeze({ status: "known", source: "own-native-request-header", route: Object.freeze(route) });
327
+ }
328
+ catch {
329
+ record.actualRoute = Object.freeze({ status: "unknown", reason: "invalid-own-request-header" });
330
+ }
331
+ }
332
+ this.publishObservedCall(record);
333
+ }
334
+ finishObservedTool(exec, result) {
335
+ const record = this.observedCallTokens.get(exec.token);
336
+ if (record === undefined)
337
+ return;
338
+ this.observedCallTokens.delete(exec.token);
339
+ if (record.phase === "reserved" || record.delivery === "caller" && record.phase === "active"
340
+ || record.delivery === "parent" && result.isError && record.runId === undefined) {
341
+ this.settleObservedActivation(record, result.isError ? undefined : "completed");
342
+ }
343
+ }
344
+ retireObservedParent(parent) {
345
+ for (const record of this.observedCallRecords.get(parent) ?? []) {
346
+ this.observedCallTokens.delete(record.token);
347
+ if (this.observedCallChildren.get(record.childId) === record)
348
+ this.observedCallChildren.delete(record.childId);
349
+ if (record.runId !== undefined && this.observedCallRuns.get(record.runId) === record)
350
+ this.observedCallRuns.delete(record.runId);
351
+ }
352
+ this.observedCalls.delete(parent);
353
+ this.observedCallRecords.delete(parent);
354
+ this.ambiguousCallIds.delete(parent);
355
+ for (const subscriber of this.callSubscribers)
356
+ if (subscriber.parent === parent)
357
+ subscriber.notify();
358
+ }
359
+ async *observeRoleCalls(parent, admission, signal, check) {
360
+ const subscriber = new RoleCallSubscriber(parent, admission);
361
+ this.callSubscribers.add(subscriber);
362
+ try {
363
+ const assertCurrent = () => {
364
+ signal.throwIfAborted();
365
+ check();
366
+ if (this.assert(parent) !== admission)
367
+ throw new SubagentError("Call observation admission changed", "UNAUTHORIZED");
368
+ };
369
+ assertCurrent();
370
+ const calls = [...this.observedCalls.get(parent)?.values() ?? []]
371
+ .filter(record => record.parentAdmission === admission).map(record => this.observedCall(record));
372
+ const snapshot = Object.freeze({ type: "snapshot", sessionId: parent.id,
373
+ admissionEpoch: admission.epoch, calls: Object.freeze(calls) });
374
+ yield snapshot;
375
+ while (!signal.aborted) {
376
+ await subscriber.changed(signal);
377
+ assertCurrent();
378
+ for (const change of subscriber.take()) {
379
+ assertCurrent();
380
+ const update = change.type === "update"
381
+ ? Object.freeze({ type: "update", sessionId: parent.id, admissionEpoch: admission.epoch, call: change.call })
382
+ : Object.freeze({ type: "remove", sessionId: parent.id, admissionEpoch: admission.epoch, callId: change.callId });
383
+ yield update;
384
+ }
385
+ }
386
+ }
387
+ finally {
388
+ this.callSubscribers.delete(subscriber);
389
+ }
390
+ }
391
+ notifyObservedParent(parent) {
392
+ for (const subscriber of this.callSubscribers)
393
+ if (subscriber.parent === parent)
394
+ subscriber.notify();
395
+ }
396
+ installCachedAdmissionRoute(agent, expected) {
397
+ const cache = expected ?? this.admissionRoutes.get(agent), live = this.live.get(agent);
398
+ if (cache === undefined || cache !== this.admissionRoutes.get(agent) || live === undefined || this.failedInstallations.has(agent)
399
+ || !this.isReady || this.ctx.agents.get(agent.id) !== agent || this.agentLifetimes.get(agent)?.signal.aborted)
400
+ return undefined;
401
+ return cache.candidate?.install(live.admission);
402
+ }
403
+ installCachedAdmissionRouteSafely(agent, expected) {
404
+ const cache = expected ?? this.admissionRoutes.get(agent);
405
+ if (cache?.candidate?.restoresConfiguredPrimary !== true || this.admissionRouteFailures.get(agent)?.cache === cache)
406
+ return;
407
+ try {
408
+ this.installCachedAdmissionRoute(agent, cache);
409
+ }
410
+ catch (error) {
411
+ if (this.admissionRoutes.get(agent) === cache)
412
+ this.admissionRouteFailures.set(agent, { cache, error });
413
+ }
414
+ }
126
415
  get isReady() {
127
416
  const current = this.ctx.get("dsmmNativeAdmission");
128
417
  return this.ready && !this.lifetime.signal.aborted && current !== undefined && original(current) === original(this);
@@ -181,6 +470,10 @@ export class NativeAdmission {
181
470
  throw new SubagentError("Session configuration maintenance is in progress", "UNAUTHORIZED");
182
471
  if (!this.isReady || !live || this.ctx.agents.get(agent.id) !== agent)
183
472
  throw new SubagentError("No trusted live admission; create a new session", "UNAUTHORIZED");
473
+ const routeFailure = this.admissionRouteFailures.get(agent);
474
+ if (routeFailure !== undefined && routeFailure.cache === this.admissionRoutes.get(agent)) {
475
+ throw new SubagentError("Configured model selection installation failed; create a new session", "UNAUTHORIZED");
476
+ }
184
477
  if (this.ctx.get("sessions")?.get(agent.id) !== agent.session || agent.session.id !== agent.id || agent.session.header.id !== agent.id
185
478
  || scopeOf(agent.ctx) !== agent || original(agent.ctx.get("agents")) !== original(this.ctx.agents)
186
479
  || live.dependencies && this.dependencies(agent).some((value, index) => value !== live.dependencies[index])
@@ -288,6 +581,8 @@ export class NativeAdmission {
288
581
  }
289
582
  let prepared = false, committed = false;
290
583
  let publication;
584
+ const previousRouteCache = this.admissionRoutes.get(agent), previousRouteFailure = this.admissionRouteFailures.get(agent);
585
+ let installedRouteCache, routeInstallation;
291
586
  let providers = new Map();
292
587
  const assertCurrent = () => {
293
588
  assertAuthority();
@@ -334,23 +629,63 @@ export class NativeAdmission {
334
629
  }
335
630
  });
336
631
  assertCurrent();
632
+ const candidate = await this.admissionModelSelection?.(agent, { settings: admission.settings, epoch: admission.epoch,
633
+ admission, signal: preparationSignal, assertCurrent });
634
+ assertCurrent();
337
635
  prepared = true;
636
+ installedRouteCache = Object.freeze({ candidate });
637
+ this.admissionRoutes.set(agent, installedRouteCache);
638
+ this.admissionRouteFailures.delete(agent);
639
+ try {
640
+ routeInstallation = candidate?.install(admission);
641
+ }
642
+ catch (error) {
643
+ if (candidate?.preflightFailure !== error)
644
+ this.failedInstallations.add(agent);
645
+ throw error;
646
+ }
338
647
  await install(admission);
339
648
  assertCurrent();
340
649
  this.installing.run({ agent, admission }, describe);
341
650
  publication = Object.freeze({ ...previous, admission });
342
651
  },
343
- committed: () => { this.live.set(agent, publication); committed = true; this.configurationCommitted(tree); },
652
+ committed: () => { this.live.set(agent, publication); committed = true; this.notifyObservedParent(agent); this.configurationCommitted(tree); },
344
653
  close: async () => {
345
654
  try {
346
- if (prepared && !committed && this.ctx.agents.get(agent.id) === agent && !this.lifetime.signal.aborted)
347
- await install(previous.admission);
348
- }
349
- catch (error) {
350
- this.failedInstallations.add(agent);
351
- const refusal = new DsmmProfileError("activation", "Session configuration restoration failed. Execution is disabled; create a new session.");
352
- refusal.cause = error;
353
- throw refusal;
655
+ if (prepared && !committed) {
656
+ const errors = [];
657
+ const canRestore = this.ctx.agents.get(agent.id) === agent && !this.lifetime.signal.aborted;
658
+ if (canRestore) {
659
+ try {
660
+ await install(previous.admission);
661
+ }
662
+ catch (error) {
663
+ errors.push(error);
664
+ }
665
+ try {
666
+ routeInstallation?.rollback();
667
+ }
668
+ catch (error) {
669
+ errors.push(error);
670
+ }
671
+ }
672
+ if (installedRouteCache !== undefined && this.admissionRoutes.get(agent) === installedRouteCache) {
673
+ if (previousRouteCache === undefined)
674
+ this.admissionRoutes.delete(agent);
675
+ else
676
+ this.admissionRoutes.set(agent, previousRouteCache);
677
+ if (previousRouteFailure !== undefined && previousRouteFailure.cache === previousRouteCache)
678
+ this.admissionRouteFailures.set(agent, previousRouteFailure);
679
+ else
680
+ this.admissionRouteFailures.delete(agent);
681
+ }
682
+ if (errors.length > 0) {
683
+ this.failedInstallations.add(agent);
684
+ const refusal = new DsmmProfileError("activation", "Session configuration restoration failed. Execution is disabled; create a new session.");
685
+ refusal.cause = errors.length === 1 ? errors[0] : new AggregateError(errors, "Session configuration restoration failed");
686
+ throw refusal;
687
+ }
688
+ }
354
689
  }
355
690
  finally {
356
691
  this.selecting.delete(agent);
@@ -368,12 +703,14 @@ export class NativeAdmission {
368
703
  active.add(exec.token);
369
704
  this.executions.set(exec.agent, active);
370
705
  }
371
- async reserve(exec, invocation, provider, maxDepth) {
706
+ async reserve(exec, invocation, provider, label, delivery, maxDepth) {
372
707
  const parent = exec.agent;
373
708
  if (!parent)
374
709
  throw new SubagentError("Calling Agent required", "UNAUTHORIZED");
375
- const parentAdmission = this.assert(parent);
376
- this.policy.assertDelegation(parent, invocation.target);
710
+ const parentAdmission = this.assert(parent), role = invocation.target;
711
+ if (role === "dsmm-orchestrator")
712
+ throw new SubagentError("Orchestrator is not a delegated role", "UNAUTHORIZED");
713
+ this.policy.assertDelegation(parent, role);
377
714
  const toolFilter = this.policy.delegationToolFilter(exec);
378
715
  const presets = this.ctx.get("agentPresets");
379
716
  if (!presets)
@@ -381,7 +718,8 @@ export class NativeAdmission {
381
718
  // The child shares the parent's standing composition; its role is carried
382
719
  // by the admitted invocation, not by an own registered preset.
383
720
  const expectedPreset = presets.composedPreset(parent.ctx);
384
- const lease = await presets.acquireScope(expectedPreset);
721
+ const lease = expectedPreset === undefined ? undefined : await presets.acquireScope(expectedPreset);
722
+ const presetScope = expectedPreset === undefined ? scopeParentOf(parent) : lease.key;
385
723
  try {
386
724
  exec.signal.throwIfAborted();
387
725
  this.assert(parent);
@@ -390,15 +728,38 @@ export class NativeAdmission {
390
728
  throw new SubagentError("Creation dependencies changed", "UNAUTHORIZED");
391
729
  const childId = SessionId(randomUUID()), signal = AbortSignal.any([exec.signal, this.lifetime.signal, this.agentLifetimes.get(parent).signal]);
392
730
  const admission = freezeSettings({ ...parentAdmission, settings: structuredClone(parentAdmission.settings) });
393
- const pending = Object.freeze({ childId, parent, parentAdmission, callId: exec.callId, invocation, admission, provider, expectedPreset, presetScope: lease.key, signal, maxDepth, toolFilter });
731
+ const callId = String(exec.callId), rootCallId = String(exec.rootCallId), calls = this.callsFor(parent);
732
+ let ambiguous = this.ambiguousCallIds.get(parent);
733
+ if (ambiguous === undefined) {
734
+ ambiguous = new Set();
735
+ this.ambiguousCallIds.set(parent, ambiguous);
736
+ }
737
+ const duplicate = calls.has(callId) || ambiguous.has(callId);
738
+ if (duplicate) {
739
+ ambiguous.add(callId);
740
+ calls.delete(callId);
741
+ }
742
+ const observation = { parent, parentAdmission, token: exec.token, callId, rootCallId, childId, invocation, role,
743
+ label, provider: provider.name, delivery, phase: "reserved", actualRoute: Object.freeze({ status: "unknown", reason: "not-observed" }) };
744
+ const pending = Object.freeze({ childId, parent, parentAdmission, callId: exec.callId, invocation, admission, provider, expectedPreset, presetScope, signal, maxDepth, toolFilter, observation });
745
+ this.recordsFor(parent).add(observation);
746
+ if (!duplicate)
747
+ calls.set(callId, observation);
748
+ this.observedCallTokens.set(exec.token, observation);
749
+ this.observedCallChildren.set(childId, observation);
394
750
  this.pending.set(childId, pending);
751
+ if (duplicate)
752
+ this.publishObservedRemoval(parent, parentAdmission, callId);
753
+ else
754
+ this.publishObservedCall(observation);
395
755
  const revoke = () => { if (this.pending.get(childId) === pending)
396
756
  this.pending.delete(childId); };
397
757
  signal.addEventListener("abort", revoke, { once: true });
398
- return { childId, signal, release: async () => { revoke(); signal.removeEventListener("abort", revoke); await lease[Symbol.asyncDispose](); } };
758
+ return { childId, signal, view: () => this.observedInvocation(observation),
759
+ release: async () => { revoke(); signal.removeEventListener("abort", revoke); await lease?.[Symbol.asyncDispose](); } };
399
760
  }
400
761
  catch (error) {
401
- await lease[Symbol.asyncDispose]();
762
+ await lease?.[Symbol.asyncDispose]();
402
763
  throw error;
403
764
  }
404
765
  }
@@ -436,7 +797,12 @@ export class NativeAdmission {
436
797
  }
437
798
  track(activation) {
438
799
  this.activations.add(activation);
439
- void activation.result.finally(() => { if (!this.ctx.agents.get(activation.childId))
800
+ const observation = this.observedCallChildren.get(activation.childId);
801
+ void activation.result.then(result => { if (observation !== undefined)
802
+ this.settleObservedActivation(observation, result.stopReason); }, () => {
803
+ if (observation !== undefined)
804
+ this.settleObservedActivation(observation);
805
+ }).finally(() => { if (!this.ctx.agents.get(activation.childId))
440
806
  this.activations.delete(activation); }).catch(() => { });
441
807
  if (this.lifetime.signal.aborted)
442
808
  void activation.dispose().catch(error => this.ctx.logger.error(error));
@@ -523,6 +889,10 @@ export class NativeAdmission {
523
889
  || agent.session.id !== agent.id || agent.session.header.id !== agent.id || scopeOf(agent.ctx) !== agent
524
890
  || original(agent.ctx.get("agents")) !== original(this.ctx.agents))
525
891
  throw new SubagentError("Invalid native ownership", "UNAUTHORIZED");
892
+ const setupCursor = this.setupSelectionCursors.get(agent.session);
893
+ this.setupSelectionCursors.delete(agent.session);
894
+ if (setupCursor !== undefined)
895
+ captureSetupModelSelections(agent, setupCursor);
526
896
  const own = childOwnedSessionEvents(agent.session);
527
897
  const descriptor = foldSubagentDescriptor(own);
528
898
  if (!pending && parent && !this.owns(parent)) {
@@ -543,6 +913,8 @@ export class NativeAdmission {
543
913
  finally {
544
914
  this.live.delete(agent);
545
915
  this.candidates.delete(agent);
916
+ this.admissionRoutes.delete(agent);
917
+ this.admissionRouteFailures.delete(agent);
546
918
  this.agents.delete(agent);
547
919
  this.profiles.release(agent);
548
920
  this.policy.release(agent);
@@ -608,9 +980,8 @@ export class NativeAdmission {
608
980
  throw new SubagentError("Role is disabled", "UNAUTHORIZED");
609
981
  this.policy.assertDelegation(parent, role);
610
982
  const manual = latestNativeModelSelection(agent)?.route;
611
- continuation = await resolveRoleInvocation(parent, role, admission.settings, signal, metadata ? { level: metadata.level } : {}, manual === undefined ? undefined : {
612
- provider: manual.provider, model: manual.model, ...(manual.reasoningEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(manual.reasoningEffort) })
613
- }, resolvedModelParameterPolicy(admission));
983
+ continuation = await resolveRoleInvocation(parent, role, admission.settings, signal, metadata ? { level: metadata.level } : {}, manual === undefined ? undefined : { provider: manual.provider, model: manual.model,
984
+ ...(manual.reasoningEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(manual.reasoningEffort) }) }, resolvedModelParameterPolicy(admission));
614
985
  check();
615
986
  }
616
987
  }
@@ -658,13 +1029,26 @@ export class NativeAdmission {
658
1029
  if (denial)
659
1030
  return { kind: "deny", reason: denial };
660
1031
  } return next(); }, { prepend: true });
1032
+ const routeCandidate = await this.admissionModelSelection?.(agent, {
1033
+ settings: admission.settings, epoch: admission.epoch, admission, signal, assertCurrent: check,
1034
+ });
1035
+ check();
1036
+ const routeCache = Object.freeze({ candidate: routeCandidate });
1037
+ this.admissionRoutes.set(agent, routeCache);
1038
+ this.admissionRouteFailures.delete(agent);
1039
+ routeCandidate?.install(admission);
1040
+ check();
661
1041
  this.profiles.publish(agent, admission);
662
1042
  const published = this.profiles.admission(agent);
663
1043
  this.live.set(agent, Object.freeze({ admission: published, preset, scopeParent: scopeParentOf(agent), parent, invocation: pending?.invocation ?? continuation, dependencies, provider: pending?.provider ?? continuationProvider }));
664
- if (pending)
1044
+ if (pending) {
1045
+ this.bindObservedChild(pending.observation, agent, published);
665
1046
  this.pending.delete(agent.id);
1047
+ }
666
1048
  }
667
1049
  catch (error) {
1050
+ this.admissionRoutes.delete(agent);
1051
+ this.admissionRouteFailures.delete(agent);
668
1052
  this.policy.release(agent);
669
1053
  throw error;
670
1054
  }