dsh-harness-reflex 0.1.0 → 0.3.0

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 (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
package/dist/testing.js CHANGED
@@ -1,17 +1,62 @@
1
1
  import { Context } from '@deepseek-ai/cordis';
2
- import { agentEvents } from '@deepseek-ai/dsh-agent';
2
+ import { agentEvents, modelSelectionProjectionDefinition } from '@deepseek-ai/dsh-agent';
3
+ import { createScope } from '@deepseek-ai/dsh-scope';
3
4
  import LlmRuntime, { LlmAdapter, isAgentLoopRequest } from '@deepseek-ai/dsh-llm';
4
- import ToolRuntime from '@deepseek-ai/dsh-tools';
5
+ import ToolRuntime, { defineTool } from '@deepseek-ai/dsh-tools';
5
6
  import SystemPrompt from '@deepseek-ai/dsh-system-prompt';
6
7
  import CommandRuntime from '@deepseek-ai/dsh-commands';
8
+ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection';
9
+ import { Session } from '@deepseek-ai/dsh-session';
10
+ import * as nativeExecutor from '@deepseek-ai/dsh-tool-executor-native';
7
11
  import { apply, applyReflex, Config, inject, name as pluginName } from './index.js';
8
12
  /**
9
- * Mint a registry-legal call id.
10
- * @param id - unique suffix.
11
- * @returns the branded id.
13
+ * Run one synthesized call through the real registry pipeline.
14
+ * @param ctx - a context whose `tools` service is live.
15
+ * @param call - the call to dispatch.
16
+ * @returns the batch entry whose id matches {@link TestToolCall.callId}.
17
+ * @throws Error when the batch settled a different call.
18
+ */
19
+ export async function executeOne(ctx, call) {
20
+ const batch = await ctx.tools.execute({
21
+ calls: [{ type: 'tool-call', id: call.callId, name: call.name, arguments: JSON.stringify(call.args ?? {}) }],
22
+ signal: new AbortController().signal,
23
+ ...(call.agent ? { agent: call.agent } : {})
24
+ });
25
+ const entry = batch.results.find((candidate) => candidate.callId === call.callId);
26
+ if (!entry)
27
+ throw new Error(`the batch settled no result for ${call.callId}`);
28
+ return entry.result;
29
+ }
30
+ /**
31
+ * The `modelSelection` an `agent/pre-step` payload now requires.
32
+ *
33
+ * The waterfall payload gained `agent`, `modelSelection`, and (in tests) a
34
+ * `model` it does not read. Requirements beyond the identity the step already
35
+ * carries are supplied from the agent's own composed options, falling back to
36
+ * the reflex route, so a test never invents a selection the loop could not.
37
+ * @param agent - the agent stepping.
38
+ * @returns the selection the loop would carry into the step.
39
+ */
40
+ export function stepSelection(agent) {
41
+ const options = agent.options;
42
+ return {
43
+ provider: options?.provider ?? 'reflex',
44
+ model: options?.model ?? 'reflex-auto',
45
+ ...(options?.reasoningEffort === undefined ? {} : { reasoningEffort: options.reasoningEffort })
46
+ };
47
+ }
48
+ /**
49
+ * Build the `agent/pre-step` payload the waterfall now declares.
50
+ * @param agent - the agent stepping.
51
+ * @param turn - turn number.
52
+ * @param step - step number.
53
+ * @param messages - messages the step carries.
54
+ * @param signal - cancellation state.
55
+ * @param modelSelection - selection the loop carries into the step; defaults to the agent's own.
56
+ * @returns the payload, spelled out rather than cast.
12
57
  */
13
- function callId(id) {
14
- return id;
58
+ export function preStepPayload(agent, turn, step, messages, signal = new AbortController().signal, modelSelection = stepSelection(agent)) {
59
+ return { agent, messages: [...messages], turn, step, signal, modelSelection };
15
60
  }
16
61
  /**
17
62
  * Test harness for the reflex Host plugin.
@@ -24,20 +69,142 @@ function callId(id) {
24
69
  *
25
70
  * @module dsh-reflex/testing
26
71
  */
72
+ /**
73
+ * Reproduce the loader's own `loader/volatile-update` dispatch.
74
+ *
75
+ * The real loader emits with `Object.create(fiber.ctx)` carrying a
76
+ * `Context.filter` that admits only listeners owned by the committing fiber.
77
+ * Cordis 4.x hands out context-bound *proxies* of a fiber, so a fiber read off
78
+ * one context is never `===` the fiber its own context reports; comparing
79
+ * against `fiber.ctx.fiber` is the identity the event store records.
80
+ *
81
+ * @param entryFiber - the fiber the loader resolved for the entry.
82
+ * @returns the receiver the loader emits with.
83
+ */
84
+ export function loaderEventReceiver(entryFiber) {
85
+ const owner = entryFiber.ctx;
86
+ const self = Object.create(owner);
87
+ self[Context.filter] = (candidate) => candidate.fiber === owner.fiber;
88
+ return self;
89
+ }
27
90
  /** The plugin as Cordis sees it, for `ctx.plugin()`-based lifecycle tests. */
28
91
  export const reflexPlugin = { name: pluginName, inject, Config, apply };
92
+ /**
93
+ * The Host's native executor, shaped as a Cordis plugin spec.
94
+ *
95
+ * dsh-tools >= 0.2.2 moved execution out of the registry: `tools.execute()`
96
+ * throws TOOL_EXECUTOR_UNAVAILABLE until an executor plugin is selected, so a
97
+ * harness that only mounts `ToolRuntime` can no longer dispatch anything. The
98
+ * module's `apply` is a plain function, so `{ ...module }` would lose its
99
+ * context binding, and `ctx.plugin()` reads `inject` only from a spec object,
100
+ * never from a derived function — hence the explicit fields.
101
+ */
102
+ export const nativeExecutorPlugin = {
103
+ name: nativeExecutor.name,
104
+ inject: nativeExecutor.inject,
105
+ apply: (scope) => nativeExecutor.apply(scope)
106
+ };
29
107
  /**
30
108
  * Boot Cordis with `systemPrompt`, `tools`, `llm`, and `commands` loaded.
109
+ *
110
+ * The Host's delegation tool is registered as part of the composition, because
111
+ * `reflex_delegate` is a wrapper around it and a harness without it would not
112
+ * reflect a normal deployment. A test that needs the no-delegation case uses
113
+ * {@link createToolContextWithoutDelegation}.
31
114
  * @returns the root context, ready for `apply` or `ctx.plugin`.
32
115
  */
33
- export async function createToolContext() {
34
- const ctx = new Context();
116
+ export async function createToolContext(options = {}) {
117
+ const ctx = await createToolContextWithoutDelegation();
118
+ ctx.tools.register(delegationStandIn(options).definition);
119
+ return ctx;
120
+ }
121
+ /**
122
+ * Mount the Host services every harness needs, including the two the plugin
123
+ * reads a session selection from.
124
+ *
125
+ * The agent runtime injects `sessionProjections` as a *required* service, and it
126
+ * registers `modelSelectionProjectionDefinition` before it drives any step. A
127
+ * harness without either is not a quieter Host, it is a different one:
128
+ * `resolveAdaptiveIntent` would fall back to "no projection", `stateOf` would
129
+ * answer `undefined`, and a selection read that is wrong only in production
130
+ * would look green here. Mounting both keeps the decision path identical.
131
+ *
132
+ * @param ctx - the context to mount onto.
133
+ */
134
+ export async function mountHostServices(ctx) {
35
135
  await ctx.plugin(SystemPrompt);
136
+ await ctx.plugin(SessionProjectionRegistry);
137
+ await ctx.plugin({
138
+ name: 'test-model-selection-projection',
139
+ inject: ['sessionProjections'],
140
+ apply: (scope) => {
141
+ const service = scope;
142
+ void service.sessionProjections.register(modelSelectionProjectionDefinition);
143
+ }
144
+ });
145
+ }
146
+ /**
147
+ * Boot Cordis with every service the plugin depends on, but **no** delegation
148
+ * tool — the one deployment shape in which `reflex_delegate` must not register.
149
+ * @returns the root context.
150
+ */
151
+ export async function createToolContextWithoutDelegation() {
152
+ const ctx = new Context();
153
+ await mountHostServices(ctx);
36
154
  await ctx.plugin(ToolRuntime);
155
+ // dsh-tools >= 0.2.2 owns dispatch but ships no executor: execution moved
156
+ // into a separately mounted executor plugin, and `tools.execute()` throws
157
+ // TOOL_EXECUTOR_UNAVAILABLE until one is selected. The Host loads the native
158
+ // executor as part of its own composition, so the harness mounts it too.
159
+ await ctx.plugin(nativeExecutorPlugin);
37
160
  await ctx.plugin(LlmRuntime);
38
161
  await ctx.plugin(CommandRuntime);
39
162
  return ctx;
40
163
  }
164
+ /**
165
+ * Build the Host delegation-tool stand-in.
166
+ * @param options - omit `reasoningEffort` to model a deployment with model selection off.
167
+ * @returns the stand-in, with its recorded dispatches.
168
+ */
169
+ export function delegationStandIn(options = {}) {
170
+ const calls = options.record ?? [];
171
+ const definition = defineTool({
172
+ name: 'subagent',
173
+ description: 'Stand-in for the Host delegation tool: publishes the same parameter list as `tool-subagent` with model selection enabled, and records what `reflex_delegate` forwards.',
174
+ parameters: {
175
+ cwd: { type: 'string' },
176
+ description: { type: 'string', required: true },
177
+ prompt: { type: 'string', required: true },
178
+ ...(options.reasoningEffort === false
179
+ ? {}
180
+ : {
181
+ provider: { type: 'string' },
182
+ model: { type: 'string' },
183
+ reasoning_effort: { type: 'string' }
184
+ })
185
+ },
186
+ output: {
187
+ schema: {
188
+ type: 'object',
189
+ additionalProperties: false,
190
+ properties: {
191
+ kind: { type: 'string', required: true, const: 'activation' },
192
+ subagentId: { type: 'string', required: true }
193
+ }
194
+ },
195
+ render: (_args, value) => [
196
+ { type: 'text', text: `started subagent ${value.subagentId}` }
197
+ ]
198
+ },
199
+ async execute(raw) {
200
+ calls.push(raw);
201
+ if (options.refuse !== undefined)
202
+ throw new Error(options.refuse);
203
+ return { kind: 'activation', subagentId: `stand-in-child-${calls.length}` };
204
+ }
205
+ });
206
+ return { name: 'subagent', calls, definition };
207
+ }
41
208
  /**
42
209
  * Boot a context and register the reflex tools on it with the exported
43
210
  * {@link applyReflex}, mirroring a Host that loads the plugin while keeping a
@@ -52,12 +219,7 @@ export async function createReflexHost(config) {
52
219
  return {
53
220
  ctx,
54
221
  runtime,
55
- callTool: (name, args = {}) => ctx.tools.execute({
56
- callId: callId(`reflex-test-${++calls}`),
57
- name,
58
- arguments: args,
59
- signal: new AbortController().signal
60
- }),
222
+ callTool: (name, args = {}) => executeOne(ctx, { callId: `reflex-test-${++calls}`, name, args }),
61
223
  dispose: () => ctx.fiber.dispose()
62
224
  };
63
225
  }
@@ -69,12 +231,71 @@ export async function createReflexHost(config) {
69
231
  * @returns the registry result (never throws for tool-level failures).
70
232
  */
71
233
  export function callTool(ctx, name, args = {}) {
72
- return ctx.tools.execute({
73
- callId: callId(`reflex-test-${name}-${Math.random().toString(36).slice(2, 8)}`),
74
- name,
75
- arguments: args,
76
- signal: new AbortController().signal
234
+ return executeOne(ctx, { callId: `reflex-test-${name}-${Math.random().toString(36).slice(2, 8)}`, name, args });
235
+ }
236
+ /**
237
+ * Boot a context, register extra tools on it *before* the plugin mounts, and
238
+ * then apply the plugin — the order the real Host uses.
239
+ *
240
+ * `reflex_delegate` is conditional on the Host's delegation tool, and that
241
+ * condition is resolved when the tool surface is installed. A stand-in
242
+ * registered afterwards would therefore never be wrapped, so tests that need a
243
+ * delegate must seed the registry first, exactly as the Host does.
244
+ * @param config - deployment config.
245
+ * @param seed - registers the pre-existing tools; called before the plugin applies.
246
+ * @param options - `delegation: false` boots a context with no Host delegation tool.
247
+ * @returns the host handle.
248
+ */
249
+ export async function createReflexHostWithTools(config, seed, options = {}) {
250
+ const ctx = options.delegation === false
251
+ ? await createToolContextWithoutDelegation()
252
+ : await createToolContext(options.record === undefined ? {} : { record: options.record });
253
+ seed(ctx);
254
+ const runtime = applyReflex(ctx, config);
255
+ let calls = 0;
256
+ return {
257
+ ctx,
258
+ runtime,
259
+ callTool: (name, args = {}) => executeOne(ctx, { callId: `reflex-test-${++calls}`, name, args }),
260
+ dispose: () => ctx.fiber.dispose()
261
+ };
262
+ }
263
+ /**
264
+ * Boot a context and put the Host delegation tool **inside an agent scope**.
265
+ *
266
+ * This is the shape a real deployment has: `tool-subagent` is attached to the
267
+ * agent preset, so `ctx.tools.get('subagent')` — the global view — does not see
268
+ * it and `ctx.tools.get('subagent', scope)` does. A test that only ever
269
+ * registers globally cannot reproduce g-054, because the global view is exactly
270
+ * the view the bug was reading.
271
+ *
272
+ * The scope is minted the way the Host mints one: under a context that declares
273
+ * `tools`, which the scoped context then inherits.
274
+ * @param options - `reasoningEffort: false` models a host with model selection off.
275
+ * @returns the root context and the scope key its delegation tool lives in.
276
+ */
277
+ export async function createScopedDelegationHost(options = {}) {
278
+ const ctx = await createToolContextWithoutDelegation();
279
+ // `ScopeKey` is structural (any object), so the key doubles as the `Agent`
280
+ // argument the public helpers take; the registry only needs it to be the same
281
+ // identity the scope was minted with.
282
+ const key = { id: `agent-scope-${Math.random().toString(36).slice(2, 8)}` };
283
+ let minted;
284
+ // `createScope` inherits the dependency API of the context it is minted under,
285
+ // so it has to be minted inside a context that declares `tools`.
286
+ await ctx.inject(['tools'], async (declaring) => {
287
+ minted = createScope(declaring, key);
288
+ minted.ctx.tools.register(delegationStandIn(options).definition);
77
289
  });
290
+ const scope = minted;
291
+ return {
292
+ ctx,
293
+ scope: key,
294
+ dispose: async () => {
295
+ await scope.dispose();
296
+ await ctx.fiber.dispose();
297
+ }
298
+ };
78
299
  }
79
300
  /**
80
301
  * Read the text a model would receive from one tool result.
@@ -188,32 +409,117 @@ export function registerPhysicalAdapter(ctx, provider, options = {}) {
188
409
  return adapter;
189
410
  }
190
411
  /**
191
- * Build the minimal agent shape the routing listeners read.
412
+ * Build the agent shape the routing listeners read.
413
+ *
414
+ * The session is a real {@link Session}, not a `{ header }` stand-in: the
415
+ * selection projection folds a session's committed events (`snapshotEvents`),
416
+ * and `resolveAdaptiveIntent` reads it. A plain object would make that read
417
+ * throw and silently downgrade every test to "no projection" — i.e. the harness
418
+ * would not reproduce the Host at all.
419
+ *
192
420
  * @param seed - identity and lineage facts.
193
421
  * @returns an object usable as the `agent` payload field.
194
422
  */
195
423
  export function fakeAgent(seed) {
424
+ const session = Session.create(seed.id, undefined, {
425
+ version: 4,
426
+ id: seed.id,
427
+ createdAt: 0,
428
+ isSeeded: false,
429
+ // Absent, not `undefined`: the header must survive a JSON round trip.
430
+ ...(seed.origin === undefined ? {} : { origin: seed.origin }),
431
+ ...(seed.delegationDepth === undefined ? {} : { delegationDepth: seed.delegationDepth })
432
+ });
196
433
  return {
197
434
  id: seed.id,
198
435
  options: { provider: seed.provider, model: seed.model },
199
- session: { header: { origin: seed.origin, delegationDepth: seed.delegationDepth } }
436
+ session
200
437
  };
201
438
  }
439
+ /**
440
+ * Reproduce `dsh-agent-loop`'s canonical request config for one step.
441
+ *
442
+ * The loop deep-freezes `structuredClone({ ...selection })` and hands it to the
443
+ * `agent/request` waterfall. Reproducing the freeze matters: a listener that
444
+ * still rewrote a field there would throw instead of quietly disagreeing with
445
+ * the guards below.
446
+ * @param selection - the step's fixed selection.
447
+ * @returns the frozen config the loop would propose.
448
+ */
449
+ function seedRequestConfig(selection) {
450
+ return Object.freeze(structuredClone({ ...selection }));
451
+ }
202
452
  /**
203
453
  * Dispatch one `agent/pre-step` and then one `agent/request` for an agent, the
204
- * way the loop does, and return the configuration the waterfall produced.
454
+ * way `dsh-agent-loop` does, and return the configuration the loop would use.
455
+ *
456
+ * The order is the loop's own (g-056), not a convenience: the step's selection
457
+ * is captured first (`this.model.current()`), passed through the `agent/pre-step`
458
+ * waterfall, and only then compared against what `agent/request` proposes. The
459
+ * two guards are the loop's two guards, message for message, so a decision that
460
+ * wrote the wrong place fails here instead of in a real session.
461
+ *
205
462
  * @param ctx - context the plugin was loaded on.
206
463
  * @param agent - the requesting agent.
207
- * @param options - step identity and the config the loop would use.
464
+ * @param options - step identity and the selection the loop fixes for the step.
208
465
  * @returns the rewritten call configuration.
466
+ * @throws Error when the waterfall proposed a provider, model or effort the step
467
+ * preparation had already fixed — exactly what the Host throws.
209
468
  */
210
469
  export async function dispatchAgentRequest(ctx, agent, options = {}) {
211
470
  const events = agentEvents(ctx, agent);
212
- const fallback = options.config ?? { provider: 'reflex', model: 'reflex-auto' };
471
+ // Captured before the waterfall, exactly like `preStep`'s `const selection`.
472
+ // A fresh object per step, exactly like `AgentModel.current()`, which returns
473
+ // `{ ...recorded }` / a new record rather than the stored one. Without the
474
+ // copy the plugin's write would land in the caller's fixture and every step
475
+ // would silently start from the previous step's routed selection.
476
+ const selection = { ...(options.selection ?? stepSelection(agent)) };
213
477
  const signal = options.signal ?? new AbortController().signal;
214
478
  const messages = options.task !== undefined ? [userMessage(options.task)] : [];
215
- await events.waterfall('agent/pre-step', { turn: options.turn ?? 1, step: options.step ?? 1, signal, messages }, async () => ({ kind: 'enter', messages }));
216
- return events.waterfall('agent/request', { turn: options.turn ?? 1, step: options.step ?? 1, signal }, async () => fallback);
479
+ await events.waterfall('agent/pre-step', preStepPayload(agent, options.turn ?? 1, options.step ?? 1, messages, signal, selection), async () => ({ kind: 'enter', messages }));
480
+ const proposed = await events.waterfall('agent/request', { turn: options.turn ?? 1, step: options.step ?? 1, signal }, async () => seedRequestConfig(selection));
481
+ if (proposed.provider !== selection.provider || proposed.model !== selection.model) {
482
+ throw new Error(`agent "${agent.id}": agent/request proposed "${proposed.provider}/${proposed.model}" after step preparation fixed "${selection.provider}/${selection.model}"; use agent.model.select() before step preparation`);
483
+ }
484
+ if (proposed.reasoningEffort !== selection.reasoningEffort) {
485
+ throw new Error(`agent "${agent.id}": agent/request proposed reasoning effort "${String(proposed.reasoningEffort ?? 'adapter default')}" after step preparation fixed "${String(selection.reasoningEffort ?? 'adapter default')}"; use agent.model.select() before step preparation`);
486
+ }
487
+ // The loop records the admitted request, which retires a matching `pending`
488
+ // selection into `lastUsed`. It happens *after* the guards, exactly as the
489
+ // loop does (it logs the header when it builds the request).
490
+ recordRequestHeader(agent, proposed);
491
+ return proposed;
492
+ }
493
+ /**
494
+ * Commit the `request/header` the loop logs once a request is admitted.
495
+ *
496
+ * The loop records the config it really dispatched, and the selection projection
497
+ * folds that event: a recorded selection equal to the header retires `pending`
498
+ * into `lastUsed`. Skipping it (as an earlier harness did) is not neutral — it
499
+ * leaves `pending` set forever, so `resolveAdaptiveIntent` would read a stale
500
+ * intent on every later step. Sessions without `append` are left alone.
501
+ *
502
+ * @param agent - the agent whose request was admitted.
503
+ * @param config - the configuration the loop would have dispatched.
504
+ */
505
+ function recordRequestHeader(agent, config) {
506
+ const session = agent.session;
507
+ if (!session || typeof session.append !== 'function')
508
+ return;
509
+ const data = {
510
+ provider: config.provider,
511
+ model: config.model,
512
+ ...(config.reasoningEffort === undefined ? {} : { reasoningEffort: config.reasoningEffort })
513
+ };
514
+ try {
515
+ session.append.call(session, 'request/header', {
516
+ header: { config: data },
517
+ reason: 'initial'
518
+ });
519
+ }
520
+ catch {
521
+ // A synthetic session without a log simply keeps no header history.
522
+ }
217
523
  }
218
524
  /**
219
525
  * Build a minimal user message carrying one text block.
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAc,MAAM,wBAAwB,CAAC;AACjE,OAAO,UAAU,EAAE,EACjB,UAAU,EACV,kBAAkB,EAQnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,WAAyC,MAAM,wBAAwB,CAAC;AAC/E,OAAO,YAAY,MAAM,gCAAgC,CAAC;AAC1D,OAAO,cAAc,MAAM,2BAA2B,CAAC;AAEvD,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,YAAY,CAAC;AAOpF;;;;GAIG;AACH,SAAS,MAAM,CAAC,EAAU;IACxB,OAAO,EAAY,CAAC;AACtB,CAAC;AAED;;;;;;;;;;GAUG;AAEH,8EAA8E;AAC9E,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAcxE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB;IACrC,MAAM,GAAG,GAAG,IAAI,OAAO,EAAE,CAAC;IAC1B,MAAM,GAAG,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAC/B,MAAM,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC9B,MAAM,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC7B,MAAM,GAAG,CAAC,MAAM,CAAC,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EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;KACC,CAAC;AAC9B,CAAC","sourcesContent":["import { Context } from '@deepseek-ai/cordis';\nimport { agentEvents, type Agent } from '@deepseek-ai/dsh-agent';\nimport LlmRuntime, {\n LlmAdapter,\n isAgentLoopRequest,\n type GenerateOptions,\n type LlmCallConfig,\n type LlmModelInfo,\n type LlmProviderInfo,\n type LlmResolvedModelInfo,\n type StreamChunk,\n type UserMessage\n} from '@deepseek-ai/dsh-llm';\nimport ToolRuntime, { type ToolExecutionResult } from '@deepseek-ai/dsh-tools';\nimport SystemPrompt from '@deepseek-ai/dsh-system-prompt';\nimport CommandRuntime from '@deepseek-ai/dsh-commands';\n\nimport { apply, applyReflex, Config, inject, name as pluginName } from './index.js';\nimport type { ReflexRuntime } from './bridge.js';\nimport type { ReflexConfig } from './config.js';\n\n/** Branded call id, taken from the registry signature so no extra dependency is needed. */\ntype CallId = Parameters<Context['tools']['execute']>[0]['callId'];\n\n/**\n * Mint a registry-legal call id.\n * @param id - unique suffix.\n * @returns the branded id.\n */\nfunction callId(id: string): CallId {\n return id as CallId;\n}\n\n/**\n * Test harness for the reflex Host plugin.\n *\n * It boots a real Cordis application with every service the plugin depends on\n * (`systemPrompt` for the tool registry, then `tools` itself, `llm` for the\n * virtual provider route, and `commands` for `/reflex-ledger`), so tests\n * exercise the production registration, validation, routing, and disposal paths\n * rather than a stand-in.\n *\n * @module dsh-reflex/testing\n */\n\n/** The plugin as Cordis sees it, for `ctx.plugin()`-based lifecycle tests. */\nexport const reflexPlugin = { name: pluginName, inject, Config, apply };\n\n/** A booted application with the reflex tools registered. */\nexport interface ReflexTestHost {\n /** Root context carrying `systemPrompt`, `tools`, `llm`, and `commands`. */\n readonly ctx: Context;\n /** Runtime returned by {@link apply}. */\n readonly runtime: ReflexRuntime;\n /** Execute one registered tool through the real registry pipeline. */\n callTool(name: string, args?: unknown): Promise<ToolExecutionResult>;\n /** Dispose the application (and with it the plugin's effects). */\n dispose(): Promise<void>;\n}\n\n/**\n * Boot Cordis with `systemPrompt`, `tools`, `llm`, and `commands` loaded.\n * @returns the root context, ready for `apply` or `ctx.plugin`.\n */\nexport async function createToolContext(): Promise<Context> {\n const ctx = new Context();\n await ctx.plugin(SystemPrompt);\n await ctx.plugin(ToolRuntime);\n await ctx.plugin(LlmRuntime);\n await ctx.plugin(CommandRuntime);\n return ctx;\n}\n\n/**\n * Boot a context and register the reflex tools on it with the exported\n * {@link applyReflex}, mirroring a Host that loads the plugin while keeping a\n * handle on the activation's runtime.\n * @param config - deployment config; defaults are resolved by the plugin.\n * @returns the host handle.\n */\nexport async function createReflexHost(config?: ReflexConfig): Promise<ReflexTestHost> {\n const ctx = await createToolContext();\n const runtime = applyReflex(ctx, config);\n let calls = 0;\n\n return {\n ctx,\n runtime,\n callTool: (name: string, args: unknown = {}) =>\n ctx.tools.execute({\n callId: callId(`reflex-test-${++calls}`),\n name,\n arguments: args,\n signal: new AbortController().signal\n }),\n dispose: () => ctx.fiber.dispose()\n };\n}\n\n/**\n * Execute one tool on an existing context.\n * @param ctx - a context whose `tools` service is live.\n * @param name - registered tool name.\n * @param args - model-shaped arguments.\n * @returns the registry result (never throws for tool-level failures).\n */\nexport function callTool(ctx: Context, name: string, args: unknown = {}): Promise<ToolExecutionResult> {\n return ctx.tools.execute({\n callId: callId(`reflex-test-${name}-${Math.random().toString(36).slice(2, 8)}`),\n name,\n arguments: args,\n signal: new AbortController().signal\n });\n}\n\n/**\n * Read the text a model would receive from one tool result.\n * @param result - a registry result.\n * @returns the first text block, or an empty string.\n */\nexport function resultText(result: ToolExecutionResult): string {\n const block = result.content?.[0];\n return block && block.type === 'text' ? block.text : '';\n}\n\n/**\n * Read the structured value of a successful tool result.\n * @param result - a registry result.\n * @returns the parsed value.\n * @throws Error when the call failed.\n */\nexport function resultValue<T = any>(result: ToolExecutionResult): T {\n if (result.isError) throw new Error(`tool failed: ${resultText(result)}`);\n return result.value as T;\n}\n\n/** One observed dispatch of the fake physical adapter. */\nexport interface PhysicalCall {\n provider: string;\n model: string;\n reasoningEffort?: string;\n /** Text of the last user message, proving the payload survived routing. */\n lastUserText?: string;\n /** Whether the request was marked as loop-assembled. */\n loopOwned: boolean;\n}\n\n/** Options of {@link FakePhysicalAdapter}. */\nexport interface FakePhysicalAdapterOptions {\n /** Model ids the adapter advertises and resolves. */\n models?: string[];\n /** Reasoning efforts the adapter declares for every model; omitted = none declared. */\n reasoningEfforts?: string[];\n /** Default reasoning effort declared for every model. */\n defaultEffort?: string;\n /** When set, every dispatch fails with this error. */\n failWith?: Error;\n}\n\n/**\n * A physical provider adapter that records every dispatch, so a test can prove\n * which provider/model a routed request actually reached.\n */\nexport class FakePhysicalAdapter extends LlmAdapter {\n /** Provider route this adapter serves. */\n readonly provider: string;\n /** Dispatches observed so far, oldest first. */\n readonly calls: PhysicalCall[] = [];\n\n #models: string[];\n #options: FakePhysicalAdapterOptions;\n\n /**\n * @param provider - provider route to serve.\n * @param options - advertised models, reasoning metadata, and failure injection.\n */\n constructor(provider: string, options: FakePhysicalAdapterOptions = {}) {\n super();\n this.provider = provider;\n this.#models = options.models ?? ['default-model'];\n this.#options = options;\n }\n\n /**\n * Describe the provider route.\n * @param provider - the owned route.\n * @returns display metadata.\n */\n override providerInfo(provider: string): LlmProviderInfo {\n return { id: provider, name: `fake(${provider})` };\n }\n\n /**\n * Advertise the configured models.\n * @param provider - the owned route.\n * @returns one entry per configured model.\n */\n override async listModels(provider: string): Promise<readonly LlmModelInfo[]> {\n return this.#models.map((model) => ({ provider, id: model, name: model }));\n }\n\n /**\n * Resolve one model, declaring the configured reasoning vocabulary.\n * @param provider - the owned route.\n * @param model - requested model id.\n * @returns identity plus reasoning metadata.\n */\n override async resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {\n const efforts = this.#options.reasoningEfforts;\n const reasoning =\n efforts && efforts.length > 0\n ? {\n efforts: efforts.map((effort) => ({ id: effort, name: effort })),\n ...(this.#options.defaultEffort ? { defaultEffort: this.#options.defaultEffort } : {})\n }\n : undefined;\n return {\n provider,\n id: model,\n name: model,\n ...(reasoning ? { reasoning: reasoning as unknown as LlmResolvedModelInfo['reasoning'] } : {})\n };\n }\n\n /**\n * Record one dispatch and emit a deterministic single-chunk response.\n * @param options - the routed request.\n * @returns the chunk stream.\n */\n override async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {\n const lastUser = [...options.messages].reverse().find((message) => message.role === 'user');\n const text = (lastUser?.content ?? []).find((block) => block.type === 'text');\n this.calls.push({\n provider: options.provider,\n model: options.model,\n ...(options.reasoningEffort === undefined ? {} : { reasoningEffort: options.reasoningEffort as unknown as string }),\n ...(text && text.type === 'text' ? { lastUserText: text.text } : {}),\n loopOwned: isAgentLoopRequest(options)\n });\n\n if (this.#options.failWith) throw this.#options.failWith;\n\n yield { type: 'text-delta', index: 0, text: `${options.provider}:${options.model}` };\n yield { type: 'finish', reason: { kind: 'stop' } };\n }\n}\n\n/**\n * Register one fake physical adapter on a context.\n * @param ctx - a context whose `llm` service is live.\n * @param provider - provider route to register.\n * @param options - adapter behavior.\n * @returns the adapter, with its recorded calls.\n */\nexport function registerPhysicalAdapter(\n ctx: Context,\n provider: string,\n options: FakePhysicalAdapterOptions = {}\n): FakePhysicalAdapter {\n const adapter = new FakePhysicalAdapter(provider, options);\n ctx.llm.registerAdapter([provider], adapter);\n return adapter;\n}\n\n/** An agent-shaped dispatch subject for routing tests. */\nexport interface FakeAgentSeed {\n /** Agent/session id. */\n id: string;\n /** `subagent` marks a delegated child session. */\n origin?: 'subagent';\n /** Delegation depth recorded on the session header. */\n delegationDepth?: number;\n /** Provider the agent was composed with. */\n provider?: string;\n /** Model the agent was composed with. */\n model?: string;\n}\n\n/**\n * Build the minimal agent shape the routing listeners read.\n * @param seed - identity and lineage facts.\n * @returns an object usable as the `agent` payload field.\n */\nexport function fakeAgent(seed: FakeAgentSeed): Agent {\n return {\n id: seed.id,\n options: { provider: seed.provider, model: seed.model },\n session: { header: { origin: seed.origin, delegationDepth: seed.delegationDepth } }\n } as unknown as Agent;\n}\n\n/**\n * Dispatch one `agent/pre-step` and then one `agent/request` for an agent, the\n * way the loop does, and return the configuration the waterfall produced.\n * @param ctx - context the plugin was loaded on.\n * @param agent - the requesting agent.\n * @param options - step identity and the config the loop would use.\n * @returns the rewritten call configuration.\n */\nexport async function dispatchAgentRequest(\n ctx: Context,\n agent: Agent,\n options: {\n turn?: number;\n step?: number;\n task?: string;\n config?: LlmCallConfig;\n /** Cancellation state the loop would carry into the request. */\n signal?: AbortSignal;\n } = {}\n): Promise<LlmCallConfig> {\n const events = agentEvents(ctx, agent);\n const fallback: LlmCallConfig = options.config ?? { provider: 'reflex', model: 'reflex-auto' };\n const signal = options.signal ?? new AbortController().signal;\n\n const messages = options.task !== undefined ? [userMessage(options.task)] : [];\n await events.waterfall(\n 'agent/pre-step',\n { turn: options.turn ?? 1, step: options.step ?? 1, signal, messages },\n async () => ({ kind: 'enter' as const, messages })\n );\n\n return events.waterfall(\n 'agent/request',\n { turn: options.turn ?? 1, step: options.step ?? 1, signal },\n async () => fallback\n );\n}\n\n/**\n * Build a minimal user message carrying one text block.\n * @param text - message text.\n * @returns the message shape `agent/pre-step` carries.\n */\nexport function userMessage(text: string): UserMessage {\n return {\n id: `test-message-${text.length}`,\n role: 'user',\n content: [{ type: 'text', text }],\n source: { kind: 'user' }\n } as unknown as UserMessage;\n}\n"]}
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAmC,MAAM,wBAAwB,CAAC;AAC1H,OAAO,EAAE,WAAW,EAAc,MAAM,wBAAwB,CAAC;AACjE,OAAO,UAAU,EAAE,EACjB,UAAU,EACV,kBAAkB,EAQnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,WAAW,EAAE,EAAE,UAAU,EAAuE,MAAM,wBAAwB,CAAC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AClB,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,oEAAoE;IACtE,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO;QACL,EAAE,EAAE,gBAAgB,IAAI,CAAC,MAAM,EAAE;QACjC,IAAI,EAAE,MAAM;QACZ,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QACjC,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;KACC,CAAC;AAC9B,CAAC","sourcesContent":["import { Context } from '@deepseek-ai/cordis';\nimport { agentEvents, modelSelectionProjectionDefinition, type Agent, type ModelSelection } from '@deepseek-ai/dsh-agent';\nimport { createScope, type Scope } from '@deepseek-ai/dsh-scope';\nimport LlmRuntime, {\n LlmAdapter,\n isAgentLoopRequest,\n type GenerateOptions,\n type LlmCallConfig,\n type LlmModelInfo,\n type LlmProviderInfo,\n type LlmResolvedModelInfo,\n type StreamChunk,\n type UserMessage\n} from '@deepseek-ai/dsh-llm';\nimport ToolRuntime, { defineTool, type ToolBatchResult, type ToolDefinition, type ToolExecutionResult } from '@deepseek-ai/dsh-tools';\nimport SystemPrompt from '@deepseek-ai/dsh-system-prompt';\nimport CommandRuntime from '@deepseek-ai/dsh-commands';\nimport SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection';\nimport { Session, type SessionId } from '@deepseek-ai/dsh-session';\nimport * as nativeExecutor from '@deepseek-ai/dsh-tool-executor-native';\nimport { apply, applyReflex, Config, inject, name as pluginName } from './index.js';\nimport type { ReflexRuntime } from './bridge.js';\nimport type { ReflexConfig } from './config.js';\n\n/**\n * Call metadata for one synthesized registry call.\n *\n * dsh-tools ≥ 0.2.2 no longer accepts a single call: `tools.execute()` takes a\n * `ToolBatchInput` and settles a `ToolBatchResult`. A call is therefore\n * addressed by `ToolCallBlock.id`, carries its arguments as the raw JSON\n * string the model would have produced, and keeps its own `callId` here only\n * to reach it back out of the batch.\n */\nexport interface TestToolCall {\n /** Model-issued call id this batch entry is addressed by. */\n readonly callId: string;\n /** Registered tool name. */\n readonly name: string;\n /** Model-shaped arguments; serialized into the call block. */\n readonly args?: unknown;\n /** Owning agent, which selects its scoped executor. */\n readonly agent?: Agent;\n}\n\n/**\n * Run one synthesized call through the real registry pipeline.\n * @param ctx - a context whose `tools` service is live.\n * @param call - the call to dispatch.\n * @returns the batch entry whose id matches {@link TestToolCall.callId}.\n * @throws Error when the batch settled a different call.\n */\nexport async function executeOne(ctx: Context, call: TestToolCall): Promise<ToolExecutionResult> {\n const batch: ToolBatchResult = await ctx.tools.execute({\n calls: [{ type: 'tool-call', id: call.callId as never, name: call.name, arguments: JSON.stringify(call.args ?? {}) }],\n signal: new AbortController().signal,\n ...(call.agent ? { agent: call.agent } : {})\n });\n const entry = batch.results.find((candidate) => (candidate.callId as unknown as string) === call.callId);\n if (!entry) throw new Error(`the batch settled no result for ${call.callId}`);\n return entry.result;\n}\n\n/** Branded reasoning effort id, taken from the selection type so no extra dependency is needed. */\ntype EffortId = NonNullable<ModelSelection['reasoningEffort']>;\n\n/**\n * The `modelSelection` an `agent/pre-step` payload now requires.\n *\n * The waterfall payload gained `agent`, `modelSelection`, and (in tests) a\n * `model` it does not read. Requirements beyond the identity the step already\n * carries are supplied from the agent's own composed options, falling back to\n * the reflex route, so a test never invents a selection the loop could not.\n * @param agent - the agent stepping.\n * @returns the selection the loop would carry into the step.\n */\nexport function stepSelection(agent: Agent): Readonly<ModelSelection> {\n const options = (agent as { options?: { provider?: string; model?: string; reasoningEffort?: unknown } }).options;\n return {\n provider: options?.provider ?? 'reflex',\n model: options?.model ?? 'reflex-auto',\n ...(options?.reasoningEffort === undefined ? {} : { reasoningEffort: options.reasoningEffort as EffortId })\n };\n}\n\n/**\n * Build the `agent/pre-step` payload the waterfall now declares.\n * @param agent - the agent stepping.\n * @param turn - turn number.\n * @param step - step number.\n * @param messages - messages the step carries.\n * @param signal - cancellation state.\n * @param modelSelection - selection the loop carries into the step; defaults to the agent's own.\n * @returns the payload, spelled out rather than cast.\n */\nexport function preStepPayload(\n agent: Agent,\n turn: number,\n step: number,\n messages: readonly UserMessage[],\n signal: AbortSignal = new AbortController().signal,\n modelSelection: Readonly<ModelSelection> = stepSelection(agent)\n): { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal; modelSelection: Readonly<ModelSelection> } {\n return { agent, messages: [...messages], turn, step, signal, modelSelection };\n}\n\n/**\n * Test harness for the reflex Host plugin.\n *\n * It boots a real Cordis application with every service the plugin depends on\n * (`systemPrompt` for the tool registry, then `tools` itself, `llm` for the\n * virtual provider route, and `commands` for `/reflex-ledger`), so tests\n * exercise the production registration, validation, routing, and disposal paths\n * rather than a stand-in.\n *\n * @module dsh-reflex/testing\n */\n\n/**\n * Reproduce the loader's own `loader/volatile-update` dispatch.\n *\n * The real loader emits with `Object.create(fiber.ctx)` carrying a\n * `Context.filter` that admits only listeners owned by the committing fiber.\n * Cordis 4.x hands out context-bound *proxies* of a fiber, so a fiber read off\n * one context is never `===` the fiber its own context reports; comparing\n * against `fiber.ctx.fiber` is the identity the event store records.\n *\n * @param entryFiber - the fiber the loader resolved for the entry.\n * @returns the receiver the loader emits with.\n */\nexport function loaderEventReceiver(entryFiber: { ctx: Context }): Record<symbol, unknown> {\n const owner = entryFiber.ctx;\n const self = Object.create(owner) as Record<symbol, unknown>;\n self[Context.filter] = (candidate: { fiber?: unknown }) => candidate.fiber === owner.fiber;\n return self;\n}\n\n/** The plugin as Cordis sees it, for `ctx.plugin()`-based lifecycle tests. */\nexport const reflexPlugin = { name: pluginName, inject, Config, apply };\n\n/**\n * The Host's native executor, shaped as a Cordis plugin spec.\n *\n * dsh-tools >= 0.2.2 moved execution out of the registry: `tools.execute()`\n * throws TOOL_EXECUTOR_UNAVAILABLE until an executor plugin is selected, so a\n * harness that only mounts `ToolRuntime` can no longer dispatch anything. The\n * module's `apply` is a plain function, so `{ ...module }` would lose its\n * context binding, and `ctx.plugin()` reads `inject` only from a spec object,\n * never from a derived function — hence the explicit fields.\n */\nexport const nativeExecutorPlugin = {\n name: nativeExecutor.name,\n inject: nativeExecutor.inject,\n apply: (scope: Context) => nativeExecutor.apply(scope)\n};\n\n/** A booted application with the reflex tools registered. */\nexport interface ReflexTestHost {\n /** Root context carrying `systemPrompt`, `tools`, `llm`, and `commands`. */\n readonly ctx: Context;\n /** Runtime returned by {@link apply}. */\n readonly runtime: ReflexRuntime;\n /** Execute one registered tool through the real registry pipeline. */\n callTool(name: string, args?: unknown): Promise<ToolExecutionResult>;\n /** Dispose the application (and with it the plugin's effects). */\n dispose(): Promise<void>;\n}\n\n/**\n * Boot Cordis with `systemPrompt`, `tools`, `llm`, and `commands` loaded.\n *\n * The Host's delegation tool is registered as part of the composition, because\n * `reflex_delegate` is a wrapper around it and a harness without it would not\n * reflect a normal deployment. A test that needs the no-delegation case uses\n * {@link createToolContextWithoutDelegation}.\n * @returns the root context, ready for `apply` or `ctx.plugin`.\n */\nexport async function createToolContext(options: { record?: Array<Record<string, unknown>> } = {}): Promise<Context> {\n const ctx = await createToolContextWithoutDelegation();\n ctx.tools.register(delegationStandIn(options).definition);\n return ctx;\n}\n\n/**\n * Mount the Host services every harness needs, including the two the plugin\n * reads a session selection from.\n *\n * The agent runtime injects `sessionProjections` as a *required* service, and it\n * registers `modelSelectionProjectionDefinition` before it drives any step. A\n * harness without either is not a quieter Host, it is a different one:\n * `resolveAdaptiveIntent` would fall back to \"no projection\", `stateOf` would\n * answer `undefined`, and a selection read that is wrong only in production\n * would look green here. Mounting both keeps the decision path identical.\n *\n * @param ctx - the context to mount onto.\n */\nexport async function mountHostServices(ctx: Context): Promise<void> {\n await ctx.plugin(SystemPrompt);\n await ctx.plugin(SessionProjectionRegistry);\n await ctx.plugin({\n name: 'test-model-selection-projection',\n inject: ['sessionProjections'],\n apply: (scope: Context) => {\n const service = scope as unknown as {\n sessionProjections: { register(definition: unknown): Promise<unknown> };\n };\n void service.sessionProjections.register(modelSelectionProjectionDefinition);\n }\n });\n}\n\n/**\n * Boot Cordis with every service the plugin depends on, but **no** delegation\n * tool — the one deployment shape in which `reflex_delegate` must not register.\n * @returns the root context.\n */\nexport async function createToolContextWithoutDelegation(): Promise<Context> {\n const ctx = new Context();\n await mountHostServices(ctx);\n await ctx.plugin(ToolRuntime);\n // dsh-tools >= 0.2.2 owns dispatch but ships no executor: execution moved\n // into a separately mounted executor plugin, and `tools.execute()` throws\n // TOOL_EXECUTOR_UNAVAILABLE until one is selected. The Host loads the native\n // executor as part of its own composition, so the harness mounts it too.\n await ctx.plugin(nativeExecutorPlugin);\n await ctx.plugin(LlmRuntime);\n await ctx.plugin(CommandRuntime);\n return ctx;\n}\n\n/**\n * The Host's delegation tool, shaped as the harness mounts it.\n *\n * `reflex_delegate` is a *wrapper*: it registers only when the Host tool exists\n * and declares `reasoning_effort` (i.e. the deployment set `modelSelection:\n * true`). A harness without that tool therefore reproduces an unusual deployment\n * rather than the normal one, so the default host mounts this stand-in — same\n * name, same parameter list as `@deepseek-ai/dsh-tool-subagent` publishes when\n * model selection is on — and records what the wrapper forwards. Tests that need\n * a Host *without* delegation simply do not seed it (see\n * {@link createReflexHostWithTools}).\n */\nexport interface DelegationStandIn {\n /** Registry name the Host uses by default. */\n readonly name: string;\n /** Every argument object the delegate forwarded, oldest first. */\n readonly calls: Array<Record<string, unknown>>;\n /** The definition to register. */\n readonly definition: ToolDefinition;\n}\n\n/**\n * Build the Host delegation-tool stand-in.\n * @param options - omit `reasoningEffort` to model a deployment with model selection off.\n * @returns the stand-in, with its recorded dispatches.\n */\nexport function delegationStandIn(\n options: { reasoningEffort?: boolean; record?: Array<Record<string, unknown>>; refuse?: string } = {}\n): DelegationStandIn {\n const calls: Array<Record<string, unknown>> = options.record ?? [];\n const definition = defineTool({\n name: 'subagent',\n description:\n 'Stand-in for the Host delegation tool: publishes the same parameter list as `tool-subagent` with model selection enabled, and records what `reflex_delegate` forwards.',\n parameters: {\n cwd: { type: 'string' },\n description: { type: 'string', required: true },\n prompt: { type: 'string', required: true },\n ...(options.reasoningEffort === false\n ? {}\n : {\n provider: { type: 'string' },\n model: { type: 'string' },\n reasoning_effort: { type: 'string' }\n })\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n kind: { type: 'string', required: true, const: 'activation' },\n subagentId: { type: 'string', required: true }\n }\n },\n render: (_args: unknown, value: unknown) => [\n { type: 'text' as const, text: `started subagent ${(value as { subagentId: string }).subagentId}` }\n ]\n },\n async execute(raw: Record<string, unknown>) {\n calls.push(raw);\n if (options.refuse !== undefined) throw new Error(options.refuse);\n return { kind: 'activation' as const, subagentId: `stand-in-child-${calls.length}` };\n }\n });\n return { name: 'subagent', calls, definition };\n}\n\n/**\n * Boot a context and register the reflex tools on it with the exported\n * {@link applyReflex}, mirroring a Host that loads the plugin while keeping a\n * handle on the activation's runtime.\n * @param config - deployment config; defaults are resolved by the plugin.\n * @returns the host handle.\n */\nexport async function createReflexHost(config?: ReflexConfig): Promise<ReflexTestHost> {\n const ctx = await createToolContext();\n const runtime = applyReflex(ctx, config);\n let calls = 0;\n\n return {\n ctx,\n runtime,\n callTool: (name: string, args: unknown = {}) => executeOne(ctx, { callId: `reflex-test-${++calls}`, name, args }),\n dispose: () => ctx.fiber.dispose()\n };\n}\n\n/**\n * Execute one tool on an existing context.\n * @param ctx - a context whose `tools` service is live.\n * @param name - registered tool name.\n * @param args - model-shaped arguments.\n * @returns the registry result (never throws for tool-level failures).\n */\nexport function callTool(ctx: Context, name: string, args: unknown = {}): Promise<ToolExecutionResult> {\n return executeOne(ctx, { callId: `reflex-test-${name}-${Math.random().toString(36).slice(2, 8)}`, name, args });\n}\n\n/**\n * Boot a context, register extra tools on it *before* the plugin mounts, and\n * then apply the plugin — the order the real Host uses.\n *\n * `reflex_delegate` is conditional on the Host's delegation tool, and that\n * condition is resolved when the tool surface is installed. A stand-in\n * registered afterwards would therefore never be wrapped, so tests that need a\n * delegate must seed the registry first, exactly as the Host does.\n * @param config - deployment config.\n * @param seed - registers the pre-existing tools; called before the plugin applies.\n * @param options - `delegation: false` boots a context with no Host delegation tool.\n * @returns the host handle.\n */\nexport async function createReflexHostWithTools(\n config: ReflexConfig | undefined,\n seed: (ctx: Context) => void,\n options: { delegation?: boolean; record?: Array<Record<string, unknown>> } = {}\n): Promise<ReflexTestHost> {\n const ctx =\n options.delegation === false\n ? await createToolContextWithoutDelegation()\n : await createToolContext(options.record === undefined ? {} : { record: options.record });\n seed(ctx);\n const runtime = applyReflex(ctx, config);\n let calls = 0;\n\n return {\n ctx,\n runtime,\n callTool: (name: string, args: unknown = {}) => executeOne(ctx, { callId: `reflex-test-${++calls}`, name, args }),\n dispose: () => ctx.fiber.dispose()\n };\n}\n\n/**\n * Boot a context and put the Host delegation tool **inside an agent scope**.\n *\n * This is the shape a real deployment has: `tool-subagent` is attached to the\n * agent preset, so `ctx.tools.get('subagent')` — the global view — does not see\n * it and `ctx.tools.get('subagent', scope)` does. A test that only ever\n * registers globally cannot reproduce g-054, because the global view is exactly\n * the view the bug was reading.\n *\n * The scope is minted the way the Host mints one: under a context that declares\n * `tools`, which the scoped context then inherits.\n * @param options - `reasoningEffort: false` models a host with model selection off.\n * @returns the root context and the scope key its delegation tool lives in.\n */\nexport async function createScopedDelegationHost(\n options: { reasoningEffort?: boolean; record?: Array<Record<string, unknown>> } = {}\n): Promise<{ ctx: Context; scope: Agent; dispose: () => Promise<void> }> {\n const ctx = await createToolContextWithoutDelegation();\n // `ScopeKey` is structural (any object), so the key doubles as the `Agent`\n // argument the public helpers take; the registry only needs it to be the same\n // identity the scope was minted with.\n const key = { id: `agent-scope-${Math.random().toString(36).slice(2, 8)}` } as unknown as Agent;\n let minted: Scope | undefined;\n // `createScope` inherits the dependency API of the context it is minted under,\n // so it has to be minted inside a context that declares `tools`.\n await ctx.inject(['tools'], async (declaring) => {\n minted = createScope(declaring, key);\n minted.ctx.tools.register(delegationStandIn(options).definition);\n });\n const scope = minted as Scope;\n return {\n ctx,\n scope: key,\n dispose: async () => {\n await scope.dispose();\n await ctx.fiber.dispose();\n }\n };\n}\n\n/**\n * Read the text a model would receive from one tool result.\n * @param result - a registry result.\n * @returns the first text block, or an empty string.\n */\nexport function resultText(result: ToolExecutionResult): string {\n const block = result.content?.[0];\n return block && block.type === 'text' ? block.text : '';\n}\n\n/**\n * Read the structured value of a successful tool result.\n * @param result - a registry result.\n * @returns the parsed value.\n * @throws Error when the call failed.\n */\nexport function resultValue<T = any>(result: ToolExecutionResult): T {\n if (result.isError) throw new Error(`tool failed: ${resultText(result)}`);\n return result.value as T;\n}\n\n/** One observed dispatch of the fake physical adapter. */\nexport interface PhysicalCall {\n provider: string;\n model: string;\n reasoningEffort?: string;\n /** Text of the last user message, proving the payload survived routing. */\n lastUserText?: string;\n /** Whether the request was marked as loop-assembled. */\n loopOwned: boolean;\n}\n\n/** Options of {@link FakePhysicalAdapter}. */\nexport interface FakePhysicalAdapterOptions {\n /** Model ids the adapter advertises and resolves. */\n models?: string[];\n /** Reasoning efforts the adapter declares for every model; omitted = none declared. */\n reasoningEfforts?: string[];\n /** Default reasoning effort declared for every model. */\n defaultEffort?: string;\n /** When set, every dispatch fails with this error. */\n failWith?: Error;\n}\n\n/**\n * A physical provider adapter that records every dispatch, so a test can prove\n * which provider/model a routed request actually reached.\n */\nexport class FakePhysicalAdapter extends LlmAdapter {\n /** Provider route this adapter serves. */\n readonly provider: string;\n /** Dispatches observed so far, oldest first. */\n readonly calls: PhysicalCall[] = [];\n\n #models: string[];\n #options: FakePhysicalAdapterOptions;\n\n /**\n * @param provider - provider route to serve.\n * @param options - advertised models, reasoning metadata, and failure injection.\n */\n constructor(provider: string, options: FakePhysicalAdapterOptions = {}) {\n super();\n this.provider = provider;\n this.#models = options.models ?? ['default-model'];\n this.#options = options;\n }\n\n /**\n * Describe the provider route.\n * @param provider - the owned route.\n * @returns display metadata.\n */\n override providerInfo(provider: string): LlmProviderInfo {\n return { id: provider, name: `fake(${provider})` };\n }\n\n /**\n * Advertise the configured models.\n * @param provider - the owned route.\n * @returns one entry per configured model.\n */\n override async listModels(provider: string): Promise<readonly LlmModelInfo[]> {\n return this.#models.map((model) => ({ provider, id: model, name: model }));\n }\n\n /**\n * Resolve one model, declaring the configured reasoning vocabulary.\n * @param provider - the owned route.\n * @param model - requested model id.\n * @returns identity plus reasoning metadata.\n */\n override async resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {\n const efforts = this.#options.reasoningEfforts;\n const reasoning =\n efforts && efforts.length > 0\n ? {\n efforts: efforts.map((effort) => ({ id: effort, name: effort })),\n ...(this.#options.defaultEffort ? { defaultEffort: this.#options.defaultEffort } : {})\n }\n : undefined;\n return {\n provider,\n id: model,\n name: model,\n ...(reasoning ? { reasoning: reasoning as unknown as LlmResolvedModelInfo['reasoning'] } : {})\n };\n }\n\n /**\n * Record one dispatch and emit a deterministic single-chunk response.\n * @param options - the routed request.\n * @returns the chunk stream.\n */\n override async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {\n const lastUser = [...options.messages].reverse().find((message) => message.role === 'user');\n const text = (lastUser?.content ?? []).find((block) => block.type === 'text');\n this.calls.push({\n provider: options.provider,\n model: options.model,\n ...(options.reasoningEffort === undefined ? {} : { reasoningEffort: options.reasoningEffort as unknown as string }),\n ...(text && text.type === 'text' ? { lastUserText: text.text } : {}),\n loopOwned: isAgentLoopRequest(options)\n });\n\n if (this.#options.failWith) throw this.#options.failWith;\n\n yield { type: 'text-delta', index: 0, text: `${options.provider}:${options.model}` };\n yield { type: 'finish', reason: { kind: 'stop' } };\n }\n}\n\n/**\n * Register one fake physical adapter on a context.\n * @param ctx - a context whose `llm` service is live.\n * @param provider - provider route to register.\n * @param options - adapter behavior.\n * @returns the adapter, with its recorded calls.\n */\nexport function registerPhysicalAdapter(\n ctx: Context,\n provider: string,\n options: FakePhysicalAdapterOptions = {}\n): FakePhysicalAdapter {\n const adapter = new FakePhysicalAdapter(provider, options);\n ctx.llm.registerAdapter([provider], adapter);\n return adapter;\n}\n\n/** An agent-shaped dispatch subject for routing tests. */\nexport interface FakeAgentSeed {\n /** Agent/session id. */\n id: string;\n /** `subagent` marks a delegated child session. */\n origin?: 'subagent';\n /** Delegation depth recorded on the session header. */\n delegationDepth?: number;\n /** Provider the agent was composed with. */\n provider?: string;\n /** Model the agent was composed with. */\n model?: string;\n}\n\n/**\n * Build the agent shape the routing listeners read.\n *\n * The session is a real {@link Session}, not a `{ header }` stand-in: the\n * selection projection folds a session's committed events (`snapshotEvents`),\n * and `resolveAdaptiveIntent` reads it. A plain object would make that read\n * throw and silently downgrade every test to \"no projection\" — i.e. the harness\n * would not reproduce the Host at all.\n *\n * @param seed - identity and lineage facts.\n * @returns an object usable as the `agent` payload field.\n */\nexport function fakeAgent(seed: FakeAgentSeed): Agent {\n const session = Session.create(seed.id as unknown as SessionId, undefined, {\n version: 4,\n id: seed.id,\n createdAt: 0,\n isSeeded: false,\n // Absent, not `undefined`: the header must survive a JSON round trip.\n ...(seed.origin === undefined ? {} : { origin: seed.origin }),\n ...(seed.delegationDepth === undefined ? {} : { delegationDepth: seed.delegationDepth })\n } as unknown as Parameters<typeof Session.create>[2]);\n return {\n id: seed.id,\n options: { provider: seed.provider, model: seed.model },\n session\n } as unknown as Agent;\n}\n\n/**\n * Reproduce `dsh-agent-loop`'s canonical request config for one step.\n *\n * The loop deep-freezes `structuredClone({ ...selection })` and hands it to the\n * `agent/request` waterfall. Reproducing the freeze matters: a listener that\n * still rewrote a field there would throw instead of quietly disagreeing with\n * the guards below.\n * @param selection - the step's fixed selection.\n * @returns the frozen config the loop would propose.\n */\nfunction seedRequestConfig(selection: Readonly<ModelSelection>): LlmCallConfig {\n return Object.freeze(structuredClone({ ...selection })) as unknown as LlmCallConfig;\n}\n\n/**\n * Dispatch one `agent/pre-step` and then one `agent/request` for an agent, the\n * way `dsh-agent-loop` does, and return the configuration the loop would use.\n *\n * The order is the loop's own (g-056), not a convenience: the step's selection\n * is captured first (`this.model.current()`), passed through the `agent/pre-step`\n * waterfall, and only then compared against what `agent/request` proposes. The\n * two guards are the loop's two guards, message for message, so a decision that\n * wrote the wrong place fails here instead of in a real session.\n *\n * @param ctx - context the plugin was loaded on.\n * @param agent - the requesting agent.\n * @param options - step identity and the selection the loop fixes for the step.\n * @returns the rewritten call configuration.\n * @throws Error when the waterfall proposed a provider, model or effort the step\n * preparation had already fixed — exactly what the Host throws.\n */\nexport async function dispatchAgentRequest(\n ctx: Context,\n agent: Agent,\n options: {\n turn?: number;\n step?: number;\n task?: string;\n /**\n * The selection the loop fixed for this step (`this.model.current()`).\n *\n * Defaults to the agent's own composition, which is what the earlier\n * harness called `config`; the field is named for the *loop's* concept so a\n * test cannot mistake it for the request config, which is derived from it.\n */\n selection?: Readonly<ModelSelection>;\n /** Cancellation state the loop would carry into the request. */\n signal?: AbortSignal;\n } = {}\n): Promise<LlmCallConfig> {\n const events = agentEvents(ctx, agent);\n // Captured before the waterfall, exactly like `preStep`'s `const selection`.\n // A fresh object per step, exactly like `AgentModel.current()`, which returns\n // `{ ...recorded }` / a new record rather than the stored one. Without the\n // copy the plugin's write would land in the caller's fixture and every step\n // would silently start from the previous step's routed selection.\n const selection: Readonly<ModelSelection> = { ...(options.selection ?? stepSelection(agent)) };\n const signal = options.signal ?? new AbortController().signal;\n\n const messages = options.task !== undefined ? [userMessage(options.task)] : [];\n await events.waterfall(\n 'agent/pre-step',\n preStepPayload(agent, options.turn ?? 1, options.step ?? 1, messages, signal, selection),\n async () => ({ kind: 'enter' as const, messages })\n );\n\n const proposed = await events.waterfall(\n 'agent/request',\n { turn: options.turn ?? 1, step: options.step ?? 1, signal },\n async () => seedRequestConfig(selection)\n );\n\n if (proposed.provider !== selection.provider || proposed.model !== selection.model) {\n throw new Error(\n `agent \"${agent.id}\": agent/request proposed \"${proposed.provider}/${proposed.model}\" after step preparation fixed \"${selection.provider}/${selection.model}\"; use agent.model.select() before step preparation`\n );\n }\n if (proposed.reasoningEffort !== selection.reasoningEffort) {\n throw new Error(\n `agent \"${agent.id}\": agent/request proposed reasoning effort \"${String(proposed.reasoningEffort ?? 'adapter default')}\" after step preparation fixed \"${String(selection.reasoningEffort ?? 'adapter default')}\"; use agent.model.select() before step preparation`\n );\n }\n // The loop records the admitted request, which retires a matching `pending`\n // selection into `lastUsed`. It happens *after* the guards, exactly as the\n // loop does (it logs the header when it builds the request).\n recordRequestHeader(agent, proposed);\n return proposed;\n}\n\n/**\n * Commit the `request/header` the loop logs once a request is admitted.\n *\n * The loop records the config it really dispatched, and the selection projection\n * folds that event: a recorded selection equal to the header retires `pending`\n * into `lastUsed`. Skipping it (as an earlier harness did) is not neutral — it\n * leaves `pending` set forever, so `resolveAdaptiveIntent` would read a stale\n * intent on every later step. Sessions without `append` are left alone.\n *\n * @param agent - the agent whose request was admitted.\n * @param config - the configuration the loop would have dispatched.\n */\nfunction recordRequestHeader(agent: Agent, config: LlmCallConfig): void {\n const session = (agent as { session?: { append?: unknown } }).session;\n if (!session || typeof session.append !== 'function') return;\n const data = {\n provider: config.provider,\n model: config.model,\n ...(config.reasoningEffort === undefined ? {} : { reasoningEffort: config.reasoningEffort })\n };\n try {\n (session.append as (type: string, value: unknown) => unknown).call(session, 'request/header', {\n header: { config: data },\n reason: 'initial'\n });\n } catch {\n // A synthetic session without a log simply keeps no header history.\n }\n}\n\n/**\n * Build a minimal user message carrying one text block.\n * @param text - message text.\n * @returns the message shape `agent/pre-step` carries.\n */\nexport function userMessage(text: string): UserMessage {\n return {\n id: `test-message-${text.length}`,\n role: 'user',\n content: [{ type: 'text', text }],\n source: { kind: 'user' }\n } as unknown as UserMessage;\n}\n"]}