@tryvira/opencode 0.1.59 → 0.1.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.js +106 -37
- package/package.json +25 -8
package/README.md
CHANGED
package/dist/index.js
CHANGED
|
@@ -1552,7 +1552,16 @@ var lastUserText = (event) => {
|
|
|
1552
1552
|
};
|
|
1553
1553
|
var latestAssistantText = (event) => {
|
|
1554
1554
|
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
1555
|
+
let lastUserIndex = -1;
|
|
1555
1556
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1557
|
+
const message2 = asRecord(messages[index]);
|
|
1558
|
+
const role = text2(message2.role ?? asRecord(message2.info).role);
|
|
1559
|
+
if (role === "user") {
|
|
1560
|
+
lastUserIndex = index;
|
|
1561
|
+
break;
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
for (let index = messages.length - 1; index > lastUserIndex; index -= 1) {
|
|
1556
1565
|
const message2 = asRecord(messages[index]);
|
|
1557
1566
|
const role = text2(message2.role ?? asRecord(message2.info).role);
|
|
1558
1567
|
if (role === "assistant") {
|
|
@@ -1561,7 +1570,7 @@ var latestAssistantText = (event) => {
|
|
|
1561
1570
|
}
|
|
1562
1571
|
}
|
|
1563
1572
|
const message = asRecord(event.message);
|
|
1564
|
-
return text2(message.role ?? asRecord(message.info).role) === "assistant" ? messageContentText(message.content ?? message.parts ?? message.text) : "";
|
|
1573
|
+
return lastUserIndex < 0 && text2(message.role ?? asRecord(message.info).role) === "assistant" ? messageContentText(message.content ?? message.parts ?? message.text) : "";
|
|
1565
1574
|
};
|
|
1566
1575
|
var scopeMembers = (event, options = {}) => {
|
|
1567
1576
|
const workspaceId = text2(options.workspaceId ?? event.workspaceId ?? asRecord(event.workspace).id);
|
|
@@ -1588,6 +1597,7 @@ var modelMetadata = (event) => {
|
|
|
1588
1597
|
var modelObservationPayload = (event, extra = {}) => ({ model: modelMetadata(event), ...extra, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } });
|
|
1589
1598
|
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}` });
|
|
1590
1599
|
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}` });
|
|
1600
|
+
var conversationOutputObservationPayload = (output) => ({ outputDigest: digest2(output), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } });
|
|
1591
1601
|
var recordModelMetrics = (client, identity, input) => {
|
|
1592
1602
|
const common = { ...identity, conversationId: input.conversationId, requestId: input.requestId, traceId: input.traceId };
|
|
1593
1603
|
const lineage = { ...input.releaseDigest ? { releaseDigest: input.releaseDigest } : {}, ...input.evaluationId ? { evaluationId: input.evaluationId } : {}, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } };
|
|
@@ -1622,6 +1632,8 @@ var createV1PromptCache = (ttlMs) => {
|
|
|
1622
1632
|
clear(sessionId);
|
|
1623
1633
|
const timer = setTimeout(() => entries.delete(sessionId), ttl);
|
|
1624
1634
|
entries.set(sessionId, { prompt, timer });
|
|
1635
|
+
}, peek(sessionId) {
|
|
1636
|
+
return entries.get(sessionId)?.prompt;
|
|
1625
1637
|
}, take(sessionId) {
|
|
1626
1638
|
const entry = entries.get(sessionId);
|
|
1627
1639
|
if (!entry) return void 0;
|
|
@@ -1629,6 +1641,25 @@ var createV1PromptCache = (ttlMs) => {
|
|
|
1629
1641
|
return entry.prompt;
|
|
1630
1642
|
}, clear, has: (sessionId) => entries.has(sessionId), size: () => entries.size };
|
|
1631
1643
|
};
|
|
1644
|
+
var createTeachTurnLedger = () => {
|
|
1645
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1646
|
+
const put = (conversationId, prompt, requestId, turnId) => {
|
|
1647
|
+
const list = entries.get(conversationId) ?? [];
|
|
1648
|
+
list.push({ prompt, requestId, turnId });
|
|
1649
|
+
entries.set(conversationId, list.slice(-20));
|
|
1650
|
+
};
|
|
1651
|
+
const take = (conversationId, requestId, turnId) => {
|
|
1652
|
+
const list = entries.get(conversationId) ?? [];
|
|
1653
|
+
const exact = list.findIndex((item2) => requestId && item2.requestId === requestId || turnId && item2.turnId === turnId);
|
|
1654
|
+
const index = exact >= 0 ? exact : list.length === 1 ? 0 : -1;
|
|
1655
|
+
if (index < 0) return void 0;
|
|
1656
|
+
const [item] = list.splice(index, 1);
|
|
1657
|
+
if (list.length) entries.set(conversationId, list);
|
|
1658
|
+
else entries.delete(conversationId);
|
|
1659
|
+
return item?.prompt;
|
|
1660
|
+
};
|
|
1661
|
+
return { put, take, clear: (conversationId) => entries.delete(conversationId), size: () => [...entries.values()].reduce((sum, list) => sum + list.length, 0) };
|
|
1662
|
+
};
|
|
1632
1663
|
var readHostOptions = (rawContext) => {
|
|
1633
1664
|
const raw = asRecord(rawContext);
|
|
1634
1665
|
const nested = asRecord(raw.options);
|
|
@@ -1647,6 +1678,7 @@ var resolveOpenCodeToolBinding = (tools, toolName) => {
|
|
|
1647
1678
|
const binding = bindings.find((value) => text2(value.host_action_name) === toolName || Array.isArray(value.aliases) && value.aliases.map(text2).includes(toolName));
|
|
1648
1679
|
return { allowedToolIds, bindings, binding, canonicalToolId: text2(binding?.tool_id) || toolName, schemaDigest: text2(binding?.schema_digest) || text2(tools.schema_digest) };
|
|
1649
1680
|
};
|
|
1681
|
+
var buildOpenCodeActionProposal = (proposal, binding, requestContext) => ({ proposal_id: proposal.conversationId + ":" + proposal.callId, tool_key: binding.canonicalToolId, arguments: proposal.args, arguments_digest: digest2(proposal.args), request_context_digest: digest2(requestContext), schema_digest: binding.schemaDigest });
|
|
1650
1682
|
var createDesktopPermissionBridge = () => {
|
|
1651
1683
|
const pending = /* @__PURE__ */ new Map();
|
|
1652
1684
|
const evaluate = (event) => {
|
|
@@ -1683,7 +1715,8 @@ var ViraOpenCodeActionError = class extends Error {
|
|
|
1683
1715
|
};
|
|
1684
1716
|
var v2Plugin = Plugin.define({
|
|
1685
1717
|
id: "vira",
|
|
1686
|
-
async setup(
|
|
1718
|
+
async setup(openCodeContext) {
|
|
1719
|
+
const ctx = openCodeContext;
|
|
1687
1720
|
const options = ctx.options ?? {};
|
|
1688
1721
|
const env = envValue;
|
|
1689
1722
|
const mode = options.mode ?? env("VIRA_HOST_MODE") ?? "off";
|
|
@@ -1696,8 +1729,9 @@ var v2Plugin = Plugin.define({
|
|
|
1696
1729
|
const capabilities = { canObserveModel: true, canInjectContext: true, canInterceptToolBefore: true, canInspectToolAfter: true, canPreventSideEffect: mode === "enforce", canInterceptResponseBeforeDisplay: false, ...options.capabilities ?? {} };
|
|
1697
1730
|
const actionContexts = /* @__PURE__ */ new Map();
|
|
1698
1731
|
const taskRuns = /* @__PURE__ */ new Map();
|
|
1699
|
-
const teachPrompts =
|
|
1732
|
+
const teachPrompts = createTeachTurnLedger();
|
|
1700
1733
|
const actionDecisions = /* @__PURE__ */ new Map();
|
|
1734
|
+
const actionDecisionDigests = /* @__PURE__ */ new Map();
|
|
1701
1735
|
const desktopPermission = createDesktopPermissionBridge();
|
|
1702
1736
|
const contextKey = (identity) => identity.organizationId + ":" + identity.projectId + ":" + identity.environmentId + ":" + (identity.workspaceId ?? "") + ":" + (identity.userId ?? "") + ":" + identity.conversationId + ":" + (identity.sessionId ?? identity.conversationId);
|
|
1703
1737
|
const findActionContext = (proposal) => {
|
|
@@ -1711,6 +1745,18 @@ var v2Plugin = Plugin.define({
|
|
|
1711
1745
|
return void 0;
|
|
1712
1746
|
};
|
|
1713
1747
|
const callKey = (proposal) => contextKey(proposal) + ":" + proposal.callId;
|
|
1748
|
+
const proposalDigest = (proposal) => digest2({ toolName: proposal.toolName, args: proposal.args, sessionId: proposal.sessionId, conversationId: proposal.conversationId });
|
|
1749
|
+
const cachedDecision = (proposal) => {
|
|
1750
|
+
const key = callKey(proposal);
|
|
1751
|
+
const cached = actionDecisions.get(key);
|
|
1752
|
+
return cached && actionDecisionDigests.get(key) === proposalDigest(proposal) ? cached : void 0;
|
|
1753
|
+
};
|
|
1754
|
+
const cacheDecision = (proposal, decision) => {
|
|
1755
|
+
const key = callKey(proposal);
|
|
1756
|
+
actionDecisions.set(key, decision);
|
|
1757
|
+
actionDecisionDigests.set(key, proposalDigest(proposal));
|
|
1758
|
+
return decision;
|
|
1759
|
+
};
|
|
1714
1760
|
const clearSessionState = (event) => {
|
|
1715
1761
|
const sessionId = text2(event.sessionID ?? event.sessionId);
|
|
1716
1762
|
const conversationId = text2(event.conversationId ?? event.sessionID ?? event.sessionId);
|
|
@@ -1721,8 +1767,8 @@ var v2Plugin = Plugin.define({
|
|
|
1721
1767
|
if (sessionId && key.includes(":" + sessionId + ":") || conversationId && key.includes(":" + conversationId + ":")) actionDecisions.delete(key);
|
|
1722
1768
|
}
|
|
1723
1769
|
for (const key of taskRuns.keys()) if (key === conversationId || key === sessionId) taskRuns.delete(key);
|
|
1724
|
-
teachPrompts.
|
|
1725
|
-
teachPrompts.
|
|
1770
|
+
teachPrompts.clear(conversationId);
|
|
1771
|
+
if (sessionId && sessionId !== conversationId) teachPrompts.clear(sessionId);
|
|
1726
1772
|
desktopPermission.clear();
|
|
1727
1773
|
};
|
|
1728
1774
|
const cancelTaskRunForSession = async (event) => {
|
|
@@ -1775,13 +1821,15 @@ var v2Plugin = Plugin.define({
|
|
|
1775
1821
|
const schemaDigest = binding.schemaDigest;
|
|
1776
1822
|
const bindingDigest = text2(bound.context.binding_digest);
|
|
1777
1823
|
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" };
|
|
1778
|
-
const proposalBody =
|
|
1824
|
+
const proposalBody = buildOpenCodeActionProposal(proposal, { canonicalToolId, schemaDigest }, bound.context);
|
|
1779
1825
|
const approvalCandidate = asRecord(asRecord(proposal).approval);
|
|
1780
1826
|
const approval = typeof approvalCandidate.approvalId === "string" && approvalCandidate.approvalId.trim() ? { approvalId: approvalCandidate.approvalId.trim() } : void 0;
|
|
1781
1827
|
const dataVersion = text2(bound.context.release_digest);
|
|
1782
1828
|
if (!dataVersion) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_DATA_VERSION_UNAVAILABLE" };
|
|
1783
1829
|
const refs = Array.isArray(bound.context.signal_attestation_refs) ? bound.context.signal_attestation_refs : [];
|
|
1784
|
-
|
|
1830
|
+
const nativeAccepted = desktopPermission.confirm(proposal);
|
|
1831
|
+
const confirmAction = async () => nativeAccepted || typeof options.confirmAction === "function" && await options.confirmAction(proposal);
|
|
1832
|
+
return authorizeWithOneShotCustomerConfirmation({ client, proposal, proposalBody, signalAttestationRefs: refs, executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, confirmAction, approvalId: approval?.approvalId });
|
|
1785
1833
|
}), ...bootstrapAiSystemId && bootstrapConnectionId ? {} : { connect: openCodeConnectConfig(scope, options) } });
|
|
1786
1834
|
let connectedAiSystemId = bootstrapAiSystemId;
|
|
1787
1835
|
let connectedConnectionId = bootstrapConnectionId;
|
|
@@ -1825,22 +1873,21 @@ var v2Plugin = Plugin.define({
|
|
|
1825
1873
|
return { ...scope, ...scopeMembers(event, options), 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 };
|
|
1826
1874
|
};
|
|
1827
1875
|
if (mode === "enforce" && options.permissionMode !== "deny" && ctx.permission?.hook) registrations.push(await ctx.permission.hook("evaluate", async (event) => {
|
|
1828
|
-
const identity = sessionIdentity(event);
|
|
1829
1876
|
const toolName = text2(event.action);
|
|
1877
|
+
const callId = text2(event.source?.id) || text2(event.messageID) || `permission:${Date.now()}`;
|
|
1830
1878
|
if (!toolName) {
|
|
1831
1879
|
event.effect = "deny";
|
|
1832
1880
|
event.message = "Vira denied an unidentifiable tool request.";
|
|
1833
1881
|
return;
|
|
1834
1882
|
}
|
|
1835
|
-
const
|
|
1836
|
-
|
|
1837
|
-
if (decision.decision === "ALLOW") {
|
|
1838
|
-
event.effect = "allow";
|
|
1839
|
-
event.message = "Vira authorized this tool request.";
|
|
1840
|
-
} else {
|
|
1883
|
+
const asked = desktopPermission.evaluate({ sessionID: text2(event.sessionID ?? event.sessionId), action: toolName, source: { id: callId } });
|
|
1884
|
+
if (!asked) {
|
|
1841
1885
|
event.effect = "deny";
|
|
1842
|
-
event.message =
|
|
1886
|
+
event.message = "Vira denied this tool request because the native confirmation context was unavailable.";
|
|
1887
|
+
return;
|
|
1843
1888
|
}
|
|
1889
|
+
event.effect = "ask";
|
|
1890
|
+
event.message = `Vira requires one-time confirmation for ${toolName}. Confirm the exact tool and arguments in OpenCode.`;
|
|
1844
1891
|
}));
|
|
1845
1892
|
registrations.push(await ctx.session.hook("context", async (event) => {
|
|
1846
1893
|
const input = lastUserText(event);
|
|
@@ -1848,7 +1895,7 @@ var v2Plugin = Plugin.define({
|
|
|
1848
1895
|
if (!input && !output) return;
|
|
1849
1896
|
const identity = sessionIdentity(event);
|
|
1850
1897
|
if (input) {
|
|
1851
|
-
teachPrompts.
|
|
1898
|
+
teachPrompts.put(identity.conversationId, input, text2(event.messageID ?? event.requestId) || void 0, text2(event.turnID) || void 0);
|
|
1852
1899
|
const result = await runtime2.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 });
|
|
1853
1900
|
const refreshed = runtime2.getConnectionIdentity();
|
|
1854
1901
|
if (!options.aiSystemId && !options.connectionId && refreshed) {
|
|
@@ -1873,13 +1920,12 @@ var v2Plugin = Plugin.define({
|
|
|
1873
1920
|
}
|
|
1874
1921
|
if (output) {
|
|
1875
1922
|
const eventId = `${identity.conversationId}:assistant:${text2(event.messageID ?? event.requestId) || digest2(output).slice(0, 16)}`;
|
|
1876
|
-
void client.observe({ ...identity, eventId, eventType: "conversation.output", traceId: text2(event.traceID), requestId: text2(event.requestId ?? event.messageID) || eventId, payload:
|
|
1923
|
+
void client.observe({ ...identity, eventId, eventType: "conversation.output", traceId: text2(event.traceID), requestId: text2(event.requestId ?? event.messageID) || eventId, payload: conversationOutputObservationPayload(output), attributes: { source: "opencode.context" } }, { idempotencyKey: `opencode:conversation.output:${eventId}` }).catch(() => void 0);
|
|
1877
1924
|
if (options.teachConsent === true) {
|
|
1878
|
-
const prompt = teachPrompts.
|
|
1925
|
+
const prompt = teachPrompts.take(identity.conversationId, text2(event.messageID ?? event.requestId) || void 0, text2(event.turnID) || void 0) || "";
|
|
1879
1926
|
if (prompt) {
|
|
1880
1927
|
void client.submitTeachConversationEvidence({ id: `opencode-teach:${identity.conversationId}:${text2(event.messageID ?? event.requestId) || digest2(output).slice(0, 16)}`, conversationId: identity.conversationId, message: `User: ${prompt}
|
|
1881
1928
|
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);
|
|
1882
|
-
teachPrompts.delete(identity.conversationId);
|
|
1883
1929
|
}
|
|
1884
1930
|
}
|
|
1885
1931
|
}
|
|
@@ -1887,15 +1933,16 @@ Assistant: ${output}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempoten
|
|
|
1887
1933
|
registrations.push(await ctx.tool.hook("execute.before", async (event) => {
|
|
1888
1934
|
const identity = sessionIdentity(event);
|
|
1889
1935
|
const proposal = { ...identity, requestId: text2(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: text2(event.traceID), turnId: text2(event.turnID) };
|
|
1890
|
-
const decision = await runtime2.beforeTool(proposal);
|
|
1891
|
-
actionDecisions.set(callKey(proposal), decision);
|
|
1936
|
+
const decision = cachedDecision(proposal) ?? cacheDecision(proposal, await runtime2.beforeTool(proposal));
|
|
1892
1937
|
if (mode === "enforce" && decision.decision !== "ALLOW") throw new ViraOpenCodeActionError(decision.decision, text2(decision.reasonCode) || "VIRA_ACTION_NOT_ALLOWED");
|
|
1893
1938
|
}));
|
|
1894
1939
|
registrations.push(await ctx.tool.hook("execute.after", async (event) => {
|
|
1895
1940
|
const identity = sessionIdentity(event);
|
|
1896
1941
|
const proposal = { ...identity, requestId: text2(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: text2(event.traceID), turnId: text2(event.turnID) };
|
|
1897
|
-
const
|
|
1898
|
-
|
|
1942
|
+
const key = callKey(proposal);
|
|
1943
|
+
const decision = cachedDecision(proposal);
|
|
1944
|
+
actionDecisions.delete(key);
|
|
1945
|
+
actionDecisionDigests.delete(key);
|
|
1899
1946
|
try {
|
|
1900
1947
|
await runtime2.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 } : {} });
|
|
1901
1948
|
} catch (error) {
|
|
@@ -1915,6 +1962,7 @@ Assistant: ${output}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempoten
|
|
|
1915
1962
|
return async () => {
|
|
1916
1963
|
actionContexts.clear();
|
|
1917
1964
|
actionDecisions.clear();
|
|
1965
|
+
actionDecisionDigests.clear();
|
|
1918
1966
|
desktopPermission.clear();
|
|
1919
1967
|
for (const registration of registrations) await registration.dispose?.();
|
|
1920
1968
|
};
|
|
@@ -1930,7 +1978,21 @@ var v1Runtime = (options) => {
|
|
|
1930
1978
|
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"), timeoutMs, allowInsecureLocalhost: options.allowInsecureLocalhost ?? env("VIRA_ALLOW_INSECURE_LOCALHOST") === "true" });
|
|
1931
1979
|
const actionContexts = /* @__PURE__ */ new Map();
|
|
1932
1980
|
const actionDecisions = /* @__PURE__ */ new Map();
|
|
1981
|
+
const actionDecisionDigests = /* @__PURE__ */ new Map();
|
|
1933
1982
|
const contextKey = (identity) => identity.organizationId + ":" + identity.projectId + ":" + identity.environmentId + ":" + identity.conversationId + ":" + (identity.sessionId ?? identity.conversationId);
|
|
1983
|
+
const callKey = (proposal) => contextKey(proposal) + ":" + proposal.callId;
|
|
1984
|
+
const proposalDigest = (proposal) => digest2({ toolName: proposal.toolName, args: proposal.args, sessionId: proposal.sessionId, conversationId: proposal.conversationId });
|
|
1985
|
+
const cachedDecision = (proposal) => {
|
|
1986
|
+
const key = callKey(proposal);
|
|
1987
|
+
const cached = actionDecisions.get(key);
|
|
1988
|
+
return cached && actionDecisionDigests.get(key) === proposalDigest(proposal) ? cached : void 0;
|
|
1989
|
+
};
|
|
1990
|
+
const cacheDecision = (proposal, decision) => {
|
|
1991
|
+
const key = callKey(proposal);
|
|
1992
|
+
actionDecisions.set(key, decision);
|
|
1993
|
+
actionDecisionDigests.set(key, proposalDigest(proposal));
|
|
1994
|
+
return decision;
|
|
1995
|
+
};
|
|
1934
1996
|
const findActionContext = (proposal) => {
|
|
1935
1997
|
const exact = actionContexts.get(contextKey(proposal));
|
|
1936
1998
|
if (exact) return exact;
|
|
@@ -1953,7 +2015,7 @@ var v1Runtime = (options) => {
|
|
|
1953
2015
|
if (!dataVersion) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_DATA_VERSION_UNAVAILABLE" };
|
|
1954
2016
|
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" };
|
|
1955
2017
|
try {
|
|
1956
|
-
const response = await client.authorizeHostAction({ executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, proposal:
|
|
2018
|
+
const response = await client.authorizeHostAction({ executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, proposal: buildOpenCodeActionProposal(proposal, binding, bound.context) });
|
|
1957
2019
|
const body = asRecord(response?.body);
|
|
1958
2020
|
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) };
|
|
1959
2021
|
} catch (error) {
|
|
@@ -1961,21 +2023,25 @@ var v1Runtime = (options) => {
|
|
|
1961
2023
|
}
|
|
1962
2024
|
};
|
|
1963
2025
|
const authorizeAction = options.authorizeAction ?? serverAuthorizeAction;
|
|
1964
|
-
return { mode, scope, client, actionContexts, actionDecisions, contextKey, runtime: createViraHostRuntime(client, { mode, timeoutMs, ...(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 }) };
|
|
2026
|
+
return { mode, scope, client, actionContexts, actionDecisions, actionDecisionDigests, contextKey, cachedDecision, cacheDecision, runtime: createViraHostRuntime(client, { mode, timeoutMs, ...(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 }) };
|
|
1965
2027
|
};
|
|
1966
2028
|
var v1Fallback = { async server(rawContext = {}) {
|
|
1967
2029
|
const options = readHostOptions(rawContext);
|
|
1968
2030
|
const configured = v1Runtime(options);
|
|
1969
2031
|
if (!configured) return {};
|
|
1970
|
-
const { mode, scope, client, runtime: runtime2, actionContexts, actionDecisions, contextKey } = configured;
|
|
2032
|
+
const { mode, scope, client, runtime: runtime2, actionContexts, actionDecisions, actionDecisionDigests, contextKey, cachedDecision, cacheDecision } = configured;
|
|
1971
2033
|
if (!options.aiSystemId || !options.connectionId) await runtime2.connectOnce();
|
|
1972
2034
|
let connectedIdentity = runtime2.getConnectionIdentity();
|
|
1973
2035
|
const env = envValue;
|
|
1974
2036
|
const promptCacheTtlMs = Math.max(1e3, Math.min(3e5, Number(options.promptCacheTtlMs ?? envValue("VIRA_V1_PROMPT_CACHE_TTL_MS") ?? 6e4) || 6e4));
|
|
1975
2037
|
const prompts = createV1PromptCache(promptCacheTtlMs);
|
|
2038
|
+
const teachPrompts = createTeachTurnLedger();
|
|
1976
2039
|
const clearSessionPrompts = (event) => {
|
|
1977
2040
|
const sessionId = text2(event.sessionID ?? event.sessionId ?? event.conversationId ?? event.id);
|
|
1978
|
-
if (sessionId)
|
|
2041
|
+
if (sessionId) {
|
|
2042
|
+
prompts.clear(sessionId);
|
|
2043
|
+
teachPrompts.clear(sessionId);
|
|
2044
|
+
}
|
|
1979
2045
|
};
|
|
1980
2046
|
const hostVersion = hostVersionFor(options, rawContext);
|
|
1981
2047
|
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 });
|
|
@@ -1995,7 +2061,7 @@ var v1Fallback = { async server(rawContext = {}) {
|
|
|
1995
2061
|
const eventId = `${sessionID}:assistant:${messageID}`;
|
|
1996
2062
|
await recordConversationOutput(client, current, { eventId, output, conversationId: sessionID, requestId: messageID, traceId: text2(data.traceID) || void 0 });
|
|
1997
2063
|
if (options.teachConsent === true) {
|
|
1998
|
-
const prompt =
|
|
2064
|
+
const prompt = teachPrompts.take(sessionID, messageID);
|
|
1999
2065
|
if (prompt) await client.submitTeachConversationEvidence({ id: `opencode-teach:${sessionID}:${messageID}`, conversationId: sessionID, message: `User: ${prompt}
|
|
2000
2066
|
Assistant: ${output}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempotencyKey: `opencode:teach:${sessionID}:${messageID}` });
|
|
2001
2067
|
}
|
|
@@ -2003,7 +2069,7 @@ Assistant: ${output}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempoten
|
|
|
2003
2069
|
const applyModel = async (input, output) => {
|
|
2004
2070
|
const sessionId = text2(input.sessionID ?? input.conversationId ?? input.id);
|
|
2005
2071
|
const direct = text2(input.prompt ?? asRecord(input.message).text ?? input.input ?? output.prompt);
|
|
2006
|
-
const prompt = direct || prompts.
|
|
2072
|
+
const prompt = direct || prompts.peek(sessionId) || "";
|
|
2007
2073
|
if (!prompt.trim()) return;
|
|
2008
2074
|
const result = await runtime2.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 });
|
|
2009
2075
|
if (!options.aiSystemId && !options.connectionId) connectedIdentity = runtime2.getConnectionIdentity();
|
|
@@ -2042,7 +2108,7 @@ Assistant: ${output}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempoten
|
|
|
2042
2108
|
const messageID = text2(input.messageID) || text2(input.partID) || digest2(completed).slice(0, 16);
|
|
2043
2109
|
await recordConversationOutput(client, current, { eventId: `${sessionID}:assistant:${messageID}`, output: completed, conversationId: sessionID, requestId: messageID });
|
|
2044
2110
|
if (options.teachConsent === true) {
|
|
2045
|
-
const prompt =
|
|
2111
|
+
const prompt = teachPrompts.take(sessionID, messageID);
|
|
2046
2112
|
if (prompt) await client.submitTeachConversationEvidence({ id: `opencode-teach:${sessionID}:${messageID}`, conversationId: sessionID, message: `User: ${prompt}
|
|
2047
2113
|
Assistant: ${completed}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempotencyKey: `opencode:teach:${sessionID}:${messageID}` });
|
|
2048
2114
|
}
|
|
@@ -2054,7 +2120,10 @@ Assistant: ${completed}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempo
|
|
|
2054
2120
|
const sessionId = text2(input.sessionID ?? input.conversationId ?? input.id);
|
|
2055
2121
|
const message = asRecord(output.message ?? input.message);
|
|
2056
2122
|
const prompt = text2(message.text ?? message.content) || partsText(output.parts ?? input.parts);
|
|
2057
|
-
if (sessionId && prompt.trim())
|
|
2123
|
+
if (sessionId && prompt.trim()) {
|
|
2124
|
+
prompts.set(sessionId, prompt.trim());
|
|
2125
|
+
teachPrompts.put(sessionId, prompt.trim(), text2(input.messageID ?? input.requestId) || void 0, text2(input.turnID) || void 0);
|
|
2126
|
+
}
|
|
2058
2127
|
},
|
|
2059
2128
|
"chat.params": async (input, output) => applyModel(input, output),
|
|
2060
2129
|
"experimental.chat.system.transform": async (input, output) => applyModel(input, output),
|
|
@@ -2062,20 +2131,20 @@ Assistant: ${completed}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempo
|
|
|
2062
2131
|
if (mode !== "enforce") return;
|
|
2063
2132
|
const metadata = asRecord(input.metadata);
|
|
2064
2133
|
const proposal = { ...identity(input), requestId: text2(input.messageID ?? input.requestId) || `opencode:${Date.now()}`, callId: required2(input.callID ?? input.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required2(metadata.tool ?? metadata.toolName ?? input.type, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(metadata.args ?? metadata.input ?? metadata.arguments), traceId: text2(input.traceID), turnId: text2(input.turnID) };
|
|
2065
|
-
const decision = await runtime2.beforeTool(proposal);
|
|
2066
|
-
actionDecisions.set(contextKey(proposal) + ":" + proposal.callId, decision);
|
|
2134
|
+
const decision = cachedDecision(proposal) ?? cacheDecision(proposal, await runtime2.beforeTool(proposal));
|
|
2067
2135
|
output.status = decision.decision === "ALLOW" ? "allow" : "deny";
|
|
2068
2136
|
},
|
|
2069
2137
|
"tool.execute.before": async (input, output) => {
|
|
2070
2138
|
const proposal = { ...identity(input), requestId: text2(input.messageID ?? input.requestId) || `opencode:${Date.now()}`, callId: required2(input.callID ?? input.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required2(input.tool ?? input.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(output.args ?? input.args ?? input.input), traceId: text2(input.traceID), turnId: text2(input.turnID) };
|
|
2071
|
-
const decision = await runtime2.beforeTool(proposal);
|
|
2072
|
-
actionDecisions.set(contextKey(proposal) + ":" + proposal.callId, decision);
|
|
2139
|
+
const decision = cachedDecision(proposal) ?? cacheDecision(proposal, await runtime2.beforeTool(proposal));
|
|
2073
2140
|
if (mode === "enforce" && decision.decision !== "ALLOW") throw new ViraOpenCodeActionError(decision.decision, text2(decision.reasonCode) || "VIRA_ACTION_NOT_ALLOWED");
|
|
2074
2141
|
},
|
|
2075
2142
|
"tool.execute.after": async (input, output) => {
|
|
2076
2143
|
const proposal = { ...identity(input), requestId: text2(input.messageID ?? input.requestId) || `opencode:${Date.now()}`, callId: required2(input.callID ?? input.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required2(input.tool ?? input.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(input.args ?? input.input), traceId: text2(input.traceID), turnId: text2(input.turnID) };
|
|
2077
|
-
const
|
|
2078
|
-
|
|
2144
|
+
const key = contextKey(proposal) + ":" + proposal.callId;
|
|
2145
|
+
const decision = cachedDecision(proposal);
|
|
2146
|
+
actionDecisions.delete(key);
|
|
2147
|
+
actionDecisionDigests.delete(key);
|
|
2079
2148
|
try {
|
|
2080
2149
|
await runtime2.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 } : {} });
|
|
2081
2150
|
} catch (error) {
|
package/package.json
CHANGED
|
@@ -1,14 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tryvira/opencode",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.60",
|
|
4
4
|
"description": "OpenCode host lifecycle integration for Vira",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
|
-
"exports": {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/index.js",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "node ../../scripts/build-opencode-plugin.mjs",
|
|
16
|
+
"pack:check": "npm run build && node ../../scripts/opencode-plugin-smoke.mjs && node ../../scripts/opencode-plugin-host-acceptance.mjs"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@tryvira/sdk": "0.1.66"
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"effect": "^4.0.0"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@opencode/plugin": "^2.3.2"
|
|
30
|
+
}
|
|
14
31
|
}
|