@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,9 +1,9 @@
1
1
  // FILE: src/runtime/snapshots.ts
2
2
  // VERSION: 2.0.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Build durable immutable family policy captures from full effective vvoc configuration plus native model overlays, and admit sessions through a staged awaited native model switch that is committed only at the accepted request boundary.
5
- // SCOPE: Host-verified parent/fork family resolution, content-addressed full-policy capture construction, staged-candidate persistence, family-qualified awaited switchModel admission, commit at acceptance with rollback that preserves a newer choice, idempotent/concurrent deduplication that preserves rejection, force-escalation reconciliation of an identical input, cross-context publication serialization through the app/location coordinator, variant derivation, and the documented SnapshotService consumed by later plugins. No host discovery, no client authentication, no permission flow, no stateless generation.
6
- // DEPENDS: [node:crypto, src/runtime/auxiliary.ts, src/runtime/coordination.ts, src/runtime/model-registry.ts, src/runtime/snapshot-config.ts, src/runtime/snapshot-store.ts, src/runtime/types.ts]
4
+ // PURPOSE: Bind each native session family to one credential-free, content-addressed behaviour policy at its first workload and materialize that stable policy with live credentials and native overlays for plugin consumers.
5
+ // SCOPE: Host-verified family resolution, per-family serialized bind/rehydrate/rebind/delete lifecycle, fail-soft binding-store recovery, reference-counted garbage collection, live credential attachment, variant derivation, and the SnapshotService consumed by native plugins. No candidate staging, accepted-input ordering, cross-context publication, host discovery, client authentication, or stateless generation.
6
+ // DEPENDS: [src/runtime/auxiliary.ts, src/runtime/coordination.ts, src/runtime/model-registry.ts, src/runtime/snapshot-config.ts, src/runtime/snapshot-store.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,37 +11,21 @@
11
11
  //
12
12
  // START_MODULE_MAP
13
13
  // MAX_LINEAGE_HOPS - Bound on host-verified parent/fork lineage traversal.
14
- // MAX_STAGED_CANDIDATES - Bound on concurrently staged per-input candidates for one family.
15
- // SnapshotCaptureInput - Inputs used to build one family capture.
16
- // SnapshotServiceDeps - Injectable native boundaries for the snapshot service.
17
- // defaultSnapshotDigest - Content digest used to address captures.
18
- // buildFamilyCapture - Build an immutable full-policy family capture.
14
+ // SnapshotServiceDeps - Injectable host and durable-binding boundaries.
19
15
  // resolveSessionFamily - Resolve a session's family root through host-verified lineage.
20
- // createSnapshotService - Build the documented snapshot service for one native context.
16
+ // createSnapshotService - Build the credential-safe family-binding service for one native context.
21
17
  // END_MODULE_MAP
22
18
  //
23
19
  // START_CHANGE_SUMMARY
24
- // LAST_CHANGE: [C-OPENCODE-V2-NATIVE T-009 - An exact-input force:false then force:true escalation reconciles the required materialization/switch without overwriting a newer explicit choice, an optional caller-supplied admission config is used verbatim, and an app/location coordinator serializes publication so concurrent acceptors across distinct contexts write the family capture once.]
20
+ // LAST_CHANGE: [C-SNAPSHOT-ANCHORING-REDESIGN T-004/T-005/T-006 - Replaced staged candidate capture with fail-soft, per-family content-addressed bindings that rehydrate across restart, consume pending CLI force-rebind markers, clean up on deletion, and attach credentials only in memory.]
25
21
  // END_CHANGE_SUMMARY
26
- import { createHash } from "node:crypto";
27
22
  import { createAuxiliaryService } from "./auxiliary.js";
28
23
  import { managedVariantFor, primarySelection, qualifySelection } from "./model-registry.js";
29
- import { agentBindingsFrom, parseRoleSelections } from "./snapshot-config.js";
30
- import { familyCaptureIntegrity } from "./snapshot-store.js";
31
- import { SnapshotAdmissionError, stagedCandidateIdentity, stagedCandidateKey, } from "./types.js";
24
+ import { behaviourContentHash, buildBehaviourProjection, } from "./snapshot-config.js";
25
+ import { listRebindRequests, rebindRequestMatches, } from "../lib/rebind-request.js";
26
+ import { SnapshotAdmissionError, } from "./types.js";
32
27
  /** Bound on host-verified parent/fork lineage traversal. */
33
28
  export const MAX_LINEAGE_HOPS = 64;
34
- /**
35
- * Bound on concurrently staged per-input admission candidates for one family.
36
- * Overflow fails the new stage closed rather than dropping an unaccepted input
37
- * that native preparation may still accept later.
38
- */
39
- export const MAX_STAGED_CANDIDATES = 8;
40
- // START_BLOCK_CAPTURE_CONSTRUCTION
41
- /** Content digest used to address captures. */
42
- export function defaultSnapshotDigest(value) {
43
- return createHash("sha256").update(value).digest("hex");
44
- }
45
29
  function variantIdFor(snapshotId, modelID, sourceVariant) {
46
30
  return sourceVariant === undefined
47
31
  ? `${snapshotId}.${modelID}`
@@ -57,11 +41,11 @@ function variantOverlayFor(selection, modelSettings) {
57
41
  ...(match?.headers === undefined ? {} : { headers: match.headers }),
58
42
  };
59
43
  }
60
- function buildVariants(selections, modelSettings) {
44
+ function buildVariants(snapshotId, selections, modelSettings) {
61
45
  const byKey = new Map();
62
46
  for (const selection of Object.values(selections)) {
63
47
  const overlay = variantOverlayFor(selection, modelSettings);
64
- const managed = managedVariantFor(selection, "");
48
+ const managed = managedVariantFor(selection, snapshotId);
65
49
  const hasOverlay = overlay.settings !== undefined || overlay.body !== undefined || overlay.headers !== undefined;
66
50
  if (!hasOverlay && managed === undefined)
67
51
  continue;
@@ -69,7 +53,7 @@ function buildVariants(selections, modelSettings) {
69
53
  const body = { ...overlay.body, ...managed?.body };
70
54
  const key = `${selection.providerID}\u0000${selection.modelID}\u0000${sourceVariant ?? ""}`;
71
55
  byKey.set(key, {
72
- id: "",
56
+ id: variantIdFor(snapshotId, selection.modelID, sourceVariant),
73
57
  providerID: selection.providerID,
74
58
  modelID: selection.modelID,
75
59
  ...(sourceVariant === undefined ? {} : { sourceVariant }),
@@ -80,47 +64,46 @@ function buildVariants(selections, modelSettings) {
80
64
  }
81
65
  return [...byKey.values()];
82
66
  }
83
- /** Build an immutable full-policy family capture. */
84
- export function buildFamilyCapture(input) {
85
- const digest = input.digest ?? defaultSnapshotDigest;
86
- const roleModels = parseRoleSelections(input.config.roles);
87
- const agents = input.config.agentBindings ?? agentBindingsFrom(input.config.agentRoles, roleModels);
88
- const modelSettings = input.config.modelSettings ?? [];
89
- const vvoc = input.config.vvoc;
90
- const modelOverride = input.explicit;
91
- const draft = {
67
+ /** Attach only live credential fields; the stored projection never carries them. */
68
+ function policyWithLiveCredentials(projection, live) {
69
+ const policy = structuredClone(projection.policy);
70
+ if (live === undefined)
71
+ return policy;
72
+ policy.secretsRedaction = {
73
+ ...policy.secretsRedaction,
74
+ secret: live.vvoc.secretsRedaction.secret,
75
+ };
76
+ const searchKey = live.vvoc.web?.search?.apiKey;
77
+ const fetchKey = live.vvoc.web?.fetch?.apiKey;
78
+ if (searchKey !== undefined || fetchKey !== undefined) {
79
+ policy.web = {
80
+ ...policy.web,
81
+ ...(searchKey === undefined ? {} : { search: { ...policy.web?.search, apiKey: searchKey } }),
82
+ ...(fetchKey === undefined ? {} : { fetch: { ...policy.web?.fetch, apiKey: fetchKey } }),
83
+ };
84
+ }
85
+ return policy;
86
+ }
87
+ function materializeCapture(input) {
88
+ const snapshotId = input.binding.snapshotHash.slice(0, 16);
89
+ const modelSettings = input.live?.modelSettings ?? [];
90
+ return {
92
91
  schemaVersion: 1,
93
- snapshotId: "",
94
- integrity: "",
92
+ snapshotId,
93
+ integrity: input.binding.snapshotHash,
95
94
  familyId: input.familyId,
96
- capturedAt: input.capturedAt ?? Date.now(),
95
+ capturedAt: Date.parse(input.binding.boundAt) || 0,
97
96
  location: input.location,
98
- roles: input.config.roles,
99
- roleModels,
100
- agents,
101
- variants: buildVariants(roleModels, modelSettings),
97
+ roles: input.projection.policy.roles,
98
+ roleModels: input.projection.roleModels,
99
+ agents: input.projection.agentBindings,
100
+ variants: buildVariants(snapshotId, input.projection.roleModels, modelSettings),
101
+ // Native overlays can carry credentials, so they are re-derived from the live registry.
102
102
  modelSettings,
103
- vvoc,
104
- ...(input.config.rawIntent === undefined ? {} : { rawIntent: input.config.rawIntent }),
105
- ...(input.config.rootDefault === undefined ? {} : { rootSelection: input.config.rootDefault }),
106
- ...(modelOverride === undefined ? {} : { modelOverride }),
107
- intent: input.intent,
108
- };
109
- // Integrity covers roles, native overlays, raw vvoc and source variants, never generated ids.
110
- const integrity = familyCaptureIntegrity(draft);
111
- const snapshotId = digest(integrity).slice(0, 16);
112
- const variants = draft.variants.map((variant) => ({
113
- ...variant,
114
- id: variantIdFor(snapshotId, variant.modelID, variant.sourceVariant),
115
- }));
116
- return {
117
- ...draft,
118
- snapshotId,
119
- integrity,
120
- variants,
103
+ vvoc: policyWithLiveCredentials(input.projection, input.live),
104
+ intent: { mode: "implicit", source: "config" },
121
105
  };
122
106
  }
123
- // END_BLOCK_CAPTURE_CONSTRUCTION
124
107
  // START_BLOCK_LINEAGE_RESOLUTION
125
108
  /** Resolve a session's family root through host-verified lineage. */
126
109
  export async function resolveSessionFamily(input) {
@@ -135,7 +118,6 @@ export async function resolveSessionFamily(input) {
135
118
  if (view === undefined) {
136
119
  throw new SnapshotAdmissionError(`Session ${current} could not be read from the host.`);
137
120
  }
138
- // An empty parentID with a fork.sessionID means the fork's source is the parent.
139
121
  const parent = typeof view.parentID === "string" && view.parentID.length > 0
140
122
  ? view.parentID
141
123
  : typeof view.forkSessionID === "string" && view.forkSessionID.length > 0
@@ -148,574 +130,379 @@ export async function resolveSessionFamily(input) {
148
130
  throw new SnapshotAdmissionError("Session lineage exceeds the supported depth.");
149
131
  }
150
132
  // END_BLOCK_LINEAGE_RESOLUTION
151
- // START_BLOCK_ADMISSION
152
- function sameSelection(left, right) {
153
- if (left === undefined || right === undefined)
154
- return left === right;
155
- return (left.providerID === right.providerID &&
156
- left.modelID === right.modelID &&
157
- (left.variant ?? "") === (right.variant ?? ""));
158
- }
159
- async function rollbackStaged(input) {
160
- let current;
161
- try {
162
- current = await input.readSessionModel(input.sessionID);
163
- }
164
- catch {
165
- return "none";
166
- }
167
- // Full identity including variant; a different current means a newer choice arrived.
168
- if (!sameSelection(current, input.candidate.selection))
169
- return "preserved-newer-choice";
170
- if (input.candidate.before === undefined)
171
- return "none";
172
- try {
173
- await input.switchModel({ sessionID: input.sessionID, model: input.candidate.before });
174
- return "reverted";
175
- }
176
- catch {
177
- return "none";
178
- }
179
- }
180
- function toReason(error) {
181
- return error instanceof Error ? error.message : String(error);
182
- }
183
- /** Build the documented snapshot service for one native context. */
133
+ // START_BLOCK_BINDING_LIFECYCLE
134
+ /** Build the credential-safe family-binding service for one native context. */
184
135
  export function createSnapshotService(deps) {
185
136
  const now = deps.now ?? Date.now;
186
- const digest = deps.digest ?? defaultSnapshotDigest;
187
- const inFlightSessions = new Map();
188
- const inFlightAccepts = new Map();
189
- const inFlightOwned = new Map();
190
- /**
191
- * Per-family serialization. Candidate read/write, switch and publication are
192
- * ordered so a concurrent stage cannot be lost or overwritten between an
193
- * acceptance validation and its publication, and late cleanup cannot delete a
194
- * newer/committed capture. When a cross-context coordinator is present the lock
195
- * is shared by every participating service, so two acceptors in distinct native
196
- * contexts publish the family capture exactly once.
197
- */
137
+ const readPendingRebinds = deps.rebindRequests ?? listRebindRequests;
198
138
  const familyLocks = new Map();
139
+ const sessionFamilies = new Map();
199
140
  let disposed = false;
141
+ const diagnose = (message) => {
142
+ // Messages are static and bounded: never include paths, parsed state, or credentials.
143
+ deps.diagnostic?.(message.slice(0, 240));
144
+ };
200
145
  function withFamilyLock(familyId, run) {
201
- if (deps.coordination !== undefined) {
146
+ if (deps.coordination !== undefined)
202
147
  return deps.coordination.withFamilyLock(familyId, run);
203
- }
204
148
  const previous = familyLocks.get(familyId) ?? Promise.resolve();
205
149
  const next = previous.then(run, run);
206
150
  familyLocks.set(familyId, next.then(() => undefined, () => undefined));
207
151
  return next;
208
152
  }
209
- const familyOf = async (sessionID) => resolveSessionFamily({ sessionID, readSession: deps.readSession });
210
- const policy = async (sessionID) => {
211
- if (disposed)
212
- return undefined;
213
- const familyId = await familyOf(sessionID);
214
- return deps.store.read(familyId);
153
+ const familyOf = async (sessionID) => {
154
+ const familyId = await resolveSessionFamily({ sessionID, readSession: deps.readSession });
155
+ sessionFamilies.set(sessionID, familyId);
156
+ return familyId;
215
157
  };
216
- async function loadCaptures() {
217
- const ids = await deps.store.list();
218
- const captures = [];
219
- for (const familyId of ids) {
220
- const capture = await deps.store.read(familyId);
221
- if (capture !== undefined)
222
- captures.push(capture);
223
- }
224
- return captures;
225
- }
226
- async function doStage(request, familyId, materialize) {
227
- const existing = await deps.store.read(familyId);
228
- if (existing !== undefined) {
229
- return { status: "reused", familyId, snapshotId: existing.snapshotId };
230
- }
231
- // A durable marker proves the family was bound before; a missing capture must fail closed.
232
- if (await deps.store.readMarker(familyId)) {
233
- return {
234
- status: "rejected",
235
- familyId,
236
- error: "A previously bound family capture is missing; refusing to adopt current configuration.",
237
- rollback: "none",
238
- };
239
- }
240
- const view = await deps.readSession(request.sessionID);
241
- if (view === undefined) {
242
- return {
243
- status: "rejected",
244
- familyId,
245
- error: `Session ${request.sessionID} could not be read for admission.`,
246
- rollback: "none",
247
- };
248
- }
249
- if (view.hasActivity === true && request.explicit === undefined) {
250
- // A session that already did work without a durable capture must not adopt current policy.
251
- return {
252
- status: "rejected",
253
- familyId,
254
- error: "An active session has no persisted family capture; refusing to adopt current configuration.",
255
- rollback: "none",
256
- };
257
- }
258
- let config;
158
+ async function readBound(familyId) {
259
159
  try {
260
- // One coherent admission config: when the caller assembled it from a single
261
- // read, use that exact value so the candidate target and the family capture
262
- // cannot observe two different vvoc snapshots.
263
- config = request.admissionConfig ?? (await deps.loadConfig(request.directory));
264
- }
265
- catch (error) {
266
- return {
267
- status: "rejected",
268
- familyId,
269
- error: toReason(error),
270
- rollback: "none",
271
- };
272
- }
273
- const intent = request.intent ??
274
- (request.explicit === undefined
275
- ? { mode: "implicit", source: "config" }
276
- : { mode: "explicit", source: "config", literal: request.explicit });
277
- let capture;
278
- try {
279
- // Resolve the family model before building the capture so `modelOverride`
280
- // records the exact model this family binds. `explicit` is the user's
281
- // documented choice; `selectionOverride` is a caller-resolved base (for
282
- // example the current model when role overriding is disabled).
283
- const parsedRoles = parseRoleSelections(config.roles);
284
- const fallback = parsedRoles.default ??
285
- config.rootDefault ??
286
- Object.values(parsedRoles)[0] ??
287
- config.agentBindings?.find((binding) => binding.selection !== undefined)?.selection;
288
- const baseSelection = request.explicit ?? request.selectionOverride ?? fallback;
289
- capture = buildFamilyCapture({
290
- familyId,
291
- location: request.location,
292
- config,
293
- intent,
294
- ...(baseSelection === undefined ? {} : { explicit: baseSelection }),
295
- capturedAt: now(),
296
- digest,
297
- });
298
- }
299
- catch (error) {
300
- return {
301
- status: "rejected",
302
- familyId,
303
- error: toReason(error),
304
- rollback: "none",
305
- };
306
- }
307
- // Per-input candidates: repeated identical input is idempotent, distinct
308
- // inputs coexist up to MAX_STAGED_CANDIDATES, and the family's first
309
- // accepted input decides the snapshot regardless of stage order.
310
- const requestIdentity = stagedCandidateIdentity(request);
311
- const candidates = await deps.store.readCandidates(familyId);
312
- const sameInput = candidates.find((candidate) => stagedCandidateKey(candidate) === requestIdentity);
313
- if (sameInput !== undefined && sameInput.revision === capture.integrity) {
314
- // Repeated identical input is idempotent. When a caller escalates to
315
- // force:true after an earlier force:false stage, the required materialization
316
- // and awaited switch are reconciled here instead of returning early with zero
317
- // switches, while a newer explicit choice is never overwritten.
318
- if (request.force === true) {
319
- const newerExplicit = request.explicit !== undefined && !sameSelection(request.explicit, sameInput.selection);
320
- const current = await deps.readSessionModel(request.sessionID).catch(() => undefined);
321
- const alreadyApplied = current !== undefined && sameSelection(current, sameInput.selection);
322
- if (!newerExplicit && !alreadyApplied) {
323
- try {
324
- await materialize?.(sameInput.capture, sameInput.selection, requestIdentity);
325
- await deps.switchModel({ sessionID: request.sessionID, model: sameInput.selection });
326
- }
327
- catch (error) {
328
- return {
329
- status: "rejected",
330
- familyId,
331
- candidateSelection: sameInput.selection,
332
- error: toReason(error),
333
- rollback: "none",
334
- };
335
- }
336
- }
160
+ const binding = await deps.store.readBinding(familyId);
161
+ if (binding === undefined || binding.familyId !== familyId) {
162
+ if (binding !== undefined)
163
+ diagnose("Invalid family binding pointer; rebinding on next workload.");
164
+ return undefined;
337
165
  }
338
- return {
339
- status: "staged",
340
- familyId,
341
- snapshotId: sameInput.capture.snapshotId,
342
- candidateSelection: sameInput.selection,
343
- rollback: "none",
344
- };
345
- }
346
- if (sameInput === undefined && candidates.length >= MAX_STAGED_CANDIDATES) {
347
- // Bounded set overflow fails the new stage closed rather than dropping an
348
- // unaccepted input that native preparation may still accept later.
349
- return {
350
- status: "rejected",
351
- familyId,
352
- error: `The family already holds ${candidates.length} staged candidates; refusing to drop an unaccepted input.`,
353
- rollback: "none",
354
- };
166
+ const projection = await deps.store.readSnapshot(binding.snapshotHash);
167
+ if (projection === undefined) {
168
+ diagnose("Missing or invalid family policy snapshot; rebinding on next workload.");
169
+ return undefined;
170
+ }
171
+ return { binding, projection };
355
172
  }
356
- const baseSelection = request.explicit ?? primarySelection(capture);
357
- if (baseSelection === undefined) {
358
- return {
359
- status: "rejected",
360
- familyId,
361
- error: "The effective configuration has no selectable model policy.",
362
- rollback: "none",
363
- };
173
+ catch {
174
+ diagnose("Family binding state could not be read; rebinding on next workload.");
175
+ return undefined;
364
176
  }
365
- // The family's captured variant must be activated, not a sibling family's.
366
- const selection = qualifySelection(capture, baseSelection);
177
+ }
178
+ async function liveConfig(directory) {
367
179
  try {
368
- // Materialize the candidate variant before the switch so resolution finds it.
369
- await materialize?.(capture, selection, requestIdentity);
180
+ return await deps.loadConfig(directory);
370
181
  }
371
- catch (error) {
372
- return {
373
- status: "rejected",
374
- familyId,
375
- candidateSelection: selection,
376
- error: toReason(error),
377
- rollback: "none",
378
- };
182
+ catch {
183
+ diagnose("Live configuration could not be read; using the credential-free bound policy.");
184
+ return undefined;
379
185
  }
380
- const candidate = {
381
- familyId,
382
- sessionID: request.sessionID,
383
- ...(request.inboxID === undefined ? {} : { inboxID: request.inboxID }),
384
- ...(request.operationID === undefined ? {} : { operationID: request.operationID }),
385
- ...(request.workload === undefined ? {} : { workload: request.workload }),
386
- stagedAt: now(),
387
- revision: capture.integrity,
388
- selection,
389
- ...(request.before === undefined ? {} : { before: request.before }),
390
- capture,
391
- };
186
+ }
187
+ async function consumePendingRebind(input) {
188
+ let requests;
392
189
  try {
393
- await deps.store.writeCandidate(candidate);
190
+ requests = await readPendingRebinds();
394
191
  }
395
- catch (error) {
396
- return {
397
- status: "rejected",
398
- familyId,
399
- candidateSelection: selection,
400
- error: toReason(error),
401
- rollback: "none",
402
- };
192
+ catch {
193
+ return undefined;
403
194
  }
404
- // A caller may bind policy without forcing a model change (role override off).
405
- if (request.force === false) {
406
- return {
407
- status: "staged",
408
- familyId,
409
- snapshotId: capture.snapshotId,
410
- candidateSelection: selection,
411
- rollback: "none",
412
- };
195
+ const match = requests.find((candidate) => rebindRequestMatches(candidate, {
196
+ directory: input.directory,
197
+ sessionId: input.sessionID,
198
+ }) && candidate.requestedAt > input.boundAt);
199
+ if (match === undefined)
200
+ return undefined;
201
+ const config = await liveConfig(input.directory);
202
+ if (config === undefined) {
203
+ diagnose("A pending rebind request could not read the current configuration.");
204
+ return undefined;
413
205
  }
414
206
  try {
415
- await deps.switchModel({ sessionID: request.sessionID, model: selection });
416
- }
417
- catch (error) {
418
- const rollback = await rollbackStaged({
419
- sessionID: request.sessionID,
420
- candidate,
421
- readSessionModel: deps.readSessionModel,
422
- switchModel: deps.switchModel,
207
+ const projection = buildBehaviourProjection({
208
+ roles: config.roles,
209
+ agentRoles: config.agentRoles,
210
+ vvoc: config.vvoc,
423
211
  });
424
- // Remove only our own candidate; never another owner's.
425
- await deps.store.removeCandidate(familyId, requestIdentity).catch(() => undefined);
426
- return {
427
- status: "rejected",
428
- familyId,
429
- candidateSelection: selection,
430
- rollback,
431
- error: toReason(error),
212
+ const contentHash = await deps.store.writeSnapshot(projection);
213
+ const binding = {
214
+ familyId: input.familyId,
215
+ snapshotHash: contentHash,
216
+ boundAt: new Date(now()).toISOString(),
432
217
  };
218
+ await deps.store.writeBinding(binding);
219
+ await collectGarbage();
220
+ return { binding, projection, config };
433
221
  }
434
- return {
435
- status: "staged",
436
- familyId,
437
- snapshotId: capture.snapshotId,
438
- candidateSelection: selection,
439
- rollback: "none",
440
- };
441
- }
442
- /**
443
- * Publish the exact winning candidate as the bound family capture. The
444
- * candidate must still exist with the same owner identity and revision; the
445
- * bound marker is written first so a crash between the two writes fails closed:
446
- * a capture is never readable without its marker, and a marker without a
447
- * capture is refused on the next admission instead of adopting current
448
- * configuration. Cleanup removes only the winning candidate, never a newer one.
449
- */
450
- async function publishCandidate(familyId, expected) {
451
- const key = stagedCandidateKey(expected);
452
- const candidates = await deps.store.readCandidates(familyId);
453
- const current = candidates.find((candidate) => stagedCandidateKey(candidate) === key);
454
- if (current === undefined || current.revision !== expected.revision) {
455
- return {
456
- status: "rejected",
457
- familyId,
458
- error: "The staged candidate changed before publication; refusing to publish.",
459
- rollback: "none",
460
- };
222
+ catch {
223
+ diagnose("A pending rebind request could not be applied.");
224
+ return undefined;
461
225
  }
226
+ }
227
+ async function boundPolicy(sessionID) {
228
+ if (disposed)
229
+ return undefined;
230
+ let familyId;
462
231
  try {
463
- await deps.store.writeMarker(familyId);
464
- await deps.store.write(familyId, current.capture);
232
+ familyId = await familyOf(sessionID);
465
233
  }
466
- catch (error) {
467
- // Remove both halves so the next read cannot expose or silently reuse a
468
- // partially published policy.
469
- await deps.store.removeMarker(familyId).catch(() => undefined);
470
- await deps.store.remove(familyId).catch(() => undefined);
471
- // Publication failure must undo our own switch unless a newer choice replaced it.
472
- const rollback = await rollbackStaged({
473
- sessionID: current.sessionID,
474
- candidate: current,
475
- readSessionModel: deps.readSessionModel,
476
- switchModel: deps.switchModel,
477
- });
478
- await deps.store.removeCandidate(familyId, key).catch(() => undefined);
479
- return {
480
- status: "rejected",
481
- familyId,
482
- candidateSelection: current.selection,
483
- rollback,
484
- error: toReason(error),
485
- };
234
+ catch {
235
+ return undefined;
486
236
  }
487
- // Consume only the winning owner.
488
- await deps.store.removeCandidate(familyId, key).catch(() => undefined);
489
- return {
490
- status: "bound",
491
- familyId,
492
- snapshotId: current.capture.snapshotId,
493
- candidateSelection: current.selection,
494
- rollback: "none",
237
+ const bound = await readBound(familyId);
238
+ if (bound === undefined)
239
+ return undefined;
240
+ const session = await deps.readSession(familyId).catch(() => undefined);
241
+ const location = {
242
+ ...deps.location,
243
+ ...(session?.locationDirectory === undefined ? {} : { directory: session.locationDirectory }),
495
244
  };
245
+ const live = await liveConfig(location.directory);
246
+ return materializeCapture({
247
+ familyId,
248
+ ...bound,
249
+ location,
250
+ ...(live === undefined ? {} : { live }),
251
+ });
496
252
  }
497
- /**
498
- * Owned generated-work gateway. Stages with the runtime's operation token and
499
- * publishes only that exact owned candidate; it never adopts a prompt
500
- * candidate.
501
- */
502
- async function doAdmitOwned(familyId, request, materialize) {
503
- const staged = await doStage(request, familyId, materialize);
504
- if (staged.status === "rejected" || staged.status === "reused")
505
- return staged;
506
- const key = stagedCandidateIdentity(request);
507
- const candidates = await deps.store.readCandidates(familyId);
508
- const candidate = candidates.find((entry) => stagedCandidateKey(entry) === key);
509
- if (candidate === undefined || candidate.operationID !== request.operationID) {
253
+ async function bind(request, materialize) {
254
+ if (disposed) {
510
255
  return {
511
256
  status: "rejected",
512
- familyId,
513
- error: "The owned operation no longer owns the staged candidate.",
257
+ familyId: request.sessionID,
258
+ error: "Snapshot service is disposed.",
514
259
  rollback: "none",
515
260
  };
516
261
  }
517
- if (candidate.inboxID !== undefined) {
518
- return {
519
- status: "rejected",
520
- familyId,
521
- error: "Refusing to publish a prompt candidate through the owned gateway.",
522
- rollback: "none",
523
- };
262
+ let familyId;
263
+ try {
264
+ familyId = await familyOf(request.sessionID);
524
265
  }
525
- return publishCandidate(familyId, candidate);
526
- }
527
- /**
528
- * First-accepted publication: among every staged prompt candidate, publish the
529
- * one whose native accepted input is earliest by durable event order, never the
530
- * most recently staged or an arbitrary map entry. Covers delayed/missed live
531
- * notifications by reconciling against the durable session log. An optional
532
- * `validate` refuses a resolved model that does not belong to the winner
533
- * without losing the winner's snapshot.
534
- */
535
- async function doAccept(familyId, request) {
536
- const existing = await deps.store.read(familyId);
537
- if (existing !== undefined)
538
- return { status: "reused", familyId, snapshotId: existing.snapshotId };
539
- const candidates = await deps.store.readCandidates(familyId);
540
- const promptCandidates = candidates.filter((candidate) => candidate.inboxID !== undefined && candidate.operationID === undefined);
541
- if (promptCandidates.length === 0) {
266
+ catch (error) {
542
267
  return {
543
268
  status: "rejected",
544
- familyId,
545
- error: "There is no staged prompt candidate to accept.",
269
+ familyId: request.sessionID,
270
+ error: String(error),
546
271
  rollback: "none",
547
272
  };
548
273
  }
549
- const sessions = [...new Set(promptCandidates.map((candidate) => candidate.sessionID))];
550
- const reconciliation = new Map();
551
- for (const sessionID of sessions) {
552
- const resolved = deps.readAcceptedInputs
553
- ? await deps.readAcceptedInputs(sessionID).catch(() => undefined)
554
- : undefined;
555
- reconciliation.set(sessionID, resolved);
556
- }
557
- // With more than one staged input, only a complete durable replay can prove
558
- // which was accepted first; an incomplete/live-only view could bind a later
559
- // policy, so fail closed until the log confirms the ordering.
560
- if (promptCandidates.length > 1) {
561
- for (const sessionID of sessions) {
562
- const resolved = reconciliation.get(sessionID);
563
- if (resolved === undefined || !resolved.complete) {
564
- return {
565
- status: "rejected",
274
+ return withFamilyLock(familyId, async () => {
275
+ const existing = await readBound(familyId);
276
+ if (existing !== undefined) {
277
+ const rebound = await consumePendingRebind({
278
+ familyId,
279
+ sessionID: request.sessionID,
280
+ directory: request.directory,
281
+ boundAt: Date.parse(existing.binding.boundAt),
282
+ });
283
+ const bound = rebound ?? existing;
284
+ const config = rebound?.config ?? (await liveConfig(request.directory));
285
+ if (config !== undefined) {
286
+ const capture = materializeCapture({
566
287
  familyId,
567
- error: "Cannot establish the first accepted input without a complete session log; refusing to bind a later policy.",
568
- rollback: "none",
569
- };
288
+ binding: bound.binding,
289
+ projection: bound.projection,
290
+ location: request.location,
291
+ live: config,
292
+ });
293
+ // Align the session to the family selection on every work item, so a
294
+ // child created before its family bound (forks) resolves the same
295
+ // qualified model instead of a stale native default.
296
+ const base = request.explicit ?? request.selectionOverride ?? primarySelection(capture);
297
+ const selection = base === undefined ? undefined : qualifySelection(capture, base);
298
+ if (selection !== undefined && request.force !== false) {
299
+ await materialize?.(capture, selection);
300
+ await deps.switchModel({ sessionID: request.sessionID, model: selection });
301
+ }
302
+ if (rebound !== undefined) {
303
+ return {
304
+ status: "bound",
305
+ familyId,
306
+ snapshotId: capture.snapshotId,
307
+ ...(selection === undefined ? {} : { selection }),
308
+ rollback: "none",
309
+ };
310
+ }
570
311
  }
312
+ return {
313
+ status: "reused",
314
+ familyId,
315
+ snapshotId: bound.binding.snapshotHash.slice(0, 16),
316
+ };
571
317
  }
572
- }
573
- const eligible = [];
574
- for (const candidate of promptCandidates) {
575
- const resolved = reconciliation.get(candidate.sessionID);
576
- const match = resolved?.inputs.find((entry) => entry.inboxID === candidate.inboxID &&
577
- (entry.itemType === "user" || entry.itemType === "synthetic"));
578
- // A log-derived match is only trusted from a complete replay; a verified
579
- // live native event may stand alone.
580
- if (match !== undefined && (match.source === "live" || resolved?.complete === true)) {
581
- eligible.push({ candidate, order: match });
318
+ const config = request.admissionConfig ?? (await liveConfig(request.directory));
319
+ if (config === undefined) {
320
+ return {
321
+ status: "rejected",
322
+ familyId,
323
+ error: "Current configuration is unavailable; family binding was not changed.",
324
+ rollback: "none",
325
+ };
326
+ }
327
+ try {
328
+ const projection = buildBehaviourProjection({
329
+ roles: config.roles,
330
+ agentRoles: config.agentRoles,
331
+ vvoc: config.vvoc,
332
+ });
333
+ const hash = behaviourContentHash(projection);
334
+ await deps.store.writeSnapshot(projection);
335
+ const binding = {
336
+ familyId,
337
+ snapshotHash: hash,
338
+ boundAt: new Date(now()).toISOString(),
339
+ };
340
+ await deps.store.writeBinding(binding);
341
+ const capture = materializeCapture({
342
+ familyId,
343
+ binding,
344
+ projection,
345
+ location: request.location,
346
+ live: config,
347
+ });
348
+ const base = request.explicit ?? request.selectionOverride ?? primarySelection(capture);
349
+ const selection = base === undefined ? undefined : qualifySelection(capture, base);
350
+ if (selection !== undefined && request.force !== false) {
351
+ await materialize?.(capture, selection);
352
+ await deps.switchModel({ sessionID: request.sessionID, model: selection });
353
+ }
354
+ return {
355
+ status: "bound",
356
+ familyId,
357
+ snapshotId: capture.snapshotId,
358
+ ...(selection === undefined ? {} : { selection }),
359
+ rollback: "none",
360
+ };
361
+ }
362
+ catch {
363
+ diagnose("Family binding could not be written; the affected family remains unbound.");
364
+ return {
365
+ status: "rejected",
366
+ familyId,
367
+ error: "Family binding could not be persisted.",
368
+ rollback: "none",
369
+ };
582
370
  }
583
- }
584
- if (eligible.length === 0) {
585
- return {
586
- status: "rejected",
587
- familyId,
588
- error: "No accepted input matching a staged workload was found.",
589
- rollback: "none",
590
- };
591
- }
592
- eligible.sort((left, right) => left.order.created - right.order.created ||
593
- (left.order.seq ?? 0) - (right.order.seq ?? 0) ||
594
- left.candidate.stagedAt - right.candidate.stagedAt ||
595
- stagedCandidateKey(left.candidate).localeCompare(stagedCandidateKey(right.candidate)));
596
- const winner = eligible[0];
597
- if (request.validate !== undefined && !request.validate(winner.candidate.selection)) {
598
- return {
599
- status: "rejected",
600
- familyId,
601
- candidateSelection: winner.candidate.selection,
602
- error: "The resolved model does not match the first accepted candidate; refusing to publish.",
603
- rollback: "none",
604
- };
605
- }
606
- return publishCandidate(familyId, winner.candidate);
607
- }
608
- async function stageWithFamily(request, materialize) {
609
- const familyId = await familyOf(request.sessionID);
610
- // Dedupe by exact input identity (session + inboxID/operationID/workload):
611
- // concurrent distinct prompts must not share one staging promise, while a
612
- // repeated identical input shares its first attempt.
613
- const sessionKey = `${familyId}\u0000${stagedCandidateIdentity(request)}`;
614
- const pending = inFlightSessions.get(sessionKey);
615
- if (pending !== undefined)
616
- return pending;
617
- const promise = withFamilyLock(familyId, () => doStage(request, familyId, materialize)).finally(() => {
618
- inFlightSessions.delete(sessionKey);
619
371
  });
620
- inFlightSessions.set(sessionKey, promise);
621
- return promise;
622
372
  }
623
- const stage = (request, materialize) => {
624
- if (disposed) {
625
- return Promise.resolve({
626
- status: "rejected",
627
- familyId: request.sessionID,
628
- error: "The snapshot service was released.",
629
- rollback: "none",
630
- });
631
- }
632
- return stageWithFamily(request, materialize);
633
- };
634
- const accept = (request) => {
635
- if (disposed) {
636
- return Promise.resolve({
637
- status: "rejected",
638
- familyId: request.sessionID,
639
- error: "The snapshot service was released.",
640
- rollback: "none",
641
- });
642
- }
643
- return (async () => {
644
- const familyId = await familyOf(request.sessionID);
645
- const key = `${familyId}\u0000${request.sessionID}\u0000${request.inboxID ?? ""}`;
646
- const pending = inFlightAccepts.get(key);
647
- if (pending !== undefined)
648
- return pending;
649
- const promise = withFamilyLock(familyId, () => doAccept(familyId, request)).finally(() => {
650
- inFlightAccepts.delete(key);
651
- });
652
- inFlightAccepts.set(key, promise);
653
- return promise;
654
- })();
655
- };
656
- const admitOwned = (request, materialize) => {
657
- if (disposed) {
658
- return Promise.resolve({
659
- status: "rejected",
660
- familyId: request.sessionID,
661
- error: "The snapshot service was released.",
662
- rollback: "none",
663
- });
373
+ async function collectGarbage() {
374
+ try {
375
+ const counts = await deps.store.countBindings();
376
+ for (const hash of await deps.store.listSnapshots()) {
377
+ if ((counts.get(hash) ?? 0) === 0)
378
+ await deps.store.removeSnapshot(hash);
379
+ }
664
380
  }
665
- if (request.operationID.length === 0) {
666
- return Promise.resolve({
667
- status: "rejected",
668
- familyId: request.sessionID,
669
- error: "An owned admission requires a non-empty operation token.",
670
- rollback: "none",
671
- });
381
+ catch {
382
+ diagnose("Family binding cleanup was deferred after a store failure.");
672
383
  }
673
- return (async () => {
674
- const familyId = await familyOf(request.sessionID);
675
- const key = `${familyId}\u0000${request.sessionID}\u0000${request.operationID}`;
676
- const pending = inFlightOwned.get(key);
677
- if (pending !== undefined)
678
- return pending;
679
- const promise = withFamilyLock(familyId, () => doAdmitOwned(familyId, request, materialize)).finally(() => {
680
- inFlightOwned.delete(key);
681
- });
682
- inFlightOwned.set(key, promise);
683
- return promise;
684
- })();
685
- };
384
+ }
686
385
  const auxiliary = createAuxiliaryService({
687
386
  familyOf,
688
- policy,
387
+ policy: boundPolicy,
689
388
  session: deps.auxiliarySession,
690
389
  });
691
- return {
390
+ const service = {
692
391
  familyOf,
693
- policy,
694
- configFor: policy,
695
- captures: async () => (disposed ? [] : loadCaptures()),
696
- variants: async (familyId) => {
392
+ policy: boundPolicy,
393
+ configFor: boundPolicy,
394
+ captures: async () => {
697
395
  if (disposed)
698
396
  return [];
699
- const captures = (await loadCaptures()).filter((capture) => familyId === undefined || capture.familyId === familyId);
397
+ const captures = [];
398
+ for (const binding of await deps.store.listBindings().catch(() => [])) {
399
+ const bound = await readBound(binding.familyId);
400
+ if (bound === undefined)
401
+ continue;
402
+ const live = await liveConfig(deps.location.directory);
403
+ captures.push(materializeCapture({
404
+ familyId: binding.familyId,
405
+ ...bound,
406
+ location: deps.location,
407
+ ...(live === undefined ? {} : { live }),
408
+ }));
409
+ }
410
+ return captures;
411
+ },
412
+ variants: async (familyId) => {
413
+ const captures = await (async () => {
414
+ if (familyId === undefined)
415
+ return await service.captures();
416
+ const capture = await boundPolicy(familyId);
417
+ return capture === undefined ? [] : [capture];
418
+ })();
700
419
  return captures.flatMap((capture) => capture.variants.map((variant) => ({
701
420
  providerID: variant.providerID,
702
421
  modelID: variant.modelID,
703
422
  variant,
704
423
  })));
705
424
  },
706
- stage,
707
- accept,
708
- admitOwned,
709
- hasStaged: async (familyId) => (await deps.store.readCandidates(familyId)).length > 0,
425
+ // Plugins still call this after their config lookup. Binding is now performed
426
+ // by the prompt/owned-work gateway, so this compatibility shim never stages.
427
+ accept: async (input) => {
428
+ const capture = await boundPolicy(input.sessionID);
429
+ if (capture !== undefined) {
430
+ return { status: "reused", familyId: capture.familyId, snapshotId: capture.snapshotId };
431
+ }
432
+ return {
433
+ status: "rejected",
434
+ familyId: input.sessionID,
435
+ error: "No family binding exists for this workload.",
436
+ rollback: "none",
437
+ };
438
+ },
439
+ admitOwned: async (request, materialize) => {
440
+ return bind(request, materialize);
441
+ },
442
+ rebind: async ({ directory, location, familyId }) => {
443
+ if (disposed)
444
+ return [];
445
+ // FileBindingStore is project-scoped; reject a caller that tries to cross it.
446
+ if (location.projectID !== deps.location.projectID)
447
+ return [];
448
+ const config = await liveConfig(directory);
449
+ if (config === undefined)
450
+ return [];
451
+ let projection;
452
+ try {
453
+ projection = buildBehaviourProjection({
454
+ roles: config.roles,
455
+ agentRoles: config.agentRoles,
456
+ vvoc: config.vvoc,
457
+ });
458
+ }
459
+ catch {
460
+ diagnose("Current configuration could not be projected for rebinding.");
461
+ return [];
462
+ }
463
+ try {
464
+ const hash = await deps.store.writeSnapshot(projection);
465
+ const matching = (await deps.store.listBindings()).filter((binding) => familyId === undefined || binding.familyId === familyId);
466
+ await Promise.all(matching.map((binding) => withFamilyLock(binding.familyId, () => deps.store.writeBinding({
467
+ familyId: binding.familyId,
468
+ snapshotHash: hash,
469
+ boundAt: new Date(now()).toISOString(),
470
+ }))));
471
+ await collectGarbage();
472
+ return matching.map((binding) => binding.familyId);
473
+ }
474
+ catch {
475
+ diagnose("Family rebinding could not be completed.");
476
+ return [];
477
+ }
478
+ },
479
+ removeFamily: async (familyId) => {
480
+ if (disposed)
481
+ return;
482
+ const resolvedFamilyId = sessionFamilies.get(familyId) ?? familyId;
483
+ await withFamilyLock(resolvedFamilyId, async () => {
484
+ try {
485
+ await deps.store.removeBinding(resolvedFamilyId);
486
+ for (const [sessionID, knownFamilyId] of sessionFamilies) {
487
+ if (knownFamilyId === resolvedFamilyId)
488
+ sessionFamilies.delete(sessionID);
489
+ }
490
+ }
491
+ catch {
492
+ diagnose("Family binding deletion was deferred after a store failure.");
493
+ return;
494
+ }
495
+ await collectGarbage();
496
+ });
497
+ },
710
498
  auxiliary,
711
499
  dispose() {
712
500
  disposed = true;
713
- inFlightSessions.clear();
714
- inFlightAccepts.clear();
715
- inFlightOwned.clear();
716
501
  familyLocks.clear();
502
+ sessionFamilies.clear();
717
503
  },
718
504
  };
505
+ return service;
719
506
  }
720
- // END_BLOCK_ADMISSION
507
+ // END_BLOCK_BINDING_LIFECYCLE
721
508
  //# sourceMappingURL=snapshots.js.map