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/config.js CHANGED
@@ -6,6 +6,96 @@ import { parseFallback } from './router.js';
6
6
  // list is exactly the drift this import removes. `./tools.js` imports this
7
7
  // module for types only, so no runtime cycle exists.
8
8
  import { REFLEX_TOOL_DEFAULT_ENABLED, REFLEX_TOOL_SUFFIXES } from './tools.js';
9
+ // The factory connection re-states the *project's* official endpoint and model
10
+ // rather than a second copy of the strings: `api.typesafe.ai/v1/systemone` and
11
+ // `jev-latest` are owned by the backend implementation, and a literal here would
12
+ // be a drift waiting to happen the next time the gateway moves.
13
+ import { DEFAULT_SYSTEMONE_ENDPOINT } from './vendor/harness-reflex/backend/jev.js';
14
+ /** Row name of the factory connection, as the panel shows it. */
15
+ export const FACTORY_PROFILE_NAME = 'JEV official';
16
+ /** The environment variable the factory connection locks onto — never another. */
17
+ export const FACTORY_PROFILE_API_KEY_ENV = 'JEV_API_KEY';
18
+ /**
19
+ * The factory connection (g-067): the project's own Jev gateway, switched on.
20
+ *
21
+ * A deployment whose settings document declares **no** `systemOne` block is a
22
+ * **fresh document**, and it should not open on "no connection, nothing works":
23
+ * the plugin ships with one working remote connection already named, already
24
+ * active, pointing at the official endpoint and model, and locked onto
25
+ * {@link FACTORY_PROFILE_API_KEY_ENV}.
26
+ *
27
+ * It is deliberately a normal profile — an entry of `systemOne.profiles` with
28
+ * nothing special about it — and it is supplied by the **schema default**
29
+ * (`Config.systemOne`), which schemastery applies only to an *absent* key. That
30
+ * single rule is the whole distinction between "fresh" and "the owner said
31
+ * something":
32
+ *
33
+ * - **deactivate** — the page writes `systemOne.active: ''`; the section is
34
+ * stated, resolves as `no-active-profile`, and **no** factory row is filled
35
+ * back in (the row stays listed, switched off);
36
+ * - **delete** — the page unsets the row *and* states the empty activation, so
37
+ * the section is `{profiles: {}, active: ''}` → `no-profiles`, and nothing is
38
+ * filled back in;
39
+ * - **rename / replace** — any authored `systemOne` block wins outright; the
40
+ * factory row is only ever materialized into a document that has none.
41
+ *
42
+ * The one write that would blur the line is a cleared path whose parent is then
43
+ * rebuilt from nothing (`{}`, which schemastery does not default): that is why
44
+ * the page never unsets `systemOne.active` or the last profile row on its own —
45
+ * it states an explicit empty activation instead.
46
+ *
47
+ * The lock matters as much as the row. `apiKeyEnv` **names** the variable, and
48
+ * naming locks (g-059): with no `JEV_API_KEY` exported the connection reports
49
+ * "named but empty" and sends no key — it never reaches for
50
+ * `SYSTEM_ONE_API_KEY`, `VLLM_API_KEY` or `OPENAI_API_KEY` behind the owner's
51
+ * back. Only the variable *name* is ever authored; the secret itself is never
52
+ * written into a settings document by this row.
53
+ *
54
+ * ## The implementation is bound, not left to `auto` (g-067 att-002)
55
+ *
56
+ * The row pins `backend: 'jev'` rather than inheriting the top-level selector.
57
+ * An independent review blocked the first attempt for exactly this: with no
58
+ * `backend` on the row, a fresh deployment (top-level `backend: 'auto'`) had its
59
+ * implementation chosen from the *environment* on every build — `auto` delegates
60
+ * to the vendored factory, which reads `SYSTEM_ONE_BACKEND`/`REFLEX_BACKEND` and
61
+ * `VLLM_BASE_URL`/`OPENAI_BASE_URL`. Exporting two variables therefore took the
62
+ * already-resolved `JEV_API_KEY` and sent it as `Authorization` to a vLLM
63
+ * endpoint nobody configured, while the panel's connection test — which treats
64
+ * `auto` as Jev — still probed the official URL and reported green.
65
+ *
66
+ * So the factory row states all three of the facts a connection has: where
67
+ * (official URL), what model, and **which implementation speaks it**. The
68
+ * implementation is no longer something the environment can change underneath a
69
+ * connection the plugin shipped. This is a row-level binding, which is the
70
+ * documented precedence for every profile — not a top-level override: an
71
+ * authored row, and a deployment's own `backend` selector for authored rows,
72
+ * are untouched.
73
+ *
74
+ * An **explicit** top-level `mock` still answers in-process: a mock never opens
75
+ * a socket, so it cannot send the key anywhere, and `createBackend` honours it
76
+ * before any transport is built (see its mock branch). What the binding removes
77
+ * is the *implicit* `auto` route, which is the one the environment decided.
78
+ */
79
+ export const FACTORY_SYSTEMONE_PROFILE = Object.freeze({
80
+ baseUrl: DEFAULT_SYSTEMONE_ENDPOINT,
81
+ model: 'jev-latest',
82
+ apiKeyEnv: FACTORY_PROFILE_API_KEY_ENV,
83
+ backend: 'jev'
84
+ });
85
+ /**
86
+ * `systemOne` block a settings document starts from.
87
+ *
88
+ * Returned fresh on every call, because schemastery stores the default it is
89
+ * given: a shared object would let one caller's edit leak into the next
90
+ * resolution.
91
+ * @returns a new factory block.
92
+ */
93
+ function factorySystemOneBlock() {
94
+ return {
95
+ profiles: { [FACTORY_PROFILE_NAME]: { ...FACTORY_SYSTEMONE_PROFILE } },
96
+ active: FACTORY_PROFILE_NAME
97
+ };
98
+ }
9
99
  /**
10
100
  * The three-state vocabulary every automatic capability shares.
11
101
  *
@@ -113,14 +203,55 @@ const EffortSchema = z.object({
113
203
  .default(0.3)
114
204
  .description('Minimum System 1 confidence for its answer to be trusted over the cue classifier.')
115
205
  }).volatile();
206
+ /**
207
+ * Schemastery schema for one System One connection profile.
208
+ *
209
+ * `apiKey` is the one field of this plugin declared `role('secret')`. That role
210
+ * is the whole mechanism behind the panel's write-only input: DSH's structural
211
+ * redaction (`dsh-settings` `redactSecrets`) walks the schema — through
212
+ * `z.dict()` entries, by `node.inner` — drops every secret slot from a value
213
+ * before it crosses a wire boundary, and records `{path, set}` in a sidecar so a
214
+ * configuration surface can render a placeholder without ever holding the value.
215
+ *
216
+ * Deliberately no `default`: a secret slot with a default would materialize a
217
+ * value nobody typed, and `plainSchema` strips `default`/`required` from secret
218
+ * slots anyway.
219
+ */
220
+ const SystemOneProfileSchema = z.object({
221
+ baseUrl: z.string().description('Jev gateway or OpenAI-compatible logits endpoint.'),
222
+ model: z
223
+ .string()
224
+ .description('Legacy single model id. Same as modelIds: [id]; it is kept as written and is never rewritten into the list form.'),
225
+ modelIds: z
226
+ .array(z.string())
227
+ .description('Every model id this connection may ask for. Omit to keep the legacy single model.'),
228
+ selectedModel: z
229
+ .string()
230
+ .description('The one model in force for this connection: the runtime and the connection test both use it. Omit = the first modelIds entry.'),
231
+ apiKey: z
232
+ .string()
233
+ .role('secret')
234
+ .description('API key of this profile, write-only: stored on save, never returned by any read. Empty = leave unchanged; clear it with the explicit Clear action.'),
235
+ apiKeyEnv: z.string().description('Name of the environment variable holding this profile’s API key — never the key itself.'),
236
+ timeoutMs: z.natural().description('Per-request timeout in milliseconds.'),
237
+ backend: z
238
+ .union(['auto', 'mock', 'jev', 'vllm'])
239
+ .description('Backend implementation serving this connection; omit to use the top-level backend.')
240
+ });
116
241
  /** Schemastery schema for the System One backend connection block. */
117
242
  const SystemOneSchema = z.object({
118
- baseUrl: z.string().description('Jev gateway or OpenAI-compatible logits endpoint; omit to use the environment.'),
119
- model: z.string().description('Model id the backend asks for; omit to use the environment default.'),
120
- apiKeyEnv: z
121
- .string()
122
- .description('Name of the environment variable holding the API key — never the key itself.'),
123
- timeoutMs: z.natural().description('Per-request timeout in milliseconds; omit for the backend default.')
243
+ /**
244
+ * Only profiles connect (g-066). The pre-g-066 flat `baseUrl` / `model` /
245
+ * `apiKeyEnv` / `timeoutMs` keys are deliberately **not** declared: schemastery
246
+ * drops undeclared keys, and an object write re-states only what it declares,
247
+ * so a document still carrying them keeps them byte for byte instead of having
248
+ * them converted (or deleted) as a side effect of a panel save.
249
+ */
250
+ profiles: z
251
+ .dict(SystemOneProfileSchema)
252
+ .default({})
253
+ .description('Named connection profiles; each may carry its own write-only apiKey and its own model list.'),
254
+ active: z.string().description('Name of the profile in force; a name no profile declares is reported, and nothing connects.')
124
255
  }).volatile();
125
256
  /**
126
257
  * Schemastery schema for the per-tool switch block.
@@ -138,6 +269,22 @@ const ToolsSchema = z
138
269
  .description(`Suffix → enabled (${REFLEX_TOOL_SUFFIXES.join(', ')}). Omitted suffixes keep their documented default (${REFLEX_TOOL_SUFFIXES.filter((suffix) => !REFLEX_TOOL_DEFAULT_ENABLED[suffix]).join(', ') || 'none'} off, the rest on).`)
139
270
  })
140
271
  .volatile();
272
+ /**
273
+ * Schemastery schema for the delegation block.
274
+ *
275
+ * One boolean, defaulting to `false`. It is authored, never written by the
276
+ * plugin: the panel's toggle writes this field, the runtime detector refuses to
277
+ * write it, and the only other file this plugin edits is the host patch the
278
+ * consent box names explicitly.
279
+ */
280
+ const DelegationSchema = z
281
+ .object({
282
+ enabled: z
283
+ .boolean()
284
+ .default(false)
285
+ .description('Consent to the host capability reflex_delegate needs: on = the host tool-subagent publishes reasoning_effort (modelSelection: true), which is written into the profile patch and applies after a DSH restart. Default false.')
286
+ })
287
+ .volatile();
141
288
  /**
142
289
  * Schemastery schema the Cordis loader validates the deployment config with.
143
290
  *
@@ -155,10 +302,22 @@ export const Config = z.object({
155
302
  ledgerPath: z.string().description('JSONL audit sink; omit to keep the ledger in memory.').volatile(),
156
303
  pruneThreshold: z.natural().default(500).volatile(),
157
304
  calibrationPath: z.string().description('Calibration curve JSON applied to choice confidences.').volatile(),
158
- systemOne: SystemOneSchema.default({}),
305
+ // The factory connection lives here, on the real schema default, rather than in
306
+ // `resolveSystemOneConfig` (g-067). Schemastery applies a default to a
307
+ // top-level key the document omits, and a fresh profile omits it: its patch
308
+ // file starts as `[]`, so the loader entry's config is `{}` and this key never
309
+ // appears. That is the only shape that gets the factory row from here: a
310
+ // document that *states* a `systemOne` block keeps it, which is what makes
311
+ // deactivation and deletion stick.
312
+ //
313
+ // It also puts the row where the Host settings form can see it: the form
314
+ // projects the *resolved* config, so a default the schema never produces would
315
+ // be a connection the panel shows and the settings page does not.
316
+ systemOne: SystemOneSchema.default(factorySystemOneBlock()),
159
317
  routing: RoutingSchema.default({}),
160
318
  effort: EffortSchema.default({}),
161
319
  tools: ToolsSchema.default({}),
320
+ delegation: DelegationSchema.default({}),
162
321
  interventions: InterventionsSchema.default({})
163
322
  });
164
323
  /**
@@ -274,6 +433,89 @@ export function resolveInterventionsConfig(authored, pruneThreshold = 500) {
274
433
  intent: optionalText(block.intent) ?? 'extract diagnostics, relevant results and errors'
275
434
  };
276
435
  }
436
+ /**
437
+ * Normalize one profile's model list and its single selected entry.
438
+ *
439
+ * Two authored shapes are accepted, and they mean the same thing:
440
+ *
441
+ * - `modelIds: [a, b, c]` + `selectedModel: b` — the g-066 shape, any number of
442
+ * ids with one in force;
443
+ * - `model: a` — the pre-g-066 shape, which is exactly `modelIds: [a]` selected.
444
+ * Accepted so an existing connection keeps working untouched; **no migration
445
+ * is written back**, so opening the panel changes nothing on disk.
446
+ *
447
+ * Both at once is refused rather than merged: they are two different statements
448
+ * about which models exist, and picking one would silently drop the other.
449
+ * A `selectedModel` outside the list is *not* an error here — resolution reports
450
+ * it (`activeProfileModelMissing`) so the panel can point at the field.
451
+ *
452
+ * @param name - profile name, for the message.
453
+ * @param entry - the authored profile.
454
+ * @returns the normalized list and the selected id (when the profile names one).
455
+ * @throws Error when `modelIds` is not a list of non-empty strings, or when both
456
+ * shapes are authored.
457
+ */
458
+ function resolveProfileModels(name, entry) {
459
+ const legacy = optionalText(entry.model);
460
+ const authored = entry.modelIds;
461
+ const selectedModel = optionalText(entry.selectedModel);
462
+ // An **empty** list is not an authoring: schemastery materializes `modelIds: []`
463
+ // for every profile that declares the field's schema but no value, so a legacy
464
+ // `model: x` arrives beside an empty list rather than alone. Treating that as
465
+ // "both shapes authored" would reject every pre-g-066 connection the moment it
466
+ // passes through the schema — the exact compatibility this rule protects.
467
+ if (Array.isArray(authored) && authored.length === 0 && legacy !== undefined) {
468
+ return checkedSelection(name, [legacy], selectedModel);
469
+ }
470
+ if (authored !== undefined && authored !== null) {
471
+ if (!Array.isArray(authored)) {
472
+ throw new Error(`systemOne.profiles["${name}"].modelIds must be a list of model ids`);
473
+ }
474
+ if (legacy !== undefined) {
475
+ throw new Error(`systemOne.profiles["${name}"] authors both model and modelIds; keep modelIds and selectedModel, or keep the single model`);
476
+ }
477
+ const modelIds = [];
478
+ for (const [index, raw] of authored.entries()) {
479
+ const id = optionalText(typeof raw === 'string' ? raw : undefined);
480
+ if (id === undefined) {
481
+ throw new Error(`systemOne.profiles["${name}"].modelIds[${String(index)}] must be a non-empty model id`);
482
+ }
483
+ // Duplicates are collapsed: the list is a set of choices, and two rows for
484
+ // one id would let the page show a selection that is not a selection.
485
+ if (!modelIds.includes(id))
486
+ modelIds.push(id);
487
+ }
488
+ return checkedSelection(name, modelIds, selectedModel);
489
+ }
490
+ return checkedSelection(name, legacy === undefined ? [] : [legacy], selectedModel);
491
+ }
492
+ /**
493
+ * Refuse the one authored selection that can never run.
494
+ *
495
+ * A `selectedModel` **outside** `modelIds` is not a preference to be re-resolved
496
+ * later: it names a model this connection does not offer, and every consumer —
497
+ * runtime, connection test, panel — would have to invent an answer. g-066
498
+ * att-002 closes it here, at the write, so it cannot be saved in the first
499
+ * place. A selection beside an **empty** list is the same mistake with nothing
500
+ * to select: it is refused rather than silently kept as "select nothing".
501
+ *
502
+ * (The resolution still reports such a document — {@link
503
+ * ResolvedSystemOneConfig.activeProfileModelMissing} — because a file edited by
504
+ * hand reaches it without passing through here, and the runtime then refuses to
505
+ * connect instead of running another model.)
506
+ *
507
+ * @param name - profile name, for the message.
508
+ * @param modelIds - the normalized list.
509
+ * @param selectedModel - the authored selection, when one was.
510
+ * @returns the normalized list and selection.
511
+ * @throws Error when the selection names nothing in the list.
512
+ */
513
+ function checkedSelection(name, modelIds, selectedModel) {
514
+ if (selectedModel !== undefined && !modelIds.includes(selectedModel)) {
515
+ throw new Error(`systemOne.profiles["${name}"].selectedModel "${selectedModel}" is not one of its modelIds (${modelIds.length === 0 ? 'the list is empty' : modelIds.join(', ')}); select a listed model instead`);
516
+ }
517
+ return { modelIds, ...(selectedModel === undefined ? {} : { selectedModel }) };
518
+ }
277
519
  /**
278
520
  * Trim one optional authored string, treating blank text as absent.
279
521
  * @param value - authored value.
@@ -287,7 +529,39 @@ function optionalText(value) {
287
529
  }
288
530
  /**
289
531
  * Validate the System One connection block and fill in every default.
290
- * @param backend - the top-level backend selector.
532
+ *
533
+ * ## The resolution rule (g-066: one connection, the active profile)
534
+ *
535
+ * **Only the active profile connects.** Every connection field — `baseUrl`,
536
+ * `model`, `apiKey`, `apiKeyEnv`, `timeoutMs`, `backend` — comes from the
537
+ * profile `active` names, or stays `undefined` and is then decided by the
538
+ * backend's own environment read and documented default.
539
+ *
540
+ * There is no block of last resort. A document with no valid active profile
541
+ * resolves to {@link ResolvedSystemOneConfig.unconfigured} with **no** connection
542
+ * fields at all, so nothing downstream can invent one:
543
+ *
544
+ * | document | `unconfigured` |
545
+ * | ----------------------------------------- | ------------------------- |
546
+ * | no profiles at all | `no-profiles` |
547
+ * | profiles, none activated | `no-active-profile` |
548
+ * | `active` naming a profile that is not there | `active-profile-missing` |
549
+ * | only the pre-g-066 flat fields | `legacy-config-required` |
550
+ *
551
+ * The pre-g-066 merge ("active profile over flat block over environment") was
552
+ * removed because the *fallback* was the bug: a mistyped or missing activation
553
+ * ran a connection the user never selected. The legacy fields are still *read*,
554
+ * but only to name the problem in `legacy-config-required` — converting them into
555
+ * a profile would be a silent configuration change (and, for `apiKeyEnv`, a
556
+ * silent choice between a literal key and a variable), so this function never
557
+ * does it.
558
+ *
559
+ * `apiKey` and `apiKeyEnv` stay independent, so a profile may carry a literal key
560
+ * while naming no variable, or name a variable and carry no key;
561
+ * {@link resolveApiKeyWithSource} decides which the transport presents.
562
+ *
563
+ * @param backend - the top-level backend selector (the fallback implementation
564
+ * choice for a profile that states none).
291
565
  * @param authored - the authored `systemOne` block.
292
566
  * @returns the resolved connection settings.
293
567
  * @throws Error when a field is present but unusable.
@@ -297,36 +571,514 @@ export function resolveSystemOneConfig(backend, authored) {
297
571
  if (!['auto', 'mock', 'jev', 'vllm'].includes(selected)) {
298
572
  throw new Error(`backend must be one of auto, mock, jev, vllm (got "${String(backend)}")`);
299
573
  }
300
- const baseUrl = optionalText(authored?.baseUrl);
301
- const model = optionalText(authored?.model);
302
- const apiKeyEnv = optionalText(authored?.apiKeyEnv);
303
- const timeoutMs = authored?.timeoutMs;
304
- if (timeoutMs !== undefined && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) {
305
- throw new Error(`systemOne.timeoutMs must be a positive integer (got "${String(timeoutMs)}")`);
574
+ const profiles = resolveSystemOneProfiles(authored?.profiles);
575
+ const hasProfiles = Object.keys(profiles).length > 0;
576
+ const active = optionalText(authored?.active);
577
+ const activeProfile = active === undefined ? undefined : profiles[active];
578
+ const activeProfileMissing = active !== undefined && activeProfile === undefined;
579
+ // The shared half of the resolved shape: what the document authors, and
580
+ // nothing that could be mistaken for a connection.
581
+ const authoredShape = {
582
+ backend: selected,
583
+ ...(hasProfiles ? { profiles } : {}),
584
+ ...(active === undefined ? {} : { active }),
585
+ ...(activeProfileMissing ? { activeProfileMissing: true } : {})
586
+ };
587
+ if (activeProfile === undefined) {
588
+ // Nothing was activated. Which of the four absence reasons applies decides
589
+ // the copy the panel shows and the message the runtime logs, so the facts are
590
+ // kept apart rather than collapsed into "not configured".
591
+ const legacy = legacyConnectionAuthored(authored);
592
+ const unconfigured = activeProfileMissing
593
+ ? 'active-profile-missing'
594
+ : hasProfiles
595
+ ? 'no-active-profile'
596
+ : legacy
597
+ ? 'legacy-config-required'
598
+ : 'no-profiles';
599
+ return { ...authoredShape, unconfigured };
600
+ }
601
+ // The profile's *selected* model: the one the runtime sends and the probe
602
+ // tests. A selection outside the list is reported — never resolved to "the
603
+ // first one", which would run a model nobody picked.
604
+ const modelIds = activeProfile.modelIds ?? [];
605
+ const selectedModel = modelForProfile(activeProfile, modelIds);
606
+ const modelSelectionBroken = selectedModel?.missing === true;
607
+ // The implementation this connection really runs (g-067 att-002), resolved by
608
+ // the precedence {@link connectionTarget} applies, so the runtime and the
609
+ // connection test cannot describe two different transports.
610
+ const implementationSelector = effectiveImplementation(selected, activeProfile.backend, activeProfile);
611
+ // The timeout is already validated per profile (`resolveProfileEntry` runs on
612
+ // every entry, the active one included), so this is a read, not a re-check: a
613
+ // second copy of the predicate here would be a check nothing can reach, and
614
+ // the mutation control proved it — disabling *this* line left every test green.
615
+ const timeoutMs = activeProfile.timeoutMs;
616
+ // Which model the transport would *really* send (g-066 att-002), decided by
617
+ // the one function the connection test reads as well.
618
+ const planned = plannedModel(modelIds, implementationSelector, selectedModel);
619
+ const connection = {
620
+ ...authoredShape,
621
+ // The selector this connection really runs under, *after* the spread so the
622
+ // authored top-level value cannot re-assert itself over the row's choice.
623
+ backend: implementationSelector,
624
+ ...(activeProfile.baseUrl === undefined ? {} : { baseUrl: activeProfile.baseUrl }),
625
+ ...(modelSelectionBroken || selectedModel?.model === undefined ? {} : { model: selectedModel.model }),
626
+ ...(activeProfile.apiKeyEnv === undefined ? {} : { apiKeyEnv: activeProfile.apiKeyEnv }),
627
+ ...(activeProfile.apiKey === undefined ? {} : { apiKey: activeProfile.apiKey }),
628
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
629
+ ...(modelSelectionBroken ? { activeProfileModelMissing: true } : {})
630
+ };
631
+ // A model the configuration puts in force but the runtime cannot honour is a
632
+ // refusal, not a connection: `unconfigured` means "build no transport", which
633
+ // is the only way the backend's default can never stand in for it.
634
+ if (planned.unusable !== undefined)
635
+ return { ...connection, unconfigured: planned.unusable };
636
+ // Spread conditionally: `model: undefined` would still be a *present* key, and
637
+ // "absent" is what the panel and the probe read as "names no model".
638
+ return planned.model === undefined ? connection : { ...connection, model: planned.model };
639
+ }
640
+ /**
641
+ * The model a connection would actually send, or why it can send none.
642
+ *
643
+ * The single implementation of the rule the runtime and the connection test both
644
+ * obey (g-066 att-002). It exists because `model === undefined` did *not* mean
645
+ * "no model": every remote backend fills an absent `model` with `|| DEFAULT`, and
646
+ * `auto` may additionally take a `SYSTEM_ONE_MODEL` from the environment. Left
647
+ * to the backend, a broken selection became a live request for a model nobody
648
+ * chose, while the probe — which has no such default — sent nothing. Both ends
649
+ * now ask this one function, in the same process, so they cannot disagree.
650
+ *
651
+ * - the profile lists ids and selects one: that id;
652
+ * - its selection is outside the list: **unusable** (`model-selection-invalid`),
653
+ * never the first id and never an implementation default;
654
+ * - it lists no id: the default of the implementation that would be built, read
655
+ * from the same environment the backend reads — unless that implementation is
656
+ * not determinable, in which case it is **unusable**
657
+ * (`model-selection-unusable`) rather than a guess between two defaults;
658
+ * - `mock` connects nowhere and names no model.
659
+ *
660
+ * @param modelIds - the profile's model list.
661
+ * @param backend - the effective implementation selector.
662
+ * @param selected - what {@link modelForProfile} answered for the profile.
663
+ * @param env - the environment the backend would read.
664
+ * @returns the model to send, or the refusal tag.
665
+ */
666
+ function plannedModel(modelIds, backend, selected, env = process.env) {
667
+ if (selected.missing === true)
668
+ return { unusable: 'model-selection-invalid' };
669
+ if (selected.model !== undefined)
670
+ return { model: selected.model };
671
+ const fallback = defaultModelAnswer(backend, env);
672
+ if (fallback.unusable === true)
673
+ return { unusable: 'model-selection-unusable' };
674
+ return fallback.model === undefined ? {} : { model: fallback.model };
675
+ }
676
+ /**
677
+ * The model a backend would fall back to, for a connection that names none.
678
+ *
679
+ * Only the *defaults* of the two remote implementations are modelled, under the
680
+ * same environment precedence as the backend classes (explicit option, then
681
+ * `SYSTEM_ONE_MODEL`, then the per-implementation variable, then the constant).
682
+ * The in-process mock is not configured by any of this and has never touched an
683
+ * endpoint, so it names no model.
684
+ *
685
+ * `unusable` is the "there is a model, but no backend here could send it"
686
+ * answer: an `auto` provider chosen from the environment by a URL rather than an
687
+ * explicit provider.
688
+ *
689
+ * @param backend - the effective implementation selector.
690
+ * @param env - the environment the backend would read; the process environment by
691
+ * default, so the runtime and the probe (in that same process) agree.
692
+ * @returns the model that would be sent, and whether it is unusable.
693
+ */
694
+ function defaultModelAnswer(backend, env = process.env) {
695
+ const named = optionalText(env.SYSTEM_ONE_MODEL);
696
+ if (backend === 'mock')
697
+ return {};
698
+ if (backend === 'jev')
699
+ return { model: named ?? optionalText(env.JEV_MODEL) ?? 'jev-latest' };
700
+ if (backend === 'vllm') {
701
+ return { model: named ?? optionalText(env.VLLM_MODEL) ?? 'Qwen/Qwen2.5-7B-Instruct' };
702
+ }
703
+ // `auto`: the vendored factory picks the implementation from the environment.
704
+ // It is modelled exactly as far as it is deterministic — an explicit provider
705
+ // variable selects one — and anything else is refused rather than guessed.
706
+ const provider = (env.SYSTEM_ONE_BACKEND ?? env.REFLEX_BACKEND ?? '').trim().toLowerCase();
707
+ if (provider === 'jev')
708
+ return { model: named ?? optionalText(env.JEV_MODEL) ?? 'jev-latest' };
709
+ if (provider === 'vllm' || provider === 'simple-jev' || provider === 'logits') {
710
+ return { model: named ?? optionalText(env.VLLM_MODEL) ?? 'Qwen/Qwen2.5-7B-Instruct' };
711
+ }
712
+ if (provider.length === 0) {
713
+ if (!named && (env.SYSTEM_ONE_API_KEY || env.JEV_API_KEY)) {
714
+ return { model: optionalText(env.JEV_MODEL) ?? 'jev-latest' };
715
+ }
716
+ if (!named && (env.VLLM_BASE_URL || env.OPENAI_BASE_URL)) {
717
+ return { model: optionalText(env.VLLM_MODEL) ?? 'Qwen/Qwen2.5-7B-Instruct' };
718
+ }
719
+ // Neither credential nor endpoint: the factory would build the in-process
720
+ // mock. That is still *not* "no model" — the runtime would answer from
721
+ // heuristics while the panel showed a configured connection — so it is
722
+ // refused like any other undeterminable implementation. A deployment that
723
+ // wants the in-process answer asks for it (`backend: mock`).
724
+ }
725
+ // A model was named but no implementation can be determined to send it.
726
+ return { unusable: true };
727
+ }
728
+ /**
729
+ * The model one profile puts in force, and whether the selection is broken.
730
+ *
731
+ * A legacy single `model` is a one-entry list, so the two authored shapes answer
732
+ * the same way: `selectedModel` if it names an entry, else the first entry, else
733
+ * absent (a connection may name no model at all and let the backend default it).
734
+ * @param profile - the normalized profile.
735
+ * @param modelIds - its model list.
736
+ * @returns the resolved choice; `missing` marks a selected id outside the list.
737
+ */
738
+ function modelForProfile(profile, modelIds) {
739
+ const chosen = profile.selectedModel;
740
+ if (chosen === undefined)
741
+ return modelIds.length === 0 ? {} : { model: modelIds[0] };
742
+ // The list is what decides: an id outside it cannot be run, even when it is the
743
+ // only text the document carries.
744
+ return modelIds.includes(chosen) ? { model: chosen } : { missing: true };
745
+ }
746
+ /**
747
+ * Whether the document carries the pre-g-066 flat connection fields.
748
+ *
749
+ * Read purely to *name* the problem: a deployment authored that way used to
750
+ * connect implicitly, and "no profile configured" would be a confusing answer
751
+ * for a document that plainly holds an address. Never a connection itself.
752
+ * @param authored - the authored `systemOne` block.
753
+ * @returns true when any legacy connection field is non-blank.
754
+ */
755
+ function legacyConnectionAuthored(authored) {
756
+ return [authored?.baseUrl, authored?.model, authored?.apiKeyEnv].some((value) => optionalText(value) !== undefined);
757
+ }
758
+ /**
759
+ * Normalize every authored profile, rejecting names the panel cannot address.
760
+ *
761
+ * A name becomes both a `z.dict` key and a segment of a settings `set` path, so
762
+ * the rules are the ones those two consumers impose: non-blank, no `.` (the path
763
+ * separator) and unique after case folding (the panel shows names as identifiers
764
+ * and two rows differing only in case would be indistinguishable).
765
+ *
766
+ * @param authored - the authored `profiles` dictionary.
767
+ * @returns the normalized profiles, in authored order.
768
+ * @throws Error when a name or a field is unusable.
769
+ */
770
+ function resolveSystemOneProfiles(authored) {
771
+ if (authored === undefined)
772
+ return {};
773
+ if (authored === null || typeof authored !== 'object' || Array.isArray(authored)) {
774
+ throw new Error('systemOne.profiles must be a dictionary of profile name → connection settings');
775
+ }
776
+ const profiles = {};
777
+ const seen = new Map();
778
+ for (const [rawName, entry] of Object.entries(authored)) {
779
+ const name = optionalText(rawName);
780
+ if (name === undefined)
781
+ throw new Error('systemOne.profiles keys must be non-empty profile names');
782
+ if (name.includes('.')) {
783
+ throw new Error(`systemOne.profiles name must not contain "." (got "${name}"): it is the settings path separator`);
784
+ }
785
+ const folded = name.toLowerCase();
786
+ const clash = seen.get(folded);
787
+ if (clash !== undefined) {
788
+ throw new Error(`systemOne.profiles has two names differing only in case ("${clash}" and "${name}")`);
789
+ }
790
+ seen.set(folded, name);
791
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
792
+ throw new Error(`systemOne.profiles["${name}"] must be an object of connection settings`);
793
+ }
794
+ const profileBackend = optionalText(entry.backend);
795
+ if (profileBackend !== undefined && !['auto', 'mock', 'jev', 'vllm'].includes(profileBackend)) {
796
+ throw new Error(`systemOne.profiles["${name}"].backend must be one of auto, mock, jev, vllm (got "${profileBackend}")`);
797
+ }
798
+ const timeoutMs = entry.timeoutMs;
799
+ // The one place a timeout is validated: every profile goes through here, so
800
+ // the active profile is covered without a second check of its own.
801
+ if (timeoutMs !== undefined && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) {
802
+ throw new Error(`systemOne.profiles["${name}"].timeoutMs must be a positive integer (got "${String(timeoutMs)}")`);
803
+ }
804
+ const baseUrl = optionalText(entry.baseUrl);
805
+ const { modelIds, selectedModel } = resolveProfileModels(name, entry);
806
+ const apiKey = optionalText(entry.apiKey);
807
+ const apiKeyEnv = optionalText(entry.apiKeyEnv);
808
+ profiles[name] = {
809
+ ...(baseUrl === undefined ? {} : { baseUrl }),
810
+ ...(modelIds.length === 0 ? {} : { modelIds }),
811
+ ...(selectedModel === undefined ? {} : { selectedModel }),
812
+ ...(apiKey === undefined ? {} : { apiKey }),
813
+ ...(apiKeyEnv === undefined ? {} : { apiKeyEnv }),
814
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
815
+ ...(profileBackend === undefined ? {} : { backend: profileBackend })
816
+ };
817
+ }
818
+ return profiles;
819
+ }
820
+ /**
821
+ * The environment variables the key chain falls back to, in order.
822
+ *
823
+ * This list is the *whole* fallback, exported so callers that want to name the
824
+ * candidates (the panel's "nothing configured" copy) read it from here instead of
825
+ * restating it. Changing the order here changes it for the backend, the panel,
826
+ * and the connection probe at once — which is the point.
827
+ */
828
+ export const API_KEY_ENV_FALLBACKS = ['SYSTEM_ONE_API_KEY', 'JEV_API_KEY', 'VLLM_API_KEY', 'OPENAI_API_KEY'];
829
+ /**
830
+ * Resolve the API key for a connection, and say where it came from.
831
+ *
832
+ * This is the **single source of truth** for the key chain. The backend
833
+ * constructors, the panel's readiness projection, and the `/systemone/test`
834
+ * probe all call it, so the panel can never again report a different reality
835
+ * from the one the runtime acts on.
836
+ *
837
+ * The chain, in order:
838
+ *
839
+ * 1. **`config.apiKey`** — a literal key from the settings document, where it is
840
+ * a declared `role('secret')` slot. It outranks every variable and makes
841
+ * `apiKeyEnv` irrelevant: a deployment that stores the secret outright has no
842
+ * use for a variable *name*.
843
+ * 2. **`config.apiKeyEnv`** — the variable the connection *names*. **Naming
844
+ * locks**: this is the only variable consulted, and if it is empty the result
845
+ * is {@link ApiKeyNotFound} — never a fallback to step 3. The settings
846
+ * document carries only the name, so a panel write cannot leak the value.
847
+ * 3. **{@link API_KEY_ENV_FALLBACKS}** — only when step 2 named nothing:
848
+ * `SYSTEM_ONE_API_KEY`, `JEV_API_KEY`, `VLLM_API_KEY`, `OPENAI_API_KEY`,
849
+ * first non-empty wins.
850
+ *
851
+ * Step 2 no longer falls through to step 3 (g-059). The earlier choice — "naming
852
+ * a variable is not a request to lock onto it" — was reversed by the owner: a
853
+ * deployment that names `SYSTEM_ONE_API_KEY` while only `JEV_API_KEY` is
854
+ * exported must read as *missing*, not silently work from a variable nobody
855
+ * named. Locking is now implied by naming, so an empty value cannot be mistaken
856
+ * for "nobody named anything".
857
+ *
858
+ * An empty string counts as absent at every step, so an exported-but-empty
859
+ * variable is never a credential.
860
+ *
861
+ * A **blank** `apiKeyEnv` (spaces only) is not a naming:
862
+ * {@link resolveSystemOneConfig} trims it away before this function sees it, so
863
+ * a stray space in the name field keeps the historical fallback instead of
864
+ * locking onto a variable whose name is a space.
865
+ *
866
+ * @param config - resolved System One connection settings (a profile's, or the flat block's).
867
+ * @param env - environment to read; defaults to `process.env`.
868
+ * @returns the key and its provenance; the locked-but-empty fact; or `undefined`
869
+ * when nothing was named and nothing was exported.
870
+ */
871
+ export function resolveApiKeyWithSource(config, env = process.env) {
872
+ if (typeof config.apiKey === 'string' && config.apiKey.length > 0)
873
+ return { key: config.apiKey, source: 'profile' };
874
+ if (typeof config.apiKeyEnv === 'string' && config.apiKeyEnv.length > 0) {
875
+ const named = env[config.apiKeyEnv];
876
+ if (typeof named === 'string' && named.length > 0)
877
+ return { key: named, source: 'env', variable: config.apiKeyEnv };
878
+ // Naming locks (g-059): a named-but-empty variable ends the lookup here. It
879
+ // must not reach the fallback loop, or the panel would report a lock the
880
+ // runtime never honoured.
881
+ return { missing: 'named', variable: config.apiKeyEnv };
882
+ }
883
+ for (const variable of API_KEY_ENV_FALLBACKS) {
884
+ const value = env[variable];
885
+ if (typeof value === 'string' && value.length > 0)
886
+ return { key: value, source: 'fallback', variable };
306
887
  }
888
+ return undefined;
889
+ }
890
+ /**
891
+ * The key a resolution carries, or `undefined` for both kinds of absence.
892
+ *
893
+ * The one place the union is flattened: a transport only needs to know *whether*
894
+ * there is a key, never *why* there is none. Panel copy must not use this —
895
+ * telling "named but empty" from "nothing configured" is the point of the union.
896
+ * @param resolution - a {@link resolveApiKeyWithSource} result.
897
+ * @returns the key, when one resolved.
898
+ */
899
+ export function resolvedKeyOf(resolution) {
900
+ return resolution === undefined || !('key' in resolution) ? undefined : resolution.key;
901
+ }
902
+ /**
903
+ * Read the API key a resolved connection block points at.
904
+ *
905
+ * A thin wrapper over {@link resolveApiKeyWithSource}: callers that need only the
906
+ * value use this one, and callers that must report *where* it came from use that
907
+ * one. Deliberately kept as the only spelling of the chain — a second
908
+ * implementation here is exactly the drift (`panel says empty, backend works`)
909
+ * this pair exists to prevent.
910
+ *
911
+ * @param config - resolved System One connection settings.
912
+ * @param env - environment to read; defaults to `process.env`.
913
+ * @returns the key, or `undefined` when no source holds one.
914
+ */
915
+ export function resolveApiKey(config, env = process.env) {
916
+ return resolvedKeyOf(resolveApiKeyWithSource(config, env));
917
+ }
918
+ /**
919
+ * Project one profile's connection facts for the connection test.
920
+ *
921
+ * The probe must send exactly the request the runtime would send, so both read
922
+ * the *same* profile fields: base URL, the **selected** model
923
+ * ({@link modelForProfile}), the key and its variable, the timeout, and the
924
+ * backend. Since g-066 there is nothing to merge — a profile that states no
925
+ * `baseUrl` inherits from **nobody**, and the backend's own environment read is
926
+ * the only thing left below it, exactly as for the runtime.
927
+ *
928
+ * The model is derived rather than read from {@link ConnectionTarget.model}, so a
929
+ * probe can never test a model the runtime does not run: one `selectedModel`
930
+ * outside `modelIds` makes both of them **absent** (and the panel says why,
931
+ * while {@link resolveSystemOneConfig} refuses to connect at all). A profile that
932
+ * lists no model is the one case where the answer is the implementation default
933
+ * — the same {@link plannedModel} the resolved connection uses, so the two can
934
+ * never disagree about which model a connection asks for.
935
+ *
936
+ * `modelUnusable` is the probe's whole answer for a connection whose model
937
+ * cannot be sent: it must not guess one instead.
938
+ *
939
+ * @param flat - the resolved block, supplying the backend fallback only.
940
+ * @param name - profile name (the probe's label).
941
+ * @param profile - the profile to project.
942
+ * @returns the target's connection facts.
943
+ */
944
+ export function connectionTarget(flat, name, profile) {
945
+ const baseUrl = optionalText(profile.baseUrl);
946
+ // The same rule {@link resolveSystemOneConfig} applies (g-067 att-002): one
947
+ // function, so the test button cannot describe a transport the runtime does
948
+ // not run — the divergence that got the first attempt blocked.
949
+ const backend = effectiveImplementation(flat.backend ?? 'auto', profile.backend, profile);
950
+ const modelIds = profile.modelIds ?? [];
951
+ const resolved = plannedModel(modelIds, backend, modelForProfile(profile, modelIds));
952
+ const model = resolved.model === undefined ? undefined : optionalText(resolved.model);
953
+ const apiKeyEnv = optionalText(profile.apiKeyEnv);
954
+ const apiKey = optionalText(profile.apiKey);
955
+ const timeoutMs = profile.timeoutMs;
307
956
  return {
308
- backend: selected,
957
+ name,
958
+ backend,
309
959
  ...(baseUrl === undefined ? {} : { baseUrl }),
310
960
  ...(model === undefined ? {} : { model }),
961
+ ...(resolved.unusable === undefined ? {} : { modelUnusable: true }),
311
962
  ...(apiKeyEnv === undefined ? {} : { apiKeyEnv }),
963
+ ...(apiKey === undefined ? {} : { apiKey }),
312
964
  ...(timeoutMs === undefined ? {} : { timeoutMs })
313
965
  };
314
966
  }
315
967
  /**
316
- * Read the API key a resolved connection block points at.
968
+ * Which backend selector one active connection really runs under (g-067 att-002).
317
969
  *
318
- * The indirection is the point: the settings document carries the variable's
319
- * *name*, so a panel write can never leak the credential into a file the Host
320
- * then renders back to every client.
321
- * @param config - resolved System One connection settings.
322
- * @param env - environment to read; defaults to `process.env`.
323
- * @returns the key, or `undefined` when the variable is unset or empty.
970
+ * One rule, asked by the resolved connection and by {@link connectionTarget}, so
971
+ * the runtime and the connection test cannot disagree about the transport.
972
+ *
973
+ * The long-standing precedence stands: **a row that names an implementation
974
+ * decides for itself**, and an unnamed row follows the top-level selector. What
975
+ * g-067 adds is a single, narrow exception — see {@link isShippedFactoryRow}.
976
+ *
977
+ * @param selected - the top-level selector.
978
+ * @param rowBackend - the profile's own `backend`, when it states one.
979
+ * @param profile - the profile, so the shipped factory row can be recognised.
980
+ * @returns the selector to resolve an implementation from.
324
981
  */
325
- export function resolveApiKey(config, env = process.env) {
326
- if (config.apiKeyEnv === undefined)
327
- return undefined;
328
- const value = env[config.apiKeyEnv];
329
- return typeof value === 'string' && value.length > 0 ? value : undefined;
982
+ function effectiveImplementation(selected, rowBackend, profile) {
983
+ // The shipped factory row binds `jev` so the *environment* cannot redirect it —
984
+ // but that binding must not silently overrule a deployment that stated its own
985
+ // implementation. Two explicit top-level settings therefore still win over the
986
+ // shipped row, and only over it: an authored row keeps the usual precedence.
987
+ //
988
+ // - `mock` answers in-process and opens no socket, so honouring it cannot send
989
+ // the connection's credential anywhere. Without this, `backend: mock` — the
990
+ // setting every fixture in this package runs on — would dial the official
991
+ // gateway with whatever key the chain resolved.
992
+ // - `vllm` asks the runtime to speak the logits protocol; leaving it on the
993
+ // row's bound `jev` would answer in a protocol the deployment did not choose.
994
+ // Its own endpoint is the row's, so nothing is reached that the connection
995
+ // does not name.
996
+ //
997
+ // `jev` needs no exception (it is what the row already binds), and `auto` is
998
+ // precisely the case the binding exists to override.
999
+ if ((selected === 'mock' || selected === 'vllm') && rowBackend === 'jev' && isShippedFactoryRow(profile)) {
1000
+ return selected;
1001
+ }
1002
+ return rowBackend ?? selected;
1003
+ }
1004
+ /**
1005
+ * Whether one profile is the **unedited** shipped factory connection.
1006
+ *
1007
+ * The exception above must not leak to an authored row that merely resembles the
1008
+ * factory one: a user who edited the address, the model or the key variable has
1009
+ * stated their own connection, and the usual precedence must apply to it. Value
1010
+ * equality is the only stable handle — schemastery materializes the default into
1011
+ * a fresh object on every resolution.
1012
+ *
1013
+ * The model is read through {@link modelForProfile}, the rule every consumer of
1014
+ * a profile's model uses, so the schema's legacy `model` beside an empty
1015
+ * `modelIds` is recognised exactly like an explicit one-entry list.
1016
+ *
1017
+ * @param profile - a resolved profile.
1018
+ * @returns true for the shipped factory row, unedited.
1019
+ */
1020
+ function isShippedFactoryRow(profile) {
1021
+ const modelIds = profile.modelIds ?? [];
1022
+ return (profile.baseUrl === FACTORY_SYSTEMONE_PROFILE.baseUrl &&
1023
+ profile.apiKeyEnv === FACTORY_SYSTEMONE_PROFILE.apiKeyEnv &&
1024
+ profile.backend === FACTORY_SYSTEMONE_PROFILE.backend &&
1025
+ modelForProfile(profile, modelIds).model === FACTORY_SYSTEMONE_PROFILE.model);
1026
+ }
1027
+ /**
1028
+ * The implementation a connection's backend selector really builds (g-067 att-002).
1029
+ *
1030
+ * The one place `auto` is turned into a concrete transport, asked by both ends
1031
+ * of the same connection: {@link createBackend} builds from it, and the
1032
+ * connection test probes with it. Any second derivation is a divergence waiting
1033
+ * to happen — and one already happened: the probe hard-coded `auto → jev` while
1034
+ * `auto` in the runtime delegated to the vendored factory, which reads the
1035
+ * environment. Under `SYSTEM_ONE_BACKEND=vllm` the test button probed the
1036
+ * official Jev URL and reported green while the runtime dialled a vLLM endpoint
1037
+ * with the same key.
1038
+ *
1039
+ * `auto` is modelled exactly as far as it is deterministic: the vendored
1040
+ * factory's own precedence, read from the environment —
1041
+ *
1042
+ * 1. an explicit `SYSTEM_ONE_BACKEND` / `REFLEX_BACKEND` selects that provider
1043
+ * (`jev`, or `vllm`/`simple-jev`/`logits` as the logits backend);
1044
+ * 2. with no selector, a Jev credential (`SYSTEM_ONE_API_KEY` / `JEV_API_KEY`)
1045
+ * selects Jev, then a vLLM endpoint selects the logits backend;
1046
+ * 3. anything else is the in-process mock.
1047
+ *
1048
+ * Note what this function does **not** do: it does not make `auto` safe. It
1049
+ * makes the two halves honest about the same answer. A connection that must not
1050
+ * follow the environment pins its own `backend` instead — which is what the
1051
+ * factory row does ({@link FACTORY_SYSTEMONE_PROFILE}).
1052
+ *
1053
+ * The one deviation from the factory is deliberate: with a selector naming a
1054
+ * provider, the factory's "any other name falls through to the mock" is kept,
1055
+ * because that is what the runtime really builds — guessing Jev there would
1056
+ * reintroduce the false green from the other side.
1057
+ *
1058
+ * @param selector - the connection's effective backend selector.
1059
+ * @param env - the environment the `auto` factory would read.
1060
+ * @returns the transport that would be built.
1061
+ */
1062
+ export function connectionImplementation(selector, env = process.env) {
1063
+ if (selector === 'mock')
1064
+ return 'mock';
1065
+ if (selector === 'jev')
1066
+ return 'jev';
1067
+ if (selector === 'vllm')
1068
+ return 'vllm';
1069
+ // `auto` (and anything unexpected reaching here): the factory's own order.
1070
+ const provider = (env.SYSTEM_ONE_BACKEND ?? env.REFLEX_BACKEND ?? '').trim().toLowerCase();
1071
+ if (provider === 'jev')
1072
+ return 'jev';
1073
+ if (provider === 'vllm' || provider === 'simple-jev' || provider === 'logits')
1074
+ return 'vllm';
1075
+ if (provider.length > 0)
1076
+ return 'mock';
1077
+ if (env.SYSTEM_ONE_API_KEY || env.JEV_API_KEY)
1078
+ return 'jev';
1079
+ if (env.VLLM_BASE_URL || env.OPENAI_BASE_URL)
1080
+ return 'vllm';
1081
+ return 'mock';
330
1082
  }
331
1083
  /**
332
1084
  * Normalize one authored pool into detached `{ provider, model, description, tags }` entries,
@@ -478,6 +1230,7 @@ export function resolveConfig(config) {
478
1230
  minConfidence
479
1231
  },
480
1232
  tools: resolveToolsConfig(validated.tools),
1233
+ delegation: resolveDelegationConfig(validated.delegation),
481
1234
  interventions: resolveInterventionsConfig(validated.interventions, validated.pruneThreshold ?? 500)
482
1235
  };
483
1236
  }
@@ -533,6 +1286,34 @@ export function resolveToolsConfig(authored) {
533
1286
  }
534
1287
  return { enabled };
535
1288
  }
1289
+ /**
1290
+ * Validate the delegation block and fill in its default.
1291
+ *
1292
+ * The default is `false` and it is load-bearing: with the switch on, the tool
1293
+ * is offered; with it off, `reflex_delegate` is not registered at all, because a
1294
+ * wrapper whose level cannot be delivered would be a capability that only looks
1295
+ * like one. A non-boolean is refused rather than coerced, for the same reason
1296
+ * every other block refuses one.
1297
+ * @param authored - the authored `delegation` block.
1298
+ * @returns the resolved switch.
1299
+ * @throws Error when the value is present but not a boolean.
1300
+ */
1301
+ export function resolveDelegationConfig(authored) {
1302
+ if (authored !== undefined && (authored === null || typeof authored !== 'object' || Array.isArray(authored))) {
1303
+ throw new Error(`delegation must be an object (got "${String(authored)}")`);
1304
+ }
1305
+ const block = authored ?? {};
1306
+ const extraKeys = Object.keys(block).filter((key) => key !== 'enabled');
1307
+ if (extraKeys.length > 0) {
1308
+ const rendered = extraKeys.map((key) => JSON.stringify(key)).join(', ');
1309
+ throw new Error(`delegation has unknown key${extraKeys.length === 1 ? '' : 's'} ${rendered}; only "enabled" is supported`);
1310
+ }
1311
+ const value = block.enabled;
1312
+ if (value !== undefined && typeof value !== 'boolean') {
1313
+ throw new Error(`delegation.enabled must be a boolean (got "${String(value)}")`);
1314
+ }
1315
+ return { enabled: value ?? false };
1316
+ }
536
1317
  /**
537
1318
  * Validate one authored `reasoningEffort` value.
538
1319
  *