@osovv/vv-opencode 2.0.0 → 2.1.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.
- package/CHANGELOG.md +51 -0
- package/README.md +87 -85
- package/dist/commands/completion.js +0 -1
- package/dist/commands/completion.js.map +1 -1
- package/dist/commands/doctor.js +6 -9
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/init.d.ts +2 -1
- package/dist/commands/init.js +7 -12
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/install.d.ts +4 -0
- package/dist/commands/install.js +40 -37
- package/dist/commands/install.js.map +1 -1
- package/dist/commands/launch.d.ts +2 -1
- package/dist/commands/launch.js +18 -14
- package/dist/commands/launch.js.map +1 -1
- package/dist/commands/patch-provider.d.ts +225 -307
- package/dist/commands/patch-provider.js +92 -296
- package/dist/commands/patch-provider.js.map +1 -1
- package/dist/commands/status.js +7 -10
- package/dist/commands/status.js.map +1 -1
- package/dist/commands/sync.d.ts +4 -0
- package/dist/commands/sync.js +38 -35
- package/dist/commands/sync.js.map +1 -1
- package/dist/index.d.ts +25 -5
- package/dist/index.js +73 -34
- package/dist/index.js.map +1 -1
- package/dist/lib/agent-tool-catalog.d.ts +1 -1
- package/dist/lib/agent-tool-catalog.js +3 -6
- package/dist/lib/agent-tool-catalog.js.map +1 -1
- package/dist/lib/agent-tool-contract.d.ts +22 -13
- package/dist/lib/agent-tool-contract.js +20 -20
- package/dist/lib/agent-tool-contract.js.map +1 -1
- package/dist/lib/analytics/types.d.ts +7 -1
- package/dist/lib/analytics/types.js +2 -2
- package/dist/lib/analytics/types.js.map +1 -1
- package/dist/lib/config-layers.d.ts +28 -6
- package/dist/lib/config-layers.js +268 -73
- package/dist/lib/config-layers.js.map +1 -1
- package/dist/lib/managed-agents.d.ts +24 -2
- package/dist/lib/managed-agents.js +45 -15
- package/dist/lib/managed-agents.js.map +1 -1
- package/dist/lib/model-roles.d.ts +5 -0
- package/dist/lib/model-roles.js +22 -1
- package/dist/lib/model-roles.js.map +1 -1
- package/dist/lib/opencode/agent-registrations.d.ts +4 -4
- package/dist/lib/opencode/agent-registrations.js +386 -197
- package/dist/lib/opencode/agent-registrations.js.map +1 -1
- package/dist/lib/opencode/inspection.d.ts +13 -13
- package/dist/lib/opencode/inspection.js +69 -106
- package/dist/lib/opencode/inspection.js.map +1 -1
- package/dist/lib/opencode/model-overrides.d.ts +2 -2
- package/dist/lib/opencode/model-overrides.js +192 -47
- package/dist/lib/opencode/model-overrides.js.map +1 -1
- package/dist/lib/opencode/paths.d.ts +6 -2
- package/dist/lib/opencode/paths.js +12 -11
- package/dist/lib/opencode/paths.js.map +1 -1
- package/dist/lib/opencode/plugin-registration.d.ts +10 -11
- package/dist/lib/opencode/plugin-registration.js +76 -138
- package/dist/lib/opencode/plugin-registration.js.map +1 -1
- package/dist/lib/opencode/shared-utils.d.ts +47 -3
- package/dist/lib/opencode/shared-utils.js +346 -15
- package/dist/lib/opencode/shared-utils.js.map +1 -1
- package/dist/lib/opencode.d.ts +5 -6
- package/dist/lib/opencode.js +10 -10
- package/dist/lib/opencode.js.map +1 -1
- package/dist/lib/vvoc-config.js +4 -4
- package/dist/lib/vvoc-config.js.map +1 -1
- package/dist/lib/vvoc-paths.d.ts +7 -0
- package/dist/lib/vvoc-paths.js +15 -1
- package/dist/lib/vvoc-paths.js.map +1 -1
- package/dist/lib/vvoc-preset-registry.d.ts +38 -50
- package/dist/lib/vvoc-preset-registry.js +38 -48
- package/dist/lib/vvoc-preset-registry.js.map +1 -1
- package/dist/plugins/analytics/index.d.ts +20 -14
- package/dist/plugins/analytics/index.js +281 -133
- package/dist/plugins/analytics/index.js.map +1 -1
- package/dist/plugins/guardian/index.d.ts +63 -42
- package/dist/plugins/guardian/index.js +217 -759
- package/dist/plugins/guardian/index.js.map +1 -1
- package/dist/plugins/hashline-edit/index.d.ts +145 -31
- package/dist/plugins/hashline-edit/index.js +679 -244
- package/dist/plugins/hashline-edit/index.js.map +1 -1
- package/dist/plugins/hashline-edit/schemas.d.ts +1 -1
- package/dist/plugins/hashline-edit/schemas.js +3 -3
- package/dist/plugins/hashline-edit/schemas.js.map +1 -1
- package/dist/plugins/model-roles/index.d.ts +18 -4
- package/dist/plugins/model-roles/index.js +44 -181
- package/dist/plugins/model-roles/index.js.map +1 -1
- package/dist/plugins/peak-hours/index.d.ts +23 -22
- package/dist/plugins/peak-hours/index.js +210 -178
- package/dist/plugins/peak-hours/index.js.map +1 -1
- package/dist/plugins/secrets-redaction/deep.js +35 -51
- package/dist/plugins/secrets-redaction/deep.js.map +1 -1
- package/dist/plugins/secrets-redaction/index.d.ts +96 -8
- package/dist/plugins/secrets-redaction/index.js +290 -102
- package/dist/plugins/secrets-redaction/index.js.map +1 -1
- package/dist/plugins/secrets-redaction/session.d.ts +9 -0
- package/dist/plugins/secrets-redaction/session.js +21 -4
- package/dist/plugins/secrets-redaction/session.js.map +1 -1
- package/dist/plugins/secrets-redaction/stream.d.ts +92 -0
- package/dist/plugins/secrets-redaction/stream.js +772 -0
- package/dist/plugins/secrets-redaction/stream.js.map +1 -0
- package/dist/plugins/spec-guard/index.d.ts +49 -18
- package/dist/plugins/spec-guard/index.js +231 -129
- package/dist/plugins/spec-guard/index.js.map +1 -1
- package/dist/plugins/system-context-injection/index.d.ts +10 -4
- package/dist/plugins/system-context-injection/index.js +271 -78
- package/dist/plugins/system-context-injection/index.js.map +1 -1
- package/dist/plugins/tool-history-compaction/index.d.ts +26 -4
- package/dist/plugins/tool-history-compaction/index.js +170 -32
- package/dist/plugins/tool-history-compaction/index.js.map +1 -1
- package/dist/plugins/tool-history-compaction/transform.d.ts +47 -16
- package/dist/plugins/tool-history-compaction/transform.js +173 -55
- package/dist/plugins/tool-history-compaction/transform.js.map +1 -1
- package/dist/plugins/web-tools/fetch-service.d.ts +51 -13
- package/dist/plugins/web-tools/fetch-service.js +106 -75
- package/dist/plugins/web-tools/fetch-service.js.map +1 -1
- package/dist/plugins/web-tools/index.d.ts +58 -16
- package/dist/plugins/web-tools/index.js +202 -91
- package/dist/plugins/web-tools/index.js.map +1 -1
- package/dist/plugins/web-tools/media-loader.d.ts +3 -3
- package/dist/plugins/web-tools/media-loader.js +3 -3
- package/dist/plugins/web-tools/media-loader.js.map +1 -1
- package/dist/plugins/web-tools/providers/native-fetch.d.ts +2 -2
- package/dist/plugins/web-tools/providers/native-fetch.js +1 -1
- package/dist/plugins/web-tools/providers/native-fetch.js.map +1 -1
- package/dist/plugins/web-tools/providers/spider.d.ts +2 -2
- package/dist/plugins/web-tools/providers/spider.js +1 -1
- package/dist/plugins/web-tools/providers/spider.js.map +1 -1
- package/dist/plugins/web-tools/providers/zai.d.ts +2 -2
- package/dist/plugins/web-tools/providers/zai.js +1 -1
- package/dist/plugins/web-tools/providers/zai.js.map +1 -1
- package/dist/plugins/web-tools/schemas.d.ts +1 -1
- package/dist/plugins/web-tools/schemas.js +3 -3
- package/dist/plugins/web-tools/schemas.js.map +1 -1
- package/dist/plugins/web-tools/search-service.d.ts +81 -12
- package/dist/plugins/web-tools/search-service.js +104 -57
- package/dist/plugins/web-tools/search-service.js.map +1 -1
- package/dist/plugins/workflow/authorization.d.ts +44 -10
- package/dist/plugins/workflow/authorization.js +113 -73
- package/dist/plugins/workflow/authorization.js.map +1 -1
- package/dist/plugins/workflow/cancellation.d.ts +86 -0
- package/dist/plugins/workflow/cancellation.js +202 -0
- package/dist/plugins/workflow/cancellation.js.map +1 -0
- package/dist/plugins/workflow/checkpoints.d.ts +7 -1
- package/dist/plugins/workflow/checkpoints.js +141 -21
- package/dist/plugins/workflow/checkpoints.js.map +1 -1
- package/dist/plugins/workflow/delegated.d.ts +14 -0
- package/dist/plugins/workflow/delegated.js +6 -5
- package/dist/plugins/workflow/delegated.js.map +1 -1
- package/dist/plugins/workflow/host.d.ts +81 -0
- package/dist/plugins/workflow/host.js +189 -0
- package/dist/plugins/workflow/host.js.map +1 -0
- package/dist/plugins/workflow/index.d.ts +69 -4
- package/dist/plugins/workflow/index.js +1391 -1026
- package/dist/plugins/workflow/index.js.map +1 -1
- package/dist/plugins/workflow/recovery.d.ts +3 -5
- package/dist/plugins/workflow/recovery.js +18 -33
- package/dist/plugins/workflow/recovery.js.map +1 -1
- package/dist/plugins/workflow/repair.d.ts +31 -5
- package/dist/plugins/workflow/repair.js +116 -48
- package/dist/plugins/workflow/repair.js.map +1 -1
- package/dist/plugins/workflow/results.d.ts +31 -31
- package/dist/plugins/workflow/results.js +4 -4
- package/dist/plugins/workflow/results.js.map +1 -1
- package/dist/plugins/workflow/schemas.d.ts +3 -3
- package/dist/plugins/workflow/schemas.js +5 -5
- package/dist/plugins/workflow/schemas.js.map +1 -1
- package/dist/plugins/workflow/system-instruction.md +4 -0
- package/dist/plugins/workflow/tooling.d.ts +6 -0
- package/dist/plugins/workflow/tooling.js +3 -1
- package/dist/plugins/workflow/tooling.js.map +1 -1
- package/dist/runtime/auxiliary.d.ts +13 -0
- package/dist/runtime/auxiliary.js +108 -0
- package/dist/runtime/auxiliary.js.map +1 -0
- package/dist/runtime/client.d.ts +88 -0
- package/dist/runtime/client.js +174 -0
- package/dist/runtime/client.js.map +1 -0
- package/dist/runtime/context-inspection-contract.d.ts +397 -0
- package/dist/runtime/context-inspection-contract.js +622 -0
- package/dist/runtime/context-inspection-contract.js.map +1 -0
- package/dist/runtime/context-inspection.d.ts +52 -0
- package/dist/runtime/context-inspection.js +324 -0
- package/dist/runtime/context-inspection.js.map +1 -0
- package/dist/runtime/context.d.ts +192 -0
- package/dist/runtime/context.js +1246 -0
- package/dist/runtime/context.js.map +1 -0
- package/dist/runtime/coordination.d.ts +40 -0
- package/dist/runtime/coordination.js +87 -0
- package/dist/runtime/coordination.js.map +1 -0
- package/dist/runtime/model-registry.d.ts +34 -0
- package/dist/runtime/model-registry.js +227 -0
- package/dist/runtime/model-registry.js.map +1 -0
- package/dist/runtime/permissions.d.ts +20 -0
- package/dist/runtime/permissions.js +250 -0
- package/dist/runtime/permissions.js.map +1 -0
- package/dist/runtime/snapshot-config.d.ts +80 -0
- package/dist/runtime/snapshot-config.js +268 -0
- package/dist/runtime/snapshot-config.js.map +1 -0
- package/dist/runtime/snapshot-store.d.ts +25 -0
- package/dist/runtime/snapshot-store.js +519 -0
- package/dist/runtime/snapshot-store.js.map +1 -0
- package/dist/runtime/snapshots.d.ts +59 -0
- package/dist/runtime/snapshots.js +721 -0
- package/dist/runtime/snapshots.js.map +1 -0
- package/dist/runtime/types.d.ts +713 -0
- package/dist/runtime/types.js +190 -0
- package/dist/runtime/types.js.map +1 -0
- package/dist/tui/analytics/indicator.d.ts +25 -26
- package/dist/tui/analytics/indicator.js +66 -74
- package/dist/tui/analytics/indicator.js.map +1 -1
- package/dist/tui/branding/footer.d.ts +7 -12
- package/dist/tui/branding/footer.js +16 -24
- package/dist/tui/branding/footer.js.map +1 -1
- package/dist/tui/context/analyze.d.ts +20 -9
- package/dist/tui/context/analyze.js +295 -257
- package/dist/tui/context/analyze.js.map +1 -1
- package/dist/tui/context/collect.d.ts +29 -3
- package/dist/tui/context/collect.js +450 -66
- package/dist/tui/context/collect.js.map +1 -1
- package/dist/tui/context/plugin.d.ts +21 -7
- package/dist/tui/context/plugin.js +65 -70
- package/dist/tui/context/plugin.js.map +1 -1
- package/dist/tui/context/types.d.ts +174 -43
- package/dist/tui/context/types.js +25 -19
- package/dist/tui/context/types.js.map +1 -1
- package/dist/tui/context/view.d.ts +33 -7
- package/dist/tui/context/view.js +136 -81
- package/dist/tui/context/view.js.map +1 -1
- package/dist/tui/peak-hours/banner.d.ts +13 -11
- package/dist/tui/peak-hours/banner.js +48 -80
- package/dist/tui/peak-hours/banner.js.map +1 -1
- package/dist/tui/policy.d.ts +69 -0
- package/dist/tui/policy.js +169 -0
- package/dist/tui/policy.js.map +1 -0
- package/dist/tui.d.ts +3 -8
- package/dist/tui.js +72 -68
- package/dist/tui.js.map +1 -1
- package/package.json +19 -15
- package/schemas/vvoc/v3.json +1 -1
- package/server.js +3 -5
- package/templates/agents/enhancer.md +10 -5
- package/templates/agents/guardian.md +10 -4
- package/templates/agents/investigator.md +4 -2
- package/templates/agents/vv-code-reviewer.md +4 -2
- package/templates/agents/vv-spec-reviewer.md +4 -2
- package/templates/skills/vv-execute/references/tool-contracts.md +1 -1
- package/tui.js +3 -5
- package/dist/plugins/analytics/v2.d.ts +0 -21
- package/dist/plugins/analytics/v2.js +0 -133
- package/dist/plugins/analytics/v2.js.map +0 -1
- package/dist/plugins/guardian/v2.d.ts +0 -13
- package/dist/plugins/guardian/v2.js +0 -161
- package/dist/plugins/guardian/v2.js.map +0 -1
- package/dist/plugins/hashline-edit/v2.d.ts +0 -12
- package/dist/plugins/hashline-edit/v2.js +0 -145
- package/dist/plugins/hashline-edit/v2.js.map +0 -1
- package/dist/plugins/model-roles/v2.d.ts +0 -24
- package/dist/plugins/model-roles/v2.js +0 -274
- package/dist/plugins/model-roles/v2.js.map +0 -1
- package/dist/plugins/peak-hours/v2.d.ts +0 -12
- package/dist/plugins/peak-hours/v2.js +0 -95
- package/dist/plugins/peak-hours/v2.js.map +0 -1
- package/dist/plugins/secrets-redaction/v2.d.ts +0 -14
- package/dist/plugins/secrets-redaction/v2.js +0 -100
- package/dist/plugins/secrets-redaction/v2.js.map +0 -1
- package/dist/plugins/spec-guard/v2.d.ts +0 -12
- package/dist/plugins/spec-guard/v2.js +0 -139
- package/dist/plugins/spec-guard/v2.js.map +0 -1
- package/dist/plugins/system-context-injection/agent-contexts.d.ts +0 -5
- package/dist/plugins/system-context-injection/agent-contexts.js +0 -164
- package/dist/plugins/system-context-injection/agent-contexts.js.map +0 -1
- package/dist/plugins/system-context-injection/v2.d.ts +0 -13
- package/dist/plugins/system-context-injection/v2.js +0 -60
- package/dist/plugins/system-context-injection/v2.js.map +0 -1
- package/dist/plugins/tool-history-compaction/v2.d.ts +0 -11
- package/dist/plugins/tool-history-compaction/v2.js +0 -56
- package/dist/plugins/tool-history-compaction/v2.js.map +0 -1
- package/dist/plugins/v2-runtime/config-watcher.d.ts +0 -26
- package/dist/plugins/v2-runtime/config-watcher.js +0 -111
- package/dist/plugins/v2-runtime/config-watcher.js.map +0 -1
- package/dist/plugins/v2-runtime/index.d.ts +0 -50
- package/dist/plugins/v2-runtime/index.js +0 -114
- package/dist/plugins/v2-runtime/index.js.map +0 -1
- package/dist/plugins/v2-runtime/location-config.d.ts +0 -51
- package/dist/plugins/v2-runtime/location-config.js +0 -91
- package/dist/plugins/v2-runtime/location-config.js.map +0 -1
- package/dist/plugins/v2-runtime/setup.d.ts +0 -48
- package/dist/plugins/v2-runtime/setup.js +0 -174
- package/dist/plugins/v2-runtime/setup.js.map +0 -1
- package/dist/plugins/web-tools/v2.d.ts +0 -11
- package/dist/plugins/web-tools/v2.js +0 -99
- package/dist/plugins/web-tools/v2.js.map +0 -1
- package/dist/plugins/workflow/v2.d.ts +0 -58
- package/dist/plugins/workflow/v2.js +0 -181
- package/dist/plugins/workflow/v2.js.map +0 -1
|
@@ -0,0 +1,1246 @@
|
|
|
1
|
+
// FILE: src/runtime/context.ts
|
|
2
|
+
// VERSION: 1.1.0
|
|
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.
|
|
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
|
+
// LINKS: [M-NATIVE-RUNTIME, V-M-NATIVE-RUNTIME]
|
|
8
|
+
// ROLE: RUNTIME
|
|
9
|
+
// MAP_MODE: EXPORTS
|
|
10
|
+
// END_MODULE_CONTRACT
|
|
11
|
+
//
|
|
12
|
+
// START_MODULE_MAP
|
|
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.
|
|
15
|
+
// 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.
|
|
18
|
+
// NativeRegistration - Releasable native registration handle.
|
|
19
|
+
// NativeForkClient - Structural full client for forks, parented imports and durable session-log reconciliation.
|
|
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.
|
|
22
|
+
// acquireNativeSnapshotRuntime - Acquire the shared native snapshot runtime for an actual Plugin.Context.
|
|
23
|
+
// rebuildAgentBindings - Recompute agent bindings from a freshly read policy without trusting a cached vvoc-applied selection.
|
|
24
|
+
// END_MODULE_MAP
|
|
25
|
+
//
|
|
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.]
|
|
29
|
+
// END_CHANGE_SUMMARY
|
|
30
|
+
import { randomBytes } from "node:crypto";
|
|
31
|
+
import { loadEffectiveVvocConfig, readRawOpenCodeModelIntent } from "../lib/config-layers.js";
|
|
32
|
+
import { getBuiltInRoleBindings, isRoleReference, parseModelSelectionWithVariant, ROLE_REFERENCE_PREFIX, } from "../lib/model-roles.js";
|
|
33
|
+
import { acquireNativeClient, nativeRuntimeDeps } from "./client.js";
|
|
34
|
+
import { coordinateHost } from "./coordination.js";
|
|
35
|
+
import { applyAgentPolicies, applyVariantRegistrations, buildVariantRegistrations, mergeModelBodyOverlay, mergeModelHeadersOverlay, primarySelection, qualifySelection, } from "./model-registry.js";
|
|
36
|
+
import { createPermissionService } from "./permissions.js";
|
|
37
|
+
import { canonicalModelVariant, classifyInitialSelection, decodeInboxEnqueuedEvent, decodeModelSelectedEvent, decodeSessionCreatedEvent, effectiveRuntimeConfig, isAcceptedWorkloadEvent, isConfigUpdateEvent, normalizeModelSelection, parseRoleSelections, } from "./snapshot-config.js";
|
|
38
|
+
import { registerContextInspectionRpc } from "./context-inspection.js";
|
|
39
|
+
import { createFileSnapshotStore } from "./snapshot-store.js";
|
|
40
|
+
import { createSnapshotService } from "./snapshots.js";
|
|
41
|
+
import { RuntimeDisposedError, SnapshotAdmissionError, SnapshotUnboundError, decodeAuxiliaryMetadata, decodeImportedSessionID, runtimeIdentity, } from "./types.js";
|
|
42
|
+
// START_BLOCK_RUNTIME_REGISTRY
|
|
43
|
+
const runtimes = new Map();
|
|
44
|
+
const contextIds = new WeakMap();
|
|
45
|
+
const depsIds = new WeakMap();
|
|
46
|
+
let nextInstance = 1;
|
|
47
|
+
function objectId(ids, value) {
|
|
48
|
+
const existing = ids.get(value);
|
|
49
|
+
if (existing !== undefined)
|
|
50
|
+
return existing;
|
|
51
|
+
const id = nextInstance;
|
|
52
|
+
nextInstance += 1;
|
|
53
|
+
ids.set(value, id);
|
|
54
|
+
return id;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Registry key scopes sharing to one dependency instance and one exact plugin
|
|
58
|
+
* context object. Same location is not the same plugin instance, so distinct
|
|
59
|
+
* contexts never reuse another context's registrations; root aggregation shares
|
|
60
|
+
* naturally because it passes the same context object.
|
|
61
|
+
*/
|
|
62
|
+
function registryKey(context, deps) {
|
|
63
|
+
return `${objectId(contextIds, context)}:${objectId(depsIds, deps)}`;
|
|
64
|
+
}
|
|
65
|
+
// END_BLOCK_RUNTIME_REGISTRY
|
|
66
|
+
// START_BLOCK_MANAGED_RUNTIME
|
|
67
|
+
class ManagedNativeRuntime {
|
|
68
|
+
context;
|
|
69
|
+
location;
|
|
70
|
+
identity;
|
|
71
|
+
instanceId;
|
|
72
|
+
permissions;
|
|
73
|
+
deps;
|
|
74
|
+
key;
|
|
75
|
+
lifetime = new AbortController();
|
|
76
|
+
refs = 0;
|
|
77
|
+
disposed = false;
|
|
78
|
+
clientPromise;
|
|
79
|
+
clientHandle;
|
|
80
|
+
constructor(context, deps, identity, key) {
|
|
81
|
+
this.context = context;
|
|
82
|
+
this.location = context.location;
|
|
83
|
+
this.identity = identity;
|
|
84
|
+
this.instanceId = randomBytes(16).toString("hex");
|
|
85
|
+
this.deps = deps;
|
|
86
|
+
this.key = key;
|
|
87
|
+
this.permissions = createPermissionService(() => this.client(), this.lifetime.signal);
|
|
88
|
+
}
|
|
89
|
+
client() {
|
|
90
|
+
if (this.disposed)
|
|
91
|
+
return Promise.reject(new RuntimeDisposedError());
|
|
92
|
+
this.clientPromise ??= this.acquireClient();
|
|
93
|
+
return this.clientPromise;
|
|
94
|
+
}
|
|
95
|
+
async acquireClient() {
|
|
96
|
+
try {
|
|
97
|
+
const handle = await acquireNativeClient({
|
|
98
|
+
context: this.context,
|
|
99
|
+
deps: this.deps,
|
|
100
|
+
instanceId: this.instanceId,
|
|
101
|
+
lifetimeSignal: this.lifetime.signal,
|
|
102
|
+
});
|
|
103
|
+
if (this.disposed) {
|
|
104
|
+
await handle.dispose();
|
|
105
|
+
throw new RuntimeDisposedError();
|
|
106
|
+
}
|
|
107
|
+
this.clientHandle = handle;
|
|
108
|
+
return handle.client;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
this.clientPromise = undefined;
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
retainRef() {
|
|
116
|
+
if (this.disposed)
|
|
117
|
+
throw new RuntimeDisposedError();
|
|
118
|
+
this.refs += 1;
|
|
119
|
+
}
|
|
120
|
+
async releaseRef() {
|
|
121
|
+
if (this.disposed)
|
|
122
|
+
return;
|
|
123
|
+
this.refs -= 1;
|
|
124
|
+
if (this.refs <= 0)
|
|
125
|
+
await this.dispose();
|
|
126
|
+
}
|
|
127
|
+
async dispose() {
|
|
128
|
+
if (this.disposed)
|
|
129
|
+
return;
|
|
130
|
+
this.disposed = true;
|
|
131
|
+
runtimes.delete(this.key);
|
|
132
|
+
// Abort in-flight permission waits and the challenge before releasing registrations.
|
|
133
|
+
this.lifetime.abort();
|
|
134
|
+
const handle = this.clientHandle;
|
|
135
|
+
this.clientHandle = undefined;
|
|
136
|
+
this.clientPromise = undefined;
|
|
137
|
+
if (handle !== undefined)
|
|
138
|
+
await handle.dispose();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export function acquireRuntime(context, deps) {
|
|
142
|
+
// The no-dependency overload pins Client to the full native client; the cast bridges only that default.
|
|
143
|
+
const resolvedDeps = (deps ?? nativeRuntimeDeps);
|
|
144
|
+
const key = registryKey(context, resolvedDeps);
|
|
145
|
+
let existing = runtimes.get(key);
|
|
146
|
+
if (existing === undefined) {
|
|
147
|
+
existing = new ManagedNativeRuntime(context, resolvedDeps, runtimeIdentity(context.location), key);
|
|
148
|
+
runtimes.set(key, existing);
|
|
149
|
+
}
|
|
150
|
+
const runtime = existing;
|
|
151
|
+
runtime.retainRef();
|
|
152
|
+
let released = false;
|
|
153
|
+
const lease = {
|
|
154
|
+
// Same key implies the same context object and dependency instance, so the stored runtime matches the requested client type.
|
|
155
|
+
runtime: runtime,
|
|
156
|
+
release: async () => {
|
|
157
|
+
if (released)
|
|
158
|
+
return;
|
|
159
|
+
released = true;
|
|
160
|
+
await runtime.releaseRef();
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
return lease;
|
|
164
|
+
}
|
|
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
|
+
const pluginContextSeam = true;
|
|
199
|
+
void pluginContextSeam;
|
|
200
|
+
const nativeRuntimes = new Map();
|
|
201
|
+
function toSelection(ref) {
|
|
202
|
+
if (ref === undefined || ref === null)
|
|
203
|
+
return undefined;
|
|
204
|
+
if (typeof ref !== "object")
|
|
205
|
+
return undefined;
|
|
206
|
+
const record = ref;
|
|
207
|
+
if (record.id === undefined || record.providerID === undefined)
|
|
208
|
+
return undefined;
|
|
209
|
+
return normalizeModelSelection({
|
|
210
|
+
providerID: String(record.providerID),
|
|
211
|
+
modelID: String(record.id),
|
|
212
|
+
...(record.variant === undefined ? {} : { variant: String(record.variant) }),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
function sameModelSelection(left, right) {
|
|
216
|
+
if (left === undefined || right === undefined)
|
|
217
|
+
return left === right;
|
|
218
|
+
return (left.providerID === right.providerID &&
|
|
219
|
+
left.modelID === right.modelID &&
|
|
220
|
+
canonicalModelVariant(left.variant) === canonicalModelVariant(right.variant));
|
|
221
|
+
}
|
|
222
|
+
function toRef(selection) {
|
|
223
|
+
return {
|
|
224
|
+
id: selection.modelID,
|
|
225
|
+
providerID: selection.providerID,
|
|
226
|
+
...(selection.variant === undefined ? {} : { variant: selection.variant }),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function cloneOverlay(value) {
|
|
230
|
+
return value === undefined ? undefined : { ...value };
|
|
231
|
+
}
|
|
232
|
+
function wantedModelKeys(config) {
|
|
233
|
+
const keys = new Set();
|
|
234
|
+
for (const selection of Object.values(parseRoleSelections(config.roles))) {
|
|
235
|
+
keys.add(`${selection.providerID}/${selection.modelID}`);
|
|
236
|
+
}
|
|
237
|
+
if (config.rootDefault !== undefined) {
|
|
238
|
+
keys.add(`${config.rootDefault.providerID}/${config.rootDefault.modelID}`);
|
|
239
|
+
}
|
|
240
|
+
if (config.nativeDefault !== undefined) {
|
|
241
|
+
keys.add(`${config.nativeDefault.providerID}/${config.nativeDefault.modelID}`);
|
|
242
|
+
}
|
|
243
|
+
// Custom/literal agent models outside the role map still need their overlay captured.
|
|
244
|
+
for (const binding of config.agentBindings ?? []) {
|
|
245
|
+
if (binding.selection !== undefined) {
|
|
246
|
+
keys.add(`${binding.selection.providerID}/${binding.selection.modelID}`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return keys;
|
|
250
|
+
}
|
|
251
|
+
function captureModelSettings(editor, wanted, ownVariantIds) {
|
|
252
|
+
const captured = [];
|
|
253
|
+
for (const model of editor.list()) {
|
|
254
|
+
const providerID = String(model.providerID);
|
|
255
|
+
// The wire/route id (`Model.Info.id`) is what sessions and requests reference,
|
|
256
|
+
// which differs from the catalog `modelID` for aliased models.
|
|
257
|
+
const modelID = String(model.id);
|
|
258
|
+
if (wanted.size > 0 && !wanted.has(`${providerID}/${modelID}`))
|
|
259
|
+
continue;
|
|
260
|
+
captured.push({
|
|
261
|
+
providerID,
|
|
262
|
+
modelID,
|
|
263
|
+
...(model.settings === undefined ? {} : { settings: cloneOverlay(model.settings) }),
|
|
264
|
+
...(model.body === undefined ? {} : { body: cloneOverlay(model.body) }),
|
|
265
|
+
...(model.headers === undefined ? {} : { headers: { ...model.headers } }),
|
|
266
|
+
});
|
|
267
|
+
for (const variant of model.variants) {
|
|
268
|
+
// Never re-capture vvoc-generated variants as native overlays (no accumulation).
|
|
269
|
+
if (ownVariantIds.has(String(variant.id)))
|
|
270
|
+
continue;
|
|
271
|
+
captured.push({
|
|
272
|
+
providerID,
|
|
273
|
+
modelID,
|
|
274
|
+
variant: String(variant.id),
|
|
275
|
+
...(variant.settings === undefined ? {} : { settings: cloneOverlay(variant.settings) }),
|
|
276
|
+
...(variant.body === undefined ? {} : { body: cloneOverlay(variant.body) }),
|
|
277
|
+
...(variant.headers === undefined ? {} : { headers: { ...variant.headers } }),
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return captured;
|
|
282
|
+
}
|
|
283
|
+
/** Resolve one raw OpenCode model string (role reference or literal) to a selection. */
|
|
284
|
+
function resolveRawIntent(raw, roleModels) {
|
|
285
|
+
const trimmed = raw.trim();
|
|
286
|
+
if (isRoleReference(trimmed)) {
|
|
287
|
+
const role = trimmed.slice(ROLE_REFERENCE_PREFIX.length);
|
|
288
|
+
const selection = roleModels[role];
|
|
289
|
+
return { role, ...(selection === undefined ? {} : { selection }) };
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
const parsed = parseModelSelectionWithVariant(trimmed);
|
|
293
|
+
return {
|
|
294
|
+
selection: {
|
|
295
|
+
providerID: parsed.provider,
|
|
296
|
+
modelID: parsed.model,
|
|
297
|
+
...(parsed.variant === undefined ? {} : { variant: parsed.variant }),
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
return {};
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function captureAgentBindings(editor, config) {
|
|
306
|
+
const roleModels = parseRoleSelections(config.roles);
|
|
307
|
+
const rawAgents = config.rawIntent?.agents ?? {};
|
|
308
|
+
const bindings = new Map();
|
|
309
|
+
const record = (agentID, role, selection) => {
|
|
310
|
+
bindings.set(agentID, {
|
|
311
|
+
agentID,
|
|
312
|
+
...(role === undefined ? {} : { role }),
|
|
313
|
+
...(selection === undefined ? {} : { selection }),
|
|
314
|
+
});
|
|
315
|
+
};
|
|
316
|
+
for (const agent of editor.list()) {
|
|
317
|
+
const agentID = String(agent.id);
|
|
318
|
+
const role = config.agentRoles[agentID];
|
|
319
|
+
const literal = toSelection(agent.model);
|
|
320
|
+
const selection = literal ?? (role === undefined ? undefined : roleModels[role]);
|
|
321
|
+
record(agentID, role, selection);
|
|
322
|
+
}
|
|
323
|
+
// Raw OpenCode intent survives host normalization and overrides the native view.
|
|
324
|
+
for (const [agentID, raw] of Object.entries(rawAgents)) {
|
|
325
|
+
const resolved = resolveRawIntent(raw, roleModels);
|
|
326
|
+
const native = bindings.get(agentID);
|
|
327
|
+
record(agentID, resolved.role ?? native?.role, resolved.selection ?? native?.selection);
|
|
328
|
+
}
|
|
329
|
+
return [...bindings.values()];
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Recompute agent bindings from a freshly read config without trusting a cached
|
|
333
|
+
* selection that vvoc itself may have applied under a previous role set. A
|
|
334
|
+
* vvoc-role-managed agent's selection is recomputed from the current role model,
|
|
335
|
+
* raw OpenCode intent still wins, and an agent with no role keeps its genuine
|
|
336
|
+
* native literal. This is what makes `vvoc.json` role changes take effect on the
|
|
337
|
+
* first unbound workload even when the host emits no `config.updated`.
|
|
338
|
+
*/
|
|
339
|
+
export function rebuildAgentBindings(cached, config) {
|
|
340
|
+
const roleModels = parseRoleSelections(config.roles);
|
|
341
|
+
const rawAgents = config.rawIntent?.agents ?? {};
|
|
342
|
+
const byAgent = new Map();
|
|
343
|
+
for (const binding of cached)
|
|
344
|
+
byAgent.set(binding.agentID, binding);
|
|
345
|
+
for (const agentID of Object.keys(config.agentRoles)) {
|
|
346
|
+
if (!byAgent.has(agentID))
|
|
347
|
+
byAgent.set(agentID, { agentID });
|
|
348
|
+
}
|
|
349
|
+
const result = new Map();
|
|
350
|
+
for (const [agentID, binding] of byAgent) {
|
|
351
|
+
const role = config.agentRoles[agentID] ?? binding.role;
|
|
352
|
+
const roleSelection = role === undefined ? undefined : roleModels[role];
|
|
353
|
+
// A role-managed agent's authority is the current role model; the cached
|
|
354
|
+
// selection may already carry a vvoc-applied model from an older role set.
|
|
355
|
+
const selection = roleSelection ?? binding.selection;
|
|
356
|
+
result.set(agentID, {
|
|
357
|
+
agentID,
|
|
358
|
+
...(role === undefined ? {} : { role }),
|
|
359
|
+
...(selection === undefined ? {} : { selection }),
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
for (const [agentID, raw] of Object.entries(rawAgents)) {
|
|
363
|
+
const resolved = resolveRawIntent(raw, roleModels);
|
|
364
|
+
const native = result.get(agentID) ?? byAgent.get(agentID);
|
|
365
|
+
const role = resolved.role ?? native?.role;
|
|
366
|
+
const selection = resolved.selection ?? native?.selection;
|
|
367
|
+
result.set(agentID, {
|
|
368
|
+
agentID,
|
|
369
|
+
...(role === undefined ? {} : { role }),
|
|
370
|
+
...(selection === undefined ? {} : { selection }),
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
return [...result.values()];
|
|
374
|
+
}
|
|
375
|
+
function readDefaultModel(editor) {
|
|
376
|
+
const ref = editor.default.get();
|
|
377
|
+
return ref === undefined ? undefined : { providerID: ref.providerID, modelID: ref.modelID };
|
|
378
|
+
}
|
|
379
|
+
function toSessionView(info) {
|
|
380
|
+
const model = toSelection(info.model);
|
|
381
|
+
const parentID = info.parentID === undefined ? undefined : String(info.parentID);
|
|
382
|
+
const forkSessionID = info.fork === undefined ? undefined : String(info.fork.sessionID);
|
|
383
|
+
const locationDirectory = info.location === undefined ? undefined : String(info.location.directory);
|
|
384
|
+
const agent = info.agent === undefined ? undefined : String(info.agent);
|
|
385
|
+
const metadata = isRecord(info.metadata) ? info.metadata : undefined;
|
|
386
|
+
const hasActivity = info.time?.idle !== undefined ||
|
|
387
|
+
(info.tokens !== undefined && (info.tokens.input ?? 0) + (info.tokens.output ?? 0) > 0);
|
|
388
|
+
return {
|
|
389
|
+
id: info.id,
|
|
390
|
+
...(parentID === undefined ? {} : { parentID }),
|
|
391
|
+
...(forkSessionID === undefined ? {} : { forkSessionID }),
|
|
392
|
+
...(locationDirectory === undefined ? {} : { locationDirectory }),
|
|
393
|
+
...(agent === undefined ? {} : { agent }),
|
|
394
|
+
...(metadata === undefined ? {} : { metadata }),
|
|
395
|
+
...(model === undefined ? {} : { model }),
|
|
396
|
+
...(hasActivity ? { hasActivity: true } : {}),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
function isRecord(value) {
|
|
400
|
+
return typeof value === "object" && value !== null;
|
|
401
|
+
}
|
|
402
|
+
const PUMP_ERROR_MAX_CHARS = 500;
|
|
403
|
+
const PLACEHOLDER_TOKEN_RE = /__VVOC_SECRET_[A-Z_]+_[0-9a-f]{12}(?:_\d+)?__/g;
|
|
404
|
+
/**
|
|
405
|
+
* Bounded, credential-safe diagnostic for one contained event-pump failure. The
|
|
406
|
+
* raw thrown value is never stored verbatim: placeholder tokens are redacted and
|
|
407
|
+
* the result is capped so an error carrying configuration text cannot leak or
|
|
408
|
+
* grow without bound.
|
|
409
|
+
*/
|
|
410
|
+
function describePumpError(error) {
|
|
411
|
+
const raw = error instanceof Error
|
|
412
|
+
? `${error.name}: ${error.message}`
|
|
413
|
+
: typeof error === "string"
|
|
414
|
+
? error
|
|
415
|
+
: "unknown error";
|
|
416
|
+
const redacted = raw.replace(PLACEHOLDER_TOKEN_RE, "[redacted]");
|
|
417
|
+
return redacted.length > PUMP_ERROR_MAX_CHARS
|
|
418
|
+
? `${redacted.slice(0, PUMP_ERROR_MAX_CHARS)}…`
|
|
419
|
+
: redacted;
|
|
420
|
+
}
|
|
421
|
+
function extractTitleMessages(messages) {
|
|
422
|
+
const extracted = [];
|
|
423
|
+
if (!Array.isArray(messages))
|
|
424
|
+
return extracted;
|
|
425
|
+
for (const message of messages) {
|
|
426
|
+
if (!isRecord(message))
|
|
427
|
+
continue;
|
|
428
|
+
const role = typeof message.role === "string" ? message.role : "unknown";
|
|
429
|
+
const text = extractMessageText(message.content);
|
|
430
|
+
if (text.length > 0)
|
|
431
|
+
extracted.push({ role, text });
|
|
432
|
+
}
|
|
433
|
+
return extracted;
|
|
434
|
+
}
|
|
435
|
+
function extractMessageText(content) {
|
|
436
|
+
if (typeof content === "string")
|
|
437
|
+
return content;
|
|
438
|
+
if (!Array.isArray(content))
|
|
439
|
+
return "";
|
|
440
|
+
const parts = [];
|
|
441
|
+
for (const part of content) {
|
|
442
|
+
if (typeof part === "string") {
|
|
443
|
+
parts.push(part);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
if (!isRecord(part))
|
|
447
|
+
continue;
|
|
448
|
+
if (typeof part.text === "string")
|
|
449
|
+
parts.push(part.text);
|
|
450
|
+
}
|
|
451
|
+
return parts.join("\n");
|
|
452
|
+
}
|
|
453
|
+
/** Selection the family expects for a given request kind and session agent. */
|
|
454
|
+
function expectedSelection(capture, agentID) {
|
|
455
|
+
// An explicit family choice is the session's model and must not be overridden
|
|
456
|
+
// by an agent-role binding.
|
|
457
|
+
if (capture.intent.mode === "explicit" && capture.modelOverride !== undefined) {
|
|
458
|
+
return qualifySelection(capture, capture.modelOverride);
|
|
459
|
+
}
|
|
460
|
+
if (agentID !== undefined) {
|
|
461
|
+
const binding = capture.agents.find((agent) => agent.agentID === agentID);
|
|
462
|
+
if (binding?.selection !== undefined) {
|
|
463
|
+
return qualifySelection(capture, binding.selection);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
const base = primarySelection(capture);
|
|
467
|
+
return base === undefined ? undefined : qualifySelection(capture, base);
|
|
468
|
+
}
|
|
469
|
+
function selectionMatches(actual, expected) {
|
|
470
|
+
if (expected === undefined)
|
|
471
|
+
return true;
|
|
472
|
+
if (actual === undefined)
|
|
473
|
+
return false;
|
|
474
|
+
// Identity plus variant: a resolved request must use the captured variant exactly.
|
|
475
|
+
return sameModelSelection(actual, expected);
|
|
476
|
+
}
|
|
477
|
+
/** The model a family expects for host title work: the captured fast/small role. */
|
|
478
|
+
function titleExpectedSelection(capture) {
|
|
479
|
+
const small = capture.roleModels.fast;
|
|
480
|
+
return small === undefined ? undefined : qualifySelection(capture, small);
|
|
481
|
+
}
|
|
482
|
+
function initializeNativeSnapshotRuntime(ctx, options) {
|
|
483
|
+
return (async () => {
|
|
484
|
+
const runtimeLease = options?.runtimeDeps === undefined
|
|
485
|
+
? acquireRuntime(ctx)
|
|
486
|
+
: acquireRuntime(ctx, options.runtimeDeps);
|
|
487
|
+
const runtime = runtimeLease.runtime;
|
|
488
|
+
const owned = [];
|
|
489
|
+
const lifecycle = new AbortController();
|
|
490
|
+
let runtimeReleased = false;
|
|
491
|
+
const releaseRuntime = async () => {
|
|
492
|
+
if (runtimeReleased)
|
|
493
|
+
return;
|
|
494
|
+
runtimeReleased = true;
|
|
495
|
+
lifecycle.abort();
|
|
496
|
+
for (const registration of owned)
|
|
497
|
+
await registration.dispose();
|
|
498
|
+
await runtimeLease.release();
|
|
499
|
+
};
|
|
500
|
+
try {
|
|
501
|
+
const base = effectiveRuntimeConfig(await loadEffectiveVvocConfig({ cwd: ctx.location.directory }));
|
|
502
|
+
const state = {
|
|
503
|
+
config: base,
|
|
504
|
+
agentBindings: [],
|
|
505
|
+
modelSettings: [],
|
|
506
|
+
nativeDefault: undefined,
|
|
507
|
+
registrations: [],
|
|
508
|
+
// Per-family pending materialization so concurrent families cannot overwrite
|
|
509
|
+
// each other's in-flight variant registrations.
|
|
510
|
+
pendingRegistrations: new Map(),
|
|
511
|
+
materializedVariants: new Set(),
|
|
512
|
+
ownVariantIds: new Set(),
|
|
513
|
+
roleOverride: false,
|
|
514
|
+
configError: undefined,
|
|
515
|
+
creationModels: new Map(),
|
|
516
|
+
creationDefaults: new Map(),
|
|
517
|
+
explicitSelections: new Map(),
|
|
518
|
+
pluginSwitches: new Map(),
|
|
519
|
+
suppressedTitles: new Set(),
|
|
520
|
+
};
|
|
521
|
+
const store = options?.store ?? createFileSnapshotStore({ scopeKey: ctx.location.project.id });
|
|
522
|
+
/**
|
|
523
|
+
* Read the host's final native model collection. A model transform registered
|
|
524
|
+
* by this plugin may run before later config transforms, so a transform-local
|
|
525
|
+
* editor is neither the capture source nor proof a variant survived; the
|
|
526
|
+
* host's final list is. Returns undefined when the host exposes no list call.
|
|
527
|
+
*/
|
|
528
|
+
async function readFinalModelEntries() {
|
|
529
|
+
const list = ctx.model.list;
|
|
530
|
+
if (typeof list !== "function")
|
|
531
|
+
return undefined;
|
|
532
|
+
let raw;
|
|
533
|
+
try {
|
|
534
|
+
raw = await list.call(ctx.model);
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
return undefined;
|
|
538
|
+
}
|
|
539
|
+
const data = isRecord(raw) && Array.isArray(raw.data)
|
|
540
|
+
? raw.data
|
|
541
|
+
: Array.isArray(raw)
|
|
542
|
+
? raw
|
|
543
|
+
: [];
|
|
544
|
+
return data.filter(isRecord);
|
|
545
|
+
}
|
|
546
|
+
const readFinalOverlays = async (config) => {
|
|
547
|
+
const entries = await readFinalModelEntries();
|
|
548
|
+
if (entries === undefined)
|
|
549
|
+
return undefined;
|
|
550
|
+
const wanted = wantedModelKeys(config);
|
|
551
|
+
const captured = [];
|
|
552
|
+
const overlay = (providerID, modelID, variant, base, source) => {
|
|
553
|
+
const settings = mergeModelBodyOverlay(isRecord(base.settings) ? base.settings : undefined, isRecord(source.settings) ? source.settings : undefined);
|
|
554
|
+
const body = mergeModelBodyOverlay(isRecord(base.body) ? base.body : undefined, isRecord(source.body) ? source.body : undefined);
|
|
555
|
+
const headers = mergeModelHeadersOverlay(isRecord(base.headers) ? base.headers : undefined, isRecord(source.headers) ? source.headers : undefined);
|
|
556
|
+
return {
|
|
557
|
+
providerID,
|
|
558
|
+
modelID,
|
|
559
|
+
...(variant === undefined ? {} : { variant }),
|
|
560
|
+
...(settings === undefined ? {} : { settings }),
|
|
561
|
+
...(body === undefined ? {} : { body }),
|
|
562
|
+
...(headers === undefined ? {} : { headers }),
|
|
563
|
+
};
|
|
564
|
+
};
|
|
565
|
+
for (const entry of entries) {
|
|
566
|
+
const providerID = entry.providerID;
|
|
567
|
+
const modelID = entry.id;
|
|
568
|
+
if (typeof providerID !== "string" || typeof modelID !== "string")
|
|
569
|
+
continue;
|
|
570
|
+
if (wanted.size > 0 && !wanted.has(`${providerID}/${modelID}`))
|
|
571
|
+
continue;
|
|
572
|
+
captured.push(overlay(providerID, modelID, undefined, entry, entry));
|
|
573
|
+
if (Array.isArray(entry.variants)) {
|
|
574
|
+
for (const variant of entry.variants) {
|
|
575
|
+
if (!isRecord(variant) || typeof variant.id !== "string")
|
|
576
|
+
continue;
|
|
577
|
+
// Never re-capture our own generated variants (no accumulation).
|
|
578
|
+
if (state.ownVariantIds.has(variant.id))
|
|
579
|
+
continue;
|
|
580
|
+
// Each source variant gets the base merged with THAT variant's own
|
|
581
|
+
// native overlay, so two source variants of one model stay distinct.
|
|
582
|
+
captured.push(overlay(providerID, modelID, variant.id, entry, variant));
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return captured;
|
|
587
|
+
};
|
|
588
|
+
const readConfig = async (directory) => {
|
|
589
|
+
const vvoc = effectiveRuntimeConfig(await loadEffectiveVvocConfig({ cwd: directory }));
|
|
590
|
+
const rawIntent = await readRawOpenCodeModelIntent(directory);
|
|
591
|
+
const roleModels = parseRoleSelections(vvoc.roles);
|
|
592
|
+
const rootRaw = rawIntent?.model;
|
|
593
|
+
const rootResolved = rootRaw === undefined ? undefined : resolveRawIntent(rootRaw, roleModels).selection;
|
|
594
|
+
// Bindings are recomputed from THIS read's roles + raw intent + the cached
|
|
595
|
+
// genuine native literals, so a fresh vvoc role is reflected without trusting
|
|
596
|
+
// a selection vvoc previously applied to the native agent entry.
|
|
597
|
+
const agentBindings = rebuildAgentBindings(state.agentBindings, {
|
|
598
|
+
...vvoc,
|
|
599
|
+
...(rawIntent === undefined ? {} : { rawIntent }),
|
|
600
|
+
});
|
|
601
|
+
const baseConfig = {
|
|
602
|
+
...vvoc,
|
|
603
|
+
...(rawIntent === undefined ? {} : { rawIntent }),
|
|
604
|
+
...(rootResolved === undefined ? {} : { rootDefault: rootResolved }),
|
|
605
|
+
agentBindings,
|
|
606
|
+
modelSettings: state.modelSettings,
|
|
607
|
+
...(state.nativeDefault === undefined ? {} : { nativeDefault: state.nativeDefault }),
|
|
608
|
+
};
|
|
609
|
+
// Capture the final native model overlay (post config-transform) when the
|
|
610
|
+
// host exposes it, so a snapshot variant reflects the real request payload.
|
|
611
|
+
const overlays = await readFinalOverlays(baseConfig);
|
|
612
|
+
if (overlays !== undefined)
|
|
613
|
+
state.modelSettings = overlays;
|
|
614
|
+
return { ...baseConfig, modelSettings: state.modelSettings };
|
|
615
|
+
};
|
|
616
|
+
// Initialize the live config with raw OpenCode intent before any transform runs.
|
|
617
|
+
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
|
+
/**
|
|
686
|
+
* Create a real parented auxiliary child through the authenticated full
|
|
687
|
+
* client's `session.import`. The child carries host-owned metadata naming
|
|
688
|
+
* its intended workload role, so its selection is recoverable after restart
|
|
689
|
+
* without an ephemeral in-process exemption.
|
|
690
|
+
*/
|
|
691
|
+
const importAuxiliaryChild = async (input) => {
|
|
692
|
+
const client = await runtime.client();
|
|
693
|
+
const parent = await ctx.session.get({ sessionID: input.parentID });
|
|
694
|
+
const projectID = parent.projectID === undefined ? "" : String(parent.projectID);
|
|
695
|
+
if (projectID.length === 0) {
|
|
696
|
+
throw new SnapshotAdmissionError("Auxiliary child import requires the parent session project id.");
|
|
697
|
+
}
|
|
698
|
+
const sessionID = `ses_${randomBytes(16).toString("hex")}`;
|
|
699
|
+
const now = Date.now();
|
|
700
|
+
const payload = {
|
|
701
|
+
info: {
|
|
702
|
+
id: sessionID,
|
|
703
|
+
parentID: input.parentID,
|
|
704
|
+
projectID,
|
|
705
|
+
...(input.agent === undefined ? {} : { agent: input.agent }),
|
|
706
|
+
model: {
|
|
707
|
+
id: input.model.modelID,
|
|
708
|
+
providerID: input.model.providerID,
|
|
709
|
+
...(input.model.variant === undefined ? {} : { variant: input.model.variant }),
|
|
710
|
+
},
|
|
711
|
+
cost: 0,
|
|
712
|
+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
|
713
|
+
time: { created: now, updated: now },
|
|
714
|
+
title: input.title,
|
|
715
|
+
location: { directory: input.locationDirectory },
|
|
716
|
+
metadata: {
|
|
717
|
+
vvocAuxiliary: {
|
|
718
|
+
kind: input.kind,
|
|
719
|
+
...(input.role === undefined ? {} : { role: input.role }),
|
|
720
|
+
},
|
|
721
|
+
},
|
|
722
|
+
// Conservative: the auxiliary child needs generation, never tools.
|
|
723
|
+
permissions: [{ action: "*", resource: "*", effect: "deny" }],
|
|
724
|
+
},
|
|
725
|
+
messages: [],
|
|
726
|
+
location: { directory: input.locationDirectory },
|
|
727
|
+
};
|
|
728
|
+
const imported = await client.session.import(payload);
|
|
729
|
+
const importedID = decodeImportedSessionID(imported);
|
|
730
|
+
if (importedID === undefined || importedID !== sessionID) {
|
|
731
|
+
throw new SnapshotAdmissionError("Native session import did not return the expected auxiliary child id.");
|
|
732
|
+
}
|
|
733
|
+
// The parent binding must be durable before the child is used.
|
|
734
|
+
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
735
|
+
const view = toSessionView(await ctx.session.get({ sessionID }));
|
|
736
|
+
if (view.parentID === input.parentID)
|
|
737
|
+
return { sessionID };
|
|
738
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
739
|
+
}
|
|
740
|
+
throw new SnapshotAdmissionError("Imported auxiliary child did not persist its parent lineage.");
|
|
741
|
+
};
|
|
742
|
+
const deps = {
|
|
743
|
+
store,
|
|
744
|
+
...(options?.now === undefined ? {} : { now: options.now }),
|
|
745
|
+
// Distinct plugin contexts copied from one host share the native app/location
|
|
746
|
+
// object identity, so their snapshot services share one per-family
|
|
747
|
+
// publication lock without sharing any client, registration or disposal.
|
|
748
|
+
coordination: coordinateHost({ app: ctx.app, location: ctx.location }),
|
|
749
|
+
loadConfig: async (directory) => {
|
|
750
|
+
const fresh = await readConfig(directory);
|
|
751
|
+
state.config = fresh;
|
|
752
|
+
return fresh;
|
|
753
|
+
},
|
|
754
|
+
readSession: async (sessionID) => toSessionView(await ctx.session.get({ sessionID })),
|
|
755
|
+
readSessionModel: async (sessionID) => toSelection((await ctx.session.get({ sessionID })).model),
|
|
756
|
+
switchModel: ({ sessionID, model }) => ctx.session.switchModel({ sessionID, model: toRef(model) }),
|
|
757
|
+
readAcceptedInputs,
|
|
758
|
+
auxiliarySession: {
|
|
759
|
+
create: importAuxiliaryChild,
|
|
760
|
+
switchModel: async ({ sessionID, model }) => {
|
|
761
|
+
await ctx.session.switchModel({ sessionID, model: toRef(model) });
|
|
762
|
+
},
|
|
763
|
+
generate: (input) => ctx.session.generate(input),
|
|
764
|
+
},
|
|
765
|
+
};
|
|
766
|
+
const snapshots = createSnapshotService(deps);
|
|
767
|
+
const allPending = () => [...state.pendingRegistrations.values()].flat();
|
|
768
|
+
const applyVariants = (editor) => applyVariantRegistrations(editor, [...state.registrations, ...allPending()]);
|
|
769
|
+
const refresh = async () => {
|
|
770
|
+
state.registrations = buildVariantRegistrations(await snapshots.captures());
|
|
771
|
+
await ctx.model.reload();
|
|
772
|
+
await ctx.agent.reload();
|
|
773
|
+
};
|
|
774
|
+
/**
|
|
775
|
+
* Read the final native model collection after a reload. A model transform
|
|
776
|
+
* registered by this plugin may run before later config transforms, so a
|
|
777
|
+
* transform-local editor is not proof the variant survived; the host's final
|
|
778
|
+
* model list is. Returns undefined when the host exposes no list call (tests).
|
|
779
|
+
*/
|
|
780
|
+
const materializeCandidate = async (candidateIdentity, capture, selection) => {
|
|
781
|
+
if (selection.variant === undefined)
|
|
782
|
+
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]));
|
|
786
|
+
await ctx.model.reload();
|
|
787
|
+
const finalEntries = await readFinalModelEntries();
|
|
788
|
+
const exists = finalEntries === undefined
|
|
789
|
+
? state.materializedVariants.has(selection.variant)
|
|
790
|
+
: finalEntries.some((entry) => {
|
|
791
|
+
if (entry.providerID !== selection.providerID || entry.id !== selection.modelID) {
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
return (Array.isArray(entry.variants) &&
|
|
795
|
+
entry.variants.some((variant) => isRecord(variant) && String(variant.id) === selection.variant));
|
|
796
|
+
});
|
|
797
|
+
if (!exists) {
|
|
798
|
+
state.pendingRegistrations.delete(candidateIdentity);
|
|
799
|
+
await ctx.model.reload();
|
|
800
|
+
throw new SnapshotAdmissionError(`Captured variant ${selection.variant} is not materializable on ${selection.providerID}/${selection.modelID}.`);
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
const switchSession = async (sessionID, selection) => {
|
|
804
|
+
state.pluginSwitches.set(sessionID, selection);
|
|
805
|
+
await ctx.session.switchModel({ sessionID, model: toRef(selection) });
|
|
806
|
+
};
|
|
807
|
+
/** Unbound candidate selection for a session's agent from the live policy. */
|
|
808
|
+
const candidateTarget = (agentID) => {
|
|
809
|
+
const bindings = state.config.agentBindings ?? [];
|
|
810
|
+
if (agentID !== undefined) {
|
|
811
|
+
const binding = bindings.find((agent) => agent.agentID === agentID);
|
|
812
|
+
if (binding?.selection !== undefined)
|
|
813
|
+
return binding.selection;
|
|
814
|
+
}
|
|
815
|
+
const roleModels = parseRoleSelections(state.config.roles);
|
|
816
|
+
if (roleModels.default !== undefined)
|
|
817
|
+
return roleModels.default;
|
|
818
|
+
if (state.config.rootDefault !== undefined)
|
|
819
|
+
return state.config.rootDefault;
|
|
820
|
+
for (const selection of Object.values(roleModels))
|
|
821
|
+
return selection;
|
|
822
|
+
for (const binding of bindings) {
|
|
823
|
+
if (binding.selection !== undefined)
|
|
824
|
+
return binding.selection;
|
|
825
|
+
}
|
|
826
|
+
return state.config.nativeDefault;
|
|
827
|
+
};
|
|
828
|
+
/**
|
|
829
|
+
* One coherent workload selection for a bound family. An explicit post-bind
|
|
830
|
+
* user choice always wins; role overriding disabled means the host's current
|
|
831
|
+
* model is already the policy. Otherwise the agent's captured binding, then
|
|
832
|
+
* the family primary, with the family's captured variant qualified.
|
|
833
|
+
*/
|
|
834
|
+
const expectedForSession = (capture, agentID, sessionID, metadata) => {
|
|
835
|
+
// A real parented auxiliary child recovers its intended role from
|
|
836
|
+
// host-owned metadata, not an in-process exemption.
|
|
837
|
+
const auxiliary = decodeAuxiliaryMetadata(metadata);
|
|
838
|
+
if (auxiliary !== undefined) {
|
|
839
|
+
const base = auxiliary.role === undefined
|
|
840
|
+
? primarySelection(capture)
|
|
841
|
+
: capture.roleModels[auxiliary.role];
|
|
842
|
+
return base === undefined ? undefined : qualifySelection(capture, base);
|
|
843
|
+
}
|
|
844
|
+
if (!state.roleOverride)
|
|
845
|
+
return capture.modelOverride ?? capture.rootSelection;
|
|
846
|
+
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.
|
|
849
|
+
if (explicit !== undefined)
|
|
850
|
+
return normalizeModelSelection(explicit);
|
|
851
|
+
return expectedSelection(capture, agentID);
|
|
852
|
+
};
|
|
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) => {
|
|
862
|
+
await ensureTransforms();
|
|
863
|
+
const view = toSessionView(await ctx.session.get({ sessionID }));
|
|
864
|
+
const sessionModel = view.model;
|
|
865
|
+
const pluginSwitch = state.pluginSwitches.get(sessionID);
|
|
866
|
+
const ownSwitch = pluginSwitch !== undefined && sameModelSelection(sessionModel, pluginSwitch);
|
|
867
|
+
// The default captured at creation, never the possibly-changed current default.
|
|
868
|
+
const creationDefault = state.creationDefaults.get(sessionID) ?? state.nativeDefault;
|
|
869
|
+
const intent = ownSwitch
|
|
870
|
+
? { mode: "implicit", source: "switch" }
|
|
871
|
+
: classifyInitialSelection({ sessionModel, creationDefault });
|
|
872
|
+
const existing = await snapshots.policy(sessionID);
|
|
873
|
+
if (existing !== undefined) {
|
|
874
|
+
// A bound family owns an immutable capture, so its policy/model handling
|
|
875
|
+
// never consults the mutable current config. Resolve it before any fresh
|
|
876
|
+
// read: an invalid on-disk vvoc must not fail an already-bound family.
|
|
877
|
+
// A session model that changed outside our own switch is a user choice and
|
|
878
|
+
// must survive, even if the event pump has not recorded it yet.
|
|
879
|
+
const baseExpected = expectedSelection(existing, view.agent);
|
|
880
|
+
if (!ownSwitch &&
|
|
881
|
+
baseExpected !== undefined &&
|
|
882
|
+
sessionModel !== undefined &&
|
|
883
|
+
!sameModelSelection(sessionModel, baseExpected) &&
|
|
884
|
+
!sameModelSelection(sessionModel, pluginSwitch)) {
|
|
885
|
+
state.explicitSelections.set(sessionID, normalizeModelSelection(sessionModel));
|
|
886
|
+
}
|
|
887
|
+
if (!state.roleOverride || state.explicitSelections.has(sessionID))
|
|
888
|
+
return;
|
|
889
|
+
const target = expectedForSession(existing, view.agent, sessionID);
|
|
890
|
+
if (target !== undefined && !sameModelSelection(sessionModel, target)) {
|
|
891
|
+
await switchSession(sessionID, target);
|
|
892
|
+
}
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
// Only a truly unbound candidate needs the freshest current config:
|
|
896
|
+
// 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
|
|
899
|
+
// re-read a different vvoc snapshot than the target was derived from.
|
|
900
|
+
const admissionConfig = await readConfig(ctx.location.directory);
|
|
901
|
+
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
|
+
const explicitSelection = intent.mode === "explicit" ? intent.literal : undefined;
|
|
907
|
+
const target = explicitSelection ?? candidateTarget(view.agent);
|
|
908
|
+
const base = state.roleOverride ? target : (sessionModel ?? target);
|
|
909
|
+
// The agent-aware resolved target drives staging, not the capture's default
|
|
910
|
+
// role; when role overriding is off the session's current model is bound.
|
|
911
|
+
const selectionOverride = explicitSelection === undefined && base !== undefined ? base : undefined;
|
|
912
|
+
const outcome = await snapshots.stage({
|
|
913
|
+
sessionID,
|
|
914
|
+
directory: ctx.location.directory,
|
|
915
|
+
location: runtimeIdentity(ctx.location),
|
|
916
|
+
admissionConfig,
|
|
917
|
+
...(explicitSelection === undefined ? {} : { explicit: explicitSelection }),
|
|
918
|
+
...(selectionOverride === undefined ? {} : { selectionOverride }),
|
|
919
|
+
...(sessionModel === undefined ? {} : { before: sessionModel }),
|
|
920
|
+
...(inboxID === undefined ? {} : { inboxID }),
|
|
921
|
+
workload: "prompt",
|
|
922
|
+
force: state.roleOverride,
|
|
923
|
+
}, async (capture, selection, candidateIdentity) => {
|
|
924
|
+
await materializeCandidate(candidateIdentity, capture, selection);
|
|
925
|
+
state.pluginSwitches.set(sessionID, selection);
|
|
926
|
+
});
|
|
927
|
+
if (outcome.status === "rejected") {
|
|
928
|
+
throw new SnapshotAdmissionError(outcome.error ?? `Admission for ${sessionID} did not produce a persisted policy.`);
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
const guardResolvedModel = async (sessionID, agentID, actual, kind) => {
|
|
932
|
+
await ensureTransforms();
|
|
933
|
+
if (kind === "title" && state.suppressedTitles.has(sessionID)) {
|
|
934
|
+
// The title hook already supplied the result; the host still runs this
|
|
935
|
+
// hook before it checks `result`, so a refused dispatch here would fail
|
|
936
|
+
// a title that never reaches the provider.
|
|
937
|
+
state.suppressedTitles.delete(sessionID);
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
const view = toSessionView(await ctx.session.get({ sessionID }));
|
|
941
|
+
const effectiveAgent = agentID ?? view.agent;
|
|
942
|
+
const familyId = await snapshots.familyOf(sessionID);
|
|
943
|
+
const capture = await snapshots.policy(sessionID);
|
|
944
|
+
if (capture !== undefined) {
|
|
945
|
+
const expected = kind === "title"
|
|
946
|
+
? titleExpectedSelection(capture)
|
|
947
|
+
: expectedForSession(capture, effectiveAgent, sessionID, view.metadata);
|
|
948
|
+
if (!selectionMatches(actual, expected)) {
|
|
949
|
+
throw new SnapshotAdmissionError(`Resolved ${kind} model ${actual?.providerID ?? "?"}/${actual?.modelID ?? "?"} does not match the captured family selection for ${familyId}.`);
|
|
950
|
+
}
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
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"}).`);
|
|
988
|
+
};
|
|
989
|
+
const modelTransform = (editor) => {
|
|
990
|
+
const own = new Set([...state.registrations, ...allPending()].map((registration) => registration.variant.id));
|
|
991
|
+
state.ownVariantIds = own;
|
|
992
|
+
state.modelSettings = captureModelSettings(editor, wantedModelKeys(state.config), own);
|
|
993
|
+
state.nativeDefault = readDefaultModel(editor) ?? state.nativeDefault;
|
|
994
|
+
applyVariants(editor);
|
|
995
|
+
// Cheap transform-local readback; the final-list readback happens before switch.
|
|
996
|
+
state.materializedVariants = new Set([...state.registrations, ...allPending()].flatMap((registration) => {
|
|
997
|
+
const model = editor.get(registration.providerID, registration.modelID);
|
|
998
|
+
return model !== undefined &&
|
|
999
|
+
model.variants.some((variant) => String(variant.id) === registration.variant.id)
|
|
1000
|
+
? [registration.variant.id]
|
|
1001
|
+
: [];
|
|
1002
|
+
}));
|
|
1003
|
+
if (!state.roleOverride)
|
|
1004
|
+
return;
|
|
1005
|
+
const defaultRole = parseRoleSelections(state.config.roles).default;
|
|
1006
|
+
if (defaultRole !== undefined) {
|
|
1007
|
+
editor.default.set(defaultRole.providerID, defaultRole.modelID);
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
1010
|
+
// Global agent transform represents current unbound candidates only; family
|
|
1011
|
+
// variants are applied per-session at switch time, never from another family.
|
|
1012
|
+
const agentTransform = (editor) => {
|
|
1013
|
+
state.agentBindings = captureAgentBindings(editor, state.config);
|
|
1014
|
+
if (state.roleOverride) {
|
|
1015
|
+
applyAgentPolicies(editor, state.agentBindings, []);
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
let eagerTransformsRegistered = false;
|
|
1019
|
+
let suffixTransformsRegistered = false;
|
|
1020
|
+
const registerTransforms = async () => {
|
|
1021
|
+
owned.push(await ctx.model.transform(modelTransform));
|
|
1022
|
+
owned.push(await ctx.agent.transform(agentTransform));
|
|
1023
|
+
};
|
|
1024
|
+
/**
|
|
1025
|
+
* Eager registration gives the role toggle an immediate visible effect during
|
|
1026
|
+
* setup; post config plugins register after it, so it also needs a suffix
|
|
1027
|
+
* registration after activation that appends last and keeps our variants.
|
|
1028
|
+
*/
|
|
1029
|
+
const ensureEagerTransforms = async () => {
|
|
1030
|
+
if (eagerTransformsRegistered)
|
|
1031
|
+
return;
|
|
1032
|
+
eagerTransformsRegistered = true;
|
|
1033
|
+
await registerTransforms();
|
|
1034
|
+
await ctx.model.reload();
|
|
1035
|
+
await ctx.agent.reload();
|
|
1036
|
+
};
|
|
1037
|
+
const ensureTransforms = async () => {
|
|
1038
|
+
if (suffixTransformsRegistered)
|
|
1039
|
+
return;
|
|
1040
|
+
suffixTransformsRegistered = true;
|
|
1041
|
+
await registerTransforms();
|
|
1042
|
+
await ctx.model.reload();
|
|
1043
|
+
await ctx.agent.reload();
|
|
1044
|
+
};
|
|
1045
|
+
owned.push(await ctx.session.hook("prompt", (event) => stageFor(event.sessionID, event.messageID)));
|
|
1046
|
+
// `context` and `generate` resolve their model before (or around) the hook,
|
|
1047
|
+
// so neither can stage; owned generate/synthetic work uses admitWorkload.
|
|
1048
|
+
owned.push(await ctx.session.hook("generate", async (event) => {
|
|
1049
|
+
const view = toSessionView(await ctx.session.get({ sessionID: event.sessionID }));
|
|
1050
|
+
await guardResolvedModel(event.sessionID, view.agent, view.model, "generate");
|
|
1051
|
+
}));
|
|
1052
|
+
owned.push(await ctx.session.hook("model.request", async (event) => {
|
|
1053
|
+
// The model is already resolved here: only validate/commit, never re-stage.
|
|
1054
|
+
await guardResolvedModel(event.sessionID, event.agent, toSelection(event.model), event.kind);
|
|
1055
|
+
}));
|
|
1056
|
+
const rawSmallModel = state.config.rawIntent?.smallModel;
|
|
1057
|
+
const smallModelRole = rawSmallModel !== undefined && isRoleReference(rawSmallModel)
|
|
1058
|
+
? rawSmallModel.trim().slice(ROLE_REFERENCE_PREFIX.length)
|
|
1059
|
+
: getBuiltInRoleBindings().opencodeDefaults.smallModel;
|
|
1060
|
+
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
|
+
const title = await snapshots.auxiliary.title({
|
|
1065
|
+
sessionID: event.sessionID,
|
|
1066
|
+
result: event.result,
|
|
1067
|
+
messages: extractTitleMessages(event.messages),
|
|
1068
|
+
role: smallModelRole,
|
|
1069
|
+
});
|
|
1070
|
+
if (title !== undefined && event.result !== title) {
|
|
1071
|
+
event.result = title;
|
|
1072
|
+
// The host runs model.request before it checks `result`, so remember
|
|
1073
|
+
// that this title provider dispatch is suppressed and must not refuse.
|
|
1074
|
+
state.suppressedTitles.add(event.sessionID);
|
|
1075
|
+
}
|
|
1076
|
+
}));
|
|
1077
|
+
// 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.
|
|
1083
|
+
const pump = (async () => {
|
|
1084
|
+
try {
|
|
1085
|
+
for await (const event of ctx.event.subscribe({ signal: lifecycle.signal })) {
|
|
1086
|
+
try {
|
|
1087
|
+
const created = decodeSessionCreatedEvent(event);
|
|
1088
|
+
if (created !== undefined) {
|
|
1089
|
+
state.creationModels.set(created.sessionID, created.model);
|
|
1090
|
+
// Record the default in force at creation, not a later changed default.
|
|
1091
|
+
state.creationDefaults.set(created.sessionID, state.nativeDefault);
|
|
1092
|
+
}
|
|
1093
|
+
const selected = decodeModelSelectedEvent(event);
|
|
1094
|
+
if (selected !== undefined) {
|
|
1095
|
+
const pluginSwitch = state.pluginSwitches.get(selected.sessionID);
|
|
1096
|
+
if (pluginSwitch === undefined ||
|
|
1097
|
+
!sameModelSelection(selected.model, pluginSwitch)) {
|
|
1098
|
+
// The host emits this only for a real change, so it is a user choice.
|
|
1099
|
+
state.explicitSelections.set(selected.sessionID, selected.model);
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
if (isConfigUpdateEvent(event)) {
|
|
1103
|
+
// Assign only after a fully successful read so a partially read
|
|
1104
|
+
// invalid config never becomes the mutable current config that
|
|
1105
|
+
// already bound families consult.
|
|
1106
|
+
state.config = await readConfig(ctx.location.directory);
|
|
1107
|
+
await refresh();
|
|
1108
|
+
// A successful config event is the recovery signal.
|
|
1109
|
+
state.configError = undefined;
|
|
1110
|
+
}
|
|
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();
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
catch (error) {
|
|
1132
|
+
// Contain one event's failure and keep observing later events.
|
|
1133
|
+
state.configError = describePumpError(error);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
catch (error) {
|
|
1138
|
+
// A closed/failed native stream is recorded, never silently swallowed.
|
|
1139
|
+
// There is no reconnect loop: cleanup aborts the subscription.
|
|
1140
|
+
state.configError = describePumpError(error);
|
|
1141
|
+
}
|
|
1142
|
+
})();
|
|
1143
|
+
void pump;
|
|
1144
|
+
await refresh();
|
|
1145
|
+
// Read-only native context-inspection RPC: projects the registered tool
|
|
1146
|
+
// catalog and an allowlisted family/current-runtime policy for the TUI.
|
|
1147
|
+
// Owned by this runtime's cleanup; it disposes only its own registration.
|
|
1148
|
+
owned.push(await registerContextInspectionRpc({
|
|
1149
|
+
location: ctx.location,
|
|
1150
|
+
rpc: ctx.rpc,
|
|
1151
|
+
...(ctx.tool === undefined ? {} : { tool: ctx.tool }),
|
|
1152
|
+
session: { get: (input) => ctx.session.get(input) },
|
|
1153
|
+
}, {
|
|
1154
|
+
policy: (sessionID) => snapshots.policy(sessionID),
|
|
1155
|
+
currentConfig: () => state.config,
|
|
1156
|
+
...(options?.now === undefined ? {} : { now: options.now }),
|
|
1157
|
+
}));
|
|
1158
|
+
return {
|
|
1159
|
+
runtime,
|
|
1160
|
+
snapshots,
|
|
1161
|
+
auxiliary: snapshots.auxiliary,
|
|
1162
|
+
client: () => runtime.client(),
|
|
1163
|
+
permissions: runtime.permissions,
|
|
1164
|
+
effectiveConfig: () => state.config,
|
|
1165
|
+
async admitWorkload(request) {
|
|
1166
|
+
// 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.
|
|
1172
|
+
const admissionConfig = await readConfig(request.directory);
|
|
1173
|
+
state.config = admissionConfig;
|
|
1174
|
+
return snapshots.admitOwned({
|
|
1175
|
+
...request,
|
|
1176
|
+
admissionConfig,
|
|
1177
|
+
operationID: `op_${randomBytes(16).toString("hex")}`,
|
|
1178
|
+
}, async (capture, selection, candidateIdentity) => {
|
|
1179
|
+
await materializeCandidate(candidateIdentity, capture, selection);
|
|
1180
|
+
state.pluginSwitches.set(request.sessionID, selection);
|
|
1181
|
+
});
|
|
1182
|
+
},
|
|
1183
|
+
async setRoleOverride(enabled) {
|
|
1184
|
+
state.roleOverride = enabled;
|
|
1185
|
+
// Immediate visible override; the suffix registration at first work
|
|
1186
|
+
// appends after post config transforms and keeps the final state ours.
|
|
1187
|
+
await ensureEagerTransforms();
|
|
1188
|
+
},
|
|
1189
|
+
refresh,
|
|
1190
|
+
lastConfigError: () => state.configError,
|
|
1191
|
+
release: releaseRuntime,
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
catch (error) {
|
|
1195
|
+
// Initialization failure must unwind every acquired resource and permit retry.
|
|
1196
|
+
await releaseRuntime().catch(() => undefined);
|
|
1197
|
+
throw error;
|
|
1198
|
+
}
|
|
1199
|
+
})();
|
|
1200
|
+
}
|
|
1201
|
+
/** Acquire the shared native snapshot runtime for an actual `Plugin.Context`. */
|
|
1202
|
+
export async function acquireNativeSnapshotRuntime(ctx, options) {
|
|
1203
|
+
const key = options?.runtimeDeps === undefined
|
|
1204
|
+
? String(objectId(contextIds, ctx))
|
|
1205
|
+
: `${objectId(contextIds, ctx)}:${objectId(depsIds, options.runtimeDeps)}`;
|
|
1206
|
+
let entry = nativeRuntimes.get(key);
|
|
1207
|
+
if (entry === undefined) {
|
|
1208
|
+
const init = initializeNativeSnapshotRuntime(ctx, options);
|
|
1209
|
+
entry = { refs: 0, disposed: false, init };
|
|
1210
|
+
nativeRuntimes.set(key, entry);
|
|
1211
|
+
void init.catch(() => {
|
|
1212
|
+
// A failed initialization must not poison the registry; allow a clean retry.
|
|
1213
|
+
if (nativeRuntimes.get(key) === entry)
|
|
1214
|
+
nativeRuntimes.delete(key);
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
entry.refs += 1;
|
|
1218
|
+
const owned = entry;
|
|
1219
|
+
const runtime = await owned.init;
|
|
1220
|
+
owned.runtime = runtime;
|
|
1221
|
+
// The registry erases the client type; the key includes the injected dependency identity.
|
|
1222
|
+
const typed = runtime;
|
|
1223
|
+
let released = false;
|
|
1224
|
+
return {
|
|
1225
|
+
...typed,
|
|
1226
|
+
async release() {
|
|
1227
|
+
if (released)
|
|
1228
|
+
return;
|
|
1229
|
+
released = true;
|
|
1230
|
+
await releaseNativeSnapshotRuntime(key, owned);
|
|
1231
|
+
},
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
async function releaseNativeSnapshotRuntime(key, entry) {
|
|
1235
|
+
if (entry.disposed)
|
|
1236
|
+
return;
|
|
1237
|
+
entry.refs -= 1;
|
|
1238
|
+
if (entry.refs > 0)
|
|
1239
|
+
return;
|
|
1240
|
+
entry.disposed = true;
|
|
1241
|
+
nativeRuntimes.delete(key);
|
|
1242
|
+
const runtime = entry.runtime ?? (await entry.init);
|
|
1243
|
+
await runtime.release();
|
|
1244
|
+
}
|
|
1245
|
+
// END_BLOCK_NATIVE_SNAPSHOT_RUNTIME
|
|
1246
|
+
//# sourceMappingURL=context.js.map
|