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/bridge.js CHANGED
@@ -1,7 +1,10 @@
1
- import { Calibrator, DecisionLedger, JevDecisionBackend, MockDecisionBackend, ReflexGateService, ReflexRouter, ReflexScreenService, SimpleJevDecisionBackend, StagnationDetector, ToolResultPruner, createSystemOneBackend, scoreStatement } from './vendor/harness-reflex/index.js';
2
- import { resolveApiKey, resolveConfig, volatileSnapshots } from './config.js';
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { Calibrator, DecisionLedger, JevDecisionBackend, MockDecisionBackend, ReflexGateService, ReflexRouter, ReflexScreenService, SimpleJevDecisionBackend, StagnationDetector, ToolResultPruner, scoreStatement } from './vendor/harness-reflex/index.js';
3
+ import { connectionImplementation, resolveApiKeyWithSource, resolvedKeyOf, resolveConfig, volatileSnapshots } from './config.js';
3
4
  import { EffortInterceptor, EffortStatusFeed } from './effort.js';
5
+ import { UnconfiguredBackend } from './unconfigured-backend.js';
4
6
  import { VirtualModelRouter } from './router.js';
7
+ import { attributionOf, callIdentity, classifyEvidence, ledgerAttribution, MOCK_CONNECTION_NAME, UNCONFIGURED_CONNECTION_NAME } from './attribution.js';
5
8
  /**
6
9
  * A decision backend whose implementation can be swapped while services keep
7
10
  * their reference to it.
@@ -64,6 +67,233 @@ class LiveBackend {
64
67
  return typeof health === 'function' ? health.call(this.#target) : undefined;
65
68
  }
66
69
  }
70
+ /**
71
+ * The attributed, append-only ledger sink every decision service writes through.
72
+ *
73
+ * ## Why a decorator rather than fields on the entry (g-068)
74
+ *
75
+ * `ReflexGateService`, `ReflexRouter`, `ToolResultPruner` and the rest write
76
+ * their *own* ledger entry while they run, and that entry is the one a reader
77
+ * sees. `DecisionLedger` is shared with the root stdio MCP package, whose
78
+ * contract g-068 must not touch, so this layer keeps the provenance inside the
79
+ * entry's existing open `details` bag instead of adding fields to it.
80
+ *
81
+ * ## Per-call isolation (the att-001 review's BLOCK-1)
82
+ *
83
+ * The first attempt kept **one** "current stamp" field and cleared it in a
84
+ * `finally`. Two overlapping calls then destroyed each other's attribution: the
85
+ * fast call's clear wiped the slow call's stamp, the slow call's service entry
86
+ * was written unattributed, and its payload still said `local-fallback`. The
87
+ * ledger and the payload disagreed about the same call, which is the exact
88
+ * falsehood this goal exists to remove. There is no single shared field any
89
+ * more: {@link open} returns a *token*, a service's entry is held in a buffer
90
+ * **owned by that token**, and nothing a concurrent call does can reach it.
91
+ *
92
+ * ## Written once, finished, never rewritten (BLOCK-2)
93
+ *
94
+ * A service writes its entry *before* the answer settles, when `source` is still
95
+ * unknown. Stamp-then-rewrite-the-last-JSONL-line was the first attempt's answer
96
+ * to that, and it was wrong twice over: it rewrote a line that might belong to
97
+ * another call, and rewriting a whole file is an append-only violation that can
98
+ * truncate a sink another writer is appending to. Here the service's entry is
99
+ * **buffered** on its token; when the call settles, {@link finish} appends that
100
+ * one entry exactly once — identity *and* source together, already final. An
101
+ * unregistered token (a call that threw before settling) falls back to the
102
+ * buffered group in {@link flush}, so no entry is ever lost. The JSONL file is
103
+ * therefore only ever appended to: no line is rewritten and no line is moved.
104
+ *
105
+ * ## Why attribution can honestly be `unknown`
106
+ *
107
+ * A call whose outcome cannot be proven must say so rather than claim `remote`.
108
+ * Two paths reach that state and both end up here: a backend that exposes no
109
+ * failure record at all (the vLLM logits backend) and a call whose service entry
110
+ * was written after the call had already settled ({@link AttributedLedger.report}
111
+ * explains how). See {@link classifyEvidence}.
112
+ */
113
+ export class AttributedLedger {
114
+ target;
115
+ /** Open calls: the identity each token was opened with, and the entries it holds. */
116
+ #openCalls = new Map();
117
+ /** Call tokens in dispatch order; settled calls are removed as they finish. */
118
+ #settleOrder = [];
119
+ /** Entries a service wrote while no call was open, if any. */
120
+ #unattributed = [];
121
+ #nextToken = 0;
122
+ /** Set when a call settled while its own entry was still unaccounted for. */
123
+ #aCallLandedLate = false;
124
+ /**
125
+ * @param target - the activation's real ledger sink.
126
+ */
127
+ constructor(target) {
128
+ this.target = target;
129
+ }
130
+ /**
131
+ * Open one call's ledger context.
132
+ * @param identity - the identity taken at dispatch, before the call is awaited.
133
+ * @returns the token to settle the call with, and the sink its services write through.
134
+ */
135
+ open(identity) {
136
+ const token = this.#nextToken;
137
+ this.#nextToken += 1;
138
+ this.#openCalls.set(token, { identity, held: [] });
139
+ this.#settleOrder.push(token);
140
+ return { token, ledger: this.#sinkFor(token) };
141
+ }
142
+ /**
143
+ * The sink one call's services write through.
144
+ *
145
+ * A token that is no longer open (only a service writing *after* its own call
146
+ * settled can hit this) buffers into the shared group that {@link flush}
147
+ * settles as `unknown`, rather than being dropped.
148
+ * @param token - the call's token.
149
+ * @returns the sink to hand a decision service.
150
+ */
151
+ #sinkFor(token) {
152
+ return {
153
+ record: (entry) => {
154
+ const call = this.#openCalls.get(token);
155
+ if (call !== undefined) {
156
+ // Buffered, not written: the same object is appended once the call
157
+ // settles, so the entry a reader sees is final the first time.
158
+ call.held.push({ entry, identity: call.identity });
159
+ }
160
+ else {
161
+ this.#unattributed.push(entry);
162
+ }
163
+ // The service owns this return value only to log it; the entry it will
164
+ // actually be read from is the one appended at settlement.
165
+ return { ...entry, id: '', timestamp: '' };
166
+ }
167
+ };
168
+ }
169
+ /**
170
+ * The sink a service writes through when no call is in force.
171
+ *
172
+ * A service driven directly — the automatic-intervention engine, a
173
+ * programmatic caller, a test — has no dispatch context to attribute it to.
174
+ * Its entry is appended **immediately** (dropping it would lose an audited
175
+ * judgment) with the source the service itself reported when it reported one
176
+ * (a `systemOneSource`-style field on the entry), and `unknown` otherwise. It is
177
+ * never left to read as a remote success.
178
+ * @param token - the identity-less call id, for logging only.
179
+ * @returns the unattributed sink.
180
+ */
181
+ unattributedSink() {
182
+ return {
183
+ record: (entry) => {
184
+ // A service may have been given its provenance by a caller that knew it
185
+ // (the intervention engine attributes the call itself). Honour that;
186
+ // otherwise say plainly that nothing proves where the answer came from.
187
+ const claimed = typeof entry.details?.systemOneSource === 'string';
188
+ this.target.record({
189
+ ...entry,
190
+ details: {
191
+ ...entry.details,
192
+ ...(claimed
193
+ ? {}
194
+ : ledgerAttribution({
195
+ connectionName: 'unknown',
196
+ requestedModel: null,
197
+ source: 'unknown',
198
+ detail: 'the entry was written outside the call it belongs to'
199
+ }))
200
+ }
201
+ });
202
+ return { ...entry, id: '', timestamp: '' };
203
+ }
204
+ };
205
+ }
206
+ /** Close one token's context, returning what it held. */
207
+ #close(token) {
208
+ const call = this.#openCalls.get(token);
209
+ this.#openCalls.delete(token);
210
+ const at = this.#settleOrder.indexOf(token);
211
+ if (at !== -1)
212
+ this.#settleOrder.splice(at, 1);
213
+ return call?.held ?? [];
214
+ }
215
+ /**
216
+ * Append what one call held, once, with the final source.
217
+ *
218
+ * The source is written into `details` here — the last moment it is knowable
219
+ * and the only moment anything is persisted — so no line is ever rewritten.
220
+ * @param token - the call's token.
221
+ * @param outcome - the settled outcome, source included.
222
+ * @returns how many entries this call appended.
223
+ */
224
+ finish(token, outcome) {
225
+ const held = this.#close(token);
226
+ const fields = ledgerAttribution(attributionOf(outcome.identity, outcome));
227
+ for (const item of held) {
228
+ this.target.record({ ...item.entry, details: { ...item.entry.details, ...fields } });
229
+ }
230
+ // A service that wrote only after its call settled left its entry in the
231
+ // shared group, where it cannot be told apart from another call's. Flag the
232
+ // settlement so the runtime can withdraw the claim it would otherwise make.
233
+ if (held.length === 0 && this.#unattributed.length > 0)
234
+ this.#aCallLandedLate = true;
235
+ return held.length;
236
+ }
237
+ /**
238
+ * Append what one call held, with a source that could not be verified.
239
+ * @param token - the call's token.
240
+ * @returns how many entries this call appended.
241
+ */
242
+ finishUnknown(token) {
243
+ const held = this.#close(token);
244
+ const fields = ledgerAttribution({
245
+ connectionName: 'unknown',
246
+ requestedModel: null,
247
+ source: 'unknown',
248
+ detail: 'the call did not settle, so where its answer came from is unproven'
249
+ });
250
+ for (const item of held) {
251
+ this.target.record({
252
+ ...item.entry,
253
+ details: { ...item.entry.details, ...fields, systemOneConnection: item.identity.connectionName, systemOneModel: item.identity.requestedModel }
254
+ });
255
+ }
256
+ return held.length;
257
+ }
258
+ /**
259
+ * Append entries that were written while no call was open.
260
+ *
261
+ * They cannot be attributed to a call, so they are marked `unknown` rather
262
+ * than left to read as a remote success.
263
+ * @returns whether any entry was appended.
264
+ */
265
+ flush() {
266
+ const pending = this.#unattributed;
267
+ this.#unattributed = [];
268
+ for (const entry of pending) {
269
+ const already = typeof entry.details?.systemOneSource === 'string';
270
+ this.target.record({
271
+ ...entry,
272
+ details: {
273
+ ...entry.details,
274
+ ...(already
275
+ ? {}
276
+ : ledgerAttribution({
277
+ connectionName: 'unknown',
278
+ requestedModel: null,
279
+ source: 'unknown',
280
+ detail: 'the entry was written outside the call it belongs to'
281
+ }))
282
+ }
283
+ });
284
+ }
285
+ return pending.length > 0;
286
+ }
287
+ /**
288
+ * Take, once, whether a settled call could not be tied to its own entry.
289
+ * @returns `true` when the last settlement landed late.
290
+ */
291
+ takeLateCall() {
292
+ const late = this.#aCallLandedLate;
293
+ this.#aCallLandedLate = false;
294
+ return late;
295
+ }
296
+ }
67
297
  /**
68
298
  * In-process System One runtime shared by every reflex tool of one plugin
69
299
  * activation.
@@ -98,8 +328,20 @@ export class ReflexRuntime {
98
328
  effort;
99
329
  /** Status-bar surface of the adaptive effort decisions of this activation. */
100
330
  effortStatusFeed;
331
+ /**
332
+ * Delegated-agent effort inheritance, when this activation installed one.
333
+ *
334
+ * A delegated agent cannot decide its own effort, so the marker is replaced on
335
+ * its `model/selection` before the step reads it. Held here so the panel and
336
+ * diagnostics can report how often that happened.
337
+ */
338
+ #effortInheritance;
101
339
  #disposed = false;
102
340
  #surface = [];
341
+ /** Reads the live delegation capability; set by the plugin lifecycle. */
342
+ #delegationHealth;
343
+ /** Records the agent scope the delegation capability is read in. */
344
+ #noteDelegationScope;
103
345
  #interventions;
104
346
  /**
105
347
  * The config the Host resolved for this activation, kept as it was passed in.
@@ -137,12 +379,23 @@ export class ReflexRuntime {
137
379
  */
138
380
  #toolsConfig;
139
381
  #toolPrefix;
382
+ /**
383
+ * The delegation consent currently in force.
384
+ *
385
+ * A config-only save commits this without remounting the activation, and both
386
+ * the registry and the panel must follow it: reading the startup snapshot here
387
+ * would keep registering (or withholding) `reflex_delegate` after the user
388
+ * ticked the switch.
389
+ */
390
+ #delegationConfig;
140
391
  /** Applies a freshly resolved intervention policy to the installed listeners. */
141
392
  #reconfigureInterventions;
142
393
  /** Reads how many intervention listeners are currently attached. */
143
394
  #interventionListenerCount;
144
395
  /** Reconciles the registered tool set with a freshly resolved config. */
145
396
  #reconfigureTools;
397
+ /** Re-reads the Host delegation capability and reconciles the surface. */
398
+ #refreshDelegation;
146
399
  /** Reads how many tools this activation currently has registered. */
147
400
  #toolRegistrationCount;
148
401
  /** Reads how many `tools.register` calls this activation has made in total. */
@@ -151,6 +404,73 @@ export class ReflexRuntime {
151
404
  #configResolves = 0;
152
405
  /** The stable delegate all decision services dispatch through. */
153
406
  #liveBackend;
407
+ /**
408
+ * Ledger the whole activation writes through, so an entry a service owns
409
+ * carries the provenance of the call that produced it and is appended once
410
+ * (see {@link AttributedLedger}).
411
+ */
412
+ #attributed;
413
+ /**
414
+ * Per-call sinks handed to the shared decision services.
415
+ *
416
+ * The decision services are long-lived and write their own ledger entry, but
417
+ * the call they are serving is per-dispatch. Each dispatch runs its services
418
+ * inside its own {@link #callScope}, so the sink below resolves to *that*
419
+ * call's buffer. This is why no shared "current stamp" field exists: a
420
+ * concurrent call cannot see, let alone clear, another call's context.
421
+ */
422
+ tracking = {
423
+ gate: { record: (entry) => this.#recordForCurrentCall(entry) },
424
+ prune: { record: (entry) => this.#recordForCurrentCall(entry) },
425
+ stagnation: { record: (entry) => this.#recordForCurrentCall(entry) },
426
+ route: { record: (entry) => this.#recordForCurrentCall(entry) },
427
+ screen: { record: (entry) => this.#recordForCurrentCall(entry) }
428
+ };
429
+ /** The dispatch context in force, so a service's `record` finds its own call. */
430
+ #callScope = new AsyncLocalStorage();
431
+ /**
432
+ * Route one service entry to the call whose context is in force.
433
+ *
434
+ * Falls back to the unattributed group (settled as `unknown`, never dropped)
435
+ * when a service writes outside any dispatch — that only happens for a
436
+ * programmatic caller driving a service directly.
437
+ * @param entry - the entry the service built.
438
+ * @returns the record result the service expects.
439
+ */
440
+ #recordForCurrentCall(entry) {
441
+ return (this.#callScope.getStore()?.sink ?? this.#attributed.unattributedSink()).record(entry);
442
+ }
443
+ /**
444
+ * Hand a decision service an already-attributed payload.
445
+ *
446
+ * The automatic intervention layer ({@link InterventionEngine}) drives the
447
+ * same services directly at Host hook points, so those calls never reach
448
+ * {@link #dispatch}. They still spend a System One judgment, and the goal
449
+ * requires every such call to be attributed — an entry the ledger cannot name
450
+ * is exactly the opacity g-068 removes.
451
+ *
452
+ * The returned ring is the call's own ledger token: the caller wraps the
453
+ * service call in {@link runInCall}, then reports the outcome through
454
+ * `settle` when the answer arrives, which is when the source first exists.
455
+ * @returns the ring for the call about to be made.
456
+ */
457
+ openCall() {
458
+ const identity = this.currentCallIdentity();
459
+ const { token, ledger } = this.#attributed.open(identity);
460
+ return {
461
+ ledger,
462
+ settle: (outcome) => this.#settleCall(token, identity, outcome)
463
+ };
464
+ }
465
+ /**
466
+ * Run one call inside its own ledger ring.
467
+ * @param ring - the ring from {@link openCall}.
468
+ * @param run - the work to run with that ring in force.
469
+ * @returns whatever `run` returns.
470
+ */
471
+ runInCall(ring, run) {
472
+ return this.#callScope.run({ sink: ring.ledger }, run);
473
+ }
154
474
  /** Whether this runtime owns the backend and may rebuild it on a config save. */
155
475
  #backendSwappable;
156
476
  /** Identity of the backend configuration currently in force. */
@@ -191,17 +511,26 @@ export class ReflexRuntime {
191
511
  this.#ledgerPath = config.ledgerPath;
192
512
  this.#routingConfig = config.routing;
193
513
  this.calibrator = config.calibrationPath ? new Calibrator(config.calibrationPath) : new Calibrator();
194
- this.gateService = new ReflexGateService(this.backend, this.ledger, this.calibrator);
195
- this.pruneService = new ToolResultPruner(this.backend, this.ledger, config.pruneThreshold);
196
- this.stagnationService = new StagnationDetector(this.backend, this.ledger);
197
- this.routeService = new ReflexRouter(this.backend, this.ledger);
198
- this.screenService = new ReflexScreenService(this.backend, this.ledger);
514
+ // Services that write their own ledger entry go through the attributed
515
+ // ledger, so the entry they own carries the same provenance the payload
516
+ // reports — with a source that is only written once it is knowable.
517
+ this.#attributed = new AttributedLedger(this.ledger);
518
+ // The services are typed against the whole ledger but only ever call
519
+ // `record`; the cast keeps that one-method contract honest while the
520
+ // attributed sink does the bookkeeping behind it.
521
+ const sinkOf = (sink) => sink;
522
+ this.gateService = new ReflexGateService(this.backend, sinkOf(this.tracking.gate), this.calibrator);
523
+ this.pruneService = new ToolResultPruner(this.backend, sinkOf(this.tracking.prune), config.pruneThreshold);
524
+ this.stagnationService = new StagnationDetector(this.backend, sinkOf(this.tracking.stagnation));
525
+ this.routeService = new ReflexRouter(this.backend, sinkOf(this.tracking.route));
526
+ this.screenService = new ReflexScreenService(this.backend, sinkOf(this.tracking.screen));
199
527
  this.#source = dependencies.configSource;
200
528
  this.#warn = dependencies.warn ?? (() => { });
201
529
  this.#interventionsConfig = config.interventions;
202
530
  this.#pruneThreshold = config.pruneThreshold;
203
531
  this.#toolsConfig = config.tools;
204
532
  this.#toolPrefix = config.toolPrefix;
533
+ this.#delegationConfig = config.delegation;
205
534
  const initialMark = dependencies.configSource === undefined ? [] : volatileSnapshots(dependencies.configSource);
206
535
  this.#mark = initialMark;
207
536
  this.#watchable = initialMark.length > 0;
@@ -260,52 +589,200 @@ export class ReflexRuntime {
260
589
  systemOneHealth() {
261
590
  return this.#liveBackend.currentHealth();
262
591
  }
592
+ /**
593
+ * The connection identity a call dispatched *now* would carry.
594
+ *
595
+ * Public so the panel and a test can ask the same question the dispatch path
596
+ * asks, without going through a call. It reads the live resolved connection
597
+ * block, never the activation-time snapshot, so a config-only commit is
598
+ * reflected immediately (and a profile switch cannot lag one call behind).
599
+ * @returns the identity to snapshot into the next call.
600
+ */
601
+ currentCallIdentity() {
602
+ return callIdentity(this.#systemOneConfig, this.#backendSelector);
603
+ }
604
+ /**
605
+ * Take the identity, run one call, and classify where its answer came from —
606
+ * the single place provenance is decided.
607
+ *
608
+ * The identity is snapshotted **before** `run()` is called, so the call keeps
609
+ * the connection it was dispatched under even if the backend is swapped while
610
+ * it is in flight. A thrown call is captured rather than rethrown here: some
611
+ * services answer locally after a remote failure (prune, stagnation), others
612
+ * refuse (choice, score, route, screen), and the caller decides.
613
+ *
614
+ * ## Per-call rings, not one shared stamp
615
+ *
616
+ * Every call runs inside its own {@link CallRing}, so a service that writes
617
+ * its own entry buffers it on *this* call and never on a neighbour's. Two
618
+ * overlapping calls therefore cannot borrow, erase or overwrite each other's
619
+ * attribution, which one shared "current stamp" field made trivially possible.
620
+ *
621
+ * ## Absorbed failures, and the honest `unknown`
622
+ *
623
+ * Not every remote failure arrives as a rejection. `ReflexGateService` turns a
624
+ * gateway failure into a fail-closed `escalate` verdict and *returns* it, so
625
+ * `run()` resolves normally. Where the backend publishes a failure record
626
+ * (JEV), a failure count that rose across the call proves the request was
627
+ * rejected and absorbed. Where it publishes none (the vLLM logits backend) no
628
+ * evidence proves anything, and the call reports `unknown` rather than
629
+ * claiming `remote` — see {@link classifyEvidence}.
630
+ * @param run - the call to make.
631
+ * @param options - how to read the outcome (`answered`, `localFallback`).
632
+ * @returns the value, or the failure with the classified outcome.
633
+ */
634
+ async #dispatch(run, options) {
635
+ this.#assertLive();
636
+ const identity = this.currentCallIdentity();
637
+ // A connection with no active profile, and the in-process mock, send
638
+ // nothing. Naming them apart is the whole point, so it is read from the
639
+ // identity rather than inferred from an empty health record.
640
+ const localOnly = identity.connectionName === UNCONFIGURED_CONNECTION_NAME || identity.connectionName === MOCK_CONNECTION_NAME;
641
+ const before = this.#liveBackend.currentHealth();
642
+ const ring = this.#attributed.open(identity);
643
+ let result;
644
+ let failure;
645
+ try {
646
+ result = await this.#callScope.run({ sink: ring.ledger }, run);
647
+ }
648
+ catch (error) {
649
+ failure = error instanceof Error ? error.message : String(error);
650
+ }
651
+ const after = this.#liveBackend.currentHealth();
652
+ const evidence = {
653
+ answered: failure === undefined && result !== undefined && options.answered(result),
654
+ ...(failure === undefined ? {} : { failure }),
655
+ localFallback: failure === undefined && options.localFallback?.(result) === true,
656
+ localOnly,
657
+ healthReadable: after !== undefined,
658
+ ...(before === undefined ? {} : { failuresBefore: before.consecutiveFailures }),
659
+ ...(after === undefined ? {} : { failuresAfter: after.consecutiveFailures }),
660
+ ...(after?.lastFailureReason === undefined ? {} : { lastFailureReason: after.lastFailureReason })
661
+ };
662
+ const classified = classifyEvidence(evidence);
663
+ // Appended exactly once, already final: identity *and* source together. No
664
+ // line is ever rewritten, so the JSONL sink stays append-only.
665
+ this.#attributed.finish(ring.token, { identity, ...classified });
666
+ this.#attributed.flush();
667
+ // A service that wrote only after this call settled left its entry in the
668
+ // shared group, so nothing proves that entry is this call's. The ledger line
669
+ // says `unknown`; the payload must agree with it rather than disagree.
670
+ const outcome = this.#attributed.takeLateCall()
671
+ ? { identity, ...classifyEvidence({ ...evidence, entryArrivedLate: true }) }
672
+ : { identity, ...classified };
673
+ return { ...(result === undefined ? {} : { result }), outcome, ...(failure === undefined ? {} : { failure }) };
674
+ }
675
+ /**
676
+ * Run one outbound decision inside a full attributed call.
677
+ *
678
+ * The seam the automatic-intervention engine uses: it opens a ring, runs the
679
+ * service inside it, classifies the outcome from the same evidence the tools
680
+ * use, settles the ring (append-only, once) and hands back both the value and
681
+ * the attribution so the caller can put it on its own payload.
682
+ * @param run - the decision to make.
683
+ * @param options - how to read the outcome.
684
+ * @returns the value and its attribution.
685
+ */
686
+ async attribute(run, options) {
687
+ const { result, outcome, failure } = await this.#dispatch(run, options);
688
+ if (failure !== undefined || result === undefined) {
689
+ throw new Error(failure ?? 'the System One connection produced no answer');
690
+ }
691
+ return { result, attribution: attributionOf(outcome.identity, outcome) };
692
+ }
693
+ /**
694
+ * Close one `openCall` ring: append its entries with the final source.
695
+ *
696
+ * The automatic-intervention layer calls this once its service answered, so
697
+ * a decision made at a Host hook point is attributed exactly like one made
698
+ * through a tool.
699
+ * @param token - the ring's token.
700
+ * @param identity - the identity the ring was opened with.
701
+ * @param outcome - the settled source.
702
+ * @returns the attribution for the caller's payload.
703
+ */
704
+ #settleCall(token, identity, outcome) {
705
+ this.#attributed.finish(token, { identity, ...outcome });
706
+ this.#attributed.flush();
707
+ return attributionOf(identity, outcome);
708
+ }
709
+ /**
710
+ * Append the attribution to one ledger entry's `details`.
711
+ *
712
+ * The four provenance facts ride in `details` rather than as new top-level
713
+ * `LedgerEntry` fields, because `DecisionLedger` is shared with the root stdio
714
+ * MCP package: adding keys there would be a contract change to a surface g-068
715
+ * must leave alone. `details` is already the entry's open bag, and a JSONL
716
+ * reader greps it all the same.
717
+ * @param outcome - the dispatch outcome.
718
+ * @returns the flat provenance fields to merge into `details`.
719
+ */
720
+ #provenance(outcome) {
721
+ return { ...ledgerAttribution(attributionOf(outcome.identity, outcome)) };
722
+ }
263
723
  /**
264
724
  * Multi-class choice, with the deployment's calibration curve applied to the
265
725
  * winning confidence when one is loaded.
266
726
  * @param request - question, options, and optional context.
267
- * @returns the choice response plus the calibrated confidence, when available.
727
+ * @returns the choice response plus the calibrated confidence and the
728
+ * attribution (connection, requested model, source), when available.
729
+ * @throws Error when the connection produced no answer: a choice tool must not
730
+ * invent a distribution, and the ledger still records the rejected attempt.
268
731
  */
269
732
  async choice(request) {
270
- this.#assertLive();
271
733
  const started = performance.now();
272
- const result = await this.backend.choice(request);
734
+ const { result, outcome, failure } = await this.#dispatch(() => this.backend.choice(request), {
735
+ answered: (value) => value !== undefined
736
+ });
737
+ const record = () => {
738
+ this.ledger.record({
739
+ type: 'choice',
740
+ backend: this.backend.name,
741
+ latencyMs: Math.round(performance.now() - started),
742
+ details: { action: 'choice', options: request.options.length, ...this.#provenance(outcome) }
743
+ });
744
+ };
745
+ if (result === undefined) {
746
+ record();
747
+ throw new Error(failure ?? 'the System One connection produced no answer');
748
+ }
273
749
  let calibratedConfidence;
274
750
  if (this.calibrator.isLoaded()) {
275
751
  calibratedConfidence = this.calibrator.calibrate(result.confidence).calibrated;
276
752
  }
277
- this.ledger.record({
278
- type: 'choice',
279
- backend: this.backend.name,
280
- latencyMs: Math.round(performance.now() - started),
281
- details: { action: 'choice', options: request.options.length }
282
- });
283
- return { ...result, calibratedConfidence };
753
+ record();
754
+ return { ...result, calibratedConfidence, ...attributionOf(outcome.identity, outcome) };
284
755
  }
285
756
  /**
286
757
  * Continuous 0.0 – 1.0 scoring projected from one choice call.
287
758
  * @param request - statement, rubric, and optional context.
288
- * @returns the score response recorded in the ledger.
759
+ * @returns the score response, recorded in the ledger with its attribution.
289
760
  */
290
761
  async score(request) {
291
- this.#assertLive();
292
- const result = await scoreStatement(this.backend, request);
762
+ const started = performance.now();
763
+ const { result, outcome, failure } = await this.#dispatch(() => scoreStatement(this.backend, request), {
764
+ answered: (value) => value !== undefined
765
+ });
293
766
  this.ledger.record({
294
767
  type: 'choice',
295
768
  backend: this.backend.name,
296
- latencyMs: result.latencyMs,
297
- details: { action: 'score', score: result.score }
769
+ latencyMs: result?.latencyMs ?? Math.round(performance.now() - started),
770
+ details: { action: 'score', ...(result === undefined ? {} : { score: result.score }), ...this.#provenance(outcome) }
298
771
  });
299
- return result;
772
+ if (result === undefined)
773
+ throw new Error(failure ?? 'the System One connection produced no answer');
774
+ return { ...result, ...attributionOf(outcome.identity, outcome) };
300
775
  }
301
776
  /**
302
777
  * Rank candidate skills/tools against a goal.
303
778
  * @param request - goal, candidates, and how many to return.
304
- * @returns the ranked candidates.
779
+ * @returns the ranked candidates with their attribution.
305
780
  */
306
781
  async route(request) {
307
- this.#assertLive();
308
- return this.routeService.selectBest(request.goal, request.candidates, request.topK ?? 3);
782
+ const { result, outcome, failure } = await this.#dispatch(() => this.routeService.selectBest(request.goal, request.candidates, request.topK ?? 3), { answered: (value) => value !== undefined });
783
+ if (result === undefined)
784
+ throw new Error(failure ?? 'the System One connection produced no answer');
785
+ return { ...result, ...attributionOf(outcome.identity, outcome) };
309
786
  }
310
787
  /**
311
788
  * Screen untrusted content for prompt injection and instruction hijacking.
@@ -313,17 +790,32 @@ export class ReflexRuntime {
313
790
  * @returns the screening verdict and a sanitized fence when unsafe.
314
791
  */
315
792
  async screen(request) {
316
- this.#assertLive();
317
- return this.screenService.screen(request);
793
+ const { result, outcome, failure } = await this.#dispatch(() => this.screenService.screen(request), {
794
+ answered: (value) => value !== undefined
795
+ });
796
+ if (result === undefined)
797
+ throw new Error(failure ?? 'the System One connection produced no answer');
798
+ return { ...result, ...attributionOf(outcome.identity, outcome) };
318
799
  }
319
800
  /**
320
801
  * Fail-closed verification of assertions against evidence.
802
+ *
803
+ * A remote rejection is *not* rethrown: the gate's contract is a verdict, and
804
+ * every assertion escalates. What changes is the honesty of that verdict —
805
+ * the attribution says `rejected` and carries the reason, so a local
806
+ * fail-closed escalation can no longer be read as a System One judgement.
321
807
  * @param request - assertions, evidence, and optional strictness.
322
- * @returns one outcome per assertion plus the overall verdict.
808
+ * @returns one outcome per assertion plus the overall verdict and attribution.
323
809
  */
324
810
  async gate(request) {
325
- this.#assertLive();
326
- return this.gateService.verify(request.assertions, request.evidence, { strictness: request.strictness });
811
+ const { result, outcome, failure } = await this.#dispatch(() => this.gateService.verify(request.assertions, request.evidence, { strictness: request.strictness }), { answered: (value) => value !== undefined });
812
+ if (result === undefined)
813
+ throw new Error(failure ?? 'the System One connection produced no answer');
814
+ // The service absorbs a gateway rejection into a fail-closed verdict, so a
815
+ // thrown call is impossible there; the *reason* it absorbed must still reach
816
+ // the reader. The service's own explanation already carries it, and this
817
+ // layer adds the source so the verdict is not read as a remote judgement.
818
+ return { ...result, ...attributionOf(outcome.identity, outcome) };
327
819
  }
328
820
  /**
329
821
  * Prune bulky output, preserving the lines the intent depends on.
@@ -335,16 +827,33 @@ export class ReflexRuntime {
335
827
  * @returns the compacted payload and the measured token savings.
336
828
  */
337
829
  async prune(request) {
338
- this.#assertLive();
339
- const result = await this.pruneService.prune(request.rawOutput, {
830
+ const { result, outcome, failure } = await this.#dispatch(() => this.pruneService.prune(request.rawOutput, {
340
831
  intent: request.intent,
341
832
  shadowMode: request.shadowMode
833
+ }), {
834
+ answered: (value) => value !== undefined,
835
+ // Prune is the one capability that answers locally on purpose. `judgePath`
836
+ // is its own account of which path produced the text: `local` sent no
837
+ // request at all (the payload is below the judge threshold), and
838
+ // `fallback` means the segmented request was tried and failed. Either is
839
+ // a local answer and must never be rendered as a System One judgement.
840
+ localFallback: (value) => {
841
+ const path = value.judgePath;
842
+ return path === 'fallback' || path === 'local';
843
+ }
342
844
  });
845
+ if (result === undefined)
846
+ throw new Error(failure ?? 'the System One connection produced no answer');
847
+ // A gateway failure that prune absorbed as a local fallback is still a
848
+ // rejection: `judgePath: 'fallback'` and the health record agree, and the
849
+ // reason the fallback happened is the more useful of the two to report.
850
+ const reason = result.fallbackReason ?? outcome.detail;
343
851
  return {
344
852
  tokensSaved: result.estimatedTokensSaved,
345
853
  reductionPercentage: `${result.reductionPercentage}%`,
346
854
  shadow: result.shadow,
347
- processedOutput: result.processedOutput
855
+ processedOutput: result.processedOutput,
856
+ ...attributionOf(outcome.identity, { ...outcome, ...(reason === undefined ? {} : { detail: reason }) })
348
857
  };
349
858
  }
350
859
  /**
@@ -366,7 +875,12 @@ export class ReflexRuntime {
366
875
  this.#assertLive();
367
876
  if (request.recentAction)
368
877
  this.stagnationService.recordAction(request.recentAction);
369
- return this.stagnationService.check(request.goal, request.history);
878
+ // Dispatched like every other decision: the service writes its own entry,
879
+ // and the ring's append-only settlement is what attributes it.
880
+ const { result, outcome, failure } = await this.#dispatch(() => this.stagnationService.check(request.goal, request.history), { answered: (value) => value !== undefined });
881
+ if (result === undefined)
882
+ throw new Error(failure ?? 'the System One connection produced no answer');
883
+ return result;
370
884
  }
371
885
  /**
372
886
  * Read the decision ledger.
@@ -477,6 +991,63 @@ export class ReflexRuntime {
477
991
  this.#reconfigureRouting = reconfigure;
478
992
  this.#routingRegistrationEvents = registrationEvents;
479
993
  }
994
+ /**
995
+ * Attach the live delegation-capability read of this activation.
996
+ *
997
+ * Set by the plugin lifecycle right after the tool surface, so the panel can
998
+ * explain what the Host actually publishes instead of silently omitting it.
999
+ * The runtime does not own the registry: it only reports what the Host says.
1000
+ * @param read - returns the current reading.
1001
+ * @param refresh - re-checks the registry and reconciles the tool surface.
1002
+ */
1003
+ attachDelegationHealth(read, refresh) {
1004
+ this.#delegationHealth = read;
1005
+ this.#refreshDelegation = refresh;
1006
+ }
1007
+ /**
1008
+ * Attach the hook that records the agent scope the capability is read in.
1009
+ *
1010
+ * `dsh-tools` is scoped, and a preset-hosted delegation tool is invisible from
1011
+ * the global view. The lifecycle owns the reading, so it also owns the scope:
1012
+ * this only lets a caller that *does* have an `Agent` (the panel poll, a
1013
+ * session-aware caller) tell it which scope to read as. Never decides
1014
+ * registration — that is configuration's job.
1015
+ * @param note - receives the scope to read the delegation capability in.
1016
+ */
1017
+ attachDelegationScope(note) {
1018
+ this.#noteDelegationScope = note;
1019
+ }
1020
+ /**
1021
+ * Record the scope future delegation reads should use.
1022
+ * @param agent - the calling agent, or a preset to read as.
1023
+ */
1024
+ noteDelegationScope(agent) {
1025
+ this.#noteDelegationScope?.(agent);
1026
+ }
1027
+ /** Re-check the Host delegation capability in the recorded scope. */
1028
+ checkDelegationHealth() {
1029
+ this.#refreshDelegation?.();
1030
+ return this.#delegationHealth?.();
1031
+ }
1032
+ /** The current delegation-capability reading, when the lifecycle attached one. */
1033
+ get delegationHealth() {
1034
+ return this.#delegationHealth?.();
1035
+ }
1036
+ /**
1037
+ * Attach the delegated-agent effort inheritance of this activation.
1038
+ * @param inheritance - the installed listener, or undefined to detach.
1039
+ */
1040
+ attachEffortInheritance(inheritance) {
1041
+ this.#effortInheritance = inheritance;
1042
+ }
1043
+ /**
1044
+ * How many delegated selections this activation rewrote to a concrete level.
1045
+ *
1046
+ * Monotonic: it counts the marker replacements, not the steps that used them.
1047
+ */
1048
+ get effortInheritanceRewrites() {
1049
+ return this.#effortInheritance?.rewrites ?? 0;
1050
+ }
480
1051
  /** Provider registrations this activation made (monotonic; diagnostics). */
481
1052
  get routingRegistrationEvents() {
482
1053
  return this.#routingRegistrationEvents?.() ?? 0;
@@ -532,6 +1103,10 @@ export class ReflexRuntime {
532
1103
  ...(fallback === undefined ? {} : { fallback })
533
1104
  },
534
1105
  effort: { ...this.effort.policy },
1106
+ // The delegation consent is a deployment switch, written by the panel and
1107
+ // re-resolved on every commit; a cached activation value would keep showing
1108
+ // "off" after the user ticked it.
1109
+ delegation: this.#delegationConfig,
535
1110
  interventions: this.#interventionsConfig,
536
1111
  pruneThreshold: this.#pruneThreshold
537
1112
  };
@@ -627,6 +1202,7 @@ export class ReflexRuntime {
627
1202
  // values rather than from the activation-time snapshot.
628
1203
  this.#toolsConfig = resolved.tools;
629
1204
  this.#toolPrefix = resolved.toolPrefix;
1205
+ this.#delegationConfig = resolved.delegation;
630
1206
  this.#reconfigureInterventions?.(resolved.interventions, resolved.pruneThreshold);
631
1207
  this.#reconfigureTools?.(resolved);
632
1208
  // Routing lifecycle last: enabling/disabling the route and renaming the
@@ -691,49 +1267,145 @@ function backendSignature(config) {
691
1267
  const { backend, systemOne, interventions } = config;
692
1268
  return JSON.stringify([
693
1269
  backend,
1270
+ // g-066: the resolved connection fields, which are the *active profile's*
1271
+ // (plus the "unconfigured" reason, so activating or losing a profile
1272
+ // rebuilds). They are listed here rather than left to the per-profile rows
1273
+ // below because a resolved field is the one the transport is built from.
1274
+ systemOne.unconfigured ?? '',
694
1275
  systemOne.baseUrl ?? '',
695
1276
  systemOne.model ?? '',
696
1277
  systemOne.apiKeyEnv ?? '',
697
1278
  systemOne.timeoutMs ?? null,
1279
+ // g-057: switching the active profile (or editing any profile's connection
1280
+ // facts) must rebuild the backend, otherwise the panel would report a new
1281
+ // profile as active while the running transport still served the old one.
1282
+ // The *keys* are represented by presence only: a signature is a diagnostic
1283
+ // value, and a rotated key must not change what an edited profile is
1284
+ // observed to be — but a profile that gained or lost a key must.
1285
+ systemOne.active ?? '',
1286
+ Object.entries(systemOne.profiles ?? {}).map(([name, profile]) => [
1287
+ name,
1288
+ profile.baseUrl ?? '',
1289
+ // The model *list* and the selection, not the resolved model: a save that
1290
+ // only changes which listed model is selected must rebuild the transport,
1291
+ // and so must one that adds a model the selection could point at.
1292
+ (profile.modelIds ?? []).join('\u0000'),
1293
+ profile.selectedModel ?? '',
1294
+ profile.apiKeyEnv ?? '',
1295
+ profile.timeoutMs ?? null,
1296
+ profile.backend ?? '',
1297
+ profile.apiKey === undefined ? '' : 'set'
1298
+ ]),
698
1299
  interventions.pruneJudgeMinChars
699
1300
  ]);
700
1301
  }
701
1302
  /**
702
1303
  * Build the backend a plugin activation should use.
703
1304
  *
1305
+ * ## Nothing connects without an active profile (g-066)
1306
+ *
1307
+ * The connection fields come from the active profile only, so when
1308
+ * {@link ResolvedSystemOneConfig.unconfigured} is set there is nothing to build
1309
+ * and this function **refuses**. Building a backend anyway is exactly the old
1310
+ * fallback: with no profile resolved, the vendored factory would choose `jev`
1311
+ * because `JEV_API_KEY` happens to be exported, and the plugin would make a
1312
+ * request nobody configured. Returning the mock backend instead was the other
1313
+ * candidate and was rejected as well: "unconfigured" must not look like "answered
1314
+ * locally with heuristics" in the ledger or the panel.
1315
+ *
1316
+ * The replacement is {@link UnconfiguredBackend}: the same deterministic local
1317
+ * heuristics, under a name that says what is wrong, plus a health record that
1318
+ * reports the missing connection instead of staying silent. `backend` may still
1319
+ * be `mock` **explicitly**, which is a deployment choosing the in-process
1320
+ * implementation on purpose — the two must remain distinguishable.
1321
+ *
704
1322
  * The connection block of the resolved config overrides the environment for
705
1323
  * this plugin instance only: the backend implementations already fall back to
706
1324
  * the environment for every omitted option, so an explicitly configured
707
1325
  * deployment and an env-configured one behave the same when the block is empty.
1326
+ *
1327
+ * The key is the exception worth naming: it is resolved **here**, through
1328
+ * {@link resolveApiKeyWithSource}, and handed to the backend explicitly. The
1329
+ * backends keep their own environment reads for the fields they own (base URL,
1330
+ * model), but a key that only arrived through their fallback would be invisible
1331
+ * to {@link resolveApiKeyWithSource} — and therefore to the panel, which is how
1332
+ * "the panel says the env var is empty while the backend works" was possible.
1333
+ * One chain, one answer for both.
1334
+ *
1335
+ * Every construction here also passes `apiKeyResolved: true` (g-059). That flag
1336
+ * makes "the chain resolved no key" *final*: without it both backends would
1337
+ * re-read `SYSTEM_ONE_API_KEY` / `JEV_API_KEY` (and the logits backend would
1338
+ * invent `dummy`) whenever the key was omitted, so a block naming an empty
1339
+ * variable would show as missing on the panel while its requests still
1340
+ * authenticated — the divergence this file exists to close, pointing the other
1341
+ * way. The flag defaults to `false` in the vendored backends, so every other
1342
+ * construction (tests, probes, a bare import) keeps the historical chain.
708
1343
  * @param config - resolved plugin configuration.
709
- * @param env - environment the API-key indirection reads; defaults to `process.env`.
710
- * @returns the forced backend, or one chosen from the environment for `auto`.
1344
+ * @param env - environment the API-key chain reads; defaults to `process.env`.
1345
+ * @returns the forced backend, the local-only one when nothing is configured, or
1346
+ * one chosen from the environment for `auto`.
711
1347
  */
712
1348
  export function createBackend(config, env = process.env) {
713
1349
  const { backend, baseUrl, model, timeoutMs } = config.systemOne;
714
- const apiKey = resolveApiKey(config.systemOne, env);
715
- switch (backend) {
1350
+ // An explicitly chosen `mock` is a decision, not a connection: it answers
1351
+ // in-process and reads nothing. It therefore outranks the "no active profile"
1352
+ // rule — which exists to stop *network* connections nobody configured, and
1353
+ // which would otherwise make `backend: 'mock'` impossible to ask for without
1354
+ // also authoring a profile that the mock never uses.
1355
+ if (backend === 'mock')
1356
+ return new MockDecisionBackend();
1357
+ // No active profile — or an active profile whose model cannot be sent — no
1358
+ // connection (g-066 att-002). Checked before the key chain and before the
1359
+ // provider selector below, because both of them read the environment:
1360
+ // reaching either would be the implicit request this removes.
1361
+ //
1362
+ // The model reasons are here for a reason the review found the hard way: a
1363
+ // transport built for a broken selection still sends *something*, because
1364
+ // every implementation fills an absent `model` with `|| DEFAULT_MODEL`. The
1365
+ // only place that fallback can be kept from firing is "no transport at all",
1366
+ // and `UnconfiguredBackend` issues no request.
1367
+ if (config.systemOne.unconfigured !== undefined) {
1368
+ return new UnconfiguredBackend(config.systemOne.unconfigured);
1369
+ }
1370
+ const apiKey = resolvedKeyOf(resolveApiKeyWithSource(config.systemOne, env));
1371
+ // `auto` is resolved by the *one* function the connection test asks as well
1372
+ // (g-067 att-002), so the runtime and the "Test" button can never describe two
1373
+ // different transports for the same connection. Before this, `auto` here was
1374
+ // a delegation to the vendored factory and `auto` there was a hard-coded Jev:
1375
+ // with `SYSTEM_ONE_BACKEND=vllm` exported, the button went green on the
1376
+ // official URL while this function built a request carrying the very same
1377
+ // resolved key to a vLLM endpoint. The factory is still what `auto` *means* —
1378
+ // `connectionImplementation` reads the same precedence it does — it is just no
1379
+ // longer consulted twice.
1380
+ const implementation = backend === 'auto' ? connectionImplementation('auto', env) : backend;
1381
+ switch (implementation) {
716
1382
  case 'mock':
1383
+ // The environment's `auto` answer is the in-process mock: it opens no
1384
+ // socket, so nothing configured (or resolved) leaves this process.
717
1385
  return new MockDecisionBackend();
718
1386
  case 'jev':
719
1387
  return new JevDecisionBackend({
720
1388
  ...(baseUrl === undefined ? {} : { baseUrl }),
721
1389
  ...(apiKey === undefined ? {} : { apiKey }),
1390
+ // The chain above is the whole chain: no second read behind its back.
1391
+ apiKeyResolved: true,
722
1392
  ...(model === undefined ? {} : { model }),
723
1393
  ...(timeoutMs === undefined ? {} : { timeoutMs }),
724
1394
  // The resolved config wins over SYSTEM_ONE_PRUNE_JUDGE_MIN_CHARS: the
725
1395
  // backend only reads the environment when no explicit value is given.
726
1396
  pruneJudgeMinChars: config.interventions.pruneJudgeMinChars
727
1397
  });
728
- case 'vllm':
1398
+ default:
1399
+ // `vllm`, and `auto` when the environment selected the logits backend.
729
1400
  return new SimpleJevDecisionBackend({
730
1401
  ...(baseUrl === undefined ? {} : { vllmBaseUrl: baseUrl }),
731
1402
  ...(apiKey === undefined ? {} : { apiKey }),
1403
+ // Same for the logits backend, whose `dummy` fallback would otherwise
1404
+ // turn "no key" into a header nobody configured.
1405
+ apiKeyResolved: true,
732
1406
  ...(model === undefined ? {} : { model }),
733
1407
  ...(timeoutMs === undefined ? {} : { timeoutMs })
734
1408
  });
735
- default:
736
- return createSystemOneBackend();
737
1409
  }
738
1410
  }
739
1411
  /**