@tryvira/opencode 0.1.5 → 0.1.7

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 +46 -10
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # `@tryvira/opencode`
1
+ # `@tryvira/opencode` 0.1.7
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
@@ -1224,7 +1224,7 @@ function createViraHostRuntime(client, config) {
1224
1224
  nonEmpty(result.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
1225
1225
  if (mode === "off" || !capabilities.canInspectToolAfter) return { status: "off" };
1226
1226
  const observedResult = result.ok ? result.result : { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" };
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", 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 } : {} };
1228
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");
1229
1229
  };
1230
1230
  const executeTool = async (input) => {
@@ -1236,11 +1236,11 @@ function createViraHostRuntime(client, config) {
1236
1236
  try {
1237
1237
  const result = await input.execute(proposal.args);
1238
1238
  const resultDigest = digest(result);
1239
- const observation = await afterTool({ ...proposal, ok: true, result, resultDigest });
1239
+ const observation = await afterTool({ ...proposal, ok: true, result, resultDigest, ...decision.authorityReceiptDigest ? { authorityReceiptDigest: decision.authorityReceiptDigest } : {}, ...decision.decisionDigest ? { decisionDigest: decision.decisionDigest } : {} });
1240
1240
  return { decision, executed: true, result, observation };
1241
1241
  } catch (error) {
1242
1242
  const errorCode = error instanceof Error ? error.message : "GOVERNED_TOOL_FAILED";
1243
- const observation = await afterTool({ ...proposal, ok: false, errorCode, resultDigest: digest({ errorCode }) });
1243
+ const observation = await afterTool({ ...proposal, ok: false, errorCode, resultDigest: digest({ errorCode }), ...decision.authorityReceiptDigest ? { authorityReceiptDigest: decision.authorityReceiptDigest } : {}, ...decision.decisionDigest ? { decisionDigest: decision.decisionDigest } : {} });
1244
1244
  throw Object.assign(error instanceof Error ? error : new Error(errorCode), { decision, observation });
1245
1245
  }
1246
1246
  };
@@ -1291,10 +1291,31 @@ var v2Plugin = Plugin.define({
1291
1291
  const client = new ViraClient({ baseUrl: required2(apiUrl, "VIRA_HOST_API_URL_REQUIRED"), apiKey });
1292
1292
  const capabilities = { canObserveModel: true, canInjectContext: true, canInterceptToolBefore: true, canInspectToolAfter: true, canPreventSideEffect: mode === "enforce", canInterceptResponseBeforeDisplay: false, ...options.capabilities ?? {} };
1293
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
+ };
1294
1307
  const runtime = createViraHostRuntime(client, { mode, capabilities, authorizeAction: options.authorizeAction ?? (async (proposal) => {
1295
- const contextKey = proposal.organizationId + ":" + proposal.projectId + ":" + proposal.environmentId + ":" + proposal.conversationId;
1296
- const bound = actionContexts.get(contextKey);
1308
+ const bound = actionContexts.get(contextKey(proposal));
1297
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" };
1298
1319
  try {
1299
1320
  const approval = asRecord(asRecord(proposal).approval);
1300
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 } : {} });
@@ -1313,14 +1334,16 @@ var v2Plugin = Plugin.define({
1313
1334
  connectedConnectionId = identity?.connectionId ?? "";
1314
1335
  }
1315
1336
  const registrations = [];
1316
- 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 });
1317
1338
  registrations.push(await ctx.session.hook("context", async (event) => {
1318
1339
  const identity = sessionIdentity(event);
1319
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) });
1320
1341
  const responseBody = asRecord(result.response?.body);
1321
1342
  const runtimeContext = asRecord(event.viraRuntimeContext ?? responseBody.requestContext ?? responseBody.context);
1322
1343
  const executionId = text(event.executionId ?? responseBody.executionId);
1323
- 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));
1324
1347
  if (result.status === "applied" && result.projection) {
1325
1348
  const system = Array.isArray(event.system) ? event.system : event.system = [];
1326
1349
  if (!system.some((item) => text(asRecord(item).text) === result.projection)) system.push({ type: "text", text: result.projection });
@@ -1328,20 +1351,33 @@ var v2Plugin = Plugin.define({
1328
1351
  }));
1329
1352
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
1330
1353
  const identity = sessionIdentity(event);
1331
- 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);
1332
1357
  if (mode === "enforce" && decision.decision !== "ALLOW") throw new ViraOpenCodeActionError(decision.decision, text(decision.reasonCode) || "VIRA_ACTION_NOT_ALLOWED");
1333
1358
  }));
1334
1359
  registrations.push(await ctx.tool.hook("execute.after", async (event) => {
1335
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));
1336
1364
  try {
1337
- 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 } : {} });
1338
1366
  } catch (error) {
1339
1367
  if (mode === "enforce") throw error;
1340
1368
  }
1341
1369
  }));
1342
- 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
+ }));
1343
1378
  return async () => {
1344
1379
  actionContexts.clear();
1380
+ actionDecisions.clear();
1345
1381
  for (const registration of registrations) await registration.dispose?.();
1346
1382
  };
1347
1383
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryvira/opencode",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "OpenCode V2 host lifecycle integration for Vira",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",