@osovv/vv-opencode 2.1.4 → 2.1.6

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 (60) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -2
  3. package/dist/commands/doctor.js +5 -1
  4. package/dist/commands/doctor.js.map +1 -1
  5. package/dist/commands/init.js +8 -2
  6. package/dist/commands/init.js.map +1 -1
  7. package/dist/commands/install.js +4 -2
  8. package/dist/commands/install.js.map +1 -1
  9. package/dist/commands/plugin-toggle.d.ts +16 -0
  10. package/dist/commands/plugin-toggle.js +33 -1
  11. package/dist/commands/plugin-toggle.js.map +1 -1
  12. package/dist/commands/preset.d.ts +8 -0
  13. package/dist/commands/preset.js +22 -1
  14. package/dist/commands/preset.js.map +1 -1
  15. package/dist/commands/role.js +29 -1
  16. package/dist/commands/role.js.map +1 -1
  17. package/dist/commands/status.js +5 -1
  18. package/dist/commands/status.js.map +1 -1
  19. package/dist/commands/sync.js +4 -2
  20. package/dist/commands/sync.js.map +1 -1
  21. package/dist/lib/opencode/cli-plugin-registration.d.ts +36 -0
  22. package/dist/lib/opencode/cli-plugin-registration.js +115 -0
  23. package/dist/lib/opencode/cli-plugin-registration.js.map +1 -0
  24. package/dist/lib/opencode/inspection.d.ts +12 -0
  25. package/dist/lib/opencode/inspection.js +17 -1
  26. package/dist/lib/opencode/inspection.js.map +1 -1
  27. package/dist/lib/opencode/paths.d.ts +2 -0
  28. package/dist/lib/opencode/paths.js +4 -2
  29. package/dist/lib/opencode/paths.js.map +1 -1
  30. package/dist/lib/opencode.d.ts +1 -0
  31. package/dist/lib/opencode.js +4 -3
  32. package/dist/lib/opencode.js.map +1 -1
  33. package/dist/lib/rebind-request.d.ts +41 -0
  34. package/dist/lib/rebind-request.js +134 -0
  35. package/dist/lib/rebind-request.js.map +1 -0
  36. package/dist/plugins/system-context-injection/index.js +49 -9
  37. package/dist/plugins/system-context-injection/index.js.map +1 -1
  38. package/dist/runtime/context.d.ts +9 -11
  39. package/dist/runtime/context.js +97 -188
  40. package/dist/runtime/context.js.map +1 -1
  41. package/dist/runtime/snapshot-config.d.ts +26 -0
  42. package/dist/runtime/snapshot-config.js +76 -2
  43. package/dist/runtime/snapshot-config.js.map +1 -1
  44. package/dist/runtime/snapshot-store.d.ts +38 -0
  45. package/dist/runtime/snapshot-store.js +150 -1
  46. package/dist/runtime/snapshot-store.js.map +1 -1
  47. package/dist/runtime/snapshots.d.ts +14 -37
  48. package/dist/runtime/snapshots.js +349 -562
  49. package/dist/runtime/snapshots.js.map +1 -1
  50. package/dist/runtime/types.d.ts +30 -71
  51. package/dist/runtime/types.js +20 -21
  52. package/dist/runtime/types.js.map +1 -1
  53. package/dist/tui/rebind/plugin.d.ts +22 -0
  54. package/dist/tui/rebind/plugin.js +101 -0
  55. package/dist/tui/rebind/plugin.js.map +1 -0
  56. package/dist/tui.js +7 -6
  57. package/dist/tui.js.map +1 -1
  58. package/package.json +1 -1
  59. package/schemas/vvoc/v3.json +1 -1
  60. package/templates/skills/vv-execute/references/tool-contracts.md +1 -1
@@ -1,8 +1,8 @@
1
1
  // FILE: src/runtime/context.ts
2
2
  // VERSION: 1.1.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Acquire, share by exact plugin-context identity, and release the lifecycle-managed native runtime, the snapshot service, and the centralized native snapshot runtime (client/permissions/snapshots/config/model/auxiliary) consumed by every later native plugin.
5
- // SCOPE: Context-identity reference-counted runtime/snapshot registries, per-acquisition idempotent release leases, lazy authenticated-client caching, permission-service exposure, native model/agent overlay capture, default-model transform, config.updated reconfiguration, coherent single-read admission configuration (fresh vvoc + raw intent + rebuilt provenance-aware agent bindings passed to both target and capture), cross-context app/location coordination, core stage/commit/guard/title hook registration, the read-only context-inspection RPC, and idempotent teardown without stopping the host. No service discovery until a client is requested, no location-only sharing, no global configuration singleton, no parallel fake runtime, and no V1 compatibility facade.
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, 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
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]
7
7
  // LINKS: [M-NATIVE-RUNTIME, V-M-NATIVE-RUNTIME]
8
8
  // ROLE: RUNTIME
@@ -11,21 +11,21 @@
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 snapshot service shared by one exact plugin context and dependency instance.
14
+ // acquireSnapshotService - Return a per-acquisition release lease for the family-binding service shared by one exact plugin context and dependency instance.
15
15
  // NativeSessionInfoLike - Structural native session info used for lineage and provenance.
16
16
  // NativeSnapshotHookEvents - Structural native hook event map used by the shared runtime.
17
17
  // NativeSnapshotContext - Narrow structural native Plugin.Context used to acquire the shared snapshot runtime.
18
18
  // NativeRegistration - Releasable native registration handle.
19
- // NativeForkClient - Structural full client for forks, parented imports and durable session-log reconciliation.
19
+ // NativeForkClient - Structural full client for forks and parented imports.
20
20
  // NativeSnapshotRuntimeOptions - Optional injectable native boundaries for the shared snapshot runtime.
21
- // NativeSnapshotRuntime - Documented shared native runtime: client, permissions, snapshots, effective config, model reload, role override, pre-admission gateway and refresh.
21
+ // NativeSnapshotRuntime - Documented shared native runtime: client, permissions, family bindings, effective config, model reload, role override, first-work gateway and refresh.
22
22
  // acquireNativeSnapshotRuntime - Acquire the shared native snapshot runtime for an actual Plugin.Context.
23
23
  // rebuildAgentBindings - Recompute agent bindings from a freshly read policy without trusting a cached vvoc-applied selection.
24
24
  // END_MODULE_MAP
25
25
  //
26
26
  // START_CHANGE_SUMMARY
27
- // LAST_CHANGE: [C-OPENCODE-V2-NATIVE T-009 - One coherent admission config: bindings are rebuilt from the fresh role map plus raw intent so a vvoc role change with no config.updated selects and captures the new model; the same value drives the candidate target and the family capture for prompt and owned work, and services share an app/location-identity coordinator.]
28
- // PREVIOUS: [C-OPENCODE-V2-NATIVE T-008 - Registers the read-only context-inspection RPC (registered catalog plus allowlisted family/current-runtime policy) inside the shared runtime and includes it in owned cleanup.]
27
+ // LAST_CHANGE: [C-SNAPSHOT-ANCHORING-REDESIGN T-004/T-005/T-008 - Replaced candidate acceptance with durable bind-on-first-work, runtime rehydration of credential-free bindings, live overlay materialization, explicit-selection qualification that matches the host-resolved family variant, native session-deletion cleanup.]
28
+ // PREVIOUS: [C-OPENCODE-V2-NATIVE T-009 - One coherent admission config: bindings are rebuilt from the fresh role map plus raw intent so a vvoc role change with no config.updated selects and captures the new model; the same value drives the candidate target and the family capture for prompt and owned work, and services share an app/location-identity coordinator.]
29
29
  // END_CHANGE_SUMMARY
30
30
  import { randomBytes } from "node:crypto";
31
31
  import { loadEffectiveVvocConfig, readRawOpenCodeModelIntent } from "../lib/config-layers.js";
@@ -34,9 +34,9 @@ import { acquireNativeClient, nativeRuntimeDeps } from "./client.js";
34
34
  import { coordinateHost } from "./coordination.js";
35
35
  import { applyAgentPolicies, applyVariantRegistrations, buildVariantRegistrations, mergeModelBodyOverlay, mergeModelHeadersOverlay, primarySelection, qualifySelection, } from "./model-registry.js";
36
36
  import { createPermissionService } from "./permissions.js";
37
- import { canonicalModelVariant, classifyInitialSelection, decodeInboxEnqueuedEvent, decodeModelSelectedEvent, decodeSessionCreatedEvent, effectiveRuntimeConfig, isAcceptedWorkloadEvent, isConfigUpdateEvent, normalizeModelSelection, parseRoleSelections, } from "./snapshot-config.js";
37
+ import { canonicalModelVariant, classifyInitialSelection, decodeModelSelectedEvent, decodeSessionCreatedEvent, effectiveRuntimeConfig, isConfigUpdateEvent, normalizeModelSelection, parseRoleSelections, } from "./snapshot-config.js";
38
38
  import { registerContextInspectionRpc } from "./context-inspection.js";
39
- import { createFileSnapshotStore } from "./snapshot-store.js";
39
+ import { FileBindingStore } from "./snapshot-store.js";
40
40
  import { createSnapshotService } from "./snapshots.js";
41
41
  import { RuntimeDisposedError, SnapshotAdmissionError, SnapshotUnboundError, decodeAuxiliaryMetadata, decodeImportedSessionID, runtimeIdentity, } from "./types.js";
42
42
  // START_BLOCK_RUNTIME_REGISTRY
@@ -229,6 +229,14 @@ function toRef(selection) {
229
229
  function cloneOverlay(value) {
230
230
  return value === undefined ? undefined : { ...value };
231
231
  }
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}.`)));
239
+ }
232
240
  function wantedModelKeys(config) {
233
241
  const keys = new Set();
234
242
  for (const selection of Object.values(parseRoleSelections(config.roles))) {
@@ -266,7 +274,7 @@ function captureModelSettings(editor, wanted, ownVariantIds) {
266
274
  });
267
275
  for (const variant of model.variants) {
268
276
  // Never re-capture vvoc-generated variants as native overlays (no accumulation).
269
- if (ownVariantIds.has(String(variant.id)))
277
+ if (isManagedVariantID(String(variant.id), modelID, ownVariantIds))
270
278
  continue;
271
279
  captured.push({
272
280
  providerID,
@@ -474,6 +482,26 @@ function selectionMatches(actual, expected) {
474
482
  // Identity plus variant: a resolved request must use the captured variant exactly.
475
483
  return sameModelSelection(actual, expected);
476
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
+ }
477
505
  /** The model a family expects for host title work: the captured fast/small role. */
478
506
  function titleExpectedSelection(capture) {
479
507
  const small = capture.roleModels.fast;
@@ -518,7 +546,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
518
546
  pluginSwitches: new Map(),
519
547
  suppressedTitles: new Set(),
520
548
  };
521
- const store = options?.store ?? createFileSnapshotStore({ scopeKey: ctx.location.project.id });
549
+ const store = options?.store ?? new FileBindingStore({ scopeKey: ctx.location.project.id });
522
550
  /**
523
551
  * Read the host's final native model collection. A model transform registered
524
552
  * by this plugin may run before later config transforms, so a transform-local
@@ -575,7 +603,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
575
603
  if (!isRecord(variant) || typeof variant.id !== "string")
576
604
  continue;
577
605
  // Never re-capture our own generated variants (no accumulation).
578
- if (state.ownVariantIds.has(variant.id))
606
+ if (isManagedVariantID(variant.id, modelID, state.ownVariantIds))
579
607
  continue;
580
608
  // Each source variant gets the base merged with THAT variant's own
581
609
  // native overlay, so two source variants of one model stay distinct.
@@ -615,73 +643,6 @@ function initializeNativeSnapshotRuntime(ctx, options) {
615
643
  };
616
644
  // Initialize the live config with raw OpenCode intent before any transform runs.
617
645
  state.config = await readConfig(ctx.location.directory);
618
- /**
619
- * Live accepted inputs observed on the event stream, keyed by
620
- * `sessionID\0inboxID`, carrying the native event time and durable sequence
621
- * used to order the first accepted workload. Merged with the durable log.
622
- */
623
- const liveAccepted = new Map();
624
- /**
625
- * Reconcile accepted inputs for a session. Returns the verified inputs plus
626
- * whether the durable log replay reached a genuine `log.synced` watermark
627
- * for THIS session. A truncated/wrong/timeout replay yields `complete:false`
628
- * but may still carry verified live events; callers must not order multiple
629
- * candidates from an incomplete view. Returns undefined when neither source
630
- * proves any acceptance.
631
- */
632
- const readAcceptedInputs = async (sessionID) => {
633
- const accepted = new Map();
634
- for (const entry of liveAccepted.values()) {
635
- if (entry.sessionID === sessionID)
636
- accepted.set(entry.inboxID, entry);
637
- }
638
- let complete = false;
639
- try {
640
- const client = await runtime.client();
641
- const stream = client.session.log({ sessionID, follow: false }, { signal: AbortSignal.timeout(5000) });
642
- for await (const item of stream) {
643
- if (!isRecord(item))
644
- continue;
645
- const type = typeof item.type === "string" ? item.type : "";
646
- if (type === "log.synced") {
647
- const aggregateID = item.aggregateID;
648
- if (typeof aggregateID !== "string" || aggregateID !== sessionID) {
649
- throw new SnapshotAdmissionError("The session log synced a different aggregate; refusing to trust the replay.");
650
- }
651
- const seq = item.seq;
652
- if (seq !== undefined && (typeof seq !== "number" || !Number.isFinite(seq))) {
653
- throw new SnapshotAdmissionError("The session log synced with an invalid sequence; refusing to trust the replay.");
654
- }
655
- complete = true;
656
- break;
657
- }
658
- const decoded = decodeInboxEnqueuedEvent({
659
- type,
660
- data: item.data,
661
- created: item.created,
662
- durable: isRecord(item.durable) ? item.durable : undefined,
663
- });
664
- if (decoded !== undefined && decoded.sessionID === sessionID) {
665
- accepted.set(decoded.inboxID, {
666
- sessionID,
667
- inboxID: decoded.inboxID,
668
- itemType: decoded.itemType,
669
- created: decoded.created ?? Date.now(),
670
- ...(decoded.seq === undefined ? {} : { seq: decoded.seq }),
671
- source: "log",
672
- });
673
- }
674
- }
675
- }
676
- catch {
677
- // The live entries below remain verified; the caller decides whether an
678
- // incomplete view is enough (it is not, when multiple inputs are staged).
679
- complete = false;
680
- }
681
- if (!complete && accepted.size === 0)
682
- return undefined;
683
- return { inputs: [...accepted.values()], complete };
684
- };
685
646
  /**
686
647
  * Create a real parented auxiliary child through the authenticated full
687
648
  * client's `session.import`. The child carries host-owned metadata naming
@@ -741,6 +702,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
741
702
  };
742
703
  const deps = {
743
704
  store,
705
+ location: runtimeIdentity(ctx.location),
744
706
  ...(options?.now === undefined ? {} : { now: options.now }),
745
707
  // Distinct plugin contexts copied from one host share the native app/location
746
708
  // object identity, so their snapshot services share one per-family
@@ -754,7 +716,6 @@ function initializeNativeSnapshotRuntime(ctx, options) {
754
716
  readSession: async (sessionID) => toSessionView(await ctx.session.get({ sessionID })),
755
717
  readSessionModel: async (sessionID) => toSelection((await ctx.session.get({ sessionID })).model),
756
718
  switchModel: ({ sessionID, model }) => ctx.session.switchModel({ sessionID, model: toRef(model) }),
757
- readAcceptedInputs,
758
719
  auxiliarySession: {
759
720
  create: importAuxiliaryChild,
760
721
  switchModel: async ({ sessionID, model }) => {
@@ -777,12 +738,11 @@ function initializeNativeSnapshotRuntime(ctx, options) {
777
738
  * transform-local editor is not proof the variant survived; the host's final
778
739
  * model list is. Returns undefined when the host exposes no list call (tests).
779
740
  */
780
- const materializeCandidate = async (candidateIdentity, capture, selection) => {
741
+ const materializeBinding = async (capture, selection) => {
781
742
  if (selection.variant === undefined)
782
743
  return;
783
- // Materialize this candidate's qualified variant before its switch, keyed
784
- // by candidate identity so a concurrent candidate's variants are not erased.
785
- state.pendingRegistrations.set(candidateIdentity, buildVariantRegistrations([capture]));
744
+ // Materialize this family's qualified live variant before its first switch.
745
+ state.pendingRegistrations.set(capture.snapshotId, buildVariantRegistrations([capture]));
786
746
  await ctx.model.reload();
787
747
  const finalEntries = await readFinalModelEntries();
788
748
  const exists = finalEntries === undefined
@@ -795,7 +755,7 @@ function initializeNativeSnapshotRuntime(ctx, options) {
795
755
  entry.variants.some((variant) => isRecord(variant) && String(variant.id) === selection.variant));
796
756
  });
797
757
  if (!exists) {
798
- state.pendingRegistrations.delete(candidateIdentity);
758
+ state.pendingRegistrations.delete(capture.snapshotId);
799
759
  await ctx.model.reload();
800
760
  throw new SnapshotAdmissionError(`Captured variant ${selection.variant} is not materializable on ${selection.providerID}/${selection.modelID}.`);
801
761
  }
@@ -804,8 +764,8 @@ function initializeNativeSnapshotRuntime(ctx, options) {
804
764
  state.pluginSwitches.set(sessionID, selection);
805
765
  await ctx.session.switchModel({ sessionID, model: toRef(selection) });
806
766
  };
807
- /** Unbound candidate selection for a session's agent from the live policy. */
808
- const candidateTarget = (agentID) => {
767
+ /** First-work selection for a session's agent from the live policy. */
768
+ const bindingTarget = (agentID) => {
809
769
  const bindings = state.config.agentBindings ?? [];
810
770
  if (agentID !== undefined) {
811
771
  const binding = bindings.find((agent) => agent.agentID === agentID);
@@ -844,21 +804,14 @@ function initializeNativeSnapshotRuntime(ctx, options) {
844
804
  if (!state.roleOverride)
845
805
  return capture.modelOverride ?? capture.rootSelection;
846
806
  const explicit = state.explicitSelections.get(sessionID);
847
- // An explicit user choice wins exactly as chosen; never re-qualify it with the
848
- // family variant, or the host-resolved request for that choice would mismatch.
807
+ // An explicit user choice wins, but the host resolves the request against the
808
+ // family-qualified variant id after the first-work switch, so the expectation
809
+ // must use the same qualification or the guard rejects the resolved request.
849
810
  if (explicit !== undefined)
850
- return normalizeModelSelection(explicit);
811
+ return qualifySelection(capture, explicit);
851
812
  return expectedSelection(capture, agentID);
852
813
  };
853
- /** Publish a staged candidate for an accepted workload before use. */
854
- const reconcileAcceptedFamily = async (sessionID) => {
855
- if ((await snapshots.policy(sessionID)) !== undefined)
856
- return;
857
- const outcome = await snapshots.accept({ sessionID });
858
- if (outcome.status === "bound")
859
- await refresh();
860
- };
861
- const stageFor = async (sessionID, inboxID) => {
814
+ const bindFor = async (sessionID) => {
862
815
  await ensureTransforms();
863
816
  const view = toSessionView(await ctx.session.get({ sessionID }));
864
817
  const sessionModel = view.model;
@@ -869,6 +822,11 @@ function initializeNativeSnapshotRuntime(ctx, options) {
869
822
  const intent = ownSwitch
870
823
  ? { mode: "implicit", source: "switch" }
871
824
  : classifyInitialSelection({ sessionModel, creationDefault });
825
+ if (intent.mode === "explicit" && intent.literal !== undefined) {
826
+ // Creation provenance is an explicit host selection just like a later
827
+ // model-selected event, so preserve it through the model guard.
828
+ state.explicitSelections.set(sessionID, intent.literal);
829
+ }
872
830
  const existing = await snapshots.policy(sessionID);
873
831
  if (existing !== undefined) {
874
832
  // A bound family owns an immutable capture, so its policy/model handling
@@ -892,40 +850,37 @@ function initializeNativeSnapshotRuntime(ctx, options) {
892
850
  }
893
851
  return;
894
852
  }
895
- // Only a truly unbound candidate needs the freshest current config:
853
+ // Only a truly unbound family needs the freshest current config:
896
854
  // vvoc.json changes do not emit a host `config.updated`, and a stale
897
- // candidate target would otherwise bind the previous role selection. The
898
- // SAME immutable value is passed into the service so its capture cannot
855
+ // family target would otherwise bind the previous role selection. The
856
+ // SAME immutable value is passed into the service so its projection cannot
899
857
  // re-read a different vvoc snapshot than the target was derived from.
900
858
  const admissionConfig = await readConfig(ctx.location.directory);
901
859
  state.config = admissionConfig;
902
- // Reconcile/restage by exact input identity. The snapshot service manages
903
- // candidate ownership: a still-staged sibling workload never blocks this
904
- // session's stage, and a first prompt rejected during native preparation
905
- // is superseded by the next same-session prompt rather than deadlocking it.
906
860
  const explicitSelection = intent.mode === "explicit" ? intent.literal : undefined;
907
- const target = explicitSelection ?? candidateTarget(view.agent);
861
+ const target = explicitSelection ?? bindingTarget(view.agent);
908
862
  const base = state.roleOverride ? target : (sessionModel ?? target);
909
- // The agent-aware resolved target drives staging, not the capture's default
863
+ // The agent-aware resolved target drives binding, not the capture's default
910
864
  // role; when role overriding is off the session's current model is bound.
911
865
  const selectionOverride = explicitSelection === undefined && base !== undefined ? base : undefined;
912
- const outcome = await snapshots.stage({
866
+ const outcome = await snapshots.admitOwned({
913
867
  sessionID,
914
868
  directory: ctx.location.directory,
915
869
  location: runtimeIdentity(ctx.location),
916
870
  admissionConfig,
917
871
  ...(explicitSelection === undefined ? {} : { explicit: explicitSelection }),
918
872
  ...(selectionOverride === undefined ? {} : { selectionOverride }),
919
- ...(sessionModel === undefined ? {} : { before: sessionModel }),
920
- ...(inboxID === undefined ? {} : { inboxID }),
921
- workload: "prompt",
922
873
  force: state.roleOverride,
923
- }, async (capture, selection, candidateIdentity) => {
924
- await materializeCandidate(candidateIdentity, capture, selection);
874
+ }, async (capture, selection) => {
875
+ await materializeBinding(capture, selection);
925
876
  state.pluginSwitches.set(sessionID, selection);
926
877
  });
927
878
  if (outcome.status === "rejected") {
928
- throw new SnapshotAdmissionError(outcome.error ?? `Admission for ${sessionID} did not produce a persisted policy.`);
879
+ throw new SnapshotAdmissionError(outcome.error ?? `Binding for ${sessionID} did not produce a persisted policy.`);
880
+ }
881
+ if (outcome.status === "bound") {
882
+ await refresh();
883
+ state.pendingRegistrations.clear();
929
884
  }
930
885
  };
931
886
  const guardResolvedModel = async (sessionID, agentID, actual, kind) => {
@@ -945,46 +900,13 @@ function initializeNativeSnapshotRuntime(ctx, options) {
945
900
  const expected = kind === "title"
946
901
  ? titleExpectedSelection(capture)
947
902
  : expectedForSession(capture, effectiveAgent, sessionID, view.metadata);
948
- if (!selectionMatches(actual, expected)) {
903
+ if (!selectionMatches(actual, expected) &&
904
+ !sameSourceSelection(capture, actual, expected)) {
949
905
  throw new SnapshotAdmissionError(`Resolved ${kind} model ${actual?.providerID ?? "?"}/${actual?.modelID ?? "?"} does not match the captured family selection for ${familyId}.`);
950
906
  }
951
907
  return;
952
908
  }
953
- // No committed capture yet. Await workload-correlated acceptance and
954
- // persistence: the pump may still be committing, so retry briefly while a
955
- // candidate exists. The service owns correlation and never commits
956
- // arbitrary pending; the validate callback refuses a mismatched model
957
- // before publication.
958
- const deadline = Date.now() + 3000;
959
- let lastError;
960
- for (;;) {
961
- const captureNow = await snapshots.policy(sessionID);
962
- if (captureNow !== undefined) {
963
- const expected = kind === "title"
964
- ? titleExpectedSelection(captureNow)
965
- : expectedForSession(captureNow, effectiveAgent, sessionID, view.metadata);
966
- if (!selectionMatches(actual, expected)) {
967
- throw new SnapshotAdmissionError(`Resolved ${kind} model ${actual?.providerID ?? "?"}/${actual?.modelID ?? "?"} does not match the captured family selection for ${familyId}.`);
968
- }
969
- return;
970
- }
971
- if (!(await snapshots.hasStaged(familyId))) {
972
- throw new SnapshotUnboundError(`Refusing unbound ${kind} dispatch for session ${sessionID} before a family policy is bound.`);
973
- }
974
- const outcome = await snapshots.accept({
975
- sessionID,
976
- validate: (selection) => selectionMatches(actual, selection),
977
- });
978
- if (outcome.status === "bound" || outcome.status === "reused") {
979
- await refresh();
980
- return;
981
- }
982
- lastError = outcome.error;
983
- if (Date.now() >= deadline)
984
- break;
985
- await new Promise((resolve) => setTimeout(resolve, 100));
986
- }
987
- throw new SnapshotUnboundError(`Refusing unbound ${kind} dispatch for session ${sessionID} before a family policy is bound (${lastError ?? "no accepted workload"}).`);
909
+ throw new SnapshotUnboundError(`Refusing unbound ${kind} dispatch for session ${sessionID} before first-work family binding.`);
988
910
  };
989
911
  const modelTransform = (editor) => {
990
912
  const own = new Set([...state.registrations, ...allPending()].map((registration) => registration.variant.id));
@@ -1042,9 +964,9 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1042
964
  await ctx.model.reload();
1043
965
  await ctx.agent.reload();
1044
966
  };
1045
- owned.push(await ctx.session.hook("prompt", (event) => stageFor(event.sessionID, event.messageID)));
967
+ owned.push(await ctx.session.hook("prompt", (event) => bindFor(event.sessionID)));
1046
968
  // `context` and `generate` resolve their model before (or around) the hook,
1047
- // so neither can stage; owned generate/synthetic work uses admitWorkload.
969
+ // so neither can bind; owned generate/synthetic work uses admitWorkload.
1048
970
  owned.push(await ctx.session.hook("generate", async (event) => {
1049
971
  const view = toSessionView(await ctx.session.get({ sessionID: event.sessionID }));
1050
972
  await guardResolvedModel(event.sessionID, view.agent, view.model, "generate");
@@ -1058,9 +980,6 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1058
980
  ? rawSmallModel.trim().slice(ROLE_REFERENCE_PREFIX.length)
1059
981
  : getBuiltInRoleBindings().opencodeDefaults.smallModel;
1060
982
  owned.push(await ctx.session.hook("title", async (event) => {
1061
- // The host resolved and may dispatch the title before the event pump has
1062
- // committed the accepted candidate; reconcile it so title work is bound.
1063
- await reconcileAcceptedFamily(event.sessionID);
1064
983
  const title = await snapshots.auxiliary.title({
1065
984
  sessionID: event.sessionID,
1066
985
  result: event.result,
@@ -1075,11 +994,8 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1075
994
  }
1076
995
  }));
1077
996
  // One native event pump: creation provenance, explicit choice capture, config
1078
- // refresh and the accepted-input boundary all share a single subscription.
1079
- // Failures are contained PER EVENT: a bad config/refresh/accept never ends
1080
- // the only subscription, so later session.created/model.selected/inbox
1081
- // events are still observed and a later config event recovers the health
1082
- // flag once the invalid input is fixed.
997
+ // refresh, and family-deletion cleanup share a single subscription. Failures
998
+ // are contained per event so later updates still recover runtime health.
1083
999
  const pump = (async () => {
1084
1000
  try {
1085
1001
  for await (const event of ctx.event.subscribe({ signal: lifecycle.signal })) {
@@ -1108,24 +1024,16 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1108
1024
  // A successful config event is the recovery signal.
1109
1025
  state.configError = undefined;
1110
1026
  }
1111
- if (isAcceptedWorkloadEvent(event)) {
1112
- // Record the verified native acceptance with its event time/sequence,
1113
- // then let the service pick the FIRST accepted candidate across the
1114
- // family rather than the one whose notification arrived first.
1115
- const enqueued = decodeInboxEnqueuedEvent(event);
1116
- if (enqueued === undefined)
1117
- continue;
1118
- liveAccepted.set(`${enqueued.sessionID}\u0000${enqueued.inboxID}`, {
1119
- sessionID: enqueued.sessionID,
1120
- inboxID: enqueued.inboxID,
1121
- itemType: enqueued.itemType,
1122
- created: enqueued.created ?? Date.now(),
1123
- ...(enqueued.seq === undefined ? {} : { seq: enqueued.seq }),
1124
- source: "live",
1125
- });
1126
- const outcome = await snapshots.accept({ sessionID: enqueued.sessionID });
1127
- if (outcome.status === "bound")
1128
- await refresh();
1027
+ if (event.type === "session.deleted" && isRecord(event.data)) {
1028
+ const sessionID = event.data.sessionID;
1029
+ if (typeof sessionID === "string") {
1030
+ await snapshots.removeFamily(sessionID);
1031
+ state.creationModels.delete(sessionID);
1032
+ state.creationDefaults.delete(sessionID);
1033
+ state.explicitSelections.delete(sessionID);
1034
+ state.pluginSwitches.delete(sessionID);
1035
+ state.suppressedTitles.delete(sessionID);
1036
+ }
1129
1037
  }
1130
1038
  }
1131
1039
  catch (error) {
@@ -1164,21 +1072,22 @@ function initializeNativeSnapshotRuntime(ctx, options) {
1164
1072
  effectiveConfig: () => state.config,
1165
1073
  async admitWorkload(request) {
1166
1074
  // Supported pre-admission gateway for owned direct generate/synthetic:
1167
- // mint an operation token this runtime owns, then stage, materialize the
1168
- // qualified variant, switch and publish before the caller triggers native
1169
- // model resolution. It cannot publish a prompt candidate that still needs
1170
- // correlated native acceptance. The same coherent config that drives the
1171
- // target is passed to the service so owned work obeys the same rule.
1075
+ // bind, materialize the qualified live variant, and switch before the
1076
+ // caller triggers native model resolution.
1172
1077
  const admissionConfig = await readConfig(request.directory);
1173
1078
  state.config = admissionConfig;
1174
- return snapshots.admitOwned({
1079
+ const outcome = await snapshots.admitOwned({
1175
1080
  ...request,
1176
1081
  admissionConfig,
1177
- operationID: `op_${randomBytes(16).toString("hex")}`,
1178
- }, async (capture, selection, candidateIdentity) => {
1179
- await materializeCandidate(candidateIdentity, capture, selection);
1082
+ }, async (capture, selection) => {
1083
+ await materializeBinding(capture, selection);
1180
1084
  state.pluginSwitches.set(request.sessionID, selection);
1181
1085
  });
1086
+ if (outcome.status === "bound") {
1087
+ await refresh();
1088
+ state.pendingRegistrations.clear();
1089
+ }
1090
+ return outcome;
1182
1091
  },
1183
1092
  async setRoleOverride(enabled) {
1184
1093
  state.roleOverride = enabled;