@tryvira/opencode 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +8 -1
  2. package/dist/index.js +65 -10
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # `@tryvira/opencode`
1
+ # `@tryvira/opencode` 0.1.6
2
2
 
3
3
  OpenCode V2 server plugin for Vira host lifecycle governance.
4
4
 
@@ -15,3 +15,10 @@ When the runtime context hook exposes a server-issued `executionId` and a
15
15
  `vira.request-behavior-context.v2`, the plugin can call
16
16
  `/v1/runtime/actions/authorize` automatically. If that binding is absent,
17
17
  enforce mode blocks the tool instead of guessing an execution or release.
18
+
19
+ The V2 binding is scoped to the exact OpenCode session and conversation, carries
20
+ the server expiry, and is discarded on fork, compaction, expiry, or plugin
21
+ shutdown. Tool proposals must be present in the server-issued tool allowlist
22
+ and carry the context's schema and binding digests. Tool result and failure
23
+ observations retain the matching authority and decision digests. V1 hook names
24
+ remain a separate compatibility surface and do not provide V2 action context.
package/dist/index.js CHANGED
@@ -1210,7 +1210,9 @@ function createViraHostRuntime(client, config) {
1210
1210
  if (mode !== "enforce") return { decision: "ABSTAIN", reasonCode: mode === "off" ? "HOST_MODE_OFF" : "OBSERVE_ONLY" };
1211
1211
  let decision;
1212
1212
  try {
1213
- decision = await withTimeout(Promise.resolve(config.authorizeAction(proposal)), timeoutMs, "SDK_HOST_ACTION_AUTHORIZATION_TIMEOUT");
1213
+ const authorized = await withTimeout(Promise.resolve(config.authorizeAction(proposal)), timeoutMs, "SDK_HOST_ACTION_AUTHORIZATION_TIMEOUT");
1214
+ const authorizedBody = bodyOf(authorized);
1215
+ decision = typeof authorizedBody.decision === "string" ? authorizedBody : authorized;
1214
1216
  } catch {
1215
1217
  return { decision: "ERROR", reasonCode: "VIRA_ACTION_AUTHORIZATION_TIMEOUT" };
1216
1218
  }
@@ -1222,13 +1224,30 @@ function createViraHostRuntime(client, config) {
1222
1224
  nonEmpty(result.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
1223
1225
  if (mode === "off" || !capabilities.canInspectToolAfter) return { status: "off" };
1224
1226
  const observedResult = result.ok ? result.result : { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" };
1225
- 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", requestId: result.requestId, conversationId: result.conversationId, ...result.sessionId ? { sessionId: result.sessionId } : {}, ...result.turnId ? { turnId: result.turnId } : {} };
1227
+ 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 } : {} };
1226
1228
  return 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");
1227
1229
  };
1230
+ const executeTool = async (input) => {
1231
+ if (!input || typeof input !== "object" || typeof input.execute !== "function") throw new Error("SDK_GOVERNED_TOOL_EXECUTION_REQUIRED");
1232
+ const proposal = input.proposal;
1233
+ const decision = await beforeTool(proposal);
1234
+ if (decision.decision !== "ALLOW") return { decision, executed: false };
1235
+ if (!isAllow(decision)) throw new Error("SDK_HOST_ALLOW_RECEIPT_INVALID");
1236
+ try {
1237
+ const result = await input.execute(proposal.args);
1238
+ const resultDigest = digest(result);
1239
+ const observation = await afterTool({ ...proposal, ok: true, result, resultDigest });
1240
+ return { decision, executed: true, result, observation };
1241
+ } catch (error) {
1242
+ const errorCode = error instanceof Error ? error.message : "GOVERNED_TOOL_FAILED";
1243
+ const observation = await afterTool({ ...proposal, ok: false, errorCode, resultDigest: digest({ errorCode }) });
1244
+ throw Object.assign(error instanceof Error ? error : new Error(errorCode), { decision, observation });
1245
+ }
1246
+ };
1228
1247
  const endSession = (identity) => {
1229
1248
  projections.delete(sessionKey({ ...identity, requestId: "session-end", input: "" }));
1230
1249
  };
1231
- return Object.freeze({ mode, capabilities, connectOnce, getConnectionIdentity: () => connectionIdentity, beforeModel, beforeTool, afterTool, endSession, getProjection: (identity) => projections.get(sessionKey({ ...identity, requestId: "projection", input: "" })), supportsPostModelVerification: capabilities.canInterceptResponseBeforeDisplay });
1250
+ 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 });
1232
1251
  }
1233
1252
 
1234
1253
  // src/index.ts
@@ -1272,10 +1291,31 @@ var v2Plugin = Plugin.define({
1272
1291
  const client = new ViraClient({ baseUrl: required2(apiUrl, "VIRA_HOST_API_URL_REQUIRED"), apiKey });
1273
1292
  const capabilities = { canObserveModel: true, canInjectContext: true, canInterceptToolBefore: true, canInspectToolAfter: true, canPreventSideEffect: mode === "enforce", canInterceptResponseBeforeDisplay: false, ...options.capabilities ?? {} };
1274
1293
  const actionContexts = /* @__PURE__ */ new Map();
1294
+ const actionDecisions = /* @__PURE__ */ new Map();
1295
+ const contextKey = (identity) => identity.organizationId + ":" + identity.projectId + ":" + identity.environmentId + ":" + identity.conversationId + ":" + (identity.sessionId ?? identity.conversationId);
1296
+ const callKey = (proposal) => contextKey(proposal) + ":" + proposal.callId;
1297
+ const clearSessionState = (event) => {
1298
+ const sessionId = text(event.sessionID ?? event.sessionId);
1299
+ const conversationId = text(event.conversationId ?? event.sessionID ?? event.sessionId);
1300
+ for (const [key, bound] of actionContexts) {
1301
+ if (sessionId && bound.sessionId === sessionId || conversationId && bound.conversationId === conversationId) actionContexts.delete(key);
1302
+ }
1303
+ for (const key of actionDecisions.keys()) {
1304
+ if (sessionId && key.includes(":" + sessionId + ":") || conversationId && key.includes(":" + conversationId + ":")) actionDecisions.delete(key);
1305
+ }
1306
+ };
1275
1307
  const runtime = createViraHostRuntime(client, { mode, capabilities, authorizeAction: options.authorizeAction ?? (async (proposal) => {
1276
- const contextKey = proposal.organizationId + ":" + proposal.projectId + ":" + proposal.environmentId + ":" + proposal.conversationId;
1277
- const bound = actionContexts.get(contextKey);
1308
+ const bound = actionContexts.get(contextKey(proposal));
1278
1309
  if (!bound) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CONTEXT_UNAVAILABLE" };
1310
+ if (!Number.isFinite(bound.expiresAt) || Date.now() >= bound.expiresAt) {
1311
+ actionContexts.delete(contextKey(proposal));
1312
+ return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CONTEXT_EXPIRED" };
1313
+ }
1314
+ const tools = asRecord(bound.context.tools);
1315
+ const allowedToolIds = Array.isArray(tools.allowed_tool_ids) ? tools.allowed_tool_ids.map(text) : [];
1316
+ const schemaDigest = text(tools.schema_digest);
1317
+ const bindingDigest = text(bound.context.binding_digest);
1318
+ 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" };
1279
1319
  try {
1280
1320
  const approval = asRecord(asRecord(proposal).approval);
1281
1321
  const response = await client.authorizeHostAction({ executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, 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: String(asRecord(asRecord(bound.context).tools).schema_digest ?? "") }, ...Object.keys(approval).length ? { approval } : {} });
@@ -1294,14 +1334,16 @@ var v2Plugin = Plugin.define({
1294
1334
  connectedConnectionId = identity?.connectionId ?? "";
1295
1335
  }
1296
1336
  const registrations = [];
1297
- 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.sessionID ?? event.conversationId, "VIRA_HOST_SESSION_REQUIRED") });
1337
+ 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: text(event.sessionId ?? event.sessionID ?? event.conversationId) || void 0 });
1298
1338
  registrations.push(await ctx.session.hook("context", async (event) => {
1299
1339
  const identity = sessionIdentity(event);
1300
1340
  const result = await runtime.beforeModel({ ...identity, requestId: text(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, input: required2(lastUserText(event), "VIRA_HOST_MODEL_INPUT_REQUIRED"), traceId: text(event.traceID), turnId: text(event.turnID) });
1301
1341
  const responseBody = asRecord(result.response?.body);
1302
1342
  const runtimeContext = asRecord(event.viraRuntimeContext ?? responseBody.requestContext ?? responseBody.context);
1303
1343
  const executionId = text(event.executionId ?? responseBody.executionId);
1304
- if (executionId && runtimeContext.abi === "vira.request-behavior-context.v2") actionContexts.set(identity.organizationId + ":" + identity.projectId + ":" + identity.environmentId + ":" + identity.conversationId, { executionId, context: runtimeContext });
1344
+ const expiresAt = Number(runtimeContext.expires_at_unix_ms);
1345
+ 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 });
1346
+ else if (executionId) actionContexts.delete(contextKey(identity));
1305
1347
  if (result.status === "applied" && result.projection) {
1306
1348
  const system = Array.isArray(event.system) ? event.system : event.system = [];
1307
1349
  if (!system.some((item) => text(asRecord(item).text) === result.projection)) system.push({ type: "text", text: result.projection });
@@ -1309,20 +1351,33 @@ var v2Plugin = Plugin.define({
1309
1351
  }));
1310
1352
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
1311
1353
  const identity = sessionIdentity(event);
1312
- const decision = await runtime.beforeTool({ ...identity, requestId: text(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, callId: required2(event.callID ?? event.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required2(event.tool ?? event.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(event.input ?? event.args), traceId: text(event.traceID), turnId: text(event.turnID) });
1354
+ const proposal = { ...identity, requestId: text(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, callId: required2(event.callID ?? event.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required2(event.tool ?? event.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(event.input ?? event.args), traceId: text(event.traceID), turnId: text(event.turnID) };
1355
+ const decision = await runtime.beforeTool(proposal);
1356
+ actionDecisions.set(callKey(proposal), decision);
1313
1357
  if (mode === "enforce" && decision.decision !== "ALLOW") throw new ViraOpenCodeActionError(decision.decision, text(decision.reasonCode) || "VIRA_ACTION_NOT_ALLOWED");
1314
1358
  }));
1315
1359
  registrations.push(await ctx.tool.hook("execute.after", async (event) => {
1316
1360
  const identity = sessionIdentity(event);
1361
+ const proposal = { ...identity, requestId: text(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, callId: required2(event.callID ?? event.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required2(event.tool ?? event.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(event.input ?? event.args), traceId: text(event.traceID), turnId: text(event.turnID) };
1362
+ const decision = actionDecisions.get(callKey(proposal));
1363
+ actionDecisions.delete(callKey(proposal));
1317
1364
  try {
1318
- await runtime.afterTool({ ...identity, requestId: text(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, callId: required2(event.callID ?? event.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required2(event.tool ?? event.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(event.input ?? event.args), ok: event.status === "completed", result: event.result, errorCode: text(asRecord(event.error).code), traceId: text(event.traceID), turnId: text(event.turnID) });
1365
+ await runtime.afterTool({ ...proposal, ok: event.status === "completed", result: event.result, errorCode: text(asRecord(event.error).code), ...decision?.authorityReceiptDigest ? { authorityReceiptDigest: decision.authorityReceiptDigest } : {}, ...decision?.decisionDigest ? { decisionDigest: decision.decisionDigest } : {} });
1319
1366
  } catch (error) {
1320
1367
  if (mode === "enforce") throw error;
1321
1368
  }
1322
1369
  }));
1323
- registrations.push(await ctx.session.hook("fork", (event) => runtime.endSession({ ...scope, hostName: "opencode", hostVersion: ctx.app?.version ?? "unknown", aiSystemId: options.aiSystemId ?? "", connectionId: options.connectionId ?? "", conversationId: text(event.sessionID) })));
1370
+ registrations.push(await ctx.session.hook("fork", (event) => {
1371
+ clearSessionState(event);
1372
+ return runtime.endSession({ ...scope, hostName: "opencode", hostVersion: ctx.app?.version ?? "unknown", aiSystemId: options.aiSystemId ?? "", connectionId: options.connectionId ?? "", conversationId: text(event.sessionID), sessionId: text(event.sessionID) || void 0 });
1373
+ }));
1374
+ registrations.push(await ctx.session.hook("compaction", (event) => {
1375
+ clearSessionState(event);
1376
+ runtime.endSession({ ...scope, hostName: "opencode", hostVersion: ctx.app?.version ?? "unknown", aiSystemId: options.aiSystemId ?? "", connectionId: options.connectionId ?? "", conversationId: text(event.sessionID ?? event.conversationId), sessionId: text(event.sessionID ?? event.conversationId) || void 0 });
1377
+ }));
1324
1378
  return async () => {
1325
1379
  actionContexts.clear();
1380
+ actionDecisions.clear();
1326
1381
  for (const registration of registrations) await registration.dispose?.();
1327
1382
  };
1328
1383
  }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@tryvira/opencode",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
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", "README.md"],
9
9
  "scripts": {"build": "node ../../scripts/build-opencode-plugin.mjs", "pack:check": "npm run build && npm pack --dry-run"},
10
- "dependencies": {"@tryvira/sdk": "0.1.50"},
10
+ "dependencies": {"@tryvira/sdk": "0.1.51"},
11
11
  "peerDependencies": {"effect": "^4.0.0"},
12
12
  "engines": {"node": ">=20"},
13
13
  "license": "MIT"