@osovv/vv-opencode 2.3.3 → 2.5.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 (108) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +18 -13
  3. package/dist/cli.js +5 -3
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/doctor.d.ts +4 -0
  6. package/dist/commands/doctor.js +60 -51
  7. package/dist/commands/doctor.js.map +1 -1
  8. package/dist/commands/plugin-toggle.d.ts +0 -16
  9. package/dist/commands/plugin-toggle.js +2 -34
  10. package/dist/commands/plugin-toggle.js.map +1 -1
  11. package/dist/commands/preset.d.ts +0 -8
  12. package/dist/commands/preset.js +3 -24
  13. package/dist/commands/preset.js.map +1 -1
  14. package/dist/commands/role.js +2 -30
  15. package/dist/commands/role.js.map +1 -1
  16. package/dist/commands/session.d.ts +50 -0
  17. package/dist/commands/session.js +354 -0
  18. package/dist/commands/session.js.map +1 -0
  19. package/dist/lib/managed-agents.js +2 -2
  20. package/dist/lib/managed-agents.js.map +1 -1
  21. package/dist/lib/managed-skills.js +3 -3
  22. package/dist/lib/managed-skills.js.map +1 -1
  23. package/dist/lib/opencode/agent-registrations.js +103 -13
  24. package/dist/lib/opencode/agent-registrations.js.map +1 -1
  25. package/dist/lib/opencode/inspection.js +131 -5
  26. package/dist/lib/opencode/inspection.js.map +1 -1
  27. package/dist/plugins/analytics/index.js +8 -19
  28. package/dist/plugins/analytics/index.js.map +1 -1
  29. package/dist/plugins/guardian/index.js +7 -21
  30. package/dist/plugins/guardian/index.js.map +1 -1
  31. package/dist/plugins/hashline-edit/index.js +6 -20
  32. package/dist/plugins/hashline-edit/index.js.map +1 -1
  33. package/dist/plugins/model-roles/index.d.ts +3 -3
  34. package/dist/plugins/model-roles/index.js +8 -8
  35. package/dist/plugins/model-roles/index.js.map +1 -1
  36. package/dist/plugins/peak-hours/index.js +9 -20
  37. package/dist/plugins/peak-hours/index.js.map +1 -1
  38. package/dist/plugins/secrets-redaction/index.js +11 -24
  39. package/dist/plugins/secrets-redaction/index.js.map +1 -1
  40. package/dist/plugins/spec-guard/index.js +10 -22
  41. package/dist/plugins/spec-guard/index.js.map +1 -1
  42. package/dist/plugins/system-context-injection/guidance.d.ts +6 -0
  43. package/dist/plugins/system-context-injection/guidance.js +79 -0
  44. package/dist/plugins/system-context-injection/guidance.js.map +1 -0
  45. package/dist/plugins/system-context-injection/index.js +20 -121
  46. package/dist/plugins/system-context-injection/index.js.map +1 -1
  47. package/dist/plugins/tool-history-compaction/index.js +14 -25
  48. package/dist/plugins/tool-history-compaction/index.js.map +1 -1
  49. package/dist/plugins/web-tools/index.js +14 -25
  50. package/dist/plugins/web-tools/index.js.map +1 -1
  51. package/dist/plugins/workflow/index.d.ts +3 -2
  52. package/dist/plugins/workflow/index.js +6 -22
  53. package/dist/plugins/workflow/index.js.map +1 -1
  54. package/dist/plugins/workflow/input-validation.d.ts +1 -1
  55. package/dist/plugins/workflow/input-validation.js +2 -2
  56. package/dist/plugins/workflow/input-validation.js.map +1 -1
  57. package/dist/plugins/workflow/results.d.ts +40 -40
  58. package/dist/plugins/workflow/system-instruction.md +20 -0
  59. package/dist/runtime/auxiliary.d.ts +11 -6
  60. package/dist/runtime/auxiliary.js +43 -35
  61. package/dist/runtime/auxiliary.js.map +1 -1
  62. package/dist/runtime/context-inspection.d.ts +7 -6
  63. package/dist/runtime/context-inspection.js +37 -43
  64. package/dist/runtime/context-inspection.js.map +1 -1
  65. package/dist/runtime/context.d.ts +22 -45
  66. package/dist/runtime/context.js +348 -634
  67. package/dist/runtime/context.js.map +1 -1
  68. package/dist/runtime/model-registry.d.ts +3 -34
  69. package/dist/runtime/model-registry.js +10 -190
  70. package/dist/runtime/model-registry.js.map +1 -1
  71. package/dist/runtime/session-settings.d.ts +204 -0
  72. package/dist/runtime/session-settings.js +445 -0
  73. package/dist/runtime/session-settings.js.map +1 -0
  74. package/dist/runtime/snapshot-config.d.ts +7 -70
  75. package/dist/runtime/snapshot-config.js +16 -198
  76. package/dist/runtime/snapshot-config.js.map +1 -1
  77. package/dist/runtime/types.d.ts +15 -256
  78. package/dist/runtime/types.js +9 -63
  79. package/dist/runtime/types.js.map +1 -1
  80. package/dist/tui/settings/plugin.d.ts +29 -0
  81. package/dist/tui/settings/plugin.js +134 -0
  82. package/dist/tui/settings/plugin.js.map +1 -0
  83. package/dist/tui.js +12 -12
  84. package/dist/tui.js.map +1 -1
  85. package/package.json +1 -1
  86. package/schemas/vvoc/v3.json +1 -1
  87. package/templates/agents/vv-code-reviewer.md +2 -2
  88. package/templates/agents/vv-controller.md +176 -151
  89. package/templates/agents/vv-implementer.md +2 -2
  90. package/templates/agents/vv-reflector.md +7 -0
  91. package/templates/agents/vv-spec-reviewer.md +2 -2
  92. package/templates/skills/vv-execute/SKILL.md +25 -4
  93. package/templates/skills/vv-execute/references/tool-contracts.md +3 -3
  94. package/templates/skills/vv-reflect/SKILL.md +1 -0
  95. package/templates/skills/vv-reflect/references/session-graph.py +581 -7
  96. package/templates/skills/vv-review/SKILL.md +2 -2
  97. package/dist/lib/rebind-request.d.ts +0 -41
  98. package/dist/lib/rebind-request.js +0 -134
  99. package/dist/lib/rebind-request.js.map +0 -1
  100. package/dist/runtime/snapshot-store.d.ts +0 -63
  101. package/dist/runtime/snapshot-store.js +0 -668
  102. package/dist/runtime/snapshot-store.js.map +0 -1
  103. package/dist/runtime/snapshots.d.ts +0 -36
  104. package/dist/runtime/snapshots.js +0 -508
  105. package/dist/runtime/snapshots.js.map +0 -1
  106. package/dist/tui/rebind/plugin.d.ts +0 -22
  107. package/dist/tui/rebind/plugin.js +0 -101
  108. package/dist/tui/rebind/plugin.js.map +0 -1
@@ -1,9 +1,9 @@
1
1
  // FILE: src/runtime/context.ts
2
- // VERSION: 1.1.0
2
+ // VERSION: 2.0.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Acquire, share by exact plugin-context identity, and release the lifecycle-managed native runtime, family-binding service, and centralized native runtime (client/permissions/bindings/config/model/auxiliary) consumed by every later native plugin.
5
- // SCOPE: Context-identity reference-counted registries, per-acquisition idempotent leases, lazy authenticated-client caching, permission-service exposure, native model/agent overlay capture, default-model transform, config.updated reconfiguration, coherent first-work binding, rehydrated guard/variants, one-shot first-work admission tolerance for a dispatch resolved before the binding switch lands, session-deletion cleanup, cross-context coordination, the read-only context-inspection RPC, and idempotent teardown without stopping the host. No candidate staging, accepted-input publication, service discovery until a client is requested, location-only sharing, global configuration singleton, parallel fake runtime, or V1 compatibility facade.
6
- // DEPENDS: [node:crypto, @opencode/plugin, src/lib/config-layers.ts, src/runtime/client.ts, src/runtime/coordination.ts, src/runtime/context-inspection.ts, src/runtime/model-registry.ts, src/runtime/permissions.ts, src/runtime/snapshot-config.ts, src/runtime/snapshot-store.ts, src/runtime/snapshots.ts, src/runtime/types.ts]
4
+ // PURPOSE: Acquire, share by exact plugin-context identity, and release the lifecycle-managed native runtime and the centralized native runtime (client/permissions/settings/config/model/auxiliary) consumed by every later native plugin, resolving session-owned family settings from the family root's metadata.
5
+ // SCOPE: Context-identity reference-counted registries, per-acquisition idempotent leases, lazy authenticated-client caching, permission-service exposure, native model/agent overlay capture, default-model transform, config.updated reconfiguration, lazy family-settings birth and resolution through host-verified lineage with read-modify-write metadata writes, one-shot creation reconciliation for host-created children, session-deletion cache hygiene, cross-context coordination, the read-only context-inspection RPC, and idempotent teardown without stopping the host. No candidate staging, no dispatch guard, no family snapshot store, no service discovery until a client is requested, no location-only sharing, no global configuration singleton, and no V1 compatibility facade.
6
+ // DEPENDS: [node:crypto, @opencode/plugin, src/lib/config-layers.ts, src/runtime/client.ts, src/runtime/coordination.ts, src/runtime/context-inspection.ts, src/runtime/model-registry.ts, src/runtime/permissions.ts, src/runtime/session-settings.ts, src/runtime/snapshot-config.ts, src/runtime/types.ts]
7
7
  // LINKS: [M-NATIVE-RUNTIME, V-M-NATIVE-RUNTIME]
8
8
  // ROLE: RUNTIME
9
9
  // MAP_MODE: EXPORTS
@@ -11,34 +11,33 @@
11
11
  //
12
12
  // START_MODULE_MAP
13
13
  // acquireRuntime - Return a per-acquisition release lease for the runtime shared by one exact plugin context.
14
- // acquireSnapshotService - Return a per-acquisition release lease for the family-binding service shared by one exact plugin context and dependency instance.
15
14
  // NativeSessionInfoLike - Structural native session info used for lineage and provenance.
16
- // NativeSnapshotHookEvents - Structural native hook event map used by the shared runtime.
17
- // NativeSnapshotContext - Narrow structural native Plugin.Context used to acquire the shared snapshot runtime.
15
+ // NativeHookEvents - Structural native hook event map used by the shared runtime.
16
+ // NativeSnapshotContext - Narrow structural native Plugin.Context used to acquire the shared runtime.
18
17
  // NativeRegistration - Releasable native registration handle.
19
18
  // NativeForkClient - Structural full client for forks and parented imports.
20
- // NativeSnapshotRuntimeOptions - Optional injectable native boundaries for the shared snapshot runtime.
21
- // NativeSnapshotRuntime - Documented shared native runtime: client, permissions, family bindings, effective config, model reload, role override, first-work gateway and refresh.
22
- // acquireNativeSnapshotRuntime - Acquire the shared native snapshot runtime for an actual Plugin.Context.
19
+ // NativeSnapshotRuntimeOptions - Optional injectable native boundaries for the shared runtime.
20
+ // NativeSnapshotRuntime - Documented shared native runtime: client, permissions, family settings, auxiliary work, effective config, role override, refresh.
21
+ // acquireNativeSnapshotRuntime - Acquire the shared native runtime for an actual Plugin.Context.
23
22
  // rebuildAgentBindings - Recompute agent bindings from a freshly read policy without trusting a cached vvoc-applied selection.
24
23
  // END_MODULE_MAP
25
24
  //
26
25
  // START_CHANGE_SUMMARY
27
- // LAST_CHANGE: [Direct fix follow-up - The pump-missed user-choice capture in bindFor now ends the first-work tolerance too, keeping every explicit-choice path symmetric with the event pump so a stale window can never admit a later bare-base dispatch.]
28
- // PREVIOUS: [Direct fix - First-work admission tolerance: the host may resolve a dispatch against the unqualified role base before the prompt hook's binding switch lands, so the guard now accepts that one bare-base resolution for a session this runtime just bound and switched, instead of killing the session's first turn with SnapshotAdmissionError.]
26
+ // LAST_CHANGE: [C-SESSION-OWNED-SETTINGS T-002 - Replaced the family-binding snapshot service and dispatch guard with session-owned settings: lazy root birth, lineage resolution, RMW metadata writes, one-shot creation reconciliation, and the legacy-binding migration.]
27
+ // PREVIOUS: [Direct fix follow-up - The pump-missed user-choice capture in bindFor now ends the first-work tolerance too, keeping every explicit-choice path symmetric with the event pump so a stale window can never admit a later bare-base dispatch.]
29
28
  // END_CHANGE_SUMMARY
30
29
  import { randomBytes } from "node:crypto";
31
30
  import { loadEffectiveVvocConfig, readRawOpenCodeModelIntent } from "../lib/config-layers.js";
32
31
  import { getBuiltInRoleBindings, isRoleReference, parseModelSelectionWithVariant, ROLE_REFERENCE_PREFIX, } from "../lib/model-roles.js";
33
32
  import { acquireNativeClient, nativeRuntimeDeps } from "./client.js";
34
33
  import { coordinateHost } from "./coordination.js";
35
- import { applyAgentPolicies, applyVariantRegistrations, buildVariantRegistrations, mergeModelBodyOverlay, mergeModelHeadersOverlay, primarySelection, qualifySelection, } from "./model-registry.js";
34
+ import { applyAgentPolicies } from "./model-registry.js";
36
35
  import { createPermissionService } from "./permissions.js";
37
- import { canonicalModelVariant, classifyInitialSelection, decodeModelSelectedEvent, decodeSessionCreatedEvent, effectiveRuntimeConfig, isConfigUpdateEvent, normalizeModelSelection, parseRoleSelections, } from "./snapshot-config.js";
36
+ import { canonicalModelVariant, decodeSessionCreatedEvent, effectiveRuntimeConfig, isConfigUpdateEvent, parseRoleSelections, } from "./snapshot-config.js";
38
37
  import { registerContextInspectionRpc } from "./context-inspection.js";
39
- import { FileBindingStore } from "./snapshot-store.js";
40
- import { createSnapshotService } from "./snapshots.js";
41
- import { RuntimeDisposedError, SnapshotAdmissionError, SnapshotUnboundError, decodeAuxiliaryMetadata, decodeImportedSessionID, runtimeIdentity, } from "./types.js";
38
+ import { INTERNAL_PRIMARY_AGENTS, isFamilyRootView, mergeSettingsIntoMetadata, migrateFamilyBindings, fileLegacyBindingsReader, projectFamilyConfig, readSettingsFromMetadata, resolveSessionFamily, settingsFromConfig, settingsId, } from "./session-settings.js";
39
+ import { createAuxiliaryService } from "./auxiliary.js";
40
+ import { RuntimeDisposedError, decodeAuxiliaryMetadata, decodeImportedSessionID, runtimeIdentity, } from "./types.js";
42
41
  // START_BLOCK_RUNTIME_REGISTRY
43
42
  const runtimes = new Map();
44
43
  const contextIds = new WeakMap();
@@ -162,39 +161,6 @@ export function acquireRuntime(context, deps) {
162
161
  };
163
162
  return lease;
164
163
  }
165
- const snapshotServices = new Map();
166
- /**
167
- * Return a per-acquisition release lease for the snapshot service shared by one
168
- * exact plugin context object and dependency instance. Distinct contexts never
169
- * share a service, so per-location policies cannot leak across projects.
170
- */
171
- export function acquireSnapshotService(context, deps) {
172
- const key = `${objectId(contextIds, context)}:${objectId(depsIds, deps)}`;
173
- let entry = snapshotServices.get(key);
174
- if (entry === undefined) {
175
- entry = { service: createSnapshotService(deps), refs: 0, disposed: false };
176
- snapshotServices.set(key, entry);
177
- }
178
- const owned = entry;
179
- owned.refs += 1;
180
- let released = false;
181
- return {
182
- snapshots: owned.service,
183
- release: async () => {
184
- if (released)
185
- return;
186
- released = true;
187
- if (owned.disposed)
188
- return;
189
- owned.refs -= 1;
190
- if (owned.refs <= 0) {
191
- owned.disposed = true;
192
- snapshotServices.delete(key);
193
- owned.service.dispose();
194
- }
195
- },
196
- };
197
- }
198
164
  const pluginContextSeam = true;
199
165
  void pluginContextSeam;
200
166
  const nativeRuntimes = new Map();
@@ -206,11 +172,12 @@ function toSelection(ref) {
206
172
  const record = ref;
207
173
  if (record.id === undefined || record.providerID === undefined)
208
174
  return undefined;
209
- return normalizeModelSelection({
175
+ const variant = record.variant === undefined || record.variant === null ? undefined : String(record.variant);
176
+ return {
210
177
  providerID: String(record.providerID),
211
178
  modelID: String(record.id),
212
- ...(record.variant === undefined ? {} : { variant: String(record.variant) }),
213
- });
179
+ ...(variant === undefined ? {} : { variant: canonicalModelVariant(variant) }),
180
+ };
214
181
  }
215
182
  function sameModelSelection(left, right) {
216
183
  if (left === undefined || right === undefined)
@@ -226,67 +193,83 @@ function toRef(selection) {
226
193
  ...(selection.variant === undefined ? {} : { variant: selection.variant }),
227
194
  };
228
195
  }
229
- function cloneOverlay(value) {
230
- return value === undefined ? undefined : { ...value };
196
+ function readDefaultModel(editor) {
197
+ const ref = editor.default.get();
198
+ return ref === undefined ? undefined : { providerID: ref.providerID, modelID: ref.modelID };
231
199
  }
232
- /** True for a snapshot-qualified variant previously materialized by this runtime. */
233
- function isManagedVariantID(variantID, modelID, ownVariantIds) {
234
- if (ownVariantIds.has(variantID))
235
- return true;
236
- const prefix = variantID.slice(0, 16);
237
- const suffix = variantID.slice(16);
238
- return (/^[0-9a-f]{16}$/.test(prefix) && (suffix === `.${modelID}` || suffix.startsWith(`.${modelID}.`)));
200
+ function toSessionView(info) {
201
+ const model = toSelection(info.model);
202
+ const parentID = info.parentID === undefined ? undefined : String(info.parentID);
203
+ const forkSessionID = info.fork === undefined ? undefined : String(info.fork.sessionID);
204
+ const locationDirectory = info.location === undefined ? undefined : String(info.location.directory);
205
+ const agent = info.agent === undefined ? undefined : String(info.agent);
206
+ const metadata = isRecord(info.metadata) ? info.metadata : undefined;
207
+ const hasActivity = info.time?.idle !== undefined ||
208
+ (info.tokens !== undefined && (info.tokens.input ?? 0) + (info.tokens.output ?? 0) > 0);
209
+ return {
210
+ id: info.id,
211
+ ...(parentID === undefined ? {} : { parentID }),
212
+ ...(forkSessionID === undefined ? {} : { forkSessionID }),
213
+ ...(locationDirectory === undefined ? {} : { locationDirectory }),
214
+ ...(agent === undefined ? {} : { agent }),
215
+ ...(metadata === undefined ? {} : { metadata }),
216
+ ...(model === undefined ? {} : { model }),
217
+ ...(hasActivity ? { hasActivity: true } : {}),
218
+ };
239
219
  }
240
- function wantedModelKeys(config) {
241
- const keys = new Set();
242
- for (const selection of Object.values(parseRoleSelections(config.roles))) {
243
- keys.add(`${selection.providerID}/${selection.modelID}`);
244
- }
245
- if (config.rootDefault !== undefined) {
246
- keys.add(`${config.rootDefault.providerID}/${config.rootDefault.modelID}`);
247
- }
248
- if (config.nativeDefault !== undefined) {
249
- keys.add(`${config.nativeDefault.providerID}/${config.nativeDefault.modelID}`);
250
- }
251
- // Custom/literal agent models outside the role map still need their overlay captured.
252
- for (const binding of config.agentBindings ?? []) {
253
- if (binding.selection !== undefined) {
254
- keys.add(`${binding.selection.providerID}/${binding.selection.modelID}`);
255
- }
220
+ function isRecord(value) {
221
+ return typeof value === "object" && value !== null;
222
+ }
223
+ const PUMP_ERROR_MAX_CHARS = 500;
224
+ const PLACEHOLDER_TOKEN_RE = /__VVOC_SECRET_[A-Z_]+_[0-9a-f]{12}(?:_\d+)?__/g;
225
+ /**
226
+ * Bounded, credential-safe diagnostic for one contained event-pump failure. The
227
+ * raw thrown value is never stored verbatim: placeholder tokens are redacted and
228
+ * the result is capped so an error carrying configuration text cannot leak or
229
+ * grow without bound.
230
+ */
231
+ function describePumpError(error) {
232
+ const raw = error instanceof Error
233
+ ? `${error.name}: ${error.message}`
234
+ : typeof error === "string"
235
+ ? error
236
+ : "unknown error";
237
+ const redacted = raw.replace(PLACEHOLDER_TOKEN_RE, "[redacted]");
238
+ return redacted.length > PUMP_ERROR_MAX_CHARS
239
+ ? `${redacted.slice(0, PUMP_ERROR_MAX_CHARS)}…`
240
+ : redacted;
241
+ }
242
+ function extractTitleMessages(messages) {
243
+ const extracted = [];
244
+ if (!Array.isArray(messages))
245
+ return extracted;
246
+ for (const message of messages) {
247
+ if (!isRecord(message))
248
+ continue;
249
+ const role = typeof message.role === "string" ? message.role : "unknown";
250
+ const text = extractMessageText(message.content);
251
+ if (text.length > 0)
252
+ extracted.push({ role, text });
256
253
  }
257
- return keys;
254
+ return extracted;
258
255
  }
259
- function captureModelSettings(editor, wanted, ownVariantIds) {
260
- const captured = [];
261
- for (const model of editor.list()) {
262
- const providerID = String(model.providerID);
263
- // The wire/route id (`Model.Info.id`) is what sessions and requests reference,
264
- // which differs from the catalog `modelID` for aliased models.
265
- const modelID = String(model.id);
266
- if (wanted.size > 0 && !wanted.has(`${providerID}/${modelID}`))
256
+ function extractMessageText(content) {
257
+ if (typeof content === "string")
258
+ return content;
259
+ if (!Array.isArray(content))
260
+ return "";
261
+ const parts = [];
262
+ for (const part of content) {
263
+ if (typeof part === "string") {
264
+ parts.push(part);
267
265
  continue;
268
- captured.push({
269
- providerID,
270
- modelID,
271
- ...(model.settings === undefined ? {} : { settings: cloneOverlay(model.settings) }),
272
- ...(model.body === undefined ? {} : { body: cloneOverlay(model.body) }),
273
- ...(model.headers === undefined ? {} : { headers: { ...model.headers } }),
274
- });
275
- for (const variant of model.variants) {
276
- // Never re-capture vvoc-generated variants as native overlays (no accumulation).
277
- if (isManagedVariantID(String(variant.id), modelID, ownVariantIds))
278
- continue;
279
- captured.push({
280
- providerID,
281
- modelID,
282
- variant: String(variant.id),
283
- ...(variant.settings === undefined ? {} : { settings: cloneOverlay(variant.settings) }),
284
- ...(variant.body === undefined ? {} : { body: cloneOverlay(variant.body) }),
285
- ...(variant.headers === undefined ? {} : { headers: { ...variant.headers } }),
286
- });
287
266
  }
267
+ if (!isRecord(part))
268
+ continue;
269
+ if (typeof part.text === "string")
270
+ parts.push(part.text);
288
271
  }
289
- return captured;
272
+ return parts.join("\n");
290
273
  }
291
274
  /** Resolve one raw OpenCode model string (role reference or literal) to a selection. */
292
275
  function resolveRawIntent(raw, roleModels) {
@@ -341,8 +324,8 @@ function captureAgentBindings(editor, config) {
341
324
  * selection that vvoc itself may have applied under a previous role set. A
342
325
  * vvoc-role-managed agent's selection is recomputed from the current role model,
343
326
  * raw OpenCode intent still wins, and an agent with no role keeps its genuine
344
- * native literal. This is what makes `vvoc.json` role changes take effect on the
345
- * first unbound workload even when the host emits no `config.updated`.
327
+ * native literal. This is what makes `vvoc.json` role changes take effect for
328
+ * newly created sessions even when the host emits no `config.updated`.
346
329
  */
347
330
  export function rebuildAgentBindings(cached, config) {
348
331
  const roleModels = parseRoleSelections(config.roles);
@@ -380,133 +363,8 @@ export function rebuildAgentBindings(cached, config) {
380
363
  }
381
364
  return [...result.values()];
382
365
  }
383
- function readDefaultModel(editor) {
384
- const ref = editor.default.get();
385
- return ref === undefined ? undefined : { providerID: ref.providerID, modelID: ref.modelID };
386
- }
387
- function toSessionView(info) {
388
- const model = toSelection(info.model);
389
- const parentID = info.parentID === undefined ? undefined : String(info.parentID);
390
- const forkSessionID = info.fork === undefined ? undefined : String(info.fork.sessionID);
391
- const locationDirectory = info.location === undefined ? undefined : String(info.location.directory);
392
- const agent = info.agent === undefined ? undefined : String(info.agent);
393
- const metadata = isRecord(info.metadata) ? info.metadata : undefined;
394
- const hasActivity = info.time?.idle !== undefined ||
395
- (info.tokens !== undefined && (info.tokens.input ?? 0) + (info.tokens.output ?? 0) > 0);
396
- return {
397
- id: info.id,
398
- ...(parentID === undefined ? {} : { parentID }),
399
- ...(forkSessionID === undefined ? {} : { forkSessionID }),
400
- ...(locationDirectory === undefined ? {} : { locationDirectory }),
401
- ...(agent === undefined ? {} : { agent }),
402
- ...(metadata === undefined ? {} : { metadata }),
403
- ...(model === undefined ? {} : { model }),
404
- ...(hasActivity ? { hasActivity: true } : {}),
405
- };
406
- }
407
- function isRecord(value) {
408
- return typeof value === "object" && value !== null;
409
- }
410
- const PUMP_ERROR_MAX_CHARS = 500;
411
- const PLACEHOLDER_TOKEN_RE = /__VVOC_SECRET_[A-Z_]+_[0-9a-f]{12}(?:_\d+)?__/g;
412
- /**
413
- * Bounded, credential-safe diagnostic for one contained event-pump failure. The
414
- * raw thrown value is never stored verbatim: placeholder tokens are redacted and
415
- * the result is capped so an error carrying configuration text cannot leak or
416
- * grow without bound.
417
- */
418
- function describePumpError(error) {
419
- const raw = error instanceof Error
420
- ? `${error.name}: ${error.message}`
421
- : typeof error === "string"
422
- ? error
423
- : "unknown error";
424
- const redacted = raw.replace(PLACEHOLDER_TOKEN_RE, "[redacted]");
425
- return redacted.length > PUMP_ERROR_MAX_CHARS
426
- ? `${redacted.slice(0, PUMP_ERROR_MAX_CHARS)}…`
427
- : redacted;
428
- }
429
- function extractTitleMessages(messages) {
430
- const extracted = [];
431
- if (!Array.isArray(messages))
432
- return extracted;
433
- for (const message of messages) {
434
- if (!isRecord(message))
435
- continue;
436
- const role = typeof message.role === "string" ? message.role : "unknown";
437
- const text = extractMessageText(message.content);
438
- if (text.length > 0)
439
- extracted.push({ role, text });
440
- }
441
- return extracted;
442
- }
443
- function extractMessageText(content) {
444
- if (typeof content === "string")
445
- return content;
446
- if (!Array.isArray(content))
447
- return "";
448
- const parts = [];
449
- for (const part of content) {
450
- if (typeof part === "string") {
451
- parts.push(part);
452
- continue;
453
- }
454
- if (!isRecord(part))
455
- continue;
456
- if (typeof part.text === "string")
457
- parts.push(part.text);
458
- }
459
- return parts.join("\n");
460
- }
461
- /** Selection the family expects for a given request kind and session agent. */
462
- function expectedSelection(capture, agentID) {
463
- // An explicit family choice is the session's model and must not be overridden
464
- // by an agent-role binding.
465
- if (capture.intent.mode === "explicit" && capture.modelOverride !== undefined) {
466
- return qualifySelection(capture, capture.modelOverride);
467
- }
468
- if (agentID !== undefined) {
469
- const binding = capture.agents.find((agent) => agent.agentID === agentID);
470
- if (binding?.selection !== undefined) {
471
- return qualifySelection(capture, binding.selection);
472
- }
473
- }
474
- const base = primarySelection(capture);
475
- return base === undefined ? undefined : qualifySelection(capture, base);
476
- }
477
- function selectionMatches(actual, expected) {
478
- if (expected === undefined)
479
- return true;
480
- if (actual === undefined)
481
- return false;
482
- // Identity plus variant: a resolved request must use the captured variant exactly.
483
- return sameModelSelection(actual, expected);
484
- }
485
- /** Map a family-qualified variant id back to its native source variant. */
486
- function sourceVariantOf(capture, selection) {
487
- if (selection?.variant === undefined)
488
- return undefined;
489
- const known = capture.variants.find((variant) => variant.id === selection.variant);
490
- return known?.sourceVariant ?? selection.variant;
491
- }
492
- /**
493
- * True when two selections denote the same model and the same source variant,
494
- * accepting the native variant id and its family-qualified id as equivalent.
495
- * The host may resolve either form depending on whether the session model was
496
- * rewritten through the family switch, and both denote the same request body.
497
- */
498
- function sameSourceSelection(capture, actual, expected) {
499
- if (actual === undefined || expected === undefined)
500
- return false;
501
- return (actual.providerID === expected.providerID &&
502
- actual.modelID === expected.modelID &&
503
- sourceVariantOf(capture, actual) === sourceVariantOf(capture, expected));
504
- }
505
- /** The model a family expects for host title work: the captured fast/small role. */
506
- function titleExpectedSelection(capture) {
507
- const small = capture.roleModels.fast;
508
- return small === undefined ? undefined : qualifySelection(capture, small);
509
- }
366
+ // END_BLOCK_NATIVE_RUNTIME
367
+ // START_BLOCK_RUNTIME_INITIALIZATION
510
368
  function initializeNativeSnapshotRuntime(ctx, options) {
511
369
  return (async () => {
512
370
  const runtimeLease = options?.runtimeDeps === undefined
@@ -530,94 +388,15 @@ function initializeNativeSnapshotRuntime(ctx, options) {
530
388
  const state = {
531
389
  config: base,
532
390
  agentBindings: [],
533
- modelSettings: [],
534
391
  nativeDefault: undefined,
535
- registrations: [],
536
- // Per-family pending materialization so concurrent families cannot overwrite
537
- // each other's in-flight variant registrations.
538
- pendingRegistrations: new Map(),
539
- materializedVariants: new Set(),
540
- ownVariantIds: new Set(),
541
392
  roleOverride: false,
542
393
  configError: undefined,
543
- creationModels: new Map(),
544
- creationDefaults: new Map(),
545
- explicitSelections: new Map(),
546
- pluginSwitches: new Map(),
547
- suppressedTitles: new Set(),
548
- // Sessions this runtime just bound and switched at first work. The host may
549
- // resolve the dispatch against the pre-binding role base while the hook's
550
- // own switch is still landing, so the guard tolerates exactly that one
551
- // bare-base resolution instead of failing the session's first turn.
552
- firstWorkPending: new Set(),
553
394
  };
554
- const store = options?.store ?? new FileBindingStore({ scopeKey: ctx.location.project.id });
555
395
  /**
556
- * Read the host's final native model collection. A model transform registered
557
- * by this plugin may run before later config transforms, so a transform-local
558
- * editor is neither the capture source nor proof a variant survived; the
559
- * host's final list is. Returns undefined when the host exposes no list call.
396
+ * Structural host session read used by lineage resolution, birth, and
397
+ * migration. Returns the checked session view shape.
560
398
  */
561
- async function readFinalModelEntries() {
562
- const list = ctx.model.list;
563
- if (typeof list !== "function")
564
- return undefined;
565
- let raw;
566
- try {
567
- raw = await list.call(ctx.model);
568
- }
569
- catch {
570
- return undefined;
571
- }
572
- const data = isRecord(raw) && Array.isArray(raw.data)
573
- ? raw.data
574
- : Array.isArray(raw)
575
- ? raw
576
- : [];
577
- return data.filter(isRecord);
578
- }
579
- const readFinalOverlays = async (config) => {
580
- const entries = await readFinalModelEntries();
581
- if (entries === undefined)
582
- return undefined;
583
- const wanted = wantedModelKeys(config);
584
- const captured = [];
585
- const overlay = (providerID, modelID, variant, base, source) => {
586
- const settings = mergeModelBodyOverlay(isRecord(base.settings) ? base.settings : undefined, isRecord(source.settings) ? source.settings : undefined);
587
- const body = mergeModelBodyOverlay(isRecord(base.body) ? base.body : undefined, isRecord(source.body) ? source.body : undefined);
588
- const headers = mergeModelHeadersOverlay(isRecord(base.headers) ? base.headers : undefined, isRecord(source.headers) ? source.headers : undefined);
589
- return {
590
- providerID,
591
- modelID,
592
- ...(variant === undefined ? {} : { variant }),
593
- ...(settings === undefined ? {} : { settings }),
594
- ...(body === undefined ? {} : { body }),
595
- ...(headers === undefined ? {} : { headers }),
596
- };
597
- };
598
- for (const entry of entries) {
599
- const providerID = entry.providerID;
600
- const modelID = entry.id;
601
- if (typeof providerID !== "string" || typeof modelID !== "string")
602
- continue;
603
- if (wanted.size > 0 && !wanted.has(`${providerID}/${modelID}`))
604
- continue;
605
- captured.push(overlay(providerID, modelID, undefined, entry, entry));
606
- if (Array.isArray(entry.variants)) {
607
- for (const variant of entry.variants) {
608
- if (!isRecord(variant) || typeof variant.id !== "string")
609
- continue;
610
- // Never re-capture our own generated variants (no accumulation).
611
- if (isManagedVariantID(variant.id, modelID, state.ownVariantIds))
612
- continue;
613
- // Each source variant gets the base merged with THAT variant's own
614
- // native overlay, so two source variants of one model stay distinct.
615
- captured.push(overlay(providerID, modelID, variant.id, entry, variant));
616
- }
617
- }
618
- }
619
- return captured;
620
- };
399
+ const readSession = async (sessionID) => toSessionView(await ctx.session.get({ sessionID }));
621
400
  const readConfig = async (directory) => {
622
401
  const vvoc = effectiveRuntimeConfig(await loadEffectiveVvocConfig({ cwd: directory }));
623
402
  const rawIntent = await readRawOpenCodeModelIntent(directory);
@@ -631,20 +410,12 @@ function initializeNativeSnapshotRuntime(ctx, options) {
631
410
  ...vvoc,
632
411
  ...(rawIntent === undefined ? {} : { rawIntent }),
633
412
  });
634
- const baseConfig = {
413
+ return {
635
414
  ...vvoc,
636
415
  ...(rawIntent === undefined ? {} : { rawIntent }),
637
416
  ...(rootResolved === undefined ? {} : { rootDefault: rootResolved }),
638
417
  agentBindings,
639
- modelSettings: state.modelSettings,
640
- ...(state.nativeDefault === undefined ? {} : { nativeDefault: state.nativeDefault }),
641
418
  };
642
- // Capture the final native model overlay (post config-transform) when the
643
- // host exposes it, so a snapshot variant reflects the real request payload.
644
- const overlays = await readFinalOverlays(baseConfig);
645
- if (overlays !== undefined)
646
- state.modelSettings = overlays;
647
- return { ...baseConfig, modelSettings: state.modelSettings };
648
419
  };
649
420
  // Initialize the live config with raw OpenCode intent before any transform runs.
650
421
  state.config = await readConfig(ctx.location.directory);
@@ -659,7 +430,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
659
430
  const parent = await ctx.session.get({ sessionID: input.parentID });
660
431
  const projectID = parent.projectID === undefined ? "" : String(parent.projectID);
661
432
  if (projectID.length === 0) {
662
- throw new SnapshotAdmissionError("Auxiliary child import requires the parent session project id.");
433
+ throw new Error("Auxiliary child import requires the parent session project id.");
663
434
  }
664
435
  const sessionID = `ses_${randomBytes(16).toString("hex")}`;
665
436
  const now = Date.now();
@@ -694,7 +465,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
694
465
  const imported = await client.session.import(payload);
695
466
  const importedID = decodeImportedSessionID(imported);
696
467
  if (importedID === undefined || importedID !== sessionID) {
697
- throw new SnapshotAdmissionError("Native session import did not return the expected auxiliary child id.");
468
+ throw new Error("Native session import did not return the expected auxiliary child id.");
698
469
  }
699
470
  // The parent binding must be durable before the child is used.
700
471
  for (let attempt = 0; attempt < 20; attempt += 1) {
@@ -703,258 +474,206 @@ function initializeNativeSnapshotRuntime(ctx, options) {
703
474
  return { sessionID };
704
475
  await new Promise((resolve) => setTimeout(resolve, 100));
705
476
  }
706
- throw new SnapshotAdmissionError("Imported auxiliary child did not persist its parent lineage.");
707
- };
708
- const deps = {
709
- store,
710
- location: runtimeIdentity(ctx.location),
711
- ...(options?.now === undefined ? {} : { now: options.now }),
712
- // Distinct plugin contexts copied from one host share the native app/location
713
- // object identity, so their snapshot services share one per-family
714
- // publication lock without sharing any client, registration or disposal.
715
- coordination: coordinateHost({ app: ctx.app, location: ctx.location }),
716
- loadConfig: async (directory) => {
717
- const fresh = await readConfig(directory);
718
- state.config = fresh;
719
- return fresh;
720
- },
721
- readSession: async (sessionID) => toSessionView(await ctx.session.get({ sessionID })),
722
- readSessionModel: async (sessionID) => toSelection((await ctx.session.get({ sessionID })).model),
723
- switchModel: ({ sessionID, model }) => ctx.session.switchModel({ sessionID, model: toRef(model) }),
724
- auxiliarySession: {
725
- create: importAuxiliaryChild,
726
- switchModel: async ({ sessionID, model }) => {
727
- await ctx.session.switchModel({ sessionID, model: toRef(model) });
728
- },
729
- generate: (input) => ctx.session.generate(input),
730
- },
731
- };
732
- const snapshots = createSnapshotService(deps);
733
- const allPending = () => [...state.pendingRegistrations.values()].flat();
734
- const applyVariants = (editor) => applyVariantRegistrations(editor, [...state.registrations, ...allPending()]);
735
- const refresh = async () => {
736
- state.registrations = buildVariantRegistrations(await snapshots.captures());
737
- await ctx.model.reload();
738
- await ctx.agent.reload();
477
+ throw new Error("Imported auxiliary child did not persist its parent lineage.");
739
478
  };
479
+ // START_BLOCK_SETTINGS_SERVICE
740
480
  /**
741
- * Read the final native model collection after a reload. A model transform
742
- * registered by this plugin may run before later config transforms, so a
743
- * transform-local editor is not proof the variant survived; the host's final
744
- * model list is. Returns undefined when the host exposes no list call (tests).
481
+ * Per-family RMW serialization. Distinct plugin contexts copied from one
482
+ * host share the native app/location object identity, so their settings
483
+ * services share one per-family lock without sharing any client,
484
+ * registration, or disposal.
745
485
  */
746
- const materializeBinding = async (capture, selection) => {
747
- if (selection.variant === undefined)
748
- return;
749
- // Materialize this family's qualified live variant before its first switch.
750
- state.pendingRegistrations.set(capture.snapshotId, buildVariantRegistrations([capture]));
751
- await ctx.model.reload();
752
- const finalEntries = await readFinalModelEntries();
753
- const exists = finalEntries === undefined
754
- ? state.materializedVariants.has(selection.variant)
755
- : finalEntries.some((entry) => {
756
- if (entry.providerID !== selection.providerID || entry.id !== selection.modelID) {
757
- return false;
758
- }
759
- return (Array.isArray(entry.variants) &&
760
- entry.variants.some((variant) => isRecord(variant) && String(variant.id) === selection.variant));
761
- });
762
- if (!exists) {
763
- state.pendingRegistrations.delete(capture.snapshotId);
764
- await ctx.model.reload();
765
- throw new SnapshotAdmissionError(`Captured variant ${selection.variant} is not materializable on ${selection.providerID}/${selection.modelID}.`);
766
- }
486
+ const coordination = coordinateHost({
487
+ app: ctx.app,
488
+ location: ctx.location,
489
+ });
490
+ const familyLocks = new Map();
491
+ const withFamilyLock = (familyId, run) => {
492
+ if (coordination !== undefined)
493
+ return coordination.withFamilyLock(familyId, run);
494
+ const previous = familyLocks.get(familyId) ?? Promise.resolve();
495
+ const next = previous.then(run, run);
496
+ familyLocks.set(familyId, next.then(() => undefined, () => undefined));
497
+ return next;
498
+ };
499
+ // Lineage and birth caches: lineage is stable for a session's lifetime,
500
+ // and the born fact is cached per process so the birth check stays one
501
+ // read per session ever.
502
+ const familyRoots = new Map();
503
+ const bornRoots = new Set();
504
+ const birthInFlight = new Map();
505
+ const reconciledChildren = new Set();
506
+ const diagnostic = (message) => {
507
+ // Messages are static and bounded: never include paths, parsed state, or credentials.
508
+ state.configError = message.slice(0, 240);
767
509
  };
768
- const switchSession = async (sessionID, selection) => {
769
- state.pluginSwitches.set(sessionID, selection);
770
- await ctx.session.switchModel({ sessionID, model: toRef(selection) });
510
+ const familyOf = async (sessionID) => {
511
+ const cached = familyRoots.get(sessionID);
512
+ if (cached !== undefined)
513
+ return cached;
514
+ const root = await resolveSessionFamily({ sessionID, readSession });
515
+ familyRoots.set(sessionID, root);
516
+ return root;
771
517
  };
772
- /** First-work selection for a session's agent from the live policy. */
773
- const bindingTarget = (agentID) => {
774
- const bindings = state.config.agentBindings ?? [];
775
- if (agentID !== undefined) {
776
- const binding = bindings.find((agent) => agent.agentID === agentID);
777
- if (binding?.selection !== undefined)
778
- return binding.selection;
518
+ const buildView = (familyId, settings, source, root) => {
519
+ let roleModels;
520
+ try {
521
+ roleModels = parseRoleSelections(settings.roles);
779
522
  }
780
- const roleModels = parseRoleSelections(state.config.roles);
781
- if (roleModels.default !== undefined)
782
- return roleModels.default;
783
- if (state.config.rootDefault !== undefined)
784
- return state.config.rootDefault;
785
- for (const selection of Object.values(roleModels))
786
- return selection;
787
- for (const binding of bindings) {
788
- if (binding.selection !== undefined)
789
- return binding.selection;
523
+ catch {
524
+ // A corrupt role binding must not fail the request path; the live
525
+ // configuration resolves instead, with a bounded diagnostic.
526
+ diagnostic("Family settings roles are invalid; resolving the live configuration.");
527
+ return undefined;
790
528
  }
791
- return state.config.nativeDefault;
529
+ return {
530
+ familyId,
531
+ locationDirectory: root.locationDirectory,
532
+ ...(root.model === undefined ? {} : { rootModel: root.model }),
533
+ settings,
534
+ vvoc: projectFamilyConfig(settings, state.config.vvoc),
535
+ roleModels,
536
+ source,
537
+ settingsId: settingsId(settings),
538
+ };
792
539
  };
540
+ const fallbackView = (familyId) => buildView(familyId, settingsFromConfig(state.config.vvoc), "config", { id: familyId });
793
541
  /**
794
- * One coherent workload selection for a bound family. An explicit post-bind
795
- * user choice always wins; role overriding disabled means the host's current
796
- * model is already the policy. Otherwise the agent's captured binding, then
797
- * the family primary, with the family's captured variant qualified.
542
+ * Birth a root family record under the per-family lock: re-read the
543
+ * fresh metadata, skip when another writer won the race, otherwise
544
+ * resolve the current effective configuration and read-modify-write only
545
+ * the settings key. The current request keeps using the in-memory value.
798
546
  */
799
- const expectedForSession = (capture, agentID, sessionID, metadata) => {
800
- // A real parented auxiliary child recovers its intended role from
801
- // host-owned metadata, not an in-process exemption.
802
- const auxiliary = decodeAuxiliaryMetadata(metadata);
803
- if (auxiliary !== undefined) {
804
- const base = auxiliary.role === undefined
805
- ? primarySelection(capture)
806
- : capture.roleModels[auxiliary.role];
807
- return base === undefined ? undefined : qualifySelection(capture, base);
808
- }
809
- if (!state.roleOverride)
810
- return capture.modelOverride ?? capture.rootSelection;
811
- const explicit = state.explicitSelections.get(sessionID);
812
- // An explicit user choice wins, but the host resolves the request against the
813
- // family-qualified variant id after the first-work switch, so the expectation
814
- // must use the same qualification or the guard rejects the resolved request.
815
- if (explicit !== undefined)
816
- return qualifySelection(capture, explicit);
817
- return expectedSelection(capture, agentID);
818
- };
819
- const bindFor = async (sessionID) => {
820
- await ensureTransforms();
821
- const view = toSessionView(await ctx.session.get({ sessionID }));
822
- const sessionModel = view.model;
823
- const pluginSwitch = state.pluginSwitches.get(sessionID);
824
- const ownSwitch = pluginSwitch !== undefined && sameModelSelection(sessionModel, pluginSwitch);
825
- // The default captured at creation, never the possibly-changed current default.
826
- const creationDefault = state.creationDefaults.get(sessionID) ?? state.nativeDefault;
827
- const intent = ownSwitch
828
- ? { mode: "implicit", source: "switch" }
829
- : classifyInitialSelection({ sessionModel, creationDefault });
830
- if (intent.mode === "explicit" && intent.literal !== undefined) {
831
- // Creation provenance is an explicit host selection just like a later
832
- // model-selected event, so preserve it through the model guard.
833
- state.explicitSelections.set(sessionID, intent.literal);
834
- }
835
- const existing = await snapshots.policy(sessionID);
836
- if (existing !== undefined) {
837
- // A bound family owns an immutable capture, so its policy/model handling
838
- // never consults the mutable current config. Resolve it before any fresh
839
- // read: an invalid on-disk vvoc must not fail an already-bound family.
840
- // A session model that changed outside our own switch is a user choice and
841
- // must survive, even if the event pump has not recorded it yet.
842
- const baseExpected = expectedSelection(existing, view.agent);
843
- if (!ownSwitch &&
844
- baseExpected !== undefined &&
845
- sessionModel !== undefined &&
846
- !sameModelSelection(sessionModel, baseExpected) &&
847
- !sameModelSelection(sessionModel, pluginSwitch)) {
848
- state.explicitSelections.set(sessionID, normalizeModelSelection(sessionModel));
849
- // Every recorded user choice ends the first-work tolerance, exactly
850
- // like the event-pump path: a later bare-base dispatch is genuine
851
- // drift again, never silently admitted through a stale window.
852
- state.firstWorkPending.delete(sessionID);
547
+ const birthRoot = async (familyId) => {
548
+ const pending = birthInFlight.get(familyId);
549
+ if (pending !== undefined)
550
+ return pending;
551
+ const run = withFamilyLock(familyId, async () => {
552
+ const fresh = await readSession(familyId);
553
+ const existing = readSettingsFromMetadata(fresh.metadata);
554
+ if (existing !== undefined && "settings" in existing) {
555
+ bornRoots.add(familyId);
556
+ return existing.settings;
853
557
  }
854
- if (!state.roleOverride || state.explicitSelections.has(sessionID))
855
- return;
856
- const target = expectedForSession(existing, view.agent, sessionID);
857
- if (target !== undefined && !sameModelSelection(sessionModel, target)) {
858
- state.firstWorkPending.add(sessionID);
859
- await switchSession(sessionID, target);
558
+ if (existing !== undefined && "error" in existing) {
559
+ diagnostic("Existing family settings are invalid; rebirthing from the live config.");
560
+ }
561
+ // The birth record must reflect the CURRENT effective configuration:
562
+ // vvoc.json edits emit no host config.updated event, so the cached
563
+ // config can be stale exactly when a family is born right after a
564
+ // config change. The read is once per family and under the family
565
+ // lock; a failed fresh read falls back to the last fully read config.
566
+ let effective = state.config;
567
+ try {
568
+ effective = await readConfig(ctx.location.directory);
569
+ }
570
+ catch {
571
+ diagnostic("Fresh config read failed at birth; using the cached effective config.");
572
+ }
573
+ const settings = settingsFromConfig(effective.vvoc);
574
+ const merged = mergeSettingsIntoMetadata(fresh.metadata, settings);
575
+ try {
576
+ await ctx.session.update({ sessionID: familyId, metadata: merged });
577
+ bornRoots.add(familyId);
578
+ return settings;
579
+ }
580
+ catch (error) {
581
+ // Fail soft: the family keeps resolving the live configuration and
582
+ // the next request retries the birth.
583
+ diagnostic(`Family settings birth failed: ${describePumpError(error).slice(0, 160)}`);
584
+ return undefined;
860
585
  }
861
- return;
862
- }
863
- // Only a truly unbound family needs the freshest current config:
864
- // vvoc.json changes do not emit a host `config.updated`, and a stale
865
- // family target would otherwise bind the previous role selection. The
866
- // SAME immutable value is passed into the service so its projection cannot
867
- // re-read a different vvoc snapshot than the target was derived from.
868
- const admissionConfig = await readConfig(ctx.location.directory);
869
- state.config = admissionConfig;
870
- const explicitSelection = intent.mode === "explicit" ? intent.literal : undefined;
871
- const target = explicitSelection ?? bindingTarget(view.agent);
872
- const base = state.roleOverride ? target : (sessionModel ?? target);
873
- // The agent-aware resolved target drives binding, not the capture's default
874
- // role; when role overriding is off the session's current model is bound.
875
- const selectionOverride = explicitSelection === undefined && base !== undefined ? base : undefined;
876
- // The admission below switches this session onto the family selection; a
877
- // dispatch the host resolved before that switch lands carries the bare
878
- // role base, so the guard gets a one-shot tolerance for this session.
879
- state.firstWorkPending.add(sessionID);
880
- const outcome = await snapshots.admitOwned({
881
- sessionID,
882
- directory: ctx.location.directory,
883
- location: runtimeIdentity(ctx.location),
884
- admissionConfig,
885
- ...(explicitSelection === undefined ? {} : { explicit: explicitSelection }),
886
- ...(selectionOverride === undefined ? {} : { selectionOverride }),
887
- force: state.roleOverride,
888
- }, async (capture, selection) => {
889
- await materializeBinding(capture, selection);
890
- state.pluginSwitches.set(sessionID, selection);
891
586
  });
892
- if (outcome.status === "rejected") {
893
- throw new SnapshotAdmissionError(outcome.error ?? `Binding for ${sessionID} did not produce a persisted policy.`);
587
+ birthInFlight.set(familyId, run);
588
+ try {
589
+ return await run;
894
590
  }
895
- if (outcome.status === "bound") {
896
- await refresh();
897
- state.pendingRegistrations.clear();
591
+ finally {
592
+ birthInFlight.delete(familyId);
898
593
  }
899
594
  };
900
- const guardResolvedModel = async (sessionID, agentID, actual, kind) => {
901
- await ensureTransforms();
902
- if (kind === "title" && state.suppressedTitles.has(sessionID)) {
903
- // The title hook already supplied the result; the host still runs this
904
- // hook before it checks `result`, so a refused dispatch here would fail
905
- // a title that never reaches the provider.
906
- state.suppressedTitles.delete(sessionID);
907
- return;
595
+ const resolveSettings = async (sessionID) => {
596
+ let familyId;
597
+ try {
598
+ familyId = await familyOf(sessionID);
908
599
  }
909
- const view = toSessionView(await ctx.session.get({ sessionID }));
910
- const effectiveAgent = agentID ?? view.agent;
911
- const familyId = await snapshots.familyOf(sessionID);
912
- const capture = await snapshots.policy(sessionID);
913
- if (capture !== undefined) {
914
- const expected = kind === "title"
915
- ? titleExpectedSelection(capture)
916
- : expectedForSession(capture, effectiveAgent, sessionID, view.metadata);
917
- // The first post-binding dispatch ends the first-work window whether
918
- // it resolves clean or not: after it, sessions resolve their switched
919
- // family model, so any bare-base dispatch is genuine drift again.
920
- const firstWork = state.firstWorkPending.delete(sessionID);
921
- if (!selectionMatches(actual, expected) &&
922
- !sameSourceSelection(capture, actual, expected)) {
923
- // A dispatch resolved before this runtime's own first-work switch
924
- // carries the bare role base of the very selection the switch just
925
- // materialized. Accept that one pre-binding resolution; every later
926
- // bare-base dispatch still rejects as drift.
927
- if (firstWork &&
928
- actual !== undefined &&
929
- expected !== undefined &&
930
- actual.providerID === expected.providerID &&
931
- actual.modelID === expected.modelID &&
932
- actual.variant === undefined) {
933
- return;
934
- }
935
- const describeSelection = (selection) => selection === undefined
936
- ? "unresolved"
937
- : `${selection.providerID}/${selection.modelID}${selection.variant === undefined ? "" : `#${selection.variant}`}`;
938
- throw new SnapshotAdmissionError(`Resolved ${kind} model ${describeSelection(actual)} does not match the captured family selection ${describeSelection(expected)} for ${familyId}.`);
600
+ catch (error) {
601
+ diagnostic(`Family resolution failed: ${describePumpError(error).slice(0, 160)}`);
602
+ return undefined;
603
+ }
604
+ let root;
605
+ try {
606
+ root = await readSession(familyId);
607
+ }
608
+ catch {
609
+ return fallbackView(familyId);
610
+ }
611
+ const read = readSettingsFromMetadata(root.metadata);
612
+ if (read !== undefined && "settings" in read) {
613
+ bornRoots.add(familyId);
614
+ const view = buildView(familyId, read.settings, "metadata", root);
615
+ return view ?? fallbackView(familyId);
616
+ }
617
+ if (read !== undefined && "error" in read) {
618
+ diagnostic("Family settings are invalid; resolving the live configuration.");
619
+ }
620
+ if (!bornRoots.has(familyId) && isFamilyRootView(root)) {
621
+ const born = await birthRoot(familyId);
622
+ if (born !== undefined) {
623
+ const view = buildView(familyId, born, "metadata", root);
624
+ return view ?? fallbackView(familyId);
939
625
  }
940
- return;
941
626
  }
942
- throw new SnapshotUnboundError(`Refusing unbound ${kind} dispatch for session ${sessionID} before first-work family binding.`);
627
+ return fallbackView(familyId);
943
628
  };
629
+ const settingsService = {
630
+ familyOf,
631
+ resolve: resolveSettings,
632
+ configFor: resolveSettings,
633
+ dispose() {
634
+ familyRoots.clear();
635
+ bornRoots.clear();
636
+ birthInFlight.clear();
637
+ reconciledChildren.clear();
638
+ familyLocks.clear();
639
+ },
640
+ };
641
+ /**
642
+ * One-shot creation reconciliation: a host-created child of a role-managed
643
+ * family adopts the family's role model exactly once at creation. There is
644
+ * no later validation; an explicit model choice after creation is never
645
+ * touched.
646
+ */
647
+ const reconcileCreatedChild = async (created) => {
648
+ if (!state.roleOverride)
649
+ return;
650
+ if (reconciledChildren.has(created.sessionID))
651
+ return;
652
+ reconciledChildren.add(created.sessionID);
653
+ const view = await readSession(created.sessionID).catch(() => undefined);
654
+ if (view === undefined)
655
+ return;
656
+ const auxiliary = decodeAuxiliaryMetadata(view.metadata);
657
+ if (auxiliary !== undefined)
658
+ return;
659
+ if (view.agent !== undefined && INTERNAL_PRIMARY_AGENTS.has(view.agent))
660
+ return;
661
+ const role = view.agent === undefined ? undefined : state.config.agentRoles[view.agent];
662
+ if (role === undefined)
663
+ return;
664
+ const settings = await resolveSettings(created.sessionID);
665
+ if (settings === undefined)
666
+ return;
667
+ const expected = settings.roleModels[role];
668
+ if (expected === undefined)
669
+ return;
670
+ if (sameModelSelection(created.model ?? view.model, expected))
671
+ return;
672
+ await ctx.session.switchModel({ sessionID: created.sessionID, model: toRef(expected) });
673
+ };
674
+ // END_BLOCK_SETTINGS_SERVICE
944
675
  const modelTransform = (editor) => {
945
- const own = new Set([...state.registrations, ...allPending()].map((registration) => registration.variant.id));
946
- state.ownVariantIds = own;
947
- state.modelSettings = captureModelSettings(editor, wantedModelKeys(state.config), own);
948
676
  state.nativeDefault = readDefaultModel(editor) ?? state.nativeDefault;
949
- applyVariants(editor);
950
- // Cheap transform-local readback; the final-list readback happens before switch.
951
- state.materializedVariants = new Set([...state.registrations, ...allPending()].flatMap((registration) => {
952
- const model = editor.get(registration.providerID, registration.modelID);
953
- return model !== undefined &&
954
- model.variants.some((variant) => String(variant.id) === registration.variant.id)
955
- ? [registration.variant.id]
956
- : [];
957
- }));
958
677
  if (!state.roleOverride)
959
678
  return;
960
679
  const defaultRole = parseRoleSelections(state.config.roles).default;
@@ -962,12 +681,12 @@ function initializeNativeSnapshotRuntime(ctx, options) {
962
681
  editor.default.set(defaultRole.providerID, defaultRole.modelID);
963
682
  }
964
683
  };
965
- // Global agent transform represents current unbound candidates only; family
966
- // variants are applied per-session at switch time, never from another family.
684
+ // The agent transform applies role policies to agent definitions, so
685
+ // newly created sessions resolve their role model natively at creation.
967
686
  const agentTransform = (editor) => {
968
687
  state.agentBindings = captureAgentBindings(editor, state.config);
969
688
  if (state.roleOverride) {
970
- applyAgentPolicies(editor, state.agentBindings, []);
689
+ applyAgentPolicies(editor, state.agentBindings);
971
690
  }
972
691
  };
973
692
  let eagerTransformsRegistered = false;
@@ -979,7 +698,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
979
698
  /**
980
699
  * Eager registration gives the role toggle an immediate visible effect during
981
700
  * setup; post config plugins register after it, so it also needs a suffix
982
- * registration after activation that appends last and keeps our variants.
701
+ * registration after activation that appends last.
983
702
  */
984
703
  const ensureEagerTransforms = async () => {
985
704
  if (eagerTransformsRegistered)
@@ -997,23 +716,24 @@ function initializeNativeSnapshotRuntime(ctx, options) {
997
716
  await ctx.model.reload();
998
717
  await ctx.agent.reload();
999
718
  };
1000
- owned.push(await ctx.session.hook("prompt", (event) => bindFor(event.sessionID)));
1001
- // `context` and `generate` resolve their model before (or around) the hook,
1002
- // so neither can bind; owned generate/synthetic work uses admitWorkload.
1003
- owned.push(await ctx.session.hook("generate", async (event) => {
1004
- const view = toSessionView(await ctx.session.get({ sessionID: event.sessionID }));
1005
- await guardResolvedModel(event.sessionID, view.agent, view.model, "generate");
1006
- }));
1007
- owned.push(await ctx.session.hook("model.request", async (event) => {
1008
- // The model is already resolved here: only validate/commit, never re-stage.
1009
- await guardResolvedModel(event.sessionID, event.agent, toSelection(event.model), event.kind);
1010
- }));
1011
719
  const rawSmallModel = state.config.rawIntent?.smallModel;
1012
720
  const smallModelRole = rawSmallModel !== undefined && isRoleReference(rawSmallModel)
1013
721
  ? rawSmallModel.trim().slice(ROLE_REFERENCE_PREFIX.length)
1014
722
  : getBuiltInRoleBindings().opencodeDefaults.smallModel;
723
+ const auxiliary = createAuxiliaryService({
724
+ familyOf,
725
+ policy: resolveSettings,
726
+ session: {
727
+ create: importAuxiliaryChild,
728
+ switchModel: async ({ sessionID, model }) => {
729
+ await ctx.session.switchModel({ sessionID, model: toRef(model) });
730
+ },
731
+ generate: (input) => ctx.session.generate(input),
732
+ },
733
+ fallbackDirectory: ctx.location.directory,
734
+ });
1015
735
  owned.push(await ctx.session.hook("title", async (event) => {
1016
- const title = await snapshots.auxiliary.title({
736
+ const title = await auxiliary.title({
1017
737
  sessionID: event.sessionID,
1018
738
  result: event.result,
1019
739
  messages: extractTitleMessages(event.messages),
@@ -1021,55 +741,45 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1021
741
  });
1022
742
  if (title !== undefined && event.result !== title) {
1023
743
  event.result = title;
1024
- // The host runs model.request before it checks `result`, so remember
1025
- // that this title provider dispatch is suppressed and must not refuse.
1026
- state.suppressedTitles.add(event.sessionID);
1027
744
  }
1028
745
  }));
1029
- // One native event pump: creation provenance, explicit choice capture, config
1030
- // refresh, and family-deletion cleanup share a single subscription. Failures
1031
- // are contained per event so later updates still recover runtime health.
746
+ // Lazy settings birth on the first context hook of a session. The hook is
747
+ // fail-soft: resolution problems never fail a model request, and plugin
748
+ // consumers resolve independently anyway.
749
+ owned.push(await ctx.session.hook("context", async (event) => {
750
+ try {
751
+ await ensureTransforms();
752
+ await resolveSettings(event.sessionID);
753
+ }
754
+ catch {
755
+ // Never fail a model request from settings work.
756
+ }
757
+ }));
758
+ // One native event pump: creation reconciliation and config refresh share a
759
+ // single subscription. Failures are contained per event so later updates
760
+ // still recover runtime health.
1032
761
  const pump = (async () => {
1033
762
  try {
1034
763
  for await (const event of ctx.event.subscribe({ signal: lifecycle.signal })) {
1035
764
  try {
1036
765
  const created = decodeSessionCreatedEvent(event);
1037
766
  if (created !== undefined) {
1038
- state.creationModels.set(created.sessionID, created.model);
1039
- // Record the default in force at creation, not a later changed default.
1040
- state.creationDefaults.set(created.sessionID, state.nativeDefault);
1041
- }
1042
- const selected = decodeModelSelectedEvent(event);
1043
- if (selected !== undefined) {
1044
- const pluginSwitch = state.pluginSwitches.get(selected.sessionID);
1045
- if (pluginSwitch === undefined ||
1046
- !sameModelSelection(selected.model, pluginSwitch)) {
1047
- // The host emits this only for a real change, so it is a user choice.
1048
- state.explicitSelections.set(selected.sessionID, selected.model);
1049
- // A user choice ends the first-work tolerance: later bare-base
1050
- // dispatches are genuine drift again.
1051
- state.firstWorkPending.delete(selected.sessionID);
1052
- }
767
+ await reconcileCreatedChild(created);
1053
768
  }
1054
769
  if (isConfigUpdateEvent(event)) {
1055
770
  // Assign only after a fully successful read so a partially read
1056
771
  // invalid config never becomes the mutable current config that
1057
- // already bound families consult.
772
+ // consumers consult; a successful read also clears the last
773
+ // contained failure.
1058
774
  state.config = await readConfig(ctx.location.directory);
1059
- await refresh();
1060
- // A successful config event is the recovery signal.
1061
775
  state.configError = undefined;
1062
776
  }
1063
777
  if (event.type === "session.deleted" && isRecord(event.data)) {
1064
778
  const sessionID = event.data.sessionID;
1065
779
  if (typeof sessionID === "string") {
1066
- await snapshots.removeFamily(sessionID);
1067
- state.creationModels.delete(sessionID);
1068
- state.creationDefaults.delete(sessionID);
1069
- state.explicitSelections.delete(sessionID);
1070
- state.pluginSwitches.delete(sessionID);
1071
- state.suppressedTitles.delete(sessionID);
1072
- state.firstWorkPending.delete(sessionID);
780
+ familyRoots.delete(sessionID);
781
+ bornRoots.delete(sessionID);
782
+ reconciledChildren.delete(sessionID);
1073
783
  }
1074
784
  }
1075
785
  }
@@ -1086,7 +796,24 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1086
796
  }
1087
797
  })();
1088
798
  void pump;
1089
- await refresh();
799
+ await ensureEagerTransforms();
800
+ // One-shot legacy migration: convert existing family bindings into root
801
+ // metadata, then prune the legacy directories. Fail-soft: any write
802
+ // failure keeps the directories for the next start.
803
+ try {
804
+ await migrateFamilyBindings({
805
+ reader: fileLegacyBindingsReader({ scopeKey: ctx.location.project.id }),
806
+ readSession,
807
+ writeSettings: async (sessionID, settings) => {
808
+ const fresh = await readSession(sessionID);
809
+ const merged = mergeSettingsIntoMetadata(fresh.metadata, settings);
810
+ await ctx.session.update({ sessionID, metadata: merged });
811
+ },
812
+ });
813
+ }
814
+ catch (error) {
815
+ diagnostic(`Legacy migration deferred: ${describePumpError(error).slice(0, 160)}`);
816
+ }
1090
817
  // Read-only native context-inspection RPC: projects the registered tool
1091
818
  // catalog and an allowlisted family/current-runtime policy for the TUI.
1092
819
  // Owned by this runtime's cleanup; it disposes only its own registration.
@@ -1096,43 +823,30 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1096
823
  ...(ctx.tool === undefined ? {} : { tool: ctx.tool }),
1097
824
  session: { get: (input) => ctx.session.get(input) },
1098
825
  }, {
1099
- policy: (sessionID) => snapshots.policy(sessionID),
826
+ policy: (sessionID) => resolveSettings(sessionID),
1100
827
  currentConfig: () => state.config,
1101
828
  ...(options?.now === undefined ? {} : { now: options.now }),
1102
829
  }));
1103
830
  return {
1104
831
  runtime,
1105
- snapshots,
1106
- auxiliary: snapshots.auxiliary,
832
+ settings: settingsService,
833
+ auxiliary,
1107
834
  client: () => runtime.client(),
1108
835
  permissions: runtime.permissions,
1109
836
  effectiveConfig: () => state.config,
1110
- async admitWorkload(request) {
1111
- // Supported pre-admission gateway for owned direct generate/synthetic:
1112
- // bind, materialize the qualified live variant, and switch before the
1113
- // caller triggers native model resolution.
1114
- const admissionConfig = await readConfig(request.directory);
1115
- state.config = admissionConfig;
1116
- const outcome = await snapshots.admitOwned({
1117
- ...request,
1118
- admissionConfig,
1119
- }, async (capture, selection) => {
1120
- await materializeBinding(capture, selection);
1121
- state.pluginSwitches.set(request.sessionID, selection);
1122
- });
1123
- if (outcome.status === "bound") {
1124
- await refresh();
1125
- state.pendingRegistrations.clear();
1126
- }
1127
- return outcome;
1128
- },
1129
837
  async setRoleOverride(enabled) {
1130
838
  state.roleOverride = enabled;
1131
- // Immediate visible override; the suffix registration at first work
1132
- // appends after post config transforms and keeps the final state ours.
839
+ // Immediate visible override: re-run the already-registered
840
+ // transforms with the new state instead of waiting for the first
841
+ // request, without stacking duplicate registrations.
1133
842
  await ensureEagerTransforms();
843
+ await ctx.model.reload();
844
+ await ctx.agent.reload();
845
+ },
846
+ refresh: async () => {
847
+ await ctx.model.reload();
848
+ await ctx.agent.reload();
1134
849
  },
1135
- refresh,
1136
850
  lastConfigError: () => state.configError,
1137
851
  release: releaseRuntime,
1138
852
  };
@@ -1144,7 +858,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1144
858
  }
1145
859
  })();
1146
860
  }
1147
- /** Acquire the shared native snapshot runtime for an actual `Plugin.Context`. */
861
+ /** Acquire the shared native runtime for an actual `Plugin.Context`. */
1148
862
  export async function acquireNativeSnapshotRuntime(ctx, options) {
1149
863
  const key = options?.runtimeDeps === undefined
1150
864
  ? String(objectId(contextIds, ctx))
@@ -1188,5 +902,5 @@ async function releaseNativeSnapshotRuntime(key, entry) {
1188
902
  const runtime = entry.runtime ?? (await entry.init);
1189
903
  await runtime.release();
1190
904
  }
1191
- // END_BLOCK_NATIVE_SNAPSHOT_RUNTIME
905
+ // END_BLOCK_RUNTIME_INITIALIZATION
1192
906
  //# sourceMappingURL=context.js.map