@tryvira/opencode 0.1.18 → 0.1.20

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 (3) hide show
  1. package/README.md +15 -2
  2. package/dist/index.js +495 -90
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # `@tryvira/opencode` 0.1.15
1
+ # `@tryvira/opencode` 0.1.20
2
2
 
3
3
  OpenCode V2 server plugin for Vira host lifecycle governance. The package default
4
4
  exports the V2 setup surface plus a compatibility `server()` transport required
@@ -7,7 +7,17 @@ exported separately as `v1Fallback` and is not the old unconditional-deny path.
7
7
 
8
8
  It resolves Vira behavior on every `context` hook, observes tool results, and in `enforce` mode blocks tool execution unless a host action authorizer returns an exact Vira `ALLOW` receipt. OpenCode V2 does not expose a supported response-before-display hook, so post-model verification is reported as unsupported rather than claimed as enforced.
9
9
 
10
- Configuration is supplied through OpenCode plugin options or environment variables: `VIRA_CONTROL_URL`, `VIRA_API_KEY`, `VIRA_ORGANIZATION_ID`, `VIRA_PROJECT_ID`, `VIRA_ENVIRONMENT_ID`, `VIRA_AI_SYSTEM_ID`, `VIRA_CONNECTION_ID`, and `VIRA_HOST_MODE` (`off`, `observe`, `enforce`). In enforce mode, provide an explicit `confirmAction(proposal)` callback for effectful actions. The callback must return `true` only after the customer confirms the exact tool and arguments; the plugin then creates a server-owned one-use approval bound to that proposal. A denial, expiry, changed argument set, or replay remains blocked. The plugin never treats model text or `confirmed:true` supplied by a caller as confirmation.
10
+ When a context event includes the assistant message that was produced, the
11
+ plugin records it as a `conversation.output` observation with the same session,
12
+ connection, trace and idempotency identity as the request. This is best-effort
13
+ observation: a transport failure does not turn a successful model response into
14
+ a failed response. User-only, tool-only and image-only events are not recorded
15
+ as assistant output. Hosts that do not include assistant messages in context
16
+ events must submit output observations through their normal Vira SDK integration.
17
+
18
+ Configuration is supplied through OpenCode plugin options or environment variables: `VIRA_CONTROL_URL`, `VIRA_API_KEY`, `VIRA_ORGANIZATION_ID`, `VIRA_PROJECT_ID`, `VIRA_ENVIRONMENT_ID`, `VIRA_AI_SYSTEM_ID`, `VIRA_CONNECTION_ID`, and `VIRA_HOST_MODE` (`off`, `observe`, `enforce`). `adapterVersion` (or `VIRA_ADAPTER_VERSION`) is the stable Vira adapter protocol version and is intentionally separate from the OpenCode application version; leave it at `1` unless the adapter contract changes. V1 `server()` and V2 `setup()` read the same options, so a fixed connection identity is not recreated with a changing host application version.
19
+
20
+ In `enforce` mode, V2 uses OpenCode's native `permission.evaluate` hook. Effectful tool calls are changed to `ask`; the customer confirms the exact tool in OpenCode's own permission UI, and only then does the plugin create a server-owned one-use approval bound to that proposal. JSON options cannot contain a confirmation callback or a `confirmed` flag. `permissionMode:"deny"` disables the native bridge and therefore fails closed. A denial, expiry, changed argument set, or replay remains blocked. The optional `confirmAction` is retained only as a programmatic embedding seam for tests/host adapters; it is not a JSON-configured approval mechanism. V1 hosts without the native permission hook remain fail-closed for approval-required actions.
11
21
  For an isolated loopback-only test boundary, `VIRA_ALLOW_INSECURE_LOCALHOST=true` may be set; production API URLs must remain HTTPS.
12
22
 
13
23
  `enforce` requires a host-provided `authorizeAction` callback that calls the
@@ -29,3 +39,6 @@ remain a separate compatibility surface. On OpenCode 1.19.x, which only accepts
29
39
  the `server()` contract, that fallback uses the same session-bound context,
30
40
  expiry, digest, authorization, and receipt rules rather than an unconditional
31
41
  deny path.
42
+ ### Quality signals
43
+
44
+ On current OpenCode V2, the plugin also subscribes to the server event stream when available. Events carrying `feedback`/`userFeedback` or `outcome`/`businessOutcome` are converted into separate `feedback.user` and `business.outcome` records. Older hosts can call the exported `recordUserCorrection` and `recordBusinessOutcome` helpers. Both paths send only status, reason codes and SHA-256 digests; raw correction or outcome content never leaves the host.
package/dist/index.js CHANGED
@@ -204,13 +204,31 @@ var ViraClient = class {
204
204
  if (!systemResult) return null;
205
205
  const systemId = String(systemResult.body.system.id ?? "");
206
206
  required(systemId, "SDK_SYSTEM_ID_MISSING");
207
- const connectionResult = await this.connectAdapter(systemId, {
208
- adapterType: input.adapterType,
209
- adapterVersion: input.adapterVersion,
210
- capabilities: input.capabilities,
211
- config: input.config,
212
- idempotencyKey: input.idempotencyKey
213
- });
207
+ let connectionResult;
208
+ try {
209
+ connectionResult = await this.connectAdapter(systemId, {
210
+ adapterType: input.adapterType,
211
+ adapterVersion: input.adapterVersion,
212
+ capabilities: input.capabilities,
213
+ config: input.config,
214
+ idempotencyKey: input.idempotencyKey
215
+ });
216
+ } catch (error) {
217
+ if (!(input.reuseExistingConnectionOnConflict !== false && error instanceof ViraApiError && error.status === 409)) throw error;
218
+ const listed = await this.listSystemConnections(systemId);
219
+ const connections = Array.isArray(listed?.body?.connections) ? listed.body.connections : [];
220
+ const requested = new Set((input.capabilities ?? []).map(String));
221
+ const reused = connections.find((connection) => String(connection.adapterType ?? "") === input.adapterType && requested.size <= new Set(Array.isArray(connection.capabilities) ? connection.capabilities.map(String) : []).size && [...requested].every((capability) => (Array.isArray(connection.capabilities) ? connection.capabilities.map(String) : []).includes(capability)));
222
+ if (!reused) throw error;
223
+ const verified = await this.getConnection(String(reused.id ?? ""));
224
+ const verifiedConnection = verified?.body?.connection && typeof verified.body.connection === "object" ? verified.body.connection : null;
225
+ if (!verifiedConnection || String(verifiedConnection.adapterType ?? "") !== input.adapterType) throw error;
226
+ const verifiedCapabilities = Array.isArray(verifiedConnection.capabilities) ? verifiedConnection.capabilities.map(String) : [];
227
+ if (![...requested].every((capability) => verifiedCapabilities.includes(capability))) throw error;
228
+ const fromVersion = String(verifiedConnection.adapterVersion ?? "");
229
+ const transition = fromVersion === input.adapterVersion ? "UNCHANGED" : "REUSE_COMPATIBLE";
230
+ connectionResult = { status: 200, requestId: verified?.requestId ?? listed?.requestId ?? error.requestId, body: { connection: verifiedConnection, handshake: { adapterType: input.adapterType, accepted: verifiedCapabilities, rejected: [], configValid: true, reusedExistingConnection: true, adapterVersionTransition: { from: fromVersion, to: input.adapterVersion, mode: transition } } } };
231
+ }
214
232
  if (!connectionResult) return null;
215
233
  const connectedId = String(connectionResult.body.connection?.id ?? "").trim();
216
234
  if (connectedId) this.boundConnectionId = connectedId;
@@ -225,9 +243,19 @@ var ViraClient = class {
225
243
  };
226
244
  }
227
245
  observe(event, options = {}) {
228
- return this.request(buildObservationRequest(event), {
229
- idempotencyKey: options.idempotencyKey ?? event.eventId
230
- });
246
+ buildObservationRequest(event);
247
+ return (async () => {
248
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : void 0;
249
+ const source = event.attributes && typeof event.attributes === "object" ? String(event.attributes.source ?? "") : "";
250
+ const safeEvent = source === "opencode.context" && payload && typeof payload.text === "string" ? { ...event, payload: { ...payload, text: void 0, textDigest: (await contentIdempotencyKey("observation:text", payload.text)).split(":").pop(), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } } : event;
251
+ const response = await this.request(buildObservationRequest(safeEvent), {
252
+ idempotencyKey: options.idempotencyKey ?? event.eventId
253
+ });
254
+ if (event.eventType === "conversation.output") {
255
+ await this.request(buildObservationRequest({ ...safeEvent, eventType: "model.response", eventId: `${event.eventId}:model.response`, payload: { ...safeEvent.payload ?? {}, status: "completed" } }), { idempotencyKey: `${options.idempotencyKey ?? event.eventId}:model.response` });
256
+ }
257
+ return response;
258
+ })();
231
259
  }
232
260
  trace(event, options = {}) {
233
261
  return this.observe({ ...event, eventType: "model.response" }, options);
@@ -472,9 +500,12 @@ var ViraClient = class {
472
500
  const body = semantic.body;
473
501
  const receipt = body.receipt && typeof body.receipt === "object" ? body.receipt : {};
474
502
  if (receipt.outcome !== "select" || typeof receipt.taskKey !== "string")
475
- return { semantic, runtime: null };
503
+ return { semantic, runtime: null, taskKeys: [], capsules: [], multiTask: false };
476
504
  const capsules = Array.isArray(body.capsules) ? body.capsules : [];
477
- const firstCapsule = capsules[0] && typeof capsules[0] === "object" ? capsules[0] : {};
505
+ const candidateValues = Array.isArray(body.intentCandidates) ? body.intentCandidates : Array.isArray(body.selectedTaskKeys) ? body.selectedTaskKeys : [];
506
+ const taskKeys = [...new Set(candidateValues.map((value) => typeof value === "string" ? value.trim() : value && typeof value === "object" ? String(value.taskKey ?? value.semanticTaskKey ?? "").trim() : "").filter(Boolean))];
507
+ if (!taskKeys.length) taskKeys.push(receipt.taskKey.trim());
508
+ const firstCapsule = capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) && typeof capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) === "object" ? capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) : capsules[0] && typeof capsules[0] === "object" ? capsules[0] : {};
478
509
  const behaviorPoint = typeof firstCapsule.behaviorKey === "string" && firstCapsule.behaviorKey.trim() ? firstCapsule.behaviorKey : receipt.taskKey;
479
510
  const runtime = input.executionBoundary ? await this.resolveBoundary({
480
511
  executionBoundary: input.executionBoundary,
@@ -482,16 +513,17 @@ var ViraClient = class {
482
513
  taskKey: receipt.taskKey,
483
514
  behaviorPoint,
484
515
  capsule: firstCapsule,
516
+ ...input.revisionId ? { revisionId: input.revisionId } : {},
485
517
  ...input.requestId ? { requestId: input.requestId } : {},
486
518
  ...input.sessionId ? { conversationId: input.sessionId } : {},
487
519
  ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {}
488
520
  },
489
521
  idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
490
522
  }) : await this.resolveRuntime({
491
- semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule, ...input.requestId ? { requestId: input.requestId } : {}, ...input.sessionId ? { conversationId: input.sessionId } : {}, ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {} },
523
+ semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule, ...input.revisionId ? { revisionId: input.revisionId } : {}, ...input.requestId ? { requestId: input.requestId } : {}, ...input.sessionId ? { conversationId: input.sessionId } : {}, ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {} },
492
524
  idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
493
525
  });
494
- return { semantic, runtime };
526
+ return { semantic, runtime, taskKeys, capsules, multiTask: taskKeys.length > 1 };
495
527
  }
496
528
  async authorizeHostAction(input) {
497
529
  required(input.scope.organizationId, "SDK_ACTION_ORGANIZATION_REQUIRED");
@@ -701,7 +733,7 @@ var ViraClient = class {
701
733
  if (!Number.isInteger(expectedVersion) || expectedVersion < 0) throw new Error("SDK_TASKRUN_STATE_VERSION_REQUIRED");
702
734
  return this.request({ method: "POST", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/continue`, body: { expectedVersion, ...options.cursor ? { cursor: options.cursor } : {} } }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:continue:${taskRunId}:${expectedVersion}` });
703
735
  }
704
- cancelTaskRun(taskRunId, expectedVersion, options = {}) {
736
+ cancelTaskRun(taskRunId, expectedVersion = 0, options = {}) {
705
737
  required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
706
738
  if (!Number.isInteger(expectedVersion) || expectedVersion < 0) throw new Error("SDK_TASKRUN_STATE_VERSION_REQUIRED");
707
739
  return this.request({ method: "POST", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/cancel`, body: { expectedVersion } }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:cancel:${taskRunId}:${expectedVersion}` });
@@ -802,6 +834,12 @@ var ViraClient = class {
802
834
  { idempotencyKey: options.idempotencyKey }
803
835
  );
804
836
  }
837
+ submitTeachConversationEvidence(evidence, options = {}) {
838
+ required(evidence.conversationId, "SDK_TEACH_CONVERSATION_ID_REQUIRED");
839
+ required(evidence.message, "SDK_TEACH_CONVERSATION_MESSAGE_REQUIRED");
840
+ if (evidence.consent !== true) throw new Error("SDK_TEACH_CONVERSATION_CONSENT_REQUIRED");
841
+ return this.request({ method: "POST", path: "/v1/teach/conversations", body: { ...evidence, privacy: evidence.privacy ?? "CONSENTED_TENANT" } }, { idempotencyKey: options.idempotencyKey });
842
+ }
805
843
  listConversationArchive(input = {}) {
806
844
  return this.request({ method: "GET", path: "/v1/teach/conversations", query: { ...input.limit === void 0 ? {} : { limit: String(input.limit) }, ...input.cursor ? { cursor: input.cursor } : {} } });
807
845
  }
@@ -1128,10 +1166,11 @@ function buildObservationRequest(event) {
1128
1166
  throw new Error("SDK_OBSERVATION_SCOPE_REQUIRED");
1129
1167
  if (!event?.eventId || !event.eventType || !event.aiSystemId || !event.connectionId)
1130
1168
  throw new Error("SDK_OBSERVATION_FIELD_REQUIRED");
1169
+ const safeEvent = event;
1131
1170
  return Object.freeze({
1132
1171
  method: "POST",
1133
1172
  path: "/v1/observations",
1134
- body: Object.freeze({ ...event })
1173
+ body: Object.freeze({ ...safeEvent })
1135
1174
  });
1136
1175
  }
1137
1176
 
@@ -1151,6 +1190,41 @@ var lifecycleTimeout = (value) => {
1151
1190
  if (!Number.isFinite(parsed) || parsed < 250) throw new Error("SDK_HOST_TIMEOUT_INVALID");
1152
1191
  return Math.min(Math.floor(parsed), 12e4);
1153
1192
  };
1193
+ var toolSessionTimeout = (value, fallback) => {
1194
+ const parsed = Number(value ?? fallback);
1195
+ if (!Number.isFinite(parsed) || parsed < 250) throw new Error("SDK_HOST_TOOL_SESSION_TIMEOUT_INVALID");
1196
+ return Math.min(Math.floor(parsed), 6e5);
1197
+ };
1198
+ var observationMaxBytes = (value) => {
1199
+ const parsed = Number(value ?? 16384);
1200
+ if (!Number.isFinite(parsed) || parsed < 512) throw new Error("SDK_HOST_OBSERVATION_BUDGET_INVALID");
1201
+ return Math.min(Math.floor(parsed), 256e3);
1202
+ };
1203
+ var sensitiveKey = /(?:authorization|cookie|set-cookie|password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|client[_-]?secret|refresh[_-]?token|id[_-]?token|session[_-]?token|ssn|social[_-]?security|credit[_-]?card|card[_-]?number|cvv|cvc|bank[_-]?account|iban|routing[_-]?number|date[_-]?of[_-]?birth|birth[_-]?date|email|phone|mobile|address|postal|zip)/i;
1204
+ var sensitiveValue = /(?:bearer\s+[a-z0-9._~+/=-]{8,}|(?:sk|pk|vira|evren|ghp|github_pat|xox[baprs])-[_a-z0-9-]{8,}|(?:eyj[a-z0-9_-]{10,}\.){2}[a-z0-9_-]{10,}|\b(?:\d[ -]*?){13,19}\b|\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b|\+?\d[\d ()-]{7,}\d)/i;
1205
+ var redactMarker = "[REDACTED]";
1206
+ var redactToolValue = (value, redactKeys, depth = 0) => {
1207
+ if (depth > 8) return "[TRUNCATED_DEPTH]";
1208
+ if (typeof value === "string") return sensitiveValue.test(value) ? redactMarker : value.length > 4096 ? `${value.slice(0, 4096)}\u2026[TRUNCATED]` : value;
1209
+ if (value === null || typeof value === "number" || typeof value === "boolean") return value;
1210
+ if (Array.isArray(value)) return value.slice(0, 100).map((item) => redactToolValue(item, redactKeys, depth + 1));
1211
+ if (value && typeof value === "object") {
1212
+ const output = {};
1213
+ for (const [key, child] of Object.entries(value).slice(0, 200)) {
1214
+ output[key] = sensitiveKey.test(key) || redactKeys.some((candidate) => candidate.trim() && candidate.toLowerCase() === key.toLowerCase()) ? redactMarker : redactToolValue(child, redactKeys, depth + 1);
1215
+ }
1216
+ return output;
1217
+ }
1218
+ return String(value);
1219
+ };
1220
+ function redactToolObservation(value, options = {}) {
1221
+ const budget = observationMaxBytes(options.maxBytes);
1222
+ const keys = options.redactKeys ?? [];
1223
+ const sanitized = redactToolValue(value, keys);
1224
+ const serialized = JSON.stringify(sanitized);
1225
+ if (Buffer.byteLength(serialized, "utf8") <= budget) return { value: sanitized, redacted: serialized.includes(redactMarker), truncated: serialized.includes("[TRUNCATED_") };
1226
+ return { value: { summary: "[REDACTED_TOOL_RESULT]", bytes: Buffer.byteLength(serialized, "utf8"), budget }, redacted: true, truncated: true };
1227
+ }
1154
1228
  var withTimeout = async (operation, timeoutMs, code) => {
1155
1229
  let timer;
1156
1230
  try {
@@ -1179,34 +1253,67 @@ function createViraHostRuntime(client, config) {
1179
1253
  if (!capabilities || typeof capabilities !== "object") throw new Error("SDK_HOST_CAPABILITIES_REQUIRED");
1180
1254
  const maxBytes = bounded(config.projectionMaxBytes, 8e3);
1181
1255
  const timeoutMs = lifecycleTimeout(config.timeoutMs);
1256
+ const toolSessionTimeoutMs = toolSessionTimeout(config.toolSessionTimeoutMs, timeoutMs);
1257
+ const toolObservationMaxBytes = observationMaxBytes(config.toolObservationMaxBytes);
1258
+ const toolObservationRedactKeys = config.toolObservationRedactKeys ?? [];
1182
1259
  if (mode === "enforce" && (!capabilities.canInterceptToolBefore || !capabilities.canPreventSideEffect)) throw new Error("SDK_HOST_ENFORCE_CAPABILITY_REQUIRED");
1183
1260
  if (mode === "enforce" && typeof config.authorizeAction !== "function") throw new Error("SDK_HOST_ACTION_AUTHORIZER_REQUIRED");
1184
1261
  let connected = null;
1185
1262
  let connectionIdentity = null;
1186
1263
  const projections = /* @__PURE__ */ new Map();
1187
- const activeToolSessions = /* @__PURE__ */ new Set();
1188
- const connectOnce = async () => {
1264
+ const activeToolSessions = /* @__PURE__ */ new Map();
1265
+ const connectOnce = async (options = {}) => {
1189
1266
  if (mode === "off" || !config.connect) return null;
1190
- if (!connected) connected = withTimeout(client.connectOnce(config.connect), timeoutMs, "SDK_HOST_CONNECT_TIMEOUT").then((result) => {
1191
- const body = bodyOf(result);
1192
- const system = body.system && typeof body.system === "object" ? body.system : {};
1193
- const connection = body.connection && typeof body.connection === "object" ? body.connection : {};
1194
- const aiSystemId = typeof system.id === "string" ? system.id.trim() : "";
1195
- const connectionId = typeof connection.id === "string" ? connection.id.trim() : "";
1196
- if (!aiSystemId || !connectionId) throw new Error("SDK_HOST_CONNECT_IDENTITY_MISSING");
1197
- connectionIdentity = { aiSystemId, connectionId };
1198
- return result;
1199
- });
1267
+ if (options.force) {
1268
+ connected = null;
1269
+ connectionIdentity = null;
1270
+ }
1271
+ if (!connected) {
1272
+ const attempt = withTimeout(client.connectOnce(config.connect), timeoutMs, "SDK_HOST_CONNECT_TIMEOUT").then((result) => {
1273
+ const body = bodyOf(result);
1274
+ const system = body.system && typeof body.system === "object" ? body.system : {};
1275
+ const connection = body.connection && typeof body.connection === "object" ? body.connection : {};
1276
+ const aiSystemId = typeof system.id === "string" ? system.id.trim() : "";
1277
+ const connectionId = typeof connection.id === "string" ? connection.id.trim() : "";
1278
+ if (!aiSystemId || !connectionId) throw new Error("SDK_HOST_CONNECT_IDENTITY_MISSING");
1279
+ connectionIdentity = { aiSystemId, connectionId };
1280
+ return result;
1281
+ });
1282
+ let cachedAttempt;
1283
+ cachedAttempt = attempt.catch((error) => {
1284
+ if (connected === cachedAttempt) connected = null;
1285
+ connectionIdentity = null;
1286
+ throw error;
1287
+ });
1288
+ connected = cachedAttempt;
1289
+ }
1200
1290
  return connected;
1201
1291
  };
1292
+ const reconnect = async () => connectOnce({ force: true });
1202
1293
  const sessionKey = (request) => `${request.organizationId}:${request.projectId}:${request.environmentId}:${request.conversationId}`;
1203
1294
  const beforeModel = async (request) => {
1204
1295
  nonEmpty(request.input, "SDK_HOST_MODEL_INPUT_REQUIRED");
1205
1296
  if (mode === "off") return { status: "off" };
1206
1297
  if (!capabilities.canInjectContext) return { status: "unavailable", reasonCode: "HOST_CONTEXT_INJECTION_UNSUPPORTED" };
1298
+ if (capabilities.canObserveModel) {
1299
+ void client.observe({ eventId: `${request.conversationId}:conversation.input:${request.requestId}`, eventType: "conversation.input", aiSystemId: request.aiSystemId, connectionId: request.connectionId, organizationId: request.organizationId, projectId: request.projectId, environmentId: request.environmentId, conversationId: request.conversationId, requestId: request.requestId, traceId: request.traceId, payload: { inputDigest: digest(request.input), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } }, { idempotencyKey: `sdk:conversation.input:${request.conversationId}:${request.requestId}` }).catch(() => void 0);
1300
+ void client.observe({ eventId: `${request.conversationId}:model.request:${request.requestId}`, eventType: "model.request", aiSystemId: request.aiSystemId, connectionId: request.connectionId, organizationId: request.organizationId, projectId: request.projectId, environmentId: request.environmentId, conversationId: request.conversationId, requestId: request.requestId, traceId: request.traceId, payload: { inputDigest: digest(request.input), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } }, { idempotencyKey: `sdk:model.request:${request.conversationId}:${request.requestId}` }).catch(() => void 0);
1301
+ }
1207
1302
  await connectOnce();
1208
- const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
1303
+ const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, profile: request.profile, revisionId: request.revisionId, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
1209
1304
  if (!semantic) return { status: "unavailable", reasonCode: "VIRA_SEMANTIC_UNAVAILABLE" };
1305
+ if (semantic.multiTask === true && semantic.taskKeys?.length > 1 && typeof client.startTaskRunFromPrompt === "function") {
1306
+ try {
1307
+ const admitted = await withTimeout(client.startTaskRunFromPrompt({ input: request.input, taskRunId: `host-task-run-${request.requestId}`, requestId: request.requestId, conversationId: request.conversationId, traceRootRef: request.traceId }), timeoutMs, "SDK_HOST_TASKRUN_ADMISSION_TIMEOUT");
1308
+ const admittedBody = bodyOf(admitted);
1309
+ const taskRun = admittedBody.taskRun && typeof admittedBody.taskRun === "object" ? admittedBody.taskRun : {};
1310
+ const taskRunId = typeof taskRun.taskRunId === "string" ? taskRun.taskRunId : `host-task-run-${request.requestId}`;
1311
+ const taskRunStateVersion = Number(taskRun.stateVersion);
1312
+ return { status: "task_run", response: admitted, taskRunId, ...Number.isInteger(taskRunStateVersion) && taskRunStateVersion >= 0 ? { taskRunStateVersion } : {}, selectedTaskKeys: semantic.taskKeys };
1313
+ } catch (error) {
1314
+ return { status: "unavailable", selectedTaskKeys: semantic.taskKeys, reasonCode: error instanceof Error ? error.message : "SDK_HOST_TASKRUN_ADMISSION_FAILED" };
1315
+ }
1316
+ }
1210
1317
  const semanticBody = bodyOf(semantic.semantic);
1211
1318
  const receipt = semanticBody.receipt && typeof semanticBody.receipt === "object" ? semanticBody.receipt : {};
1212
1319
  if (receipt.outcome !== "select" || typeof receipt.taskKey !== "string" || !semantic.runtime) {
@@ -1228,38 +1335,76 @@ function createViraHostRuntime(client, config) {
1228
1335
  nonEmpty(proposal.toolName, "SDK_HOST_TOOL_NAME_REQUIRED");
1229
1336
  if (mode !== "enforce") return { decision: "ABSTAIN", reasonCode: mode === "off" ? "HOST_MODE_OFF" : "OBSERVE_ONLY" };
1230
1337
  const toolSessionKey = `${proposal.organizationId}:${proposal.projectId}:${proposal.environmentId}:${proposal.conversationId}:${proposal.sessionId ?? proposal.conversationId}`;
1231
- if (activeToolSessions.has(toolSessionKey)) return { decision: "BLOCK", reasonCode: "SDK_HOST_TOOL_IN_FLIGHT" };
1232
- activeToolSessions.add(toolSessionKey);
1338
+ const current = activeToolSessions.get(toolSessionKey);
1339
+ if (current && current.expiresAt > Date.now()) return { decision: "BLOCK", reasonCode: "SDK_HOST_TOOL_IN_FLIGHT" };
1340
+ if (current) {
1341
+ clearTimeout(current.timer);
1342
+ activeToolSessions.delete(toolSessionKey);
1343
+ }
1344
+ const expiresAt = Date.now() + toolSessionTimeoutMs;
1345
+ const timer = setTimeout(() => {
1346
+ const held = activeToolSessions.get(toolSessionKey);
1347
+ if (held?.callId === proposal.callId) activeToolSessions.delete(toolSessionKey);
1348
+ }, toolSessionTimeoutMs);
1349
+ timer.unref?.();
1350
+ activeToolSessions.set(toolSessionKey, { callId: proposal.callId, expiresAt, timer });
1233
1351
  let decision;
1234
1352
  try {
1235
1353
  const authorized = await withTimeout(Promise.resolve(config.authorizeAction(proposal)), timeoutMs, "SDK_HOST_ACTION_AUTHORIZATION_TIMEOUT");
1236
1354
  const authorizedBody = bodyOf(authorized);
1237
1355
  decision = typeof authorizedBody.decision === "string" ? authorizedBody : authorized;
1238
1356
  } catch {
1239
- activeToolSessions.delete(toolSessionKey);
1357
+ const held = activeToolSessions.get(toolSessionKey);
1358
+ if (held?.callId === proposal.callId) {
1359
+ clearTimeout(held.timer);
1360
+ activeToolSessions.delete(toolSessionKey);
1361
+ }
1240
1362
  return { decision: "ERROR", reasonCode: "VIRA_ACTION_AUTHORIZATION_TIMEOUT" };
1241
1363
  }
1242
1364
  if (!decision || !["ALLOW", "BLOCK", "ESCALATE", "ABSTAIN", "ERROR"].includes(decision.decision)) {
1243
- activeToolSessions.delete(toolSessionKey);
1365
+ const held = activeToolSessions.get(toolSessionKey);
1366
+ if (held?.callId === proposal.callId) {
1367
+ clearTimeout(held.timer);
1368
+ activeToolSessions.delete(toolSessionKey);
1369
+ }
1244
1370
  throw new Error("SDK_HOST_ACTION_DECISION_INVALID");
1245
1371
  }
1246
- if (decision.decision !== "ALLOW") activeToolSessions.delete(toolSessionKey);
1372
+ if (decision.decision !== "ALLOW") {
1373
+ const held = activeToolSessions.get(toolSessionKey);
1374
+ if (held?.callId === proposal.callId) {
1375
+ clearTimeout(held.timer);
1376
+ activeToolSessions.delete(toolSessionKey);
1377
+ }
1378
+ }
1247
1379
  if (decision.decision === "ALLOW" && !isAllow(decision)) {
1248
- activeToolSessions.delete(toolSessionKey);
1380
+ const held = activeToolSessions.get(toolSessionKey);
1381
+ if (held?.callId === proposal.callId) {
1382
+ clearTimeout(held.timer);
1383
+ activeToolSessions.delete(toolSessionKey);
1384
+ }
1249
1385
  throw new Error("SDK_HOST_ALLOW_RECEIPT_INVALID");
1250
1386
  }
1251
1387
  return decision;
1252
1388
  };
1253
1389
  const afterTool = async (result) => {
1254
1390
  nonEmpty(result.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
1255
- if (mode === "off" || !capabilities.canInspectToolAfter) return { status: "off" };
1391
+ if (mode === "off") return { status: "off" };
1392
+ if (!capabilities.canInspectToolAfter) return { status: "skipped", executionCommitted: true };
1256
1393
  const toolSessionKey = `${result.organizationId}:${result.projectId}:${result.environmentId}:${result.conversationId}:${result.sessionId ?? result.conversationId}`;
1257
- const observedResult = result.ok ? result.result : { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" };
1394
+ const minimized = result.ok ? redactToolObservation(result.result, { maxBytes: toolObservationMaxBytes, redactKeys: toolObservationRedactKeys }) : { value: { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" }, redacted: false, truncated: false };
1395
+ const observedResult = minimized.value;
1258
1396
  const evidence = { abi: "vira.host-tool-evidence.v1", eventId: result.callId, callId: result.callId, toolName: result.toolName, argumentsDigest: digest(result.args), resultDigest: result.resultDigest ?? digest(observedResult), outcome: result.ok ? "success" : "failure", ...result.authorityReceiptDigest ? { authorityReceiptDigest: result.authorityReceiptDigest } : {}, ...result.decisionDigest ? { decisionDigest: result.decisionDigest } : {}, requestId: result.requestId, conversationId: result.conversationId, ...result.sessionId ? { sessionId: result.sessionId } : {}, ...result.turnId ? { turnId: result.turnId } : {} };
1259
1397
  try {
1260
- return await withTimeout(client.observe({ eventId: result.callId, eventType: result.ok ? "tool.result" : "tool.failed", aiSystemId: result.aiSystemId, connectionId: result.connectionId, organizationId: result.organizationId, projectId: result.projectId, environmentId: result.environmentId, conversationId: result.conversationId, requestId: result.requestId, traceId: result.traceId, payload: { result: observedResult, evidence }, resultDigest: evidence.resultDigest }), timeoutMs, "SDK_HOST_OBSERVE_TIMEOUT");
1398
+ const response = await withTimeout(client.observe({ eventId: result.callId, eventType: result.ok ? "tool.result" : "tool.failed", aiSystemId: result.aiSystemId, connectionId: result.connectionId, organizationId: result.organizationId, projectId: result.projectId, environmentId: result.environmentId, conversationId: result.conversationId, requestId: result.requestId, traceId: result.traceId, payload: { result: observedResult, evidence, minimization: { redacted: minimized.redacted, truncated: minimized.truncated, budgetBytes: toolObservationMaxBytes } }, resultDigest: evidence.resultDigest }), timeoutMs, "SDK_HOST_OBSERVE_TIMEOUT");
1399
+ return { status: "observed", response, executionCommitted: true };
1400
+ } catch (error) {
1401
+ return { status: "failed", errorCode: error instanceof Error ? error.message : "SDK_HOST_OBSERVE_FAILED", executionCommitted: true };
1261
1402
  } finally {
1262
- activeToolSessions.delete(toolSessionKey);
1403
+ const held = activeToolSessions.get(toolSessionKey);
1404
+ if (held?.callId === result.callId) {
1405
+ clearTimeout(held.timer);
1406
+ activeToolSessions.delete(toolSessionKey);
1407
+ }
1263
1408
  }
1264
1409
  };
1265
1410
  const executeTool = async (input) => {
@@ -1279,11 +1424,19 @@ function createViraHostRuntime(client, config) {
1279
1424
  throw Object.assign(error instanceof Error ? error : new Error(errorCode2), { decision, observation });
1280
1425
  }
1281
1426
  };
1427
+ const cancelTool = (identity, callId) => {
1428
+ const key = `${identity.organizationId}:${identity.projectId}:${identity.environmentId}:${identity.conversationId}:${identity.sessionId ?? identity.conversationId}`;
1429
+ const held = activeToolSessions.get(key);
1430
+ if (!held || callId && held.callId !== callId) return false;
1431
+ clearTimeout(held.timer);
1432
+ activeToolSessions.delete(key);
1433
+ return true;
1434
+ };
1282
1435
  const endSession = (identity) => {
1283
1436
  projections.delete(sessionKey({ ...identity, requestId: "session-end", input: "" }));
1284
- activeToolSessions.delete(`${identity.organizationId}:${identity.projectId}:${identity.environmentId}:${identity.conversationId}:${identity.sessionId ?? identity.conversationId}`);
1437
+ cancelTool(identity);
1285
1438
  };
1286
- return Object.freeze({ mode, capabilities, connectOnce, getConnectionIdentity: () => connectionIdentity, beforeModel, beforeTool, afterTool, executeTool, endSession, getProjection: (identity) => projections.get(sessionKey({ ...identity, requestId: "projection", input: "" })), supportsPostModelVerification: capabilities.canInterceptResponseBeforeDisplay });
1439
+ return Object.freeze({ mode, capabilities, connectOnce, reconnect, getConnectionIdentity: () => connectionIdentity, beforeModel, beforeTool, afterTool, executeTool, cancelTool, endSession, getProjection: (identity) => projections.get(sessionKey({ ...identity, requestId: "projection", input: "" })), supportsPostModelVerification: capabilities.canInterceptResponseBeforeDisplay });
1287
1440
  }
1288
1441
 
1289
1442
  // src/approval.ts
@@ -1300,7 +1453,8 @@ async function authorizeWithOneShotCustomerConfirmation(input) {
1300
1453
  const body = record(response?.body);
1301
1454
  return body.allowed === true ? { decision: "ALLOW", authorityReceiptDigest: text(body.authority_receipt_digest), decisionDigest: text(body.decision_digest) } : { decision: "BLOCK", reasonCode: text(body.reason_code) || "POLICY_DENIED", authorityReceiptDigest: text(body.authority_receipt_digest) };
1302
1455
  } catch (error) {
1303
- if (errorCode(error) !== "RUNTIME_ACTION_USER_APPROVAL_REQUIRED" || input.approvalId || typeof input.confirmAction !== "function") return { decision: "BLOCK", reasonCode: errorCode(error) || "RUNTIME_ACTION_AUTHORIZATION_FAILED" };
1456
+ if (errorCode(error) !== "RUNTIME_ACTION_USER_APPROVAL_REQUIRED" || input.approvalId) return { decision: "BLOCK", reasonCode: errorCode(error) || "RUNTIME_ACTION_AUTHORIZATION_FAILED" };
1457
+ if (typeof input.confirmAction !== "function") return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_APPROVAL_UNAVAILABLE" };
1304
1458
  if (await input.confirmAction({ ...input.proposal, approvalRequired: true }) !== true) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CUSTOMER_CONFIRMATION_DENIED" };
1305
1459
  const issued = await input.client.createHostActionApproval({ sessionId: input.sessionId, dataVersion: input.dataVersion, proposal: input.proposalBody, confirmation: { proposalId: text(input.proposalBody.proposal_id), toolName: text(input.proposalBody.tool_key), argumentsDigest: text(input.proposalBody.arguments_digest), requestContextDigest: text(input.proposalBody.request_context_digest), acknowledgedAt: (/* @__PURE__ */ new Date()).toISOString() } });
1306
1460
  const approvalId = text(record(issued?.body).approvalId);
@@ -1326,13 +1480,143 @@ var required2 = (value, code) => {
1326
1480
  var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
1327
1481
  var canonical2 = (value) => Array.isArray(value) ? "[" + value.map(canonical2).join(",") + "]" : value && typeof value === "object" ? "{" + Object.entries(value).filter(([, child]) => child !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => JSON.stringify(key) + ":" + canonical2(child)).join(",") + "}" : JSON.stringify(value);
1328
1482
  var digest2 = (value) => createHash2("sha256").update(canonical2(value), "utf8").digest("hex");
1483
+ var messageContentText = (value) => {
1484
+ if (typeof value === "string") return value.trim();
1485
+ if (!value || typeof value !== "object") return "";
1486
+ if (Array.isArray(value)) return value.map(messageContentText).filter(Boolean).join("\n").trim();
1487
+ const record2 = asRecord(value);
1488
+ if (record2.type === "image" || record2.type === "input_image") return "[image]";
1489
+ return messageContentText(record2.text ?? record2.content ?? record2.value);
1490
+ };
1329
1491
  var lastUserText = (event) => {
1330
1492
  const messages = Array.isArray(event.messages) ? event.messages : [];
1331
1493
  for (let index = messages.length - 1; index >= 0; index -= 1) {
1332
1494
  const message = asRecord(messages[index]);
1333
- if (message.role === "user") return text2(message.content ?? message.text);
1495
+ const role = text2(message.role ?? asRecord(message.info).role);
1496
+ if (role === "user") {
1497
+ const content = messageContentText(message.content ?? message.parts ?? message.text);
1498
+ if (content) return content;
1499
+ }
1500
+ }
1501
+ return messageContentText(event.input ?? event.prompt ?? event.message);
1502
+ };
1503
+ var latestAssistantText = (event) => {
1504
+ const messages = Array.isArray(event.messages) ? event.messages : [];
1505
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
1506
+ const message2 = asRecord(messages[index]);
1507
+ const role = text2(message2.role ?? asRecord(message2.info).role);
1508
+ if (role === "assistant") {
1509
+ const content = messageContentText(message2.content ?? message2.parts ?? message2.text);
1510
+ if (content) return content;
1511
+ }
1334
1512
  }
1335
- return text2(event.input ?? event.prompt);
1513
+ const message = asRecord(event.message);
1514
+ return text2(message.role ?? asRecord(message.info).role) === "assistant" ? messageContentText(message.content ?? message.parts ?? message.text) : "";
1515
+ };
1516
+ var conversationProfile = (event, options = {}) => {
1517
+ const messages = Array.isArray(event.messages) ? event.messages.slice(-20).map((value) => {
1518
+ const message = asRecord(value);
1519
+ return { role: text2(message.role ?? asRecord(message.info).role) || "unknown", text: messageContentText(message.content ?? message.parts ?? message.text) };
1520
+ }).filter((value) => value.text) : [];
1521
+ const model = asRecord(event.model);
1522
+ const hostOptions = asRecord(event.options);
1523
+ const workspaceId = text2(options.workspaceId ?? event.workspaceId ?? asRecord(event.workspace).id);
1524
+ const userId = text2(options.userId ?? event.userId ?? asRecord(event.user).id);
1525
+ return { history: messages, ...workspaceId || userId ? { scopeHierarchy: { ...workspaceId ? { workspaceId } : {}, ...userId ? { userId } : {}, sessionId: sessionRef(event) } } : {}, ...Object.keys(model).length ? { model: { provider: text2(model.provider), name: text2(model.name ?? model.model) } } : {}, ...Object.keys(hostOptions).length ? { hostOptions: { maxTokens: hostOptions.maxTokens, temperature: hostOptions.temperature, model: hostOptions.model, provider: hostOptions.provider } } : {} };
1526
+ };
1527
+ var modelMetadata = (event) => {
1528
+ const model = asRecord(event.model);
1529
+ const usage = asRecord(event.usage ?? event.tokenUsage);
1530
+ const cost = event.costMicros ?? event.cost;
1531
+ return { ...text2(model.provider) ? { provider: text2(model.provider) } : {}, ...text2(model.name ?? model.model) ? { model: text2(model.name ?? model.model) } : {}, ...Number.isFinite(Number(usage.inputTokens ?? usage.promptTokens)) ? { inputTokens: Number(usage.inputTokens ?? usage.promptTokens) } : {}, ...Number.isFinite(Number(usage.outputTokens ?? usage.completionTokens)) ? { outputTokens: Number(usage.outputTokens ?? usage.completionTokens) } : {}, ...Number.isFinite(Number(usage.totalTokens)) ? { totalTokens: Number(usage.totalTokens) } : {}, ...Number.isFinite(Number(cost)) ? { costMicros: Number(cost) } : {} };
1532
+ };
1533
+ var modelObservationPayload = (event, extra = {}) => ({ model: modelMetadata(event), ...extra, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } });
1534
+ var recordModelResponse = (client, identity, event, input) => client.observe({ ...identity, eventId: input.eventId, eventType: "model.response", conversationId: input.conversationId, requestId: input.requestId, traceId: input.traceId, payload: modelObservationPayload(event, { outputDigest: digest2(input.output), status: input.status ?? "completed", ...Number.isFinite(input.latencyMs) ? { latencyMs: input.latencyMs } : {}, ...input.projectionDigest ? { projectionDigest: input.projectionDigest } : {}, ...input.receiptDigest ? { receiptDigest: input.receiptDigest } : {}, ...input.releaseDigest ? { releaseDigest: input.releaseDigest } : {}, ...input.evaluationId ? { evaluationId: input.evaluationId } : {} }), resultDigest: digest2(input.output) }, { idempotencyKey: `opencode:model.response:${input.eventId}` });
1535
+ var recordConversationOutput = (client, identity, input) => client.observe({ ...identity, eventId: input.eventId, eventType: "conversation.output", conversationId: input.conversationId, requestId: input.requestId, traceId: input.traceId, payload: { outputDigest: digest2(input.output), ...Number.isFinite(input.latencyMs) ? { latencyMs: input.latencyMs } : {}, ...input.projectionDigest ? { projectionDigest: input.projectionDigest } : {}, ...input.receiptDigest ? { receiptDigest: input.receiptDigest } : {}, ...input.releaseDigest ? { releaseDigest: input.releaseDigest } : {}, ...input.evaluationId ? { evaluationId: input.evaluationId } : {}, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } }, resultDigest: digest2(input.output) }, { idempotencyKey: `opencode:conversation.output:${input.eventId}` });
1536
+ var recordModelMetrics = (client, identity, input) => {
1537
+ const common = { ...identity, conversationId: input.conversationId, requestId: input.requestId, traceId: input.traceId };
1538
+ const lineage = { ...input.releaseDigest ? { releaseDigest: input.releaseDigest } : {}, ...input.evaluationId ? { evaluationId: input.evaluationId } : {}, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } };
1539
+ const events = [];
1540
+ if (Number.isFinite(input.latencyMs)) events.push(client.observe({ ...common, eventId: `${input.eventId}:latency`, eventType: "latency", payload: { latencyMs: input.latencyMs, ...lineage } }, { idempotencyKey: `opencode:latency:${input.eventId}` }));
1541
+ if (Number.isFinite(input.costMicros)) events.push(client.observe({ ...common, eventId: `${input.eventId}:cost`, eventType: "cost", payload: { costMicros: input.costMicros, inputTokens: input.inputTokens, outputTokens: input.outputTokens, totalTokens: input.totalTokens, ...lineage } }, { idempotencyKey: `opencode:cost:${input.eventId}` }));
1542
+ return Promise.all(events);
1543
+ };
1544
+ var recordUserCorrection = (client, identity, input) => client.feedback({ ...identity, eventId: input.eventId, eventType: "feedback.user", conversationId: input.conversationId, requestId: input.requestId, traceId: input.traceId, payload: { status: input.status ?? "corrected", reasonCode: input.reasonCode ?? "USER_CORRECTION", ...input.correctedText ? { correctedOutputDigest: digest2(input.correctedText) } : {}, ...input.projectionDigest ? { projectionDigest: input.projectionDigest } : {}, ...input.receiptDigest ? { receiptDigest: input.receiptDigest } : {}, ...input.releaseDigest ? { releaseDigest: input.releaseDigest } : {}, ...input.evaluationId ? { evaluationId: input.evaluationId } : {}, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } }, { idempotencyKey: `opencode:feedback:${input.eventId}` });
1545
+ var recordBusinessOutcome = (client, identity, input) => client.outcome({ ...identity, eventId: input.eventId, eventType: "business.outcome", conversationId: input.conversationId, requestId: input.requestId, traceId: input.traceId, payload: { status: input.status, reasonCode: input.reasonCode ?? "HOST_REPORTED_OUTCOME", ...input.value !== void 0 ? { valueDigest: digest2(input.value) } : {}, ...input.projectionDigest ? { projectionDigest: input.projectionDigest } : {}, ...input.receiptDigest ? { receiptDigest: input.receiptDigest } : {}, ...input.releaseDigest ? { releaseDigest: input.releaseDigest } : {}, ...input.evaluationId ? { evaluationId: input.evaluationId } : {}, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } }, { idempotencyKey: `opencode:outcome:${input.eventId}` });
1546
+ var sessionRef = (event) => text2(event.sessionID ?? event.sessionId ?? event.conversationId ?? asRecord(event.session).id ?? asRecord(event.session).sessionID);
1547
+ var toolExecutionSucceeded = (input, output) => {
1548
+ const error = output.error ?? input.error;
1549
+ if (error !== void 0 && error !== null && error !== "") return false;
1550
+ const status = text2(output.status ?? input.status).toLowerCase();
1551
+ if (["failed", "failure", "error", "cancelled", "canceled", "blocked"].includes(status)) return false;
1552
+ if (["completed", "complete", "success", "succeeded", "ok"].includes(status)) return true;
1553
+ return output.ok === true || input.ok === true;
1554
+ };
1555
+ var envValue = (name) => typeof process !== "undefined" ? process.env[name] : void 0;
1556
+ var createV1PromptCache = (ttlMs) => {
1557
+ const ttl = Math.max(1e3, Math.min(3e5, Number(ttlMs) || 6e4));
1558
+ const entries = /* @__PURE__ */ new Map();
1559
+ const clear = (sessionId) => {
1560
+ const entry = entries.get(sessionId);
1561
+ if (entry) {
1562
+ clearTimeout(entry.timer);
1563
+ entries.delete(sessionId);
1564
+ }
1565
+ };
1566
+ return { set(sessionId, prompt) {
1567
+ clear(sessionId);
1568
+ const timer = setTimeout(() => entries.delete(sessionId), ttl);
1569
+ entries.set(sessionId, { prompt, timer });
1570
+ }, take(sessionId) {
1571
+ const entry = entries.get(sessionId);
1572
+ if (!entry) return void 0;
1573
+ clear(sessionId);
1574
+ return entry.prompt;
1575
+ }, clear, has: (sessionId) => entries.has(sessionId), size: () => entries.size };
1576
+ };
1577
+ var readHostOptions = (rawContext) => {
1578
+ const raw = asRecord(rawContext);
1579
+ const nested = asRecord(raw.options);
1580
+ return Object.keys(nested).length ? nested : raw;
1581
+ };
1582
+ var hostVersionFor = (options, rawContext = {}) => {
1583
+ const raw = asRecord(rawContext);
1584
+ const app = asRecord(raw.app);
1585
+ return options.hostVersion?.trim() || text2(app.version).trim() || text2(raw.version).trim() || envValue("VIRA_HOST_VERSION")?.trim() || "unknown";
1586
+ };
1587
+ var adapterVersionFor = (options) => options.adapterVersion ?? envValue("VIRA_ADAPTER_VERSION") ?? "1";
1588
+ var openCodeConnectConfig = (scope, options) => ({ ...scope, name: "OpenCode", systemType: "agent", adapterType: "custom-node", adapterVersion: adapterVersionFor(options), idempotencyKey: "opencode:vira:connect", reuseExistingConnectionOnConflict: true });
1589
+ var resolveOpenCodeToolBinding = (tools, toolName) => {
1590
+ const allowedToolIds = Array.isArray(tools.allowed_tool_ids) ? tools.allowed_tool_ids.map(text2) : [];
1591
+ const bindings = Array.isArray(tools.tool_bindings) ? tools.tool_bindings.filter((value) => value && typeof value === "object").map((value) => asRecord(value)) : [];
1592
+ const binding = bindings.find((value) => text2(value.host_action_name) === toolName || Array.isArray(value.aliases) && value.aliases.map(text2).includes(toolName));
1593
+ return { allowedToolIds, bindings, binding, canonicalToolId: text2(binding?.tool_id) || toolName, schemaDigest: text2(binding?.schema_digest) || text2(tools.schema_digest) };
1594
+ };
1595
+ var createDesktopPermissionBridge = () => {
1596
+ const pending = /* @__PURE__ */ new Map();
1597
+ const evaluate = (event) => {
1598
+ const sessionId = text2(event.sessionID);
1599
+ const action = text2(event.action);
1600
+ if (!sessionId || !action) return false;
1601
+ const key = `${sessionId}:${action}:${text2(asRecord(event.source).id)}`;
1602
+ pending.set(key, { expiresAt: Date.now() + 6e4, action });
1603
+ event.effect = "ask";
1604
+ event.message = `Vira requires one-time confirmation for ${action}. Confirm the exact tool and arguments in OpenCode.`;
1605
+ return true;
1606
+ };
1607
+ const confirm = (proposal) => {
1608
+ const sessionId = proposal.sessionId ?? proposal.conversationId;
1609
+ const prefix = `${sessionId}:${proposal.toolName}:`;
1610
+ const exact = pending.get(prefix + proposal.callId);
1611
+ const candidate = exact ?? [...pending.entries()].find(([key, value]) => key.startsWith(prefix) && value.expiresAt > Date.now())?.[1];
1612
+ if (!candidate || candidate.expiresAt <= Date.now()) {
1613
+ if (exact) pending.delete(prefix + proposal.callId);
1614
+ return false;
1615
+ }
1616
+ for (const key of pending.keys()) if (key.startsWith(prefix)) pending.delete(key);
1617
+ return true;
1618
+ };
1619
+ return { evaluate, confirm, size: () => pending.size, clear: () => pending.clear };
1336
1620
  };
1337
1621
  var ViraOpenCodeActionError = class extends Error {
1338
1622
  decision;
@@ -1344,10 +1628,9 @@ var ViraOpenCodeActionError = class extends Error {
1344
1628
  };
1345
1629
  var v2Plugin = Plugin.define({
1346
1630
  id: "vira",
1347
- async setup(rawContext) {
1348
- const ctx = rawContext;
1631
+ async setup(ctx) {
1349
1632
  const options = ctx.options ?? {};
1350
- const env = (name) => typeof process !== "undefined" ? process.env[name] : void 0;
1633
+ const env = envValue;
1351
1634
  const mode = options.mode ?? env("VIRA_HOST_MODE") ?? "off";
1352
1635
  if (mode === "off") return;
1353
1636
  const apiUrl = options.apiUrl ?? env("VIRA_CONTROL_URL") ?? env("VIRA_API_URL");
@@ -1357,7 +1640,10 @@ var v2Plugin = Plugin.define({
1357
1640
  const client = new ViraClient({ baseUrl: required2(apiUrl, "VIRA_HOST_API_URL_REQUIRED"), apiKey, allowInsecureLocalhost });
1358
1641
  const capabilities = { canObserveModel: true, canInjectContext: true, canInterceptToolBefore: true, canInspectToolAfter: true, canPreventSideEffect: mode === "enforce", canInterceptResponseBeforeDisplay: false, ...options.capabilities ?? {} };
1359
1642
  const actionContexts = /* @__PURE__ */ new Map();
1643
+ const taskRuns = /* @__PURE__ */ new Map();
1644
+ const teachPrompts = /* @__PURE__ */ new Map();
1360
1645
  const actionDecisions = /* @__PURE__ */ new Map();
1646
+ const desktopPermission = createDesktopPermissionBridge();
1361
1647
  const contextKey = (identity) => identity.organizationId + ":" + identity.projectId + ":" + identity.environmentId + ":" + identity.conversationId + ":" + (identity.sessionId ?? identity.conversationId);
1362
1648
  const callKey = (proposal) => contextKey(proposal) + ":" + proposal.callId;
1363
1649
  const clearSessionState = (event) => {
@@ -1369,7 +1655,25 @@ var v2Plugin = Plugin.define({
1369
1655
  for (const key of actionDecisions.keys()) {
1370
1656
  if (sessionId && key.includes(":" + sessionId + ":") || conversationId && key.includes(":" + conversationId + ":")) actionDecisions.delete(key);
1371
1657
  }
1658
+ for (const key of taskRuns.keys()) if (key === conversationId || key === sessionId) taskRuns.delete(key);
1659
+ teachPrompts.delete(conversationId);
1660
+ teachPrompts.delete(sessionId);
1661
+ desktopPermission.clear();
1662
+ };
1663
+ const cancelTaskRunForSession = async (event) => {
1664
+ const sessionId = text2(event.sessionID ?? event.sessionId);
1665
+ const conversationId = text2(event.conversationId ?? event.sessionID ?? event.sessionId);
1666
+ const keys = [conversationId, sessionId].filter(Boolean);
1667
+ for (const key of keys) {
1668
+ const run = taskRuns.get(key);
1669
+ if (!run) continue;
1670
+ try {
1671
+ await client.cancelTaskRun(run.taskRunId, run.stateVersion, { idempotencyKey: `opencode:task-run:cancel:${run.taskRunId}:${run.stateVersion}` });
1672
+ } catch {
1673
+ }
1674
+ }
1372
1675
  };
1676
+ const nativeConfirm = desktopPermission.confirm;
1373
1677
  const runtime = createViraHostRuntime(client, { mode, capabilities, authorizeAction: options.authorizeAction ?? (async (proposal) => {
1374
1678
  const bound = actionContexts.get(contextKey(proposal));
1375
1679
  if (!bound) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CONTEXT_UNAVAILABLE" };
@@ -1378,18 +1682,22 @@ var v2Plugin = Plugin.define({
1378
1682
  return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CONTEXT_EXPIRED" };
1379
1683
  }
1380
1684
  const tools = asRecord(bound.context.tools);
1381
- const allowedToolIds = Array.isArray(tools.allowed_tool_ids) ? tools.allowed_tool_ids.map(text2) : [];
1382
- const schemaDigest = text2(tools.schema_digest);
1685
+ const binding = resolveOpenCodeToolBinding(tools, proposal.toolName);
1686
+ const allowedToolIds = binding.allowedToolIds;
1687
+ const toolBindings = binding.bindings;
1688
+ const mappedTool = binding.binding;
1689
+ const canonicalToolId = binding.canonicalToolId;
1690
+ const schemaDigest = binding.schemaDigest;
1383
1691
  const bindingDigest = text2(bound.context.binding_digest);
1384
- if (!allowedToolIds.includes(proposal.toolName) || !/^[a-f0-9]{64}$/.test(schemaDigest) || !/^[a-f0-9]{64}$/.test(bindingDigest)) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_BINDING_UNAVAILABLE" };
1692
+ if (toolBindings.length && !mappedTool || !allowedToolIds.includes(canonicalToolId) || !/^[a-f0-9]{64}$/.test(schemaDigest) || !/^[a-f0-9]{64}$/.test(bindingDigest)) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_BINDING_UNAVAILABLE" };
1385
1693
  const proposalBody = { proposal_id: proposal.conversationId + ":" + proposal.callId, tool_key: proposal.toolName, arguments: proposal.args, arguments_digest: digest2(proposal.args), request_context_digest: digest2(bound.context), schema_digest: String(asRecord(asRecord(bound.context).tools).schema_digest ?? "") };
1386
1694
  const approvalCandidate = asRecord(asRecord(proposal).approval);
1387
1695
  const approval = typeof approvalCandidate.approvalId === "string" && approvalCandidate.approvalId.trim() ? { approvalId: approvalCandidate.approvalId.trim() } : void 0;
1388
1696
  const dataVersion = text2(bound.context.release_digest);
1389
1697
  if (!dataVersion) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_DATA_VERSION_UNAVAILABLE" };
1390
1698
  const refs = Array.isArray(bound.context.signal_attestation_refs) ? bound.context.signal_attestation_refs : [];
1391
- return authorizeWithOneShotCustomerConfirmation({ client, proposal, proposalBody, signalAttestationRefs: refs, executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, confirmAction: options.confirmAction, approvalId: approval?.approvalId });
1392
- }), ...(options.aiSystemId ?? env("VIRA_AI_SYSTEM_ID")) && (options.connectionId ?? env("VIRA_CONNECTION_ID")) ? {} : { connect: { ...scope, name: "OpenCode", systemType: "agent", adapterType: "custom-node", adapterVersion: options.hostVersion ?? ctx.app?.version ?? "unknown", idempotencyKey: "opencode:vira:connect" } } });
1699
+ return authorizeWithOneShotCustomerConfirmation({ client, proposal, proposalBody, signalAttestationRefs: refs, executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, confirmAction: options.confirmAction ?? nativeConfirm, approvalId: approval?.approvalId });
1700
+ }), ...(options.aiSystemId ?? env("VIRA_AI_SYSTEM_ID")) && (options.connectionId ?? env("VIRA_CONNECTION_ID")) ? {} : { connect: openCodeConnectConfig(scope, options) } });
1393
1701
  let connectedAiSystemId = options.aiSystemId ?? env("VIRA_AI_SYSTEM_ID") ?? "";
1394
1702
  let connectedConnectionId = options.connectionId ?? env("VIRA_CONNECTION_ID") ?? "";
1395
1703
  if (!connectedAiSystemId || !connectedConnectionId) {
@@ -1399,19 +1707,74 @@ var v2Plugin = Plugin.define({
1399
1707
  connectedConnectionId = identity?.connectionId ?? "";
1400
1708
  }
1401
1709
  const registrations = [];
1402
- const sessionIdentity = (event) => ({ ...scope, hostName: options.hostName ?? "opencode", hostVersion: options.hostVersion ?? ctx.app?.version ?? "unknown", aiSystemId: required2(connectedAiSystemId, "VIRA_HOST_AI_SYSTEM_REQUIRED"), connectionId: required2(connectedConnectionId, "VIRA_HOST_CONNECTION_REQUIRED"), conversationId: required2(event.conversationId ?? event.sessionID, "VIRA_HOST_SESSION_REQUIRED"), sessionId: text2(event.sessionId ?? event.sessionID ?? event.conversationId) || void 0 });
1710
+ if (ctx.event?.subscribe) {
1711
+ const controller = new AbortController();
1712
+ void (async () => {
1713
+ for await (const raw of ctx.event.subscribe({ signal: controller.signal })) {
1714
+ const event = asRecord(raw);
1715
+ const feedback = asRecord(event.feedback ?? event.userFeedback);
1716
+ const outcome = asRecord(event.outcome ?? event.businessOutcome);
1717
+ const conversationId = text2(event.conversationId ?? event.sessionID ?? event.sessionId);
1718
+ if (!conversationId) continue;
1719
+ try {
1720
+ const identity = { ...scope, hostName: options.hostName ?? "opencode", hostVersion: hostVersionFor(options, ctx), aiSystemId: required2(connectedAiSystemId, "VIRA_HOST_AI_SYSTEM_REQUIRED"), connectionId: required2(connectedConnectionId, "VIRA_HOST_CONNECTION_REQUIRED"), conversationId, sessionId: sessionRef(event) || void 0 };
1721
+ const eventId = text2(event.eventId ?? event.id ?? event.messageID ?? event.requestId) || `${conversationId}:${text2(event.type) || "event"}:${digest2(event).slice(0, 16)}`;
1722
+ const lineage = { conversationId, requestId: text2(event.requestId ?? event.messageID) || void 0, traceId: text2(event.traceId ?? event.traceID) || void 0, projectionDigest: text2(event.projectionDigest ?? event.projection_digest) || void 0, receiptDigest: text2(event.receiptDigest ?? event.receipt_digest) || void 0, releaseDigest: text2(event.releaseDigest ?? event.release_digest) || void 0, evaluationId: text2(event.evaluationId ?? event.evaluation_id) || void 0 };
1723
+ if (Object.keys(feedback).length) await recordUserCorrection(client, identity, { eventId, ...lineage, correctedText: text2(feedback.correctedText ?? feedback.text), status: text2(feedback.status) || "corrected", reasonCode: text2(feedback.reasonCode) || "OPENCODE_FEEDBACK" });
1724
+ if (Object.keys(outcome).length) await recordBusinessOutcome(client, identity, { eventId: `${eventId}:outcome`, ...lineage, status: text2(outcome.status) || "unknown", value: outcome.value, reasonCode: text2(outcome.reasonCode) || "OPENCODE_OUTCOME" });
1725
+ } catch {
1726
+ }
1727
+ }
1728
+ })().catch(() => void 0);
1729
+ registrations.push({ dispose: () => controller.abort() });
1730
+ }
1731
+ const sessionIdentity = (event) => {
1732
+ const sessionId = sessionRef(event);
1733
+ return { ...scope, hostName: options.hostName ?? "opencode", hostVersion: hostVersionFor(options, ctx), aiSystemId: required2(connectedAiSystemId, "VIRA_HOST_AI_SYSTEM_REQUIRED"), connectionId: required2(connectedConnectionId, "VIRA_HOST_CONNECTION_REQUIRED"), conversationId: required2(event.conversationId ?? event.sessionID ?? event.sessionId ?? asRecord(event.session).id, "VIRA_HOST_SESSION_REQUIRED"), sessionId: sessionId || void 0 };
1734
+ };
1735
+ if (mode === "enforce" && options.permissionMode !== "deny" && ctx.permission?.hook) registrations.push(await ctx.permission.hook("evaluate", async (event) => {
1736
+ desktopPermission.evaluate(event);
1737
+ }));
1403
1738
  registrations.push(await ctx.session.hook("context", async (event) => {
1739
+ const input = lastUserText(event);
1740
+ const output = latestAssistantText(event);
1741
+ if (!input && !output) return;
1404
1742
  const identity = sessionIdentity(event);
1405
- const result = await runtime.beforeModel({ ...identity, requestId: text2(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, input: required2(lastUserText(event), "VIRA_HOST_MODEL_INPUT_REQUIRED"), traceId: text2(event.traceID), turnId: text2(event.turnID), signalAttestationRefs: options.signalAttestationRefs });
1406
- const responseBody = asRecord(result.response?.body);
1407
- const runtimeContext = asRecord(event.viraRuntimeContext ?? responseBody.requestContext ?? responseBody.context);
1408
- const executionId = text2(event.executionId ?? responseBody.executionId);
1409
- const expiresAt = Number(runtimeContext.expires_at_unix_ms);
1410
- if (executionId && runtimeContext.abi === "vira.request-behavior-context.v2" && Number.isFinite(expiresAt) && expiresAt > Date.now()) actionContexts.set(contextKey(identity), { executionId, context: runtimeContext, sessionId: identity.sessionId ?? identity.conversationId, conversationId: identity.conversationId, expiresAt });
1411
- else if (executionId) actionContexts.delete(contextKey(identity));
1412
- if (result.status === "applied" && result.projection) {
1413
- const system = Array.isArray(event.system) ? event.system : event.system = [];
1414
- if (!system.some((item) => text2(asRecord(item).text) === result.projection)) system.push({ type: "text", text: result.projection });
1743
+ if (input) {
1744
+ teachPrompts.set(identity.conversationId, input);
1745
+ const result = await runtime.beforeModel({ ...identity, requestId: text2(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, input, revisionId: options.revisionId, profile: conversationProfile(event, options), traceId: text2(event.traceID), turnId: text2(event.turnID), signalAttestationRefs: options.signalAttestationRefs });
1746
+ const refreshed = runtime.getConnectionIdentity();
1747
+ if (!options.aiSystemId && !options.connectionId && refreshed) {
1748
+ connectedAiSystemId = refreshed.aiSystemId;
1749
+ connectedConnectionId = refreshed.connectionId;
1750
+ }
1751
+ const responseBody = asRecord(result.response?.body);
1752
+ const runtimeContext = asRecord(event.viraRuntimeContext ?? responseBody.requestContext ?? responseBody.context);
1753
+ const executionId = text2(event.executionId ?? responseBody.executionId);
1754
+ const expiresAt = Number(runtimeContext.expires_at_unix_ms);
1755
+ if (executionId && runtimeContext.abi === "vira.request-behavior-context.v2" && Number.isFinite(expiresAt) && expiresAt > Date.now()) actionContexts.set(contextKey(identity), { executionId, context: runtimeContext, sessionId: identity.sessionId ?? identity.conversationId, conversationId: identity.conversationId, expiresAt });
1756
+ else if (executionId) actionContexts.delete(contextKey(identity));
1757
+ if (result.status === "task_run" && result.taskRunId && Number.isInteger(result.taskRunStateVersion)) taskRuns.set(identity.conversationId, { taskRunId: result.taskRunId, stateVersion: result.taskRunStateVersion });
1758
+ const modelPolicy = asRecord(responseBody.modelPolicy ?? responseBody.model_policy);
1759
+ const hostOptions = asRecord(event.options);
1760
+ for (const key of ["maxTokens", "temperature", "model", "provider"]) if (Object.hasOwn(modelPolicy, key) && (typeof modelPolicy[key] === "number" && Number.isFinite(modelPolicy[key]) || typeof modelPolicy[key] === "string")) hostOptions[key] = modelPolicy[key];
1761
+ if (Object.keys(hostOptions).length) event.options = hostOptions;
1762
+ if (result.status === "applied" && result.projection) {
1763
+ const system = Array.isArray(event.system) ? event.system : event.system = [];
1764
+ if (!system.some((item) => text2(asRecord(item).text) === result.projection)) system.push({ type: "text", text: result.projection });
1765
+ }
1766
+ }
1767
+ if (output) {
1768
+ const eventId = `${identity.conversationId}:assistant:${text2(event.messageID ?? event.requestId) || digest2(output).slice(0, 16)}`;
1769
+ void client.observe({ ...identity, eventId, eventType: "conversation.output", traceId: text2(event.traceID), requestId: text2(event.requestId ?? event.messageID) || eventId, payload: { text: output }, attributes: { source: "opencode.context" } }, { idempotencyKey: `opencode:conversation.output:${eventId}` }).catch(() => void 0);
1770
+ if (options.teachConsent === true) {
1771
+ const prompt = teachPrompts.get(identity.conversationId) || "";
1772
+ if (prompt) {
1773
+ void client.submitTeachConversationEvidence({ id: `opencode-teach:${identity.conversationId}:${text2(event.messageID ?? event.requestId) || digest2(output).slice(0, 16)}`, conversationId: identity.conversationId, message: `User: ${prompt}
1774
+ Assistant: ${output}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempotencyKey: `opencode:teach:${identity.conversationId}:${text2(event.messageID ?? event.requestId) || digest2(output).slice(0, 16)}` }).catch(() => void 0);
1775
+ teachPrompts.delete(identity.conversationId);
1776
+ }
1777
+ }
1415
1778
  }
1416
1779
  }));
1417
1780
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
@@ -1427,36 +1790,39 @@ var v2Plugin = Plugin.define({
1427
1790
  const decision = actionDecisions.get(callKey(proposal));
1428
1791
  actionDecisions.delete(callKey(proposal));
1429
1792
  try {
1430
- await runtime.afterTool({ ...proposal, ok: event.status === "completed", result: event.result, errorCode: text2(asRecord(event.error).code), ...decision?.authorityReceiptDigest ? { authorityReceiptDigest: decision.authorityReceiptDigest } : {}, ...decision?.decisionDigest ? { decisionDigest: decision.decisionDigest } : {} });
1793
+ await runtime.afterTool({ ...proposal, ok: toolExecutionSucceeded(event, event), result: event.result ?? event.output, errorCode: text2(asRecord(event.error).code), ...decision?.authorityReceiptDigest ? { authorityReceiptDigest: decision.authorityReceiptDigest } : {}, ...decision?.decisionDigest ? { decisionDigest: decision.decisionDigest } : {} });
1431
1794
  } catch (error) {
1432
1795
  if (mode === "enforce") throw error;
1433
1796
  }
1434
1797
  }));
1435
- registrations.push(await ctx.session.hook("fork", (event) => {
1798
+ registrations.push(await ctx.session.hook("fork", async (event) => {
1799
+ await cancelTaskRunForSession(event);
1436
1800
  clearSessionState(event);
1437
- return runtime.endSession({ ...scope, hostName: "opencode", hostVersion: ctx.app?.version ?? "unknown", aiSystemId: options.aiSystemId ?? "", connectionId: options.connectionId ?? "", conversationId: text2(event.sessionID), sessionId: text2(event.sessionID) || void 0 });
1801
+ return runtime.endSession({ ...scope, hostName: "opencode", hostVersion: hostVersionFor(options, ctx), aiSystemId: options.aiSystemId ?? "", connectionId: options.connectionId ?? "", conversationId: text2(event.sessionID), sessionId: text2(event.sessionID) || void 0 });
1438
1802
  }));
1439
- registrations.push(await ctx.session.hook("compaction", (event) => {
1803
+ registrations.push(await ctx.session.hook("compaction", async (event) => {
1804
+ await cancelTaskRunForSession(event);
1440
1805
  clearSessionState(event);
1441
- runtime.endSession({ ...scope, hostName: "opencode", hostVersion: ctx.app?.version ?? "unknown", aiSystemId: options.aiSystemId ?? "", connectionId: options.connectionId ?? "", conversationId: text2(event.sessionID ?? event.conversationId), sessionId: text2(event.sessionID ?? event.conversationId) || void 0 });
1806
+ return runtime.endSession({ ...scope, hostName: "opencode", hostVersion: hostVersionFor(options, ctx), aiSystemId: options.aiSystemId ?? "", connectionId: options.connectionId ?? "", conversationId: text2(event.sessionID ?? event.conversationId), sessionId: text2(event.sessionID ?? event.conversationId) || void 0 });
1442
1807
  }));
1443
1808
  return async () => {
1444
1809
  actionContexts.clear();
1445
1810
  actionDecisions.clear();
1811
+ desktopPermission.clear();
1446
1812
  for (const registration of registrations) await registration.dispose?.();
1447
1813
  };
1448
1814
  }
1449
1815
  });
1450
- var v1Runtime = () => {
1451
- const env = (name) => typeof process !== "undefined" ? process.env[name] : void 0;
1452
- const mode = env("VIRA_HOST_MODE") ?? "off";
1816
+ var v1Runtime = (options) => {
1817
+ const env = envValue;
1818
+ const mode = options.mode ?? env("VIRA_HOST_MODE") ?? "off";
1453
1819
  if (mode === "off") return null;
1454
- const scope = { organizationId: required2(env("VIRA_ORGANIZATION_ID"), "VIRA_HOST_ORGANIZATION_REQUIRED"), projectId: required2(env("VIRA_PROJECT_ID"), "VIRA_HOST_PROJECT_REQUIRED"), environmentId: required2(env("VIRA_ENVIRONMENT_ID"), "VIRA_HOST_ENVIRONMENT_REQUIRED") };
1455
- const client = new ViraClient({ baseUrl: required2(env("VIRA_CONTROL_URL") ?? env("VIRA_API_URL"), "VIRA_HOST_API_URL_REQUIRED"), apiKey: env("VIRA_API_KEY"), allowInsecureLocalhost: env("VIRA_ALLOW_INSECURE_LOCALHOST") === "true" });
1820
+ const scope = { organizationId: required2(options.organizationId ?? env("VIRA_ORGANIZATION_ID"), "VIRA_HOST_ORGANIZATION_REQUIRED"), projectId: required2(options.projectId ?? env("VIRA_PROJECT_ID"), "VIRA_HOST_PROJECT_REQUIRED"), environmentId: required2(options.environmentId ?? env("VIRA_ENVIRONMENT_ID"), "VIRA_HOST_ENVIRONMENT_REQUIRED") };
1821
+ const client = new ViraClient({ baseUrl: required2(options.apiUrl ?? env("VIRA_CONTROL_URL") ?? env("VIRA_API_URL"), "VIRA_HOST_API_URL_REQUIRED"), apiKey: options.apiKey ?? env("VIRA_API_KEY"), allowInsecureLocalhost: options.allowInsecureLocalhost ?? env("VIRA_ALLOW_INSECURE_LOCALHOST") === "true" });
1456
1822
  const actionContexts = /* @__PURE__ */ new Map();
1457
1823
  const actionDecisions = /* @__PURE__ */ new Map();
1458
1824
  const contextKey = (identity) => identity.organizationId + ":" + identity.projectId + ":" + identity.environmentId + ":" + identity.conversationId + ":" + (identity.sessionId ?? identity.conversationId);
1459
- const authorizeAction = async (proposal) => {
1825
+ const serverAuthorizeAction = async (proposal) => {
1460
1826
  const bound = actionContexts.get(contextKey(proposal));
1461
1827
  if (!bound) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CONTEXT_UNAVAILABLE" };
1462
1828
  if (!Number.isFinite(bound.expiresAt) || Date.now() >= bound.expiresAt) {
@@ -1464,44 +1830,53 @@ var v1Runtime = () => {
1464
1830
  return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CONTEXT_EXPIRED" };
1465
1831
  }
1466
1832
  const tools = asRecord(bound.context.tools);
1467
- const allowed = Array.isArray(tools.allowed_tool_ids) ? tools.allowed_tool_ids.map(text2) : [];
1468
- const schemaDigest = text2(tools.schema_digest);
1833
+ const binding = resolveOpenCodeToolBinding(tools, proposal.toolName);
1469
1834
  const bindingDigest = text2(bound.context.binding_digest);
1470
1835
  const dataVersion = text2(bound.context.release_digest);
1471
1836
  if (!dataVersion) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_DATA_VERSION_UNAVAILABLE" };
1472
- if (!allowed.includes(proposal.toolName) || !/^[a-f0-9]{64}$/.test(schemaDigest) || !/^[a-f0-9]{64}$/.test(bindingDigest)) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_BINDING_UNAVAILABLE" };
1837
+ if (binding.bindings.length && !binding.binding || !binding.allowedToolIds.includes(binding.canonicalToolId) || !/^[a-f0-9]{64}$/.test(binding.schemaDigest) || !/^[a-f0-9]{64}$/.test(bindingDigest)) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_BINDING_UNAVAILABLE" };
1473
1838
  try {
1474
- const response = await client.authorizeHostAction({ executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, proposal: { proposal_id: proposal.conversationId + ":" + proposal.callId, tool_key: proposal.toolName, arguments: proposal.args, arguments_digest: digest2(proposal.args), request_context_digest: digest2(bound.context), schema_digest: schemaDigest } });
1839
+ const response = await client.authorizeHostAction({ executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, proposal: { proposal_id: proposal.conversationId + ":" + proposal.callId, tool_key: proposal.toolName, arguments: proposal.args, arguments_digest: digest2(proposal.args), request_context_digest: digest2(bound.context), schema_digest: binding.schemaDigest } });
1475
1840
  const body = asRecord(response?.body);
1476
1841
  return body.allowed === true ? { decision: "ALLOW", authorityReceiptDigest: text2(body.authority_receipt_digest), decisionDigest: text2(body.decision_digest) } : { decision: "BLOCK", reasonCode: text2(body.reason_code) || "POLICY_DENIED", authorityReceiptDigest: text2(body.authority_receipt_digest) };
1477
1842
  } catch (error) {
1478
1843
  return { decision: "ERROR", reasonCode: error instanceof Error ? error.message : "RUNTIME_ACTION_AUTHORIZATION_FAILED" };
1479
1844
  }
1480
1845
  };
1481
- return { mode, scope, client, actionContexts, actionDecisions, contextKey, runtime: createViraHostRuntime(client, { mode, connect: { ...scope, name: "OpenCode", systemType: "agent", adapterType: "custom-node", adapterVersion: "1.19.5", idempotencyKey: "opencode:vira:connect" }, capabilities: { canObserveModel: true, canInjectContext: true, canInterceptToolBefore: true, canInspectToolAfter: true, canPreventSideEffect: mode === "enforce", canInterceptResponseBeforeDisplay: false }, authorizeAction }) };
1846
+ const authorizeAction = options.authorizeAction ?? serverAuthorizeAction;
1847
+ return { mode, scope, client, actionContexts, actionDecisions, contextKey, runtime: createViraHostRuntime(client, { mode, ...(options.aiSystemId ?? env("VIRA_AI_SYSTEM_ID")) && (options.connectionId ?? env("VIRA_CONNECTION_ID")) ? {} : { connect: openCodeConnectConfig(scope, options) }, capabilities: { canObserveModel: true, canInjectContext: true, canInterceptToolBefore: true, canInspectToolAfter: true, canPreventSideEffect: mode === "enforce", canInterceptResponseBeforeDisplay: false, ...options.capabilities ?? {} }, authorizeAction }) };
1482
1848
  };
1483
- var v1Fallback = { async server() {
1484
- const configured = v1Runtime();
1849
+ var v1Fallback = { async server(rawContext = {}) {
1850
+ const options = readHostOptions(rawContext);
1851
+ const configured = v1Runtime(options);
1485
1852
  if (!configured) return {};
1486
1853
  const { mode, scope, runtime, actionContexts, actionDecisions, contextKey } = configured;
1487
- await runtime.connectOnce();
1488
- const connectedIdentity = runtime.getConnectionIdentity();
1489
- const env = (name) => typeof process !== "undefined" ? process.env[name] : void 0;
1490
- const prompts = /* @__PURE__ */ new Map();
1491
- const identity = (input) => ({ ...scope, hostName: "opencode", hostVersion: "1.19.5", aiSystemId: required2(connectedIdentity?.aiSystemId ?? env("VIRA_AI_SYSTEM_ID"), "VIRA_HOST_AI_SYSTEM_REQUIRED"), connectionId: required2(connectedIdentity?.connectionId ?? env("VIRA_CONNECTION_ID"), "VIRA_HOST_CONNECTION_REQUIRED"), conversationId: required2(input.sessionID ?? input.conversationId ?? input.id, "VIRA_HOST_SESSION_REQUIRED"), sessionId: text2(input.sessionID ?? input.sessionId ?? input.conversationId) || void 0 });
1854
+ if (!options.aiSystemId || !options.connectionId) await runtime.connectOnce();
1855
+ let connectedIdentity = runtime.getConnectionIdentity();
1856
+ const env = envValue;
1857
+ const promptCacheTtlMs = Math.max(1e3, Math.min(3e5, Number(options.promptCacheTtlMs ?? envValue("VIRA_V1_PROMPT_CACHE_TTL_MS") ?? 6e4) || 6e4));
1858
+ const prompts = createV1PromptCache(promptCacheTtlMs);
1859
+ const clearSessionPrompts = (event) => {
1860
+ const sessionId = text2(event.sessionID ?? event.sessionId ?? event.conversationId ?? event.id);
1861
+ if (sessionId) prompts.clear(sessionId);
1862
+ };
1863
+ const hostVersion = hostVersionFor(options, rawContext);
1864
+ const identity = (input) => ({ ...scope, hostName: options.hostName ?? "opencode", hostVersion, aiSystemId: required2(connectedIdentity?.aiSystemId ?? options.aiSystemId ?? env("VIRA_AI_SYSTEM_ID"), "VIRA_HOST_AI_SYSTEM_REQUIRED"), connectionId: required2(connectedIdentity?.connectionId ?? options.connectionId ?? env("VIRA_CONNECTION_ID"), "VIRA_HOST_CONNECTION_REQUIRED"), conversationId: required2(input.sessionID ?? input.conversationId ?? input.id, "VIRA_HOST_SESSION_REQUIRED"), sessionId: text2(input.sessionID ?? input.sessionId ?? input.conversationId) || void 0 });
1492
1865
  const partsText = (value) => Array.isArray(value) ? value.map((part) => text2(asRecord(part).text)).filter(Boolean).join("\n") : "";
1493
1866
  return {
1494
1867
  "chat.message": async (input, output) => {
1495
1868
  const sessionId = text2(input.sessionID ?? input.conversationId ?? input.id);
1496
1869
  const message = asRecord(output.message ?? input.message);
1497
1870
  const prompt = text2(message.text ?? message.content) || partsText(output.parts ?? input.parts);
1498
- if (sessionId && prompt.trim()) prompts.set(sessionId, prompt);
1871
+ if (sessionId && prompt.trim()) prompts.set(sessionId, prompt.trim());
1499
1872
  },
1500
1873
  "chat.params": async (input, output) => {
1501
1874
  const sessionId = text2(input.sessionID ?? input.conversationId ?? input.id);
1502
- const prompt = text2(input.prompt ?? asRecord(input.message).text ?? input.input ?? output.prompt) || prompts.get(sessionId) || "";
1875
+ const direct = text2(input.prompt ?? asRecord(input.message).text ?? input.input ?? output.prompt);
1876
+ const prompt = direct || prompts.take(sessionId) || "";
1503
1877
  if (!prompt.trim()) return;
1504
- const result = await runtime.beforeModel({ ...identity(input), requestId: text2(input.messageID ?? input.requestId) || `opencode:${Date.now()}`, input: prompt, traceId: text2(input.traceID), turnId: text2(input.turnID) });
1878
+ const result = await runtime.beforeModel({ ...identity(input), requestId: text2(input.messageID ?? input.requestId) || `opencode:${Date.now()}`, input: prompt, profile: conversationProfile(input, options), traceId: text2(input.traceID), turnId: text2(input.turnID), signalAttestationRefs: options.signalAttestationRefs });
1879
+ if (!options.aiSystemId && !options.connectionId) connectedIdentity = runtime.getConnectionIdentity();
1505
1880
  const responseBody = asRecord(result.response?.body);
1506
1881
  const runtimeContext = asRecord(responseBody.requestContext ?? responseBody.context);
1507
1882
  const executionId = text2(input.executionId ?? responseBody.executionId);
@@ -1509,6 +1884,11 @@ var v1Fallback = { async server() {
1509
1884
  const current = identity(input);
1510
1885
  if (executionId && runtimeContext.abi === "vira.request-behavior-context.v2" && Number.isFinite(expiresAt) && expiresAt > Date.now()) actionContexts.set(contextKey(current), { executionId, context: runtimeContext, sessionId: current.sessionId ?? current.conversationId, conversationId: current.conversationId, expiresAt });
1511
1886
  else actionContexts.delete(contextKey(current));
1887
+ const policyBody = asRecord(result.response?.body);
1888
+ const modelPolicy = asRecord(policyBody.modelPolicy ?? policyBody.model_policy);
1889
+ const hostOptions = asRecord(output.options ?? input.options);
1890
+ for (const key of ["maxTokens", "temperature", "model", "provider"]) if (Object.hasOwn(modelPolicy, key) && (typeof modelPolicy[key] === "number" && Number.isFinite(modelPolicy[key]) || typeof modelPolicy[key] === "string")) hostOptions[key] = modelPolicy[key];
1891
+ if (Object.keys(hostOptions).length) output.options = hostOptions;
1512
1892
  if (result.status === "applied" && result.projection) output.system = [...Array.isArray(output.system) ? output.system : [], result.projection];
1513
1893
  },
1514
1894
  "tool.execute.before": async (input, output) => {
@@ -1522,16 +1902,41 @@ var v1Fallback = { async server() {
1522
1902
  const decision = actionDecisions.get(contextKey(proposal) + ":" + proposal.callId);
1523
1903
  actionDecisions.delete(contextKey(proposal) + ":" + proposal.callId);
1524
1904
  try {
1525
- await runtime.afterTool({ ...proposal, ok: true, result: output.output, errorCode: text2(asRecord(output.error).code), ...decision?.authorityReceiptDigest ? { authorityReceiptDigest: decision.authorityReceiptDigest } : {}, ...decision?.decisionDigest ? { decisionDigest: decision.decisionDigest } : {} });
1905
+ await runtime.afterTool({ ...proposal, ok: toolExecutionSucceeded(input, output), result: output.output, errorCode: text2(asRecord(output.error ?? input.error).code), ...decision?.authorityReceiptDigest ? { authorityReceiptDigest: decision.authorityReceiptDigest } : {}, ...decision?.decisionDigest ? { decisionDigest: decision.decisionDigest } : {} });
1526
1906
  } catch (error) {
1527
1907
  if (mode === "enforce") throw error;
1528
1908
  }
1909
+ },
1910
+ "session.close": async (input) => {
1911
+ clearSessionPrompts(input);
1912
+ },
1913
+ "session.end": async (input) => {
1914
+ clearSessionPrompts(input);
1915
+ },
1916
+ "session.delete": async (input) => {
1917
+ clearSessionPrompts(input);
1529
1918
  }
1530
1919
  };
1531
1920
  } };
1532
1921
  var index_default = { ...v2Plugin, ...v1Fallback };
1533
1922
  export {
1534
1923
  ViraOpenCodeActionError,
1924
+ adapterVersionFor,
1925
+ createDesktopPermissionBridge,
1926
+ createV1PromptCache,
1535
1927
  index_default as default,
1928
+ hostVersionFor,
1929
+ lastUserText,
1930
+ latestAssistantText,
1931
+ messageContentText,
1932
+ openCodeConnectConfig,
1933
+ readHostOptions,
1934
+ recordBusinessOutcome,
1935
+ recordConversationOutput,
1936
+ recordModelMetrics,
1937
+ recordModelResponse,
1938
+ recordUserCorrection,
1939
+ resolveOpenCodeToolBinding,
1940
+ toolExecutionSucceeded,
1536
1941
  v1Fallback
1537
1942
  };
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@tryvira/opencode",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "description": "OpenCode V2 host lifecycle integration for Vira",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "exports": {".": "./dist/index.js"},
8
8
  "files": ["dist/index.js", "README.md"],
9
- "scripts": {"build": "node ../../scripts/build-opencode-plugin.mjs", "pack:check": "npm run build && npm pack --dry-run && node ../../scripts/opencode-plugin-smoke.mjs"},
10
- "dependencies": {"@tryvira/sdk": "0.1.58"},
9
+ "scripts": {"build": "node ../../scripts/build-opencode-plugin.mjs", "pack:check": "npm run build && node ../../scripts/opencode-plugin-smoke.mjs && node ../../scripts/opencode-plugin-host-acceptance.mjs"},
10
+ "dependencies": {"@tryvira/sdk": "0.1.59"},
11
11
  "peerDependencies": {"effect": "^4.0.0"},
12
12
  "engines": {"node": ">=20"},
13
13
  "license": "MIT"