@tryvira/opencode 0.1.84 → 0.1.85

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/dist/server.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/index.ts
8
- import { createHash as createHash3, randomUUID } from "node:crypto";
8
+ import { createHash as createHash4, randomUUID } from "node:crypto";
9
9
 
10
10
  // ../../contracts/external-host-commercial-v1.ts
11
11
  var externalHostCommercialEvidence = Object.freeze({
@@ -73,8 +73,8 @@ var contentIdempotencyKey = async (operation, request) => {
73
73
  if (!globalThis.crypto?.subtle) throw new Error("SDK_IDEMPOTENCY_CRYPTO_UNAVAILABLE");
74
74
  const bytes = new TextEncoder().encode(canonicalJson(request));
75
75
  const digest4 = await globalThis.crypto.subtle.digest("SHA-256", bytes);
76
- const hex3 = [...new Uint8Array(digest4)].map((value) => value.toString(16).padStart(2, "0")).join("");
77
- return `${operation}:${hex3}`;
76
+ const hex4 = [...new Uint8Array(digest4)].map((value) => value.toString(16).padStart(2, "0")).join("");
77
+ return `${operation}:${hex4}`;
78
78
  };
79
79
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
80
80
  var retryAfterMs = (value, now = Date.now()) => {
@@ -904,6 +904,14 @@ var ViraClient = class {
904
904
  for (const [key, value] of Object.entries(query)) if (value !== void 0) params.set(key, String(value));
905
905
  return this.request({ method: "GET", path: `/v1/runtime/traces/search${params.size ? `?${params.toString()}` : ""}` });
906
906
  }
907
+ listOptimizationTargets(input2) {
908
+ for (const value of [input2.aiSystemId, input2.connectionId]) required(value, "SDK_OPTIMIZATION_TARGET_REQUIRED");
909
+ return this.request({ method: "POST", path: "/v1/optimization/target-options", body: input2 }, { enforcing: true });
910
+ }
911
+ previewOptimizationTarget(input2) {
912
+ for (const value of [input2.aiSystemId, input2.connectionId, input2.canonicalRevisionId, input2.sourceReleaseId]) required(value, "SDK_OPTIMIZATION_TARGET_REQUIRED");
913
+ return this.request({ method: "POST", path: "/v1/optimization/target-preview", body: input2 }, { enforcing: true });
914
+ }
907
915
  startOptimization(input2, options = {}) {
908
916
  const key = typeof input2.idempotencyKey === "string" ? input2.idempotencyKey.trim() : "";
909
917
  if (!key) throw new Error("SDK_IDEMPOTENCY_KEY_REQUIRED");
@@ -1094,6 +1102,23 @@ var ViraClient = class {
1094
1102
  { idempotencyKey: await contentIdempotencyKey(`sdk:pack:install:${packId}`, body) }
1095
1103
  );
1096
1104
  }
1105
+ async revokeSignalMapping(mappingId, expectedMappingDigest) {
1106
+ required(mappingId, "SDK_SIGNAL_MAPPING_ID_REQUIRED");
1107
+ if (!/^[a-f0-9]{64}$/.test(expectedMappingDigest)) throw Error("SDK_SIGNAL_MAPPING_DIGEST_INVALID");
1108
+ const body = { expectedMappingDigest };
1109
+ return this.request({ method: "POST", path: `/v1/signals/mappings/${encodeURIComponent(mappingId)}/revoke`, body }, { idempotencyKey: await contentIdempotencyKey(`sdk:signal-mapping:revoke:${mappingId}`, body), enforcing: true });
1110
+ }
1111
+ getPackSignalReadiness(packId) {
1112
+ required(packId, "SDK_PACK_ID_REQUIRED");
1113
+ return this.request({ method: "GET", path: `/v1/packs/${encodeURIComponent(packId)}/doctor` });
1114
+ }
1115
+ async bindPackSignalMappings(packId, input2) {
1116
+ required(packId, "SDK_PACK_ID_REQUIRED");
1117
+ required(input2.aiSystemId, "SDK_AI_SYSTEM_REQUIRED");
1118
+ required(input2.connectionId, "SDK_CONNECTION_REQUIRED");
1119
+ const body = { aiSystemId: input2.aiSystemId, connectionId: input2.connectionId, approve: input2.approve === true };
1120
+ return this.request({ method: "POST", path: `/v1/packs/${encodeURIComponent(packId)}/signal-mappings`, body }, { idempotencyKey: await contentIdempotencyKey(`sdk:pack:signal-mappings:${packId}`, body) });
1121
+ }
1097
1122
  async diagnosePack(packId, input2 = {}) {
1098
1123
  required(packId, "SDK_PACK_ID_REQUIRED");
1099
1124
  const body = { runtimeBindings: [...input2.runtimeBindings ?? []], knownVerifiers: [...input2.knownVerifiers ?? []] };
@@ -1166,6 +1191,10 @@ var ViraClient = class {
1166
1191
  method: "POST",
1167
1192
  path: "/v1/runtime/resolve",
1168
1193
  body: {
1194
+ ...input2.aiSystemId ? { aiSystemId: input2.aiSystemId } : {},
1195
+ ...input2.provider !== void 0 ? { provider: input2.provider } : {},
1196
+ ...input2.model !== void 0 ? { model: input2.model } : {},
1197
+ ...input2.protocol !== void 0 ? { protocol: input2.protocol } : {},
1169
1198
  ...input2.behaviorPoint ? { behaviorPoint: input2.behaviorPoint } : {},
1170
1199
  ...input2.executionBoundary ? { executionBoundary: input2.executionBoundary } : {},
1171
1200
  ...input2.semanticContext ? { semanticContext: input2.semanticContext } : {},
@@ -1185,6 +1214,10 @@ var ViraClient = class {
1185
1214
  if (!input2.executionBoundary || typeof input2.executionBoundary !== "object")
1186
1215
  throw new Error("SDK_EXECUTION_BOUNDARY_REQUIRED");
1187
1216
  return this.resolveRuntime({
1217
+ aiSystemId: input2.aiSystemId,
1218
+ provider: input2.provider,
1219
+ model: input2.model,
1220
+ protocol: input2.protocol,
1188
1221
  executionBoundary: input2.executionBoundary,
1189
1222
  ...input2.semanticContext ? { semanticContext: input2.semanticContext } : {},
1190
1223
  idempotencyKey: input2.idempotencyKey
@@ -1312,6 +1345,10 @@ var ViraClient = class {
1312
1345
  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] : {};
1313
1346
  const behaviorPoint = typeof firstCapsule.behaviorKey === "string" && firstCapsule.behaviorKey.trim() ? firstCapsule.behaviorKey : receipt.taskKey;
1314
1347
  const runtime2 = input2.executionBoundary ? await this.resolveBoundary({
1348
+ aiSystemId: input2.aiSystemId,
1349
+ provider: input2.provider,
1350
+ model: input2.model,
1351
+ protocol: input2.protocol,
1315
1352
  executionBoundary: input2.executionBoundary,
1316
1353
  semanticContext: {
1317
1354
  taskKey: receipt.taskKey,
@@ -1324,6 +1361,10 @@ var ViraClient = class {
1324
1361
  },
1325
1362
  idempotencyKey: input2.idempotencyKey ? `sdk:runtime:${input2.idempotencyKey}` : void 0
1326
1363
  }) : await this.resolveRuntime({
1364
+ aiSystemId: input2.aiSystemId,
1365
+ provider: input2.provider,
1366
+ model: input2.model,
1367
+ protocol: input2.protocol,
1327
1368
  semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule, ...input2.revisionId ? { revisionId: input2.revisionId } : {}, ...input2.requestId ? { requestId: input2.requestId } : {}, ...input2.sessionId ? { conversationId: input2.sessionId } : {}, ...input2.signalAttestationRefs ? { signalAttestationRefs: input2.signalAttestationRefs } : {} },
1328
1369
  idempotencyKey: input2.idempotencyKey ? `sdk:runtime:${input2.idempotencyKey}` : void 0
1329
1370
  });
@@ -1339,7 +1380,7 @@ var ViraClient = class {
1339
1380
  return this.request({
1340
1381
  method: "POST",
1341
1382
  path: "/v1/runtime/actions/authorize",
1342
- body: { executionId: input2.executionId, sessionId: input2.sessionId, dataVersion: input2.dataVersion, scope: input2.scope, context: input2.context, proposal: input2.proposal, ...input2.approval ? { approval: input2.approval } : {}, ...input2.signalAttestationRefs?.length ? { signalAttestationRefs: input2.signalAttestationRefs } : {}, ...input2.aiSystemId ? { aiSystemId: input2.aiSystemId } : {} }
1383
+ body: { executionId: input2.executionId, sessionId: input2.sessionId, dataVersion: input2.dataVersion, scope: input2.scope, context: input2.context, proposal: input2.proposal, ...input2.approval ? { approval: input2.approval } : {}, ...input2.signalAttestationRefs?.length ? { signalAttestationRefs: input2.signalAttestationRefs } : {}, ...input2.aiSystemId ? { aiSystemId: input2.aiSystemId } : {}, ...input2.connectionId ? { connectionId: input2.connectionId } : {} }
1343
1384
  });
1344
1385
  }
1345
1386
  /** Queue the approved SINGLE effect on the worker, never execute it locally. */
@@ -1431,24 +1472,44 @@ var ViraClient = class {
1431
1472
  { idempotencyKey: options.idempotencyKey }
1432
1473
  );
1433
1474
  }
1434
- validateBehaviorStrategy(strategyId) {
1475
+ /** Create a separate immutable draft revision against a specific observed parent.
1476
+ * This never activates or releases the draft. */
1477
+ reviseBehaviorStrategy(strategyId, definition, parent, options = {}) {
1478
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1479
+ if (!definition || typeof definition !== "object" || Array.isArray(definition))
1480
+ throw new Error("SDK_STRATEGY_VARIANT_REQUIRED");
1481
+ if (!parent || typeof parent.variantId !== "string" || !parent.variantId.trim() || parent.variantId.trim() !== parent.variantId || parent.variantId.length > 512 || typeof parent.artifactDigest !== "string" || !/^[a-f0-9]{64}$/.test(parent.artifactDigest) || typeof parent.definitionDigest !== "string" || !/^[a-f0-9]{64}$/.test(parent.definitionDigest))
1482
+ throw new Error("SDK_STRATEGY_PARENT_INVALID");
1483
+ return this.createBehaviorStrategyVariant(strategyId, {
1484
+ definition,
1485
+ studioBoundAuthoring: true,
1486
+ expectedParentVariantId: parent.variantId,
1487
+ expectedParentArtifactDigest: parent.artifactDigest,
1488
+ expectedParentDefinitionDigest: parent.definitionDigest
1489
+ }, options);
1490
+ }
1491
+ validateBehaviorStrategy(strategyId, options = {}) {
1435
1492
  required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1493
+ if (options.variantId !== void 0 && (typeof options.variantId !== "string" || !options.variantId.trim() || options.variantId.trim() !== options.variantId || options.variantId.length > 512))
1494
+ throw new Error("SDK_STRATEGY_VARIANT_ID_INVALID");
1436
1495
  return this.request({
1437
1496
  method: "POST",
1438
1497
  path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}/validate`,
1439
- body: {}
1498
+ body: options.variantId === void 0 ? {} : { variantId: options.variantId }
1440
1499
  });
1441
1500
  }
1442
1501
  activateBehaviorStrategy(strategyId) {
1443
1502
  required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1444
1503
  return this.request({ method: "POST", path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}/activate`, body: {} });
1445
1504
  }
1446
- simulateBehaviorStrategy(strategyId, initialState = {}) {
1505
+ simulateBehaviorStrategy(strategyId, initialState = {}, options = {}) {
1447
1506
  required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1507
+ if (options.variantId !== void 0 && (typeof options.variantId !== "string" || !options.variantId.trim() || options.variantId.trim() !== options.variantId || options.variantId.length > 512))
1508
+ throw new Error("SDK_STRATEGY_VARIANT_ID_INVALID");
1448
1509
  return this.request({
1449
1510
  method: "POST",
1450
1511
  path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}/simulate`,
1451
- body: { initialState }
1512
+ body: { initialState, ...options.variantId === void 0 ? {} : { variantId: options.variantId } }
1452
1513
  });
1453
1514
  }
1454
1515
  startStrategyExecution(input2) {
@@ -1540,22 +1601,25 @@ var ViraClient = class {
1540
1601
  continueStrategyExecution(executionId, continuation) {
1541
1602
  required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1542
1603
  const input2 = typeof continuation === "string" ? { authorityDigest: continuation } : continuation ?? {};
1604
+ if (input2.expectedSequence !== void 0 && (!Number.isSafeInteger(input2.expectedSequence) || input2.expectedSequence < 0)) throw Error("SDK_STRATEGY_SEQUENCE_INVALID");
1543
1605
  return this.request({
1544
1606
  method: "POST",
1545
1607
  path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}/continue`,
1546
1608
  body: {
1547
1609
  ...input2.authorityDigest ? { authorityDigest: input2.authorityDigest } : {},
1610
+ ...input2.expectedSequence !== void 0 ? { expectedSequence: input2.expectedSequence } : {},
1548
1611
  ...input2.state ? { state: input2.state } : {},
1549
1612
  ...input2.references ? { references: input2.references } : {}
1550
1613
  }
1551
1614
  });
1552
1615
  }
1553
- cancelStrategyExecution(executionId) {
1616
+ cancelStrategyExecution(executionId, options = {}) {
1554
1617
  required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1618
+ if (options.expectedSequence !== void 0 && (!Number.isSafeInteger(options.expectedSequence) || options.expectedSequence < 0)) throw Error("SDK_STRATEGY_SEQUENCE_INVALID");
1555
1619
  return this.request({
1556
1620
  method: "POST",
1557
1621
  path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}/cancel`,
1558
- body: {}
1622
+ body: { ...options.authorityDigest !== void 0 ? { authorityDigest: options.authorityDigest } : {}, ...options.expectedSequence !== void 0 ? { expectedSequence: options.expectedSequence } : {} }
1559
1623
  });
1560
1624
  }
1561
1625
  listCompoundTaskPlans(options = {}) {
@@ -1594,13 +1658,24 @@ var ViraClient = class {
1594
1658
  const requestId = input2.requestId ?? `sdk-task-run-${id()}`;
1595
1659
  return this.startTaskRun({ taskRunId: input2.taskRunId ?? `task-run-${id()}`, requestId, aiSystemId: input2.aiSystemId, input: input2.input, ...input2.conversationId ? { conversationId: input2.conversationId } : {}, ...input2.episodeId ? { episodeId: input2.episodeId } : {}, ...input2.traceRootRef ? { traceRootRef: input2.traceRootRef } : {}, ...input2.budget ? { budget: input2.budget } : {}, ...input2.connectionId ? { connectionId: input2.connectionId } : {}, ...input2.hostCapabilities ? { hostCapabilities: [...input2.hostCapabilities] } : {} }, options);
1596
1660
  }
1661
+ /** Read authorized history; partial without a cursor is not complete. */
1662
+ listTaskRuns(options = {}) {
1663
+ const limit = options.limit === void 0 ? 50 : options.limit;
1664
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("SDK_TASKRUN_HISTORY_LIMIT_INVALID");
1665
+ const cursor = options.cursor;
1666
+ if (cursor !== void 0 && (typeof cursor !== "string" || !cursor.length || cursor.length > 256 || cursor !== cursor.trim())) throw new Error("SDK_TASKRUN_HISTORY_CURSOR_INVALID");
1667
+ const { aiSystemId, conversationId } = options;
1668
+ const scoped = aiSystemId !== void 0 || conversationId !== void 0;
1669
+ if (scoped && [aiSystemId, conversationId].some((value) => typeof value !== "string" || !value.length || value.length > 256 || value !== value.trim())) throw Error("SDK_TASKRUN_HISTORY_SESSION_SELECTION_INVALID");
1670
+ return this.request({ method: "GET", path: "/v1/task-runs", query: { limit: String(limit), ...cursor !== void 0 ? { cursor } : {}, ...scoped ? { aiSystemId, conversationId } : {} } });
1671
+ }
1597
1672
  getTaskRun(taskRunId) {
1598
1673
  required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1599
1674
  return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}` });
1600
1675
  }
1601
- getTaskRunEvidence(taskRunId) {
1676
+ getTaskRunEvidence(taskRunId, options = {}) {
1602
1677
  required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1603
- return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/evidence` });
1678
+ return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/evidence`, ...options.includeResult === true ? { query: { includeResult: "true" } } : {} });
1604
1679
  }
1605
1680
  listTaskRunEvents(taskRunId) {
1606
1681
  required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
@@ -2132,6 +2207,66 @@ var ViraClient = class {
2132
2207
  if (!aiSystemId.trim() || !unitId.trim()) throw new Error("SDK_AI_SYSTEM_UNIT_GRANT_REQUIRED");
2133
2208
  return this.request({ method: "DELETE", path: `/v1/ai-systems/${encodeURIComponent(aiSystemId)}/unit-grants/${encodeURIComponent(unitId)}`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:ai-system-unit-revoke:${globalThis.crypto.randomUUID()}`, enforcing: true });
2134
2209
  }
2210
+ listVerifiedHostInvocationResults(systemId, input2 = {}) {
2211
+ required(systemId, "SDK_AI_SYSTEM_ID_REQUIRED");
2212
+ return this.request({ method: "POST", path: `/v1/ai-systems/${encodeURIComponent(systemId)}/clone-cutover/route/reconcile/host-candidates`, body: input2 }, { enforcing: true });
2213
+ }
2214
+ freezeDepartmentOptimizationDataset(input2) {
2215
+ return this.request({ method: "POST", path: "/v1/optimization/dataset-freeze", body: input2 }, { enforcing: true });
2216
+ }
2217
+ listDepartmentOptimizationDatasets(input2) {
2218
+ return this.request({ method: "POST", path: "/v1/optimization/dataset-options", body: input2 }, { enforcing: true });
2219
+ }
2220
+ prepareFrozenOptimizationRun(input2, options = {}) {
2221
+ return this.request({ method: "POST", path: "/v1/optimization/prepare-frozen", body: input2 }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2222
+ }
2223
+ executeFrozenOptimizationRun(input2, options = {}) {
2224
+ return this.request({ method: "POST", path: "/v1/optimization/execute-frozen", body: input2 }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2225
+ }
2226
+ proposeNativePolicyScenarios(input2) {
2227
+ return this.request({ method: "POST", path: "/v1/evaluations/policy-scenarios", body: input2 }, { enforcing: true });
2228
+ }
2229
+ previewNativePolicyScenarios(input2) {
2230
+ return this.request({ method: "POST", path: "/v1/evaluations/policy-preview", body: input2 }, { enforcing: true });
2231
+ }
2232
+ admitNativeEvaluationTeachFeedback(evaluationId, input2, options = {}) {
2233
+ required(evaluationId, "SDK_EVALUATION_ID_REQUIRED");
2234
+ return this.request({ method: "POST", path: `/v1/evaluations/${encodeURIComponent(evaluationId)}/teach-feedback`, body: input2 }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2235
+ }
2236
+ previewNativeTeachDraftRevision(proposalId, input2) {
2237
+ required(proposalId, "SDK_PROPOSAL_ID_REQUIRED");
2238
+ return this.request({ method: "POST", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}/native-draft-preview`, body: input2 }, { enforcing: true });
2239
+ }
2240
+ applyNativeTeachDraftRevision(proposalId, input2, options = {}) {
2241
+ required(proposalId, "SDK_PROPOSAL_ID_REQUIRED");
2242
+ return this.request({ method: "POST", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}/native-draft-apply`, body: input2 }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2243
+ }
2244
+ compareNativeTeachRevision(input2) {
2245
+ return this.request({ method: "POST", path: "/v1/evaluations/native-revision-comparison", body: input2 }, { enforcing: true });
2246
+ }
2247
+ getNativeTeachRevisionHistory(proposalId) {
2248
+ required(proposalId, "SDK_PROPOSAL_ID_REQUIRED");
2249
+ return this.request({ method: "GET", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}/native-draft-history` });
2250
+ }
2251
+ getNativeRevisionComparisonSource(candidatePackId) {
2252
+ required(candidatePackId, "SDK_CANDIDATE_PACK_ID_REQUIRED");
2253
+ return this.request({ method: "GET", path: `/v1/evaluations/native-revision-source/${encodeURIComponent(candidatePackId)}` });
2254
+ }
2255
+ listStrategyConnectionOptions(input2) {
2256
+ required(input2.aiSystemId, "SDK_AI_SYSTEM_ID_REQUIRED");
2257
+ return this.request({ method: "GET", path: "/v1/task-runs/strategy-connections/options", query: { aiSystemId: input2.aiSystemId } });
2258
+ }
2259
+ listOptimizationReviewOptions(input2) {
2260
+ return this.request({ method: "POST", path: "/v1/optimization/review-options", body: input2 }, { enforcing: true });
2261
+ }
2262
+ listOptimizerEvaluationHistory(runId) {
2263
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
2264
+ return this.request({ method: "GET", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/evaluation-history` });
2265
+ }
2266
+ previewOptimizerStrategyPromotion(runId, input2, options = {}) {
2267
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
2268
+ return this.request({ method: "POST", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/promote-preview`, body: input2 }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2269
+ }
2135
2270
  };
2136
2271
  function buildRuntimeRequest(input2, options = {}) {
2137
2272
  const {
@@ -2237,7 +2372,64 @@ function buildObservationRequest(event) {
2237
2372
  }
2238
2373
 
2239
2374
  // ../../sdks/host-lifecycle.ts
2375
+ import { createHash as createHash2 } from "node:crypto";
2376
+
2377
+ // ../../sdks/host-taskrun-handoff.ts
2240
2378
  import { createHash } from "node:crypto";
2379
+ var record = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
2380
+ var nonempty = (v) => typeof v === "string" && v.length > 0 && v === v.trim();
2381
+ var hex = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v) && v !== "0".repeat(64);
2382
+ var statuses = ["PLANNED", "ADMITTED", "RUNNING", "WAITING_USER", "WAITING_HOST", "WAITING_APPROVAL", "PARTIAL", "COMPLETED", "FAILED", "BLOCKED", "CANCELLED"];
2383
+ function stableHostTaskRunRequest(identity, messageId, input2) {
2384
+ if (![identity.organizationId, identity.projectId, identity.environmentId, identity.aiSystemId, identity.conversationId, messageId, input2].every(nonempty)) throw Error("HOST_TASKRUN_MESSAGE_IDENTITY_REQUIRED");
2385
+ return "host-turn:" + createHash("sha256").update(JSON.stringify([identity.organizationId, identity.projectId, identity.environmentId, identity.organizationUnitId ?? null, identity.aiSystemId, identity.conversationId, identity.sessionId ?? identity.conversationId, messageId, input2])).digest("hex");
2386
+ }
2387
+ function readHostTaskRunState(response, expected, admission = false) {
2388
+ const envelope = record(response), body = record(envelope.body), run = record(body.taskRun);
2389
+ if (envelope.status !== (admission ? 201 : 200) || admission && body.proposalOnly !== false || run.taskRunId !== expected.taskRunId || run.aiSystemId !== expected.aiSystemId || run.conversationId !== expected.conversationId || ["organizationId", "projectId", "environmentId", "organizationUnitId"].some((key) => run[key] !== expected[key]) || !nonempty(run.requestId) || expected.requestId !== void 0 && run.requestId !== expected.requestId || !Number.isSafeInteger(run.stateVersion) || Number(run.stateVersion) < (expected.minimumVersion ?? 0) || !hex(run.planDigest) || !hex(run.authorityDigest) || expected.planDigest !== void 0 && run.planDigest !== expected.planDigest || expected.authorityDigest !== void 0 && run.authorityDigest !== expected.authorityDigest || !["COMPOUND", "HYBRID"].includes(String(run.mode)) || expected.mode !== void 0 && run.mode !== expected.mode || !statuses.includes(run.status)) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2390
+ if (expected.status !== void 0 && run.stateVersion === expected.minimumVersion && run.status !== expected.status) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2391
+ const tasks = run.selectedTaskKeys;
2392
+ if (!Array.isArray(tasks) || tasks.length < 2 || tasks.some((t) => !nonempty(t)) || new Set(tasks).size !== tasks.length || expected.selectedTaskKeys !== void 0 && (tasks.length !== expected.selectedTaskKeys.length || expected.selectedTaskKeys.some((t) => !tasks.includes(t)))) throw Error("HOST_TASKRUN_HANDOFF_TASK_SET_MISMATCH");
2393
+ if (admission && run.status !== "ADMITTED") throw Error("HOST_TASKRUN_NOT_ADMITTED");
2394
+ const checkpoint = record(run.checkpoint), checkpointExecutionDigest = checkpoint.executionDigest;
2395
+ if (checkpointExecutionDigest !== void 0 && !hex(checkpointExecutionDigest)) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2396
+ if (!admission && run.stateVersion === expected.minimumVersion && Object.hasOwn(expected, "checkpointExecutionDigest") && checkpointExecutionDigest !== expected.checkpointExecutionDigest) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2397
+ return { taskRunId: expected.taskRunId, requestId: run.requestId, stateVersion: Number(run.stateVersion), mode: run.mode, status: run.status, planDigest: run.planDigest, authorityDigest: run.authorityDigest, selectedTaskKeys: tasks, checkpointExecutionDigest };
2398
+ }
2399
+ function hostTaskRunTerminal(status) {
2400
+ return ["COMPLETED", "FAILED", "BLOCKED", "CANCELLED", "PARTIAL"].includes(status);
2401
+ }
2402
+ function readHostTaskRunTerminalEvidence(response, run) {
2403
+ const envelope = record(response), evidence = record(record(envelope.body).evidence);
2404
+ if (!hostTaskRunTerminal(run.status) || envelope.status !== 200 || evidence.source !== "postgres-taskrun-strategy-release-credit-evidence" || evidence.taskRunId !== run.taskRunId || evidence.organizationUnitId !== run.organizationUnitId || evidence.aiSystemId !== run.aiSystemId || evidence.mode !== run.mode || evidence.status !== run.status || evidence.stateVersion !== run.stateVersion || evidence.planDigest !== run.planDigest || evidence.authorityDigest !== run.authorityDigest || evidence.checkpointExecutionDigest !== (run.checkpointExecutionDigest ?? null) || run.status === "COMPLETED" && !hex(run.checkpointExecutionDigest)) throw Error("HOST_TASKRUN_TERMINAL_EVIDENCE_INVALID");
2405
+ return Object.freeze({ taskRunId: run.taskRunId, stateVersion: run.stateVersion, mode: run.mode, status: run.status, planDigest: run.planDigest, authorityDigest: run.authorityDigest, checkpointExecutionDigest: run.checkpointExecutionDigest ?? null, outputAvailable: false, clientExecutionAllowed: false });
2406
+ }
2407
+ function readHostTaskRunResult(response, run) {
2408
+ const terminal = readHostTaskRunTerminalEvidence(response, run), result = record(record(record(response).body).result);
2409
+ const fail = () => {
2410
+ throw Error("HOST_TASKRUN_RESULT_INVALID");
2411
+ };
2412
+ if (terminal.status !== "COMPLETED" || result.status !== "COMPLETED" || result.clientExecutionAllowed !== false || ["taskRunId", "requestId", "organizationId", "projectId", "environmentId", "organizationUnitId", "aiSystemId", "conversationId", "mode", "stateVersion", "planDigest", "authorityDigest", "checkpointExecutionDigest"].some((key) => result[key] !== run[key]) || !hex(result.resultDigest) || !Array.isArray(result.outputs) || !result.outputs.length) fail();
2413
+ const hash3 = (value) => createHash("sha256").update(JSON.stringify(value, (_, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)).digest("hex");
2414
+ const { resultDigest, ...body } = result;
2415
+ if (hash3(body) !== resultDigest) fail();
2416
+ const evidence = record(record(record(response).body).evidence);
2417
+ if (!Array.isArray(evidence.children) || evidence.children.length !== result.outputs.length) throw Error("HOST_TASKRUN_RESULT_INVALID");
2418
+ const nodes = /* @__PURE__ */ new Set(), ids = /* @__PURE__ */ new Set();
2419
+ const outputs = result.outputs.map((value) => {
2420
+ const child = record(value);
2421
+ if (!nonempty(child.nodeKey) || !nonempty(child.semanticTaskKey) || !nonempty(child.receiptId) || nodes.has(child.nodeKey) || ids.has(child.receiptId) || !hex(child.outputDigest) || !Object.hasOwn(child, "output") || child.output === void 0 || child.output === null || hash3(child.output) !== child.outputDigest) throw Error("HOST_TASKRUN_RESULT_INVALID");
2422
+ const matching = evidence.children.map(record).filter((item) => item.nodeKey === child.nodeKey);
2423
+ if (matching.length !== 1 || matching[0].semanticTaskKey !== child.semanticTaskKey || matching[0].receiptId !== child.receiptId || matching[0].status !== "COMPLETED" || matching[0].scopeEvidenceStatus !== "VERIFIED" || matching[0].outputDigest !== child.outputDigest) throw Error("HOST_TASKRUN_RESULT_INVALID");
2424
+ nodes.add(child.nodeKey);
2425
+ ids.add(child.receiptId);
2426
+ return { nodeKey: child.nodeKey, semanticTaskKey: child.semanticTaskKey, receiptId: child.receiptId, outputDigest: child.outputDigest, output: structuredClone(child.output) };
2427
+ });
2428
+ if (run.mode === "COMPOUND" ? outputs.length !== 1 || outputs[0].nodeKey !== "compound-plan" : outputs.length !== run.selectedTaskKeys.length || new Set(outputs.map((child) => child.semanticTaskKey)).size !== outputs.length || outputs.some((child) => !run.selectedTaskKeys.includes(child.semanticTaskKey))) fail();
2429
+ return Object.freeze({ ...terminal, outputAvailable: true, resultDigest, outputs });
2430
+ }
2431
+
2432
+ // ../../sdks/host-lifecycle.ts
2241
2433
  var nonEmpty = (value, code) => {
2242
2434
  if (typeof value !== "string" || !value.trim()) throw new Error(code);
2243
2435
  return value.trim();
@@ -2306,7 +2498,7 @@ var bodyOf = (response) => {
2306
2498
  };
2307
2499
  var isAllow = (decision) => decision.decision === "ALLOW" && /^[a-f0-9]{64}$/.test(decision.authorityReceiptDigest ?? "") && /^[a-f0-9]{64}$/.test(decision.decisionDigest ?? "");
2308
2500
  var canonical = (value) => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` : value && typeof value === "object" ? `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => `${JSON.stringify(key)}:${canonical(child)}`).join(",")}}` : JSON.stringify(value);
2309
- var digest = (value) => createHash("sha256").update(canonical(value), "utf8").digest("hex");
2501
+ var digest = (value) => createHash2("sha256").update(canonical(value), "utf8").digest("hex");
2310
2502
  function createViraHostRuntime(client, config2) {
2311
2503
  if (!client) throw new Error("SDK_HOST_CLIENT_REQUIRED");
2312
2504
  const mode = config2.mode ?? "off";
@@ -2366,8 +2558,18 @@ function createViraHostRuntime(client, config2) {
2366
2558
  const profile = request.profile || {};
2367
2559
  const existingHierarchy = profile.scopeHierarchy && typeof profile.scopeHierarchy === "object" && !Array.isArray(profile.scopeHierarchy) ? profile.scopeHierarchy : {};
2368
2560
  const scopedProfile = request.workspaceId || request.userId ? { ...profile, scopeHierarchy: { ...existingHierarchy, ...request.workspaceId ? { workspaceId: request.workspaceId } : {}, ...request.userId ? { userId: request.userId } : {}, sessionId: request.sessionId ?? request.conversationId } } : request.profile;
2369
- const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, aiSystemId: request.aiSystemId, profile: scopedProfile, revisionId: request.revisionId, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
2561
+ const target = profile.model && typeof profile.model === "object" && !Array.isArray(profile.model) ? profile.model : {};
2562
+ const provider = typeof target.provider === "string" && target.provider.trim() ? target.provider.trim() : void 0;
2563
+ const model = typeof target.name === "string" && target.name.trim() ? target.name.trim() : void 0;
2564
+ const protocol = target.protocol === "openai-chat" || target.protocol === "anthropic-messages" || target.protocol === "generic-chat" ? target.protocol : void 0;
2565
+ const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, aiSystemId: request.aiSystemId, ...provider ? { provider } : {}, ...model ? { model } : {}, ...protocol ? { protocol } : {}, profile: scopedProfile, revisionId: request.revisionId, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
2370
2566
  if (!semantic) return { status: "unavailable", reasonCode: "VIRA_SEMANTIC_UNAVAILABLE" };
2567
+ if (semantic.multiTask === true && config2.multiTaskHandoff === "server-owned") {
2568
+ projections.delete(sessionKey(request));
2569
+ if (mode === "observe") return { status: "abstain", selectedTaskKeys: semantic.taskKeys, reasonCode: "HOST_TASKRUN_OBSERVE_ONLY" };
2570
+ if (!Array.isArray(semantic.taskKeys) || semantic.taskKeys.length < 2 || typeof client.startTaskRunFromPrompt !== "function") return { status: "unavailable", reasonCode: "HOST_TASKRUN_HANDOFF_UNAVAILABLE" };
2571
+ if (!request.hostMessageId?.trim()) return { status: "unavailable", reasonCode: "HOST_TASKRUN_MESSAGE_IDENTITY_REQUIRED" };
2572
+ }
2371
2573
  if (semantic.multiTask === true && semantic.taskKeys?.length > 1 && typeof client.startTaskRunFromPrompt === "function") {
2372
2574
  try {
2373
2575
  const hostCapabilities = [
@@ -2377,7 +2579,12 @@ function createViraHostRuntime(client, config2) {
2377
2579
  ...capabilities.canPreventSideEffect ? ["external_action"] : [],
2378
2580
  ...capabilities.canInspectToolAfter ? ["tool_result"] : []
2379
2581
  ];
2380
- const admitted = await withTimeout(client.startTaskRunFromPrompt({ aiSystemId: request.aiSystemId, input: request.input, taskRunId: `host-task-run-${request.requestId}`, requestId: request.requestId, conversationId: request.conversationId, traceRootRef: request.traceId, ...request.connectionId ? { connectionId: request.connectionId } : {}, hostCapabilities }), timeoutMs, "SDK_HOST_TASKRUN_ADMISSION_TIMEOUT");
2582
+ const admissionRequestId = config2.multiTaskHandoff === "server-owned" ? stableHostTaskRunRequest(request, request.hostMessageId, request.input) : request.requestId;
2583
+ const admitted = await withTimeout(client.startTaskRunFromPrompt({ aiSystemId: request.aiSystemId, input: request.input, taskRunId: `host-task-run-${admissionRequestId}`, requestId: admissionRequestId, conversationId: request.conversationId, traceRootRef: request.traceId, ...request.connectionId ? { connectionId: request.connectionId } : {}, hostCapabilities }), timeoutMs, "SDK_HOST_TASKRUN_ADMISSION_TIMEOUT");
2584
+ if (config2.multiTaskHandoff === "server-owned") {
2585
+ const verified = readHostTaskRunState(admitted, { ...request, taskRunId: `host-task-run-${admissionRequestId}`, requestId: admissionRequestId, selectedTaskKeys: semantic.taskKeys }, true);
2586
+ return { status: "task_run", response: admitted, taskRunId: verified.taskRunId, taskRunStateVersion: verified.stateVersion, selectedTaskKeys: verified.selectedTaskKeys };
2587
+ }
2381
2588
  const admittedBody = bodyOf(admitted);
2382
2589
  const taskRun = admittedBody.taskRun && typeof admittedBody.taskRun === "object" ? admittedBody.taskRun : {};
2383
2590
  const taskRunId = typeof taskRun.taskRunId === "string" ? taskRun.taskRunId : `host-task-run-${request.requestId}`;
@@ -2513,7 +2720,7 @@ function createViraHostRuntime(client, config2) {
2513
2720
  }
2514
2721
 
2515
2722
  // ../runtime/src/accelerator-v4/composite-hook-session.ts
2516
- import { createHash as createHash2, createHmac } from "node:crypto";
2723
+ import { createHash as createHash3, createHmac } from "node:crypto";
2517
2724
 
2518
2725
 
2519
2726
  var external_exports = {};
@@ -2658,7 +2865,7 @@ __export(external_exports, {
2658
2865
  gte: () => _gte,
2659
2866
  guid: () => guid2,
2660
2867
  hash: () => hash,
2661
- hex: () => hex2,
2868
+ hex: () => hex3,
2662
2869
  hostname: () => hostname2,
2663
2870
  httpUrl: () => httpUrl,
2664
2871
  iban: () => iban2,
@@ -2725,7 +2932,7 @@ __export(external_exports, {
2725
2932
  properties: () => _properties,
2726
2933
  property: () => _property,
2727
2934
  readonly: () => readonly,
2728
- record: () => record,
2935
+ record: () => record2,
2729
2936
  refine: () => refine,
2730
2937
  regex: () => _regex,
2731
2938
  regexes: () => regexes_exports,
@@ -3819,8 +4026,8 @@ function base64urlToUint8Array(base64url3) {
3819
4026
  function uint8ArrayToBase64url(bytes) {
3820
4027
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
3821
4028
  }
3822
- function hexToUint8Array(hex3) {
3823
- const cleanHex = hex3.replace(/^0x/, "");
4029
+ function hexToUint8Array(hex4) {
4030
+ const cleanHex = hex4.replace(/^0x/, "");
3824
4031
  if (cleanHex.length % 2 !== 0) {
3825
4032
  throw new Error("Invalid hex string length");
3826
4033
  }
@@ -4449,7 +4656,7 @@ __export(regexes_exports, {
4449
4656
  emoji: () => emoji,
4450
4657
  extendedDuration: () => extendedDuration,
4451
4658
  guid: () => guid,
4452
- hex: () => hex,
4659
+ hex: () => hex2,
4453
4660
  hostname: () => hostname,
4454
4661
  html5Email: () => html5Email,
4455
4662
  httpProtocol: () => httpProtocol,
@@ -4574,7 +4781,7 @@ var _null = /^null$/i;
4574
4781
  var _undefined = /^undefined$/i;
4575
4782
  var lowercase = /^[^A-Z]*$/;
4576
4783
  var uppercase = /^[^a-z]*$/;
4577
- var hex = /^[0-9a-fA-F]*$/;
4784
+ var hex2 = /^[0-9a-fA-F]*$/;
4578
4785
  function fixedBase64(bodyLength, padding) {
4579
4786
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
4580
4787
  }
@@ -19168,8 +19375,8 @@ function rewriteKeyNames(ctx) {
19168
19375
  bySchema.set(entry.schema, entry);
19169
19376
  }
19170
19377
  const rewrites = /* @__PURE__ */ new Map();
19171
- for (const record3 of pendingRecords.get(ctx) ?? []) {
19172
- const seen = ctx.seen.get(record3);
19378
+ for (const record5 of pendingRecords.get(ctx) ?? []) {
19379
+ const seen = ctx.seen.get(record5);
19173
19380
  const names = (seen?.def ?? seen?.schema)?.propertyNames;
19174
19381
  if (!names || names === true || rewrites.has(names))
19175
19382
  continue;
@@ -19597,7 +19804,7 @@ __export(schemas_exports2, {
19597
19804
  function: () => _function,
19598
19805
  guid: () => guid2,
19599
19806
  hash: () => hash,
19600
- hex: () => hex2,
19807
+ hex: () => hex3,
19601
19808
  hostname: () => hostname2,
19602
19809
  httpUrl: () => httpUrl,
19603
19810
  iban: () => iban2,
@@ -19637,7 +19844,7 @@ __export(schemas_exports2, {
19637
19844
  preprocess: () => preprocess,
19638
19845
  promise: () => promise,
19639
19846
  readonly: () => readonly,
19640
- record: () => record,
19847
+ record: () => record2,
19641
19848
  refine: () => refine,
19642
19849
  set: () => set,
19643
19850
  strictObject: () => strictObject,
@@ -20290,8 +20497,8 @@ function stringFormat(format, fnOrRegex, _params = {}) {
20290
20497
  function hostname2(_params) {
20291
20498
  return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params);
20292
20499
  }
20293
- function hex2(_params) {
20294
- return _stringFormat(ZodCustomStringFormat, "hex", hex, _params);
20500
+ function hex3(_params) {
20501
+ return _stringFormat(ZodCustomStringFormat, "hex", hex2, _params);
20295
20502
  }
20296
20503
  function currencyCode2(_params) {
20297
20504
  return _stringFormat(ZodCustomStringFormat, "currency_code", currencyCode, _params);
@@ -20739,7 +20946,7 @@ var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
20739
20946
  inst.keyType = def.keyType;
20740
20947
  inst.valueType = def.valueType;
20741
20948
  });
20742
- function record(keyType, valueType, params) {
20949
+ function record2(keyType, valueType, params) {
20743
20950
  if (!valueType || !valueType._zod) {
20744
20951
  return new ZodRecord({
20745
20952
  type: "record",
@@ -21214,7 +21421,7 @@ var stringbool = (...args) => _stringbool({
21214
21421
  }, ...args);
21215
21422
  function json(params) {
21216
21423
  const jsonSchema = lazy(() => {
21217
- return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]);
21424
+ return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record2(string2(), jsonSchema)]);
21218
21425
  });
21219
21426
  return jsonSchema;
21220
21427
  }
@@ -22233,10 +22440,10 @@ function date4(params) {
22233
22440
  }
22234
22441
 
22235
22442
  // ../runtime/src/accelerator-v4/composite-hook-session.ts
22236
- var hash2 = (value) => createHash2("sha256").update(canonical2(value)).digest("hex");
22443
+ var hash2 = (value) => createHash3("sha256").update(canonical2(value)).digest("hex");
22237
22444
  var canonical2 = (value) => Array.isArray(value) ? `[${value.map(canonical2).join(",")}]` : value && typeof value === "object" ? `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical2(v)}`).join(",")}}` : JSON.stringify(value);
22238
22445
  var canonicalToolArguments = (value) => Array.isArray(value) ? `[${value.map(canonicalToolArguments).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0).map((key) => `${JSON.stringify(key)}:${canonicalToolArguments(value[key])}`).join(",")}}` : JSON.stringify(value);
22239
- var nativeAcceleratorOutputDigest = (value) => createHash2("sha256").update(canonicalToolArguments(value)).digest("hex");
22446
+ var nativeAcceleratorOutputDigest = (value) => createHash3("sha256").update(canonicalToolArguments(value)).digest("hex");
22240
22447
  var digest2 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
22241
22448
  var freezeDeep = (value) => {
22242
22449
  if (value && typeof value === "object" && !Object.isFrozen(value)) {
@@ -22360,20 +22567,20 @@ function validateToolProposalV1(value, context) {
22360
22567
 
22361
22568
  // src/approval.ts
22362
22569
  var text = (value) => typeof value === "string" ? value.trim() : "";
22363
- var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
22570
+ var record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
22364
22571
  var errorCode = (error62) => {
22365
- const body = record2(error62 instanceof ViraApiError ? error62.body : {});
22366
- return text(body.code) || text(record2(body.error).code) || text(body.reason_code) || (error62 instanceof Error ? error62.message : "");
22572
+ const body = record3(error62 instanceof ViraApiError ? error62.body : {});
22573
+ return text(body.code) || text(record3(body.error).code) || text(body.reason_code) || (error62 instanceof Error ? error62.message : "");
22367
22574
  };
22368
22575
  var authorizationResult = (response, input2) => {
22369
- const body = record2(record2(response).body);
22576
+ const body = record3(record3(response).body);
22370
22577
  const receipt = text(body.authority_receipt_digest);
22371
22578
  const decision = text(body.decision_digest);
22372
22579
  if (body.allowed === true) {
22373
22580
  if (!/^[a-f0-9]{64}$/.test(receipt) || !/^[a-f0-9]{64}$/.test(decision))
22374
22581
  return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_AUTHORITY_RECEIPT_INVALID" };
22375
22582
  const { scope, ...material } = body;
22376
- const returnedScope = record2(scope);
22583
+ const returnedScope = record3(scope);
22377
22584
  if (Object.keys(input2.scope).some((k) => returnedScope[k] !== input2.scope[k]) || Object.keys(returnedScope).length !== Object.keys(input2.scope).length) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_SCOPE_RECEIPT_MISMATCH" };
22378
22585
  try {
22379
22586
  validateActionDecisionV1(material, input2.proposalBody, input2.context);
@@ -22385,16 +22592,27 @@ var authorizationResult = (response, input2) => {
22385
22592
  return { decision: "BLOCK", reasonCode: text(body.reason_code) || "POLICY_DENIED", authorityReceiptDigest: receipt };
22386
22593
  };
22387
22594
  async function authorizeWithOneShotCustomerConfirmation(input2) {
22388
- const authorize = (approvalId) => input2.client.authorizeHostAction({ executionId: input2.executionId, sessionId: input2.sessionId, dataVersion: input2.dataVersion, scope: input2.scope, context: input2.context, proposal: input2.proposalBody, ...input2.aiSystemId ? { aiSystemId: input2.aiSystemId } : {}, ...input2.signalAttestationRefs?.length ? { signalAttestationRefs: input2.signalAttestationRefs } : {}, ...approvalId ? { approval: { approvalId } } : {} });
22595
+ const authorize = (approvalId) => input2.client.authorizeHostAction({ executionId: input2.executionId, sessionId: input2.sessionId, dataVersion: input2.dataVersion, scope: input2.scope, context: input2.context, proposal: input2.proposalBody, ...input2.aiSystemId ? { aiSystemId: input2.aiSystemId } : {}, ...input2.connectionId ? { connectionId: input2.connectionId } : {}, ...input2.signalAttestationRefs?.length ? { signalAttestationRefs: input2.signalAttestationRefs } : {}, ...approvalId ? { approval: { approvalId } } : {} });
22389
22596
  try {
22390
22597
  const response = await authorize(input2.approvalId);
22391
22598
  return authorizationResult(response, input2);
22392
22599
  } catch (error62) {
22393
22600
  if (errorCode(error62) !== "RUNTIME_ACTION_USER_APPROVAL_REQUIRED" || input2.approvalId) return { decision: "BLOCK", reasonCode: errorCode(error62) || "RUNTIME_ACTION_AUTHORIZATION_FAILED" };
22394
22601
  if (typeof input2.confirmAction !== "function") return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_APPROVAL_UNAVAILABLE" };
22395
- if (await input2.confirmAction({ ...input2.proposal, approvalRequired: true }) !== true) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CUSTOMER_CONFIRMATION_DENIED" };
22396
- const issued = await input2.client.createHostActionApproval({ sessionId: input2.sessionId, dataVersion: input2.dataVersion, proposal: input2.proposalBody, confirmation: { proposalId: text(input2.proposalBody.proposal_id), toolName: text(input2.proposalBody.tool_key), argumentsDigest: text(input2.proposalBody.arguments_digest), requestContextDigest: text(input2.proposalBody.request_context_digest), acknowledgedAt: (/* @__PURE__ */ new Date()).toISOString() } });
22397
- const approvalId = text(record2(issued?.body).approvalId);
22602
+ let confirmed = false;
22603
+ try {
22604
+ confirmed = await input2.confirmAction({ ...input2.proposal, approvalRequired: true }) === true;
22605
+ } catch {
22606
+ return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CUSTOMER_CONFIRMATION_FAILED" };
22607
+ }
22608
+ if (!confirmed) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_CUSTOMER_CONFIRMATION_DENIED" };
22609
+ let issued;
22610
+ try {
22611
+ issued = await input2.client.createHostActionApproval({ sessionId: input2.sessionId, dataVersion: input2.dataVersion, proposal: input2.proposalBody, confirmation: { proposalId: text(input2.proposalBody.proposal_id), toolName: text(input2.proposalBody.tool_key), argumentsDigest: text(input2.proposalBody.arguments_digest), requestContextDigest: text(input2.proposalBody.request_context_digest), acknowledgedAt: (/* @__PURE__ */ new Date()).toISOString() } });
22612
+ } catch (issueError) {
22613
+ return { decision: "BLOCK", reasonCode: errorCode(issueError) || "RUNTIME_ACTION_APPROVAL_ISSUE_FAILED" };
22614
+ }
22615
+ const approvalId = text(record3(issued?.body).approvalId);
22398
22616
  if (!approvalId) return { decision: "ERROR", reasonCode: "RUNTIME_ACTION_APPROVAL_RECEIPT_MISSING" };
22399
22617
  try {
22400
22618
  const response = await authorize(approvalId);
@@ -22428,6 +22646,116 @@ function createHostCallExecutionFence(maxEntries = 1e5) {
22428
22646
  });
22429
22647
  }
22430
22648
 
22649
+ // src/taskrun-handoff.ts
22650
+ var openCodeHostRequestId = (identity, messageId, input2, fallback) => messageId ? stableHostTaskRunRequest(identity, messageId, input2) : fallback;
22651
+ var OpenCodeTaskRunHandoffError = class extends Error {
22652
+ taskRunId;
22653
+ stateVersion;
22654
+ mode;
22655
+ terminalEvidence;
22656
+ finalResult;
22657
+ constructor(run, terminalEvidence, finalResult) {
22658
+ super("VIRA_TASKRUN_SERVER_HANDOFF:" + run.taskRunId + ":" + run.status);
22659
+ this.name = "OpenCodeTaskRunHandoffError";
22660
+ this.taskRunId = run.taskRunId;
22661
+ this.stateVersion = run.stateVersion;
22662
+ this.mode = run.mode;
22663
+ this.terminalEvidence = terminalEvidence;
22664
+ Object.defineProperty(this, "finalResult", { value: finalResult, enumerable: false, writable: false, configurable: false });
22665
+ }
22666
+ };
22667
+ function captureOpenCodeTaskRunHandoff(identity, result) {
22668
+ if (result.status !== "task_run" || !result.taskRunId?.startsWith("host-task-run-host-turn:") || !Number.isSafeInteger(result.taskRunStateVersion)) throw Error("OPENCODE_TASKRUN_HANDOFF_REQUIRED");
22669
+ const run = readHostTaskRunState(result.response, { ...identity, taskRunId: result.taskRunId, requestId: result.taskRunId.slice("host-task-run-".length), minimumVersion: result.taskRunStateVersion, selectedTaskKeys: result.selectedTaskKeys }, true);
22670
+ return { ...identity, ...run };
22671
+ }
22672
+ async function readOpenCodeTaskRunHandoff(client, run) {
22673
+ const state = readHostTaskRunState(await client.getTaskRun(run.taskRunId), { ...run, minimumVersion: run.stateVersion });
22674
+ return { ...run, ...state };
22675
+ }
22676
+ async function readOpenCodeTaskRunTerminalEvidence(client, run) {
22677
+ if (!hostTaskRunTerminal(run.status)) throw Error("OPENCODE_TASKRUN_NOT_TERMINAL");
22678
+ return readHostTaskRunTerminalEvidence(await client.getTaskRunEvidence(run.taskRunId), run);
22679
+ }
22680
+ async function cancelOpenCodeTaskRunHandoff(client, run) {
22681
+ const current = await readOpenCodeTaskRunHandoff(client, run);
22682
+ if (hostTaskRunTerminal(current.status)) return current;
22683
+ const response = await client.cancelTaskRun(current.taskRunId, current.stateVersion, { idempotencyKey: "opencode:task-run:cancel:" + current.taskRunId + ":" + current.stateVersion });
22684
+ const cancelled = readHostTaskRunState(response, { ...current, status: void 0, minimumVersion: current.stateVersion + 1 });
22685
+ if (cancelled.status !== "CANCELLED") throw Error("OPENCODE_TASKRUN_CANCEL_PROOF_REQUIRED");
22686
+ return { ...current, ...cancelled };
22687
+ }
22688
+ async function readOpenCodeTaskRunResult(client, run) {
22689
+ if (run.status !== "COMPLETED") throw Error("OPENCODE_TASKRUN_NOT_COMPLETED");
22690
+ return readHostTaskRunResult(await client.getTaskRunEvidence(run.taskRunId, { includeResult: true }), run);
22691
+ }
22692
+ async function openCodeTaskRunHandoffError(client, run) {
22693
+ if (run.status === "COMPLETED") {
22694
+ const response = await client.getTaskRunEvidence(run.taskRunId, { includeResult: true });
22695
+ return new OpenCodeTaskRunHandoffError(run, readHostTaskRunTerminalEvidence(response, run), readHostTaskRunResult(response, run));
22696
+ }
22697
+ return new OpenCodeTaskRunHandoffError(run, hostTaskRunTerminal(run.status) ? await readOpenCodeTaskRunTerminalEvidence(client, run) : void 0);
22698
+ }
22699
+
22700
+ // src/taskrun-result-display.ts
22701
+ var record4 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
22702
+ function createLegacyTaskRunResultDisplay(host) {
22703
+ const session = record4(record4(host).client).session;
22704
+ const api = record4(session);
22705
+ if (typeof api.prompt !== "function") return void 0;
22706
+ const prompt = api.prompt;
22707
+ return async (run, result) => {
22708
+ const sessionId = run.sessionId ?? run.conversationId;
22709
+ if (!sessionId || result.taskRunId !== run.taskRunId || result.stateVersion !== run.stateVersion || result.clientExecutionAllowed !== false || result.status !== "COMPLETED") throw Error("OPENCODE_RESULT_DISPLAY_IDENTITY_INVALID");
22710
+ const text3 = "Vira verified TaskRun result\n\n" + result.outputs.map((child) => typeof child.output === "string" ? child.output : JSON.stringify(child.output, null, 2)).join("\n\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "");
22711
+ const response = record4(await prompt.call(session, { path: { id: sessionId }, body: { noReply: true, parts: [{ type: "text", text: text3, ignored: true }] } }));
22712
+ const data = record4(response.data ?? response), info = record4(data.info), parts = data.parts;
22713
+ if (response.error !== void 0 && response.error !== null || info.sessionID !== sessionId || info.role !== "user" || !Array.isArray(parts) || parts.length !== 1 || record4(parts[0]).type !== "text" || record4(parts[0]).ignored !== true || record4(parts[0]).text !== text3) throw Error("OPENCODE_RESULT_DISPLAY_UNVERIFIED");
22714
+ };
22715
+ }
22716
+ function createOpenCodeResultDelivery(input2) {
22717
+ const attempts = /* @__PURE__ */ new Map();
22718
+ const delay = input2.delay ?? ((ms) => new Promise((resolve) => {
22719
+ const timer = setTimeout(resolve, ms);
22720
+ timer.unref?.();
22721
+ }));
22722
+ const limit = input2.maxAttempts ?? 120, interval = input2.intervalMs ?? 2500;
22723
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 120 || !Number.isSafeInteger(interval) || interval < 0 || interval > 6e4) throw Error("OPENCODE_RESULT_DELIVERY_BUDGET_INVALID");
22724
+ const start = (run) => {
22725
+ if (!input2.display || !input2.active(run)) return Promise.resolve();
22726
+ const existing = attempts.get(run.taskRunId);
22727
+ if (existing) return existing.promise;
22728
+ const item = { state: "POLLING", promise: Promise.resolve() };
22729
+ attempts.set(run.taskRunId, item);
22730
+ item.promise = (async () => {
22731
+ let current = run;
22732
+ for (let index = 0; index < limit; index++) {
22733
+ if (!input2.active(run)) return;
22734
+ current = await readOpenCodeTaskRunHandoff(input2.client, current);
22735
+ if (!input2.active(run)) return;
22736
+ if (current.status === "COMPLETED") {
22737
+ const result = await readOpenCodeTaskRunResult(input2.client, current);
22738
+ if (!input2.active(run)) return;
22739
+ const confirmed = await readOpenCodeTaskRunHandoff(input2.client, current);
22740
+ if (!input2.active(run) || confirmed.stateVersion !== current.stateVersion || confirmed.status !== current.status || confirmed.checkpointExecutionDigest !== current.checkpointExecutionDigest) return;
22741
+ item.state = "DELIVERING";
22742
+ await input2.display(current, result);
22743
+ item.state = "DELIVERED";
22744
+ return;
22745
+ }
22746
+ if (hostTaskRunTerminal(current.status)) return;
22747
+ if (index + 1 < limit) await delay(interval);
22748
+ }
22749
+ })().catch(() => {
22750
+ if (item.state === "DELIVERING") item.state = "UNCERTAIN";
22751
+ }).finally(() => {
22752
+ if (item.state === "POLLING") attempts.delete(run.taskRunId);
22753
+ });
22754
+ return item.promise;
22755
+ };
22756
+ return { start, state: (taskRunId) => attempts.get(taskRunId)?.state };
22757
+ }
22758
+
22431
22759
  // src/index.ts
22432
22760
  async function queueOpenCodeTaskRunHostDispatch(client, input2) {
22433
22761
  const response = await client.getTaskRunEvidence(input2.taskRunId);
@@ -22504,14 +22832,14 @@ var safeErrorCode = (error62) => {
22504
22832
  return error62 instanceof Error ? error62.message : "unknown";
22505
22833
  };
22506
22834
  var canonical3 = (value) => Array.isArray(value) ? "[" + value.map(canonical3).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) + ":" + canonical3(child)).join(",") + "}" : JSON.stringify(value);
22507
- var digest3 = (value) => createHash3("sha256").update(canonical3(value), "utf8").digest("hex");
22835
+ var digest3 = (value) => createHash4("sha256").update(canonical3(value), "utf8").digest("hex");
22508
22836
  var messageContentText = (value) => {
22509
22837
  if (typeof value === "string") return value.trim();
22510
22838
  if (!value || typeof value !== "object") return "";
22511
22839
  if (Array.isArray(value)) return value.map(messageContentText).filter(Boolean).join("\n").trim();
22512
- const record3 = asRecord(value);
22513
- if (record3.type === "image" || record3.type === "input_image") return "[image]";
22514
- return messageContentText(record3.text ?? record3.content ?? record3.value);
22840
+ const record5 = asRecord(value);
22841
+ if (record5.type === "image" || record5.type === "input_image") return "[image]";
22842
+ return messageContentText(record5.text ?? record5.content ?? record5.value);
22515
22843
  };
22516
22844
  var lastUserText = (event) => {
22517
22845
  const messages = Array.isArray(event.messages) ? event.messages : [];
@@ -22852,6 +23180,21 @@ var v2Plugin = Plugin.define({
22852
23180
  const executionFence = createHostCallExecutionFence();
22853
23181
  const desktopPermission = createDesktopPermissionBridge();
22854
23182
  const contextKey = (identity) => identity.organizationId + ":" + identity.projectId + ":" + identity.environmentId + ":" + (identity.workspaceId ?? "") + ":" + (identity.userId ?? "") + ":" + identity.conversationId + ":" + (identity.sessionId ?? identity.conversationId);
23183
+ const priorTaskRun = async (identity, requestId) => {
23184
+ const key = contextKey(identity), previous = taskRuns.get(key);
23185
+ if (!previous) return;
23186
+ const current = await readOpenCodeTaskRunHandoff(client, previous);
23187
+ taskRuns.set(key, current);
23188
+ if (current.taskRunId === "host-task-run-" + requestId || !hostTaskRunTerminal(current.status)) throw await openCodeTaskRunHandoffError(client, current);
23189
+ taskRuns.delete(key);
23190
+ };
23191
+ const handoffTaskRun = (identity, result) => {
23192
+ if (mode !== "enforce" || result.status !== "task_run") return;
23193
+ const key = contextKey(identity), run = captureOpenCodeTaskRunHandoff(identity, result);
23194
+ actionContexts.delete(key);
23195
+ taskRuns.set(key, run);
23196
+ throw new OpenCodeTaskRunHandoffError(run);
23197
+ };
22855
23198
  const findActionContext = (proposal) => {
22856
23199
  const exact = actionContexts.get(contextKey(proposal));
22857
23200
  if (exact) return exact;
@@ -22883,7 +23226,7 @@ var v2Plugin = Plugin.define({
22883
23226
  for (const key of actionDecisions.keys()) {
22884
23227
  if (sessionId && key.includes(":" + sessionId + ":") || conversationId && key.includes(":" + conversationId + ":")) actionDecisions.delete(key);
22885
23228
  }
22886
- for (const key of taskRuns.keys()) if (key === conversationId || key === sessionId) taskRuns.delete(key);
23229
+ for (const [key, run] of taskRuns) if (run.conversationId === conversationId || run.sessionId === sessionId) taskRuns.delete(key);
22887
23230
  teachPrompts.clear(conversationId);
22888
23231
  if (sessionId && sessionId !== conversationId) teachPrompts.clear(sessionId);
22889
23232
  executionFence.clearSession(sessionId, conversationId);
@@ -22892,13 +23235,12 @@ var v2Plugin = Plugin.define({
22892
23235
  const cancelTaskRunForSession = async (event) => {
22893
23236
  const sessionId = text2(event.sessionID ?? event.sessionId);
22894
23237
  const conversationId = text2(event.conversationId ?? event.sessionID ?? event.sessionId);
22895
- const keys = [conversationId, sessionId].filter(Boolean);
22896
- for (const key of keys) {
22897
- const run = taskRuns.get(key);
22898
- if (!run) continue;
23238
+ for (const [key, run] of taskRuns) {
23239
+ if (!(sessionId && run.sessionId === sessionId) && !(conversationId && run.conversationId === conversationId)) continue;
22899
23240
  try {
22900
- await client.cancelTaskRun(run.taskRunId, run.stateVersion, { idempotencyKey: `opencode:task-run:cancel:${run.taskRunId}:${run.stateVersion}` });
22901
- } catch {
23241
+ taskRuns.set(key, await cancelOpenCodeTaskRunHandoff(client, run));
23242
+ } catch (error62) {
23243
+ if (mode === "enforce") throw error62;
22902
23244
  }
22903
23245
  }
22904
23246
  };
@@ -22932,7 +23274,8 @@ var v2Plugin = Plugin.define({
22932
23274
  throw error62;
22933
23275
  }
22934
23276
  }
22935
- const runtime2 = createViraHostRuntime(client, { mode, capabilities, authorizeAction: (async (proposal) => {
23277
+ const runtime2 = createViraHostRuntime(client, { mode, capabilities, multiTaskHandoff: "server-owned", authorizeAction: (async (proposal) => {
23278
+ if (taskRuns.has(contextKey(proposal))) return { decision: "BLOCK", reasonCode: "TASKRUN_SERVER_HANDOFF_ACTIVE" };
22936
23279
  const bound = findActionContext(proposal);
22937
23280
  if (bound && bound.executionId.startsWith("runtime:taskrun:")) return { decision: "BLOCK", reasonCode: "SINGLE_HOST_SERVER_DISPATCH_REQUIRED" };
22938
23281
  if (options.authorizeAction) return options.authorizeAction(proposal);
@@ -22957,7 +23300,7 @@ var v2Plugin = Plugin.define({
22957
23300
  if (!dataVersion) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_DATA_VERSION_UNAVAILABLE" };
22958
23301
  const refs = Array.isArray(bound.context.signal_attestation_refs) ? bound.context.signal_attestation_refs : [];
22959
23302
  const confirmAction = async () => typeof options.confirmAction === "function" ? await options.confirmAction(proposal) : await confirmationGate.confirm(proposal, bound.expiresAt);
22960
- return authorizeWithOneShotCustomerConfirmation({ client, proposal, proposalBody, signalAttestationRefs: refs, aiSystemId: proposal.aiSystemId, executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, confirmAction, approvalId: approval?.approvalId });
23303
+ return authorizeWithOneShotCustomerConfirmation({ client, proposal, proposalBody, signalAttestationRefs: refs, aiSystemId: proposal.aiSystemId, connectionId: proposal.connectionId, executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, confirmAction, approvalId: approval?.approvalId });
22961
23304
  }), ...bootstrapAiSystemId && bootstrapConnectionId ? {} : { connect: openCodeConnectConfig(scope, options) } });
22962
23305
  let connectedAiSystemId = bootstrapAiSystemId;
22963
23306
  let connectedConnectionId = bootstrapConnectionId;
@@ -23029,7 +23372,9 @@ var v2Plugin = Plugin.define({
23029
23372
  const identity = sessionIdentity(event);
23030
23373
  const history = await ctx.session.context({ sessionID });
23031
23374
  const profile = conversationProfile({ ...event, messages: history }, options);
23032
- const resolved = await client.resolveSemanticRuntime({ input: input2, aiSystemId: identity.aiSystemId, profile, revisionId: options.revisionId, sessionId: sessionID, requestId: "opencode:route:" + messageID, signalAttestationRefs: options.signalAttestationRefs });
23375
+ const target = asRecord(profile.model);
23376
+ const provider = text2(target.provider).trim(), model = text2(target.name).trim();
23377
+ const resolved = await client.resolveSemanticRuntime({ input: input2, aiSystemId: identity.aiSystemId, ...provider ? { provider } : {}, ...model ? { model } : {}, profile, revisionId: options.revisionId, sessionId: sessionID, requestId: "opencode:route:" + messageID, signalAttestationRefs: options.signalAttestationRefs });
23033
23378
  if (!resolved) throw Error("VIRA_NATIVE_MODEL_AUTHORITY_UNAVAILABLE");
23034
23379
  if (resolved.multiTask === true) return;
23035
23380
  const policy = asRecord(asRecord(resolved.runtime?.body).modelPolicy ?? asRecord(resolved.runtime?.body).model_policy);
@@ -23047,9 +23392,11 @@ var v2Plugin = Plugin.define({
23047
23392
  const input2 = lastUserText(envelope);
23048
23393
  if (!input2) throw Error("VIRA_NATIVE_MODEL_INPUT_REQUIRED");
23049
23394
  const identity = sessionIdentity(envelope), messageId = nativeUserMessageId(envelope), requestId = "opencode:native:" + randomUUID();
23050
- const result = await runtime2.beforeModel({ ...identity, requestId, input: input2, revisionId: options.revisionId, profile: conversationProfile(envelope, options), signalAttestationRefs: options.signalAttestationRefs });
23395
+ await priorTaskRun(identity, openCodeHostRequestId(identity, messageId, input2, requestId));
23396
+ const result = await runtime2.beforeModel({ ...identity, requestId, hostMessageId: messageId, input: input2, revisionId: options.revisionId, profile: conversationProfile(envelope, options), signalAttestationRefs: options.signalAttestationRefs });
23051
23397
  const responseBody = asRecord(result.response?.body);
23052
23398
  if (result.status === "unavailable") throw Error("VIRA_NATIVE_MODEL_AUTHORITY_UNAVAILABLE");
23399
+ handoffTaskRun(identity, result);
23053
23400
  event.model = resolveNativeModelRoute(event.model, responseBody.modelPolicy ?? responseBody.model_policy, mode);
23054
23401
  resolvedModels.set(sessionID, { inputDigest: digest3(input2), messageId, result, expiresAt: Date.now() + 3e4, requestId });
23055
23402
  }));
@@ -23081,10 +23428,12 @@ var v2Plugin = Plugin.define({
23081
23428
  const identity = sessionIdentity(event);
23082
23429
  if (input2) {
23083
23430
  teachPrompts.put(identity.conversationId, input2, text2(event.messageID ?? event.requestId) || void 0, text2(event.turnID) || void 0);
23431
+ const messageId = nativeUserMessageId(event), requestId = text2(event.messageID ?? event.requestId) || "opencode:" + randomUUID();
23432
+ if (mode === "enforce") await priorTaskRun(identity, openCodeHostRequestId(identity, messageId, input2, requestId));
23084
23433
  const nativeKey = identity.sessionId ?? identity.conversationId;
23085
23434
  const native = resolvedModels.get(nativeKey);
23086
23435
  resolvedModels.delete(nativeKey);
23087
- const result = await runOpenCodeModelLifecycle(mode, () => native && native.expiresAt > Date.now() && native.inputDigest === digest3(input2) && (!native.messageId || native.messageId === nativeUserMessageId(event)) ? Promise.resolve(native.result) : runtime2.beforeModel({ ...identity, requestId: text2(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, input: input2, revisionId: options.revisionId, profile: conversationProfile(event, options), traceId: text2(event.traceID), turnId: text2(event.turnID), signalAttestationRefs: options.signalAttestationRefs }));
23436
+ const result = await runOpenCodeModelLifecycle(mode, () => native && native.expiresAt > Date.now() && native.inputDigest === digest3(input2) && (!native.messageId || native.messageId === nativeUserMessageId(event)) ? Promise.resolve(native.result) : runtime2.beforeModel({ ...identity, requestId, hostMessageId: messageId, input: input2, revisionId: options.revisionId, profile: conversationProfile(event, options), traceId: text2(event.traceID), turnId: text2(event.turnID), signalAttestationRefs: options.signalAttestationRefs }));
23088
23437
  if (!result) return;
23089
23438
  const refreshed = runtime2.getConnectionIdentity();
23090
23439
  if (!options.aiSystemId && !options.connectionId && refreshed) {
@@ -23092,12 +23441,13 @@ var v2Plugin = Plugin.define({
23092
23441
  connectedConnectionId = refreshed.connectionId;
23093
23442
  }
23094
23443
  const responseBody = asRecord(result.response?.body);
23095
- const runtimeContext = asRecord(event.viraRuntimeContext ?? responseBody.requestContext ?? responseBody.context);
23096
- const executionId = text2(event.executionId ?? responseBody.executionId);
23444
+ const programOnly = Boolean(responseBody.programSelection) && !responseBody.strategySelection;
23445
+ const runtimeContext = asRecord(programOnly ? void 0 : event.viraRuntimeContext ?? responseBody.requestContext ?? responseBody.context);
23446
+ const executionId = programOnly ? "" : text2(event.executionId ?? responseBody.executionId);
23097
23447
  const expiresAt = Number(runtimeContext.expires_at_unix_ms);
23098
23448
  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 });
23099
- else if (executionId) actionContexts.delete(contextKey(identity));
23100
- if (result.status === "task_run" && result.taskRunId && Number.isInteger(result.taskRunStateVersion)) taskRuns.set(identity.conversationId, { taskRunId: result.taskRunId, stateVersion: result.taskRunStateVersion });
23449
+ else actionContexts.delete(contextKey(identity));
23450
+ handoffTaskRun(identity, result);
23101
23451
  const modelPolicy = asRecord(responseBody.modelPolicy ?? responseBody.model_policy);
23102
23452
  const hostOptions = asRecord(event.options);
23103
23453
  if (mode === "enforce") {
@@ -23130,6 +23480,7 @@ Assistant: ${output2}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempote
23130
23480
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
23131
23481
  const identity = sessionIdentity(event);
23132
23482
  const proposal = { ...identity, requestId: text2(event.messageID ?? event.requestId) || `opencode:${Date.now()}`, callId: required3(event.callID ?? event.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required3(event.tool ?? event.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(event.input ?? event.args), nativeAgent: text2(event.agent) || void 0, traceId: text2(event.traceID), turnId: text2(event.turnID) };
23483
+ if (mode === "enforce" && taskRuns.has(contextKey(proposal))) throw new ViraOpenCodeActionError("BLOCK", "TASKRUN_SERVER_HANDOFF_ACTIVE");
23133
23484
  const decision = cachedDecision(proposal) ?? cacheDecision(proposal, await runtime2.beforeTool(proposal));
23134
23485
  if (mode === "enforce" && decision.decision !== "ALLOW") throw new ViraOpenCodeActionError(decision.decision, text2(decision.reasonCode) || "VIRA_ACTION_NOT_ALLOWED");
23135
23486
  if (mode === "enforce" && !executionFence.claim(callKey(proposal), proposal.sessionId ?? proposal.conversationId, proposal.conversationId)) throw new ViraOpenCodeActionError("BLOCK", "RUNTIME_ACTION_HOST_CALL_REPLAY");
@@ -23162,6 +23513,7 @@ Assistant: ${output2}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempote
23162
23513
  return async () => {
23163
23514
  resolvedModels.clear();
23164
23515
  promptRoutesInFlight.clear();
23516
+ taskRuns.clear();
23165
23517
  actionContexts.clear();
23166
23518
  actionDecisions.clear();
23167
23519
  actionDecisionDigests.clear();
@@ -23188,6 +23540,7 @@ var v1Runtime = async (options) => {
23188
23540
  throw error62;
23189
23541
  }
23190
23542
  const actionContexts = /* @__PURE__ */ new Map();
23543
+ const taskRuns = /* @__PURE__ */ new Map();
23191
23544
  const actionDecisions = /* @__PURE__ */ new Map();
23192
23545
  const actionDecisionDigests = /* @__PURE__ */ new Map();
23193
23546
  const executionFence = createHostCallExecutionFence();
@@ -23226,23 +23579,24 @@ var v1Runtime = async (options) => {
23226
23579
  if (!dataVersion) return { decision: "BLOCK", reasonCode: "RUNTIME_ACTION_DATA_VERSION_UNAVAILABLE" };
23227
23580
  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" };
23228
23581
  try {
23229
- return await authorizeWithOneShotCustomerConfirmation({ client, proposal, proposalBody: buildOpenCodeActionProposal(proposal, binding, bound.context), executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, aiSystemId: proposal.aiSystemId, signalAttestationRefs: Array.isArray(bound.context.signal_attestation_refs) ? bound.context.signal_attestation_refs : [] });
23582
+ return await authorizeWithOneShotCustomerConfirmation({ client, proposal, proposalBody: buildOpenCodeActionProposal(proposal, binding, bound.context), executionId: bound.executionId, sessionId: proposal.sessionId ?? proposal.conversationId, dataVersion, scope, context: bound.context, aiSystemId: proposal.aiSystemId, connectionId: proposal.connectionId, signalAttestationRefs: Array.isArray(bound.context.signal_attestation_refs) ? bound.context.signal_attestation_refs : [] });
23230
23583
  } catch (error62) {
23231
23584
  return { decision: "ERROR", reasonCode: error62 instanceof Error ? error62.message : "RUNTIME_ACTION_AUTHORIZATION_FAILED" };
23232
23585
  }
23233
23586
  };
23234
23587
  const authorizeAction = async (proposal) => {
23588
+ if (taskRuns.has(contextKey(proposal))) return { decision: "BLOCK", reasonCode: "TASKRUN_SERVER_HANDOFF_ACTIVE" };
23235
23589
  const bound = findActionContext(proposal);
23236
23590
  if (bound && bound.executionId.startsWith("runtime:taskrun:")) return { decision: "BLOCK", reasonCode: "SINGLE_HOST_SERVER_DISPATCH_REQUIRED" };
23237
23591
  return options.authorizeAction ? options.authorizeAction(proposal) : serverAuthorizeAction(proposal);
23238
23592
  };
23239
- return { mode, scope, client, actionContexts, actionDecisions, actionDecisionDigests, executionFence, 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 }) };
23593
+ return { mode, scope, client, taskRuns, actionContexts, actionDecisions, actionDecisionDigests, executionFence, contextKey, cachedDecision, cacheDecision, runtime: createViraHostRuntime(client, { mode, timeoutMs, multiTaskHandoff: "server-owned", ...(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 }) };
23240
23594
  };
23241
23595
  var v1Fallback = { async server(rawContext = {}) {
23242
23596
  const options = readHostOptions(rawContext);
23243
23597
  const configured = await v1Runtime(options);
23244
23598
  if (!configured) return {};
23245
- const { mode, scope, client, runtime: runtime2, actionContexts, actionDecisions, actionDecisionDigests, executionFence, contextKey, cachedDecision, cacheDecision } = configured;
23599
+ const { mode, scope, client, runtime: runtime2, taskRuns, actionContexts, actionDecisions, actionDecisionDigests, executionFence, contextKey, cachedDecision, cacheDecision } = configured;
23246
23600
  if (!(options.aiSystemId ?? envValue("VIRA_AI_SYSTEM_ID")) || !(options.connectionId ?? envValue("VIRA_CONNECTION_ID"))) {
23247
23601
  try {
23248
23602
  await runtime2.connectOnce();
@@ -23256,9 +23610,21 @@ var v1Fallback = { async server(rawContext = {}) {
23256
23610
  const promptCacheTtlMs = Math.max(1e3, Math.min(3e5, Number(options.promptCacheTtlMs ?? envValue("VIRA_V1_PROMPT_CACHE_TTL_MS") ?? 6e4) || 6e4));
23257
23611
  const prompts = createV1PromptCache(promptCacheTtlMs);
23258
23612
  const teachPrompts = createTeachTurnLedger();
23259
- const clearSessionPrompts = (event) => {
23613
+ const closingSessions = /* @__PURE__ */ new Set();
23614
+ const resultDelivery = createOpenCodeResultDelivery({ client, display: mode === "enforce" ? createLegacyTaskRunResultDisplay(rawContext) : void 0, active: (run) => !closingSessions.has(run.sessionId ?? run.conversationId) && taskRuns.get(contextKey(run))?.taskRunId === run.taskRunId });
23615
+ const clearSessionPrompts = async (event) => {
23260
23616
  const sessionId = text2(event.sessionID ?? event.sessionId ?? event.conversationId ?? event.id);
23261
23617
  if (sessionId) {
23618
+ closingSessions.add(sessionId);
23619
+ for (const [key, run] of taskRuns) {
23620
+ if (run.sessionId !== sessionId && run.conversationId !== sessionId) continue;
23621
+ try {
23622
+ await cancelOpenCodeTaskRunHandoff(client, run);
23623
+ taskRuns.delete(key);
23624
+ } catch (error62) {
23625
+ if (mode === "enforce") throw error62;
23626
+ }
23627
+ }
23262
23628
  prompts.clear(sessionId);
23263
23629
  teachPrompts.clear(sessionId);
23264
23630
  executionFence.clearSession(sessionId, sessionId);
@@ -23266,14 +23632,14 @@ var v1Fallback = { async server(rawContext = {}) {
23266
23632
  };
23267
23633
  const hostVersion = hostVersionFor(options, rawContext);
23268
23634
  const identity = (input2) => ({ ...scope, hostName: options.hostName ?? "opencode", hostVersion, aiSystemId: required3(connectedIdentity?.aiSystemId ?? options.aiSystemId ?? env("VIRA_AI_SYSTEM_ID"), "VIRA_HOST_AI_SYSTEM_REQUIRED"), connectionId: required3(connectedIdentity?.connectionId ?? options.connectionId ?? env("VIRA_CONNECTION_ID"), "VIRA_HOST_CONNECTION_REQUIRED"), conversationId: required3(input2.sessionID ?? input2.conversationId ?? input2.id, "VIRA_HOST_SESSION_REQUIRED"), sessionId: text2(input2.sessionID ?? input2.sessionId ?? input2.conversationId) || void 0 });
23269
- const partsText = (value) => Array.isArray(value) ? value.map((part) => text2(asRecord(part).text)).filter(Boolean).join("\n") : "";
23635
+ const partsText = (value) => Array.isArray(value) ? value.filter((part) => asRecord(part).ignored !== true).map((part) => text2(asRecord(part).text)).filter(Boolean).join("\n") : "";
23270
23636
  const persistCompletedText = async (raw) => {
23271
23637
  const envelope = asRecord(raw);
23272
23638
  const event = asRecord(envelope.event ?? raw);
23273
23639
  const data = asRecord(event.data ?? event.properties);
23274
23640
  const eventPart = asRecord(data.part ?? data.message ?? data.output);
23275
23641
  const isCompletedText = (text2(event.type) === "session.text.ended" || text2(event.type) === "message.part.updated") && text2(eventPart.type) === "text" && Boolean(asRecord(eventPart.time).end);
23276
- if (!isCompletedText) return;
23642
+ if (!isCompletedText || eventPart.ignored === true) return;
23277
23643
  const sessionID = text2(data.sessionID ?? data.sessionId ?? eventPart.sessionID ?? eventPart.sessionId);
23278
23644
  const output2 = text2(data.text ?? data.content ?? eventPart.text ?? eventPart.content);
23279
23645
  if (!sessionID || !output2.trim()) return;
@@ -23295,13 +23661,35 @@ Assistant: ${output2}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempote
23295
23661
  if (mode === "enforce") throw Error("VIRA_HOST_MODEL_INPUT_REQUIRED");
23296
23662
  return;
23297
23663
  }
23298
- const result = await runOpenCodeModelLifecycle(mode, () => runtime2.beforeModel({ ...identity(input2), requestId: text2(input2.messageID ?? input2.requestId) || `opencode:${Date.now()}`, input: prompt, profile: conversationProfile(input2, options), traceId: text2(input2.traceID), turnId: text2(input2.turnID), signalAttestationRefs: options.signalAttestationRefs }));
23664
+ const currentIdentity = identity(input2), messageId = text2(input2.messageID ?? input2.requestId), requestId = messageId || "opencode:" + randomUUID(), admissionRequestId = openCodeHostRequestId(currentIdentity, messageId, prompt.trim(), requestId), key = contextKey(currentIdentity);
23665
+ if (mode === "enforce") {
23666
+ const previous = taskRuns.get(key);
23667
+ if (previous) {
23668
+ const current2 = await readOpenCodeTaskRunHandoff(client, previous);
23669
+ taskRuns.set(key, current2);
23670
+ if (current2.taskRunId === "host-task-run-" + admissionRequestId || !hostTaskRunTerminal(current2.status)) {
23671
+ void resultDelivery.start(current2);
23672
+ throw await openCodeTaskRunHandoffError(client, current2);
23673
+ }
23674
+ if (current2.status === "COMPLETED") await resultDelivery.start(current2);
23675
+ taskRuns.delete(key);
23676
+ }
23677
+ }
23678
+ const result = await runOpenCodeModelLifecycle(mode, () => runtime2.beforeModel({ ...currentIdentity, requestId, hostMessageId: messageId, input: prompt.trim(), profile: conversationProfile(input2, options), traceId: text2(input2.traceID), turnId: text2(input2.turnID), signalAttestationRefs: options.signalAttestationRefs }));
23299
23679
  if (!result) return;
23300
23680
  if (mode === "enforce" && result.status === "unavailable") throw Error("VIRA_NATIVE_MODEL_AUTHORITY_UNAVAILABLE");
23681
+ if (mode === "enforce" && result.status === "task_run") {
23682
+ const run = captureOpenCodeTaskRunHandoff(currentIdentity, result);
23683
+ actionContexts.delete(key);
23684
+ taskRuns.set(key, run);
23685
+ void resultDelivery.start(run);
23686
+ throw new OpenCodeTaskRunHandoffError(run);
23687
+ }
23301
23688
  if (!options.aiSystemId && !options.connectionId) connectedIdentity = runtime2.getConnectionIdentity();
23302
23689
  const responseBody = asRecord(result.response?.body);
23303
- const runtimeContext = asRecord(responseBody.requestContext ?? responseBody.context);
23304
- const executionId = text2(input2.executionId ?? responseBody.executionId);
23690
+ const programOnly = Boolean(responseBody.programSelection) && !responseBody.strategySelection;
23691
+ const runtimeContext = asRecord(programOnly ? void 0 : responseBody.requestContext ?? responseBody.context);
23692
+ const executionId = programOnly ? "" : text2(input2.executionId ?? responseBody.executionId);
23305
23693
  const expiresAt = Number(runtimeContext.expires_at_unix_ms);
23306
23694
  const current = identity(input2);
23307
23695
  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 });
@@ -23345,6 +23733,9 @@ Assistant: ${completed}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempo
23345
23733
  "chat.message": async (input2, output2) => {
23346
23734
  const sessionId = text2(input2.sessionID ?? input2.conversationId ?? input2.id);
23347
23735
  const message = asRecord(output2.message ?? input2.message);
23736
+ const incomingParts = output2.parts ?? input2.parts;
23737
+ if (Array.isArray(incomingParts) && incomingParts.length && incomingParts.every((part) => asRecord(part).ignored === true)) return;
23738
+ if (sessionId) closingSessions.delete(sessionId);
23348
23739
  const prompt = text2(message.text ?? message.content) || partsText(output2.parts ?? input2.parts);
23349
23740
  if (sessionId && prompt.trim()) {
23350
23741
  prompts.set(sessionId, prompt.trim());
@@ -23363,11 +23754,16 @@ Assistant: ${completed}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempo
23363
23754
  if (mode !== "enforce") return;
23364
23755
  const metadata = asRecord(input2.metadata);
23365
23756
  const proposal = { ...identity(input2), requestId: text2(input2.messageID ?? input2.requestId) || `opencode:${Date.now()}`, callId: required3(input2.callID ?? input2.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required3(metadata.tool ?? metadata.toolName ?? input2.type, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(metadata.args ?? metadata.input ?? metadata.arguments), traceId: text2(input2.traceID), turnId: text2(input2.turnID) };
23757
+ if (taskRuns.has(contextKey(proposal))) {
23758
+ output2.status = "deny";
23759
+ return;
23760
+ }
23366
23761
  const decision = cachedDecision(proposal) ?? cacheDecision(proposal, await runtime2.beforeTool(proposal));
23367
23762
  output2.status = decision.decision === "ALLOW" ? "allow" : "deny";
23368
23763
  },
23369
23764
  "tool.execute.before": async (input2, output2) => {
23370
23765
  const proposal = { ...identity(input2), requestId: text2(input2.messageID ?? input2.requestId) || `opencode:${Date.now()}`, callId: required3(input2.callID ?? input2.id, "VIRA_HOST_TOOL_CALL_REQUIRED"), toolName: required3(input2.tool ?? input2.name, "VIRA_HOST_TOOL_NAME_REQUIRED"), args: asRecord(output2.args ?? input2.args ?? input2.input), traceId: text2(input2.traceID), turnId: text2(input2.turnID) };
23766
+ if (mode === "enforce" && taskRuns.has(contextKey(proposal))) throw new ViraOpenCodeActionError("BLOCK", "TASKRUN_SERVER_HANDOFF_ACTIVE");
23371
23767
  const decision = cachedDecision(proposal) ?? cacheDecision(proposal, await runtime2.beforeTool(proposal));
23372
23768
  if (mode === "enforce" && decision.decision !== "ALLOW") throw new ViraOpenCodeActionError(decision.decision, text2(decision.reasonCode) || "VIRA_ACTION_NOT_ALLOWED");
23373
23769
  if (mode === "enforce" && !executionFence.claim(contextKey(proposal) + ":" + proposal.callId, proposal.sessionId ?? proposal.conversationId, proposal.conversationId)) throw new ViraOpenCodeActionError("BLOCK", "RUNTIME_ACTION_HOST_CALL_REPLAY");
@@ -23385,13 +23781,13 @@ Assistant: ${completed}`, consent: true, privacy: "CONSENTED_TENANT" }, { idempo
23385
23781
  }
23386
23782
  },
23387
23783
  "session.close": async (input2) => {
23388
- clearSessionPrompts(input2);
23784
+ await clearSessionPrompts(input2);
23389
23785
  },
23390
23786
  "session.end": async (input2) => {
23391
- clearSessionPrompts(input2);
23787
+ await clearSessionPrompts(input2);
23392
23788
  },
23393
23789
  "session.delete": async (input2) => {
23394
- clearSessionPrompts(input2);
23790
+ await clearSessionPrompts(input2);
23395
23791
  }
23396
23792
  };
23397
23793
  } };
@@ -23411,7 +23807,15 @@ var runtime = Object.assign(index_default, {
23411
23807
  recordModelResponse,
23412
23808
  recordUserCorrection,
23413
23809
  createV1PromptCache,
23414
- queueOpenCodeTaskRunHostDispatch
23810
+ queueOpenCodeTaskRunHostDispatch,
23811
+ captureOpenCodeTaskRunHandoff,
23812
+ readOpenCodeTaskRunHandoff,
23813
+ readOpenCodeTaskRunTerminalEvidence,
23814
+ readOpenCodeTaskRunResult,
23815
+ createLegacyTaskRunResultDisplay,
23816
+ createOpenCodeResultDelivery,
23817
+ cancelOpenCodeTaskRunHandoff,
23818
+ OpenCodeTaskRunHandoffError
23415
23819
  });
23416
23820
  var runtime_entry_default = runtime;
23417
23821