Skip to content

The open-source app everyone uses to manage agents at work

feat(runner): add authorized scenario tool runtime (#12361)

Dottaea86e780af65
diff --git a/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts b/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts
index e461697109..88e62d37eb 100644
--- a/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts
+++ b/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts
@@ -254,6 +254,53 @@ export interface ScenarioChatdempotencyRecord {
result: CapabilityCommandResult;
}
+export interface CapabilitySemanticToolRuntimeSnapshot {
+ schema: "paperclip.capability.semantic-tool-runtime.v1";
+ resultSequence: number;
+ operationResults: Record<string, CapabilityJsonValue>;
+ extensions: Array<
+ | {
+ key: string;
+ input: string;
+ status: "pending";
+ /** Optional only for legacy pending snapshots, which are immediately reclaimable. */
+ ownerId?: string;
+ leaseExpiresAtMs?: number;
+ /** `executing` is recovered only from an exact prepared receipt. */
+ phase?: "reserved" | "executing";
+ /**
+ * Package-local mock extensions prepare their deterministic result
+ * before crossing the executing boundary, so executor loss can publish
+ * this exact receipt without replaying the extension.
+ */
+ preparedExecution?: {
+ value: CapabilityJsonValue;
+ commandResult: CapabilityCommandResult | null;
+ entityRefs: string[];
+ };
+ }
+ | {
+ key: string;
+ input: string;
+ /** The effect may have run, but no exact receipt is recoverable. */
+ status: "indeterminate";
+ reason: "idempotency_receipt_unavailable";
+ }
+ | {
+ key: string;
+ input: string;
+ /** Absent only in snapshots written before pending markers existed. */
+ status?: "completed";
+ resultId: string;
+ execution: {
+ value: CapabilityJsonValue;
+ commandResult: CapabilityCommandResult | null;
+ entityRefs: string[];
+ };
+ }
+ >;
+}
+
export interface CapabilityFixtureState {
schema: "paperclip.capability.mock-state.v1";
revision: number;
@@ -280,6 +327,8 @@ export interface CapabilityFixtureState {
audit: CapabilityAuditRecord[];
decisions: CapabilityDecisionRecord[];
idempotency: ScenarioChatdempotencyRecord[];
+ /** Durable package-local tool receipts keyed by logical run id. */
+ semanticToolRuntimes?: Record<string, CapabilitySemanticToolRuntimeSnapshot>;
faults: CapabilityFaultRule[];
}
@@ -450,6 +499,16 @@ export interface CapabilityMockControlPlanePort extends ControlPlanePort {
applyCommand(envelope: CapabilityCommandEnvelope): Promise<CapabilityCommandResult>;
tryApplyCommand(envelope: CapabilityCommandEnvelope): Promise<CapabilityCommandOutcome>;
snapshot(): Readonly<CapabilityFixtureState>;
+ loadSemanticToolRuntime(runId: string): CapabilitySemanticToolRuntimeSnapshot | null;
+ saveSemanticToolRuntime(
+ runId: string,
+ snapshot: CapabilitySemanticToolRuntimeSnapshot,
+ ): void;
+ compareAndSwapSemanticToolRuntime(
+ runId: string,
+ expected: CapabilitySemanticToolRuntimeSnapshot | null,
+ snapshot: CapabilitySemanticToolRuntimeSnapshot,
+ ): boolean;
decisionRecords(): readonly CapabilityDecisionRecord[];
serialize(): string;
}
@@ -553,6 +612,7 @@ export function createCapabilityFixtureState(seed: CapabilityFixtureSeed = {}):
audit: [],
decisions: [],
idempotency: [],
+ semanticToolRuntimes: {},
faults: structuredClone(seed.faults ?? []),
};
}
diff --git a/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts b/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts
index 59974bed97..7a8e00ef66 100644
--- a/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts
+++ b/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts
@@ -33,6 +33,7 @@ import {
type CapabilityOpenFixtureRunInput,
type CapabilityRunContext,
type CapabilitySemanticCommand,
+ type CapabilitySemanticToolRuntimeSnapshot,
type CapabilityWakeContext,
} from "./capability-control-plane-types.js";
@@ -48,6 +49,21 @@ export class CapabilityMockControlPlaneError extends Error {
this.name = "CapabilityMockControlPlaneError";
}
}
+
+export interface CapabilitySemanticToolRuntimeStore {
+ load(runId: string): CapabilitySemanticToolRuntimeSnapshot | null;
+ save(runId: string, snapshot: CapabilitySemanticToolRuntimeSnapshot): void;
+ compareAndSwap(
+ runId: string,
+ expected: CapabilitySemanticToolRuntimeSnapshot | null,
+ snapshot: CapabilitySemanticToolRuntimeSnapshot,
+ ): boolean;
+}
+
+export interface CapabilityMockControlPlaneAdapterOptions {
+ /** Optional process-independent owner for durable semantic-tool receipts. */
+ semanticToolRuntimeStore?: CapabilitySemanticToolRuntimeStore;
+}
/**
* Deterministic, serializable control-plane authority for Capability scenarios.
*
@@ -56,17 +72,39 @@ export class CapabilityMockControlPlaneError extends Error {
*/
export class CapabilityMockControlPlaneAdapter implements CapabilityMockControlPlanePort {
#state: CapabilityFixtureState;
+ readonly #semanticToolRuntimeStore:
+ | CapabilitySemanticToolRuntimeStore
+ | undefined;
- constructor(seed: CapabilityFixtureSeed | CapabilityFixtureState = {}) {
+ constructor(
+ seed: CapabilityFixtureSeed | CapabilityFixtureState = {},
+ options: CapabilityMockControlPlaneAdapterOptions = {},
+ ) {
+ this.#semanticToolRuntimeStore = options.semanticToolRuntimeStore;
this.#state = isFixtureState(seed)
? clone(seed)
: createCapabilityFixtureState(seed);
// Serialized v1 fixtures from before company-scope sentinels remain valid.
this.#state.outOfScopeTaskIds ??= [];
+ this.#state.semanticToolRuntimes ??= {};
this.#validateState();
+ if (
+ this.#semanticToolRuntimeStore === undefined &&
+ Object.values(this.#state.semanticToolRuntimes).some((snapshot) =>
+ snapshot.extensions.some((extension) => extension.status === "pending"),
+ )
+ ) {
+ throw new CapabilityMockControlPlaneError(
+ "fixture_state_invalid",
+ "restoring pending semantic extensions requires a process-independent runtime store",
+ );
+ }
}
- static restore(serialized: string): CapabilityMockControlPlaneAdapter {
+ static restore(
+ serialized: string,
+ options: CapabilityMockControlPlaneAdapterOptions = {},
+ ): CapabilityMockControlPlaneAdapter {
let parsed: unknown;
try {
parsed = JSON.parse(serialized);
@@ -82,7 +120,7 @@ export class CapabilityMockControlPlaneAdapter implements CapabilityMockControlP
"fixture state schema must be paperclip.capability.mock-state.v1",
);
}
- return new CapabilityMockControlPlaneAdapter(parsed);
+ return new CapabilityMockControlPlaneAdapter(parsed, options);
}
async start(): Promise<void> {
@@ -583,6 +621,71 @@ export class CapabilityMockControlPlaneAdapter implements CapabilityMockControlP
return deepFreeze(clone(this.#state));
}
+ loadSemanticToolRuntime(
+ runId: string,
+ ): CapabilitySemanticToolRuntimeSnapshot | null {
+ this.#run(runId);
+ if (this.#semanticToolRuntimeStore !== undefined) {
+ const durable = this.#semanticToolRuntimeStore.load(runId);
+ if (durable === null) return null;
+ if (!isSemanticToolRuntimeSnapshot(durable)) {
+ throw new CapabilityMockControlPlaneError(
+ "fixture_state_invalid",
+ "durable semantic tool runtime snapshot is invalid",
+ );
+ }
+ return clone(durable);
+ }
+ const snapshot = this.#state.semanticToolRuntimes?.[runId];
+ return snapshot === undefined ? null : clone(snapshot);
+ }
+
+ saveSemanticToolRuntime(
+ runId: string,
+ snapshot: CapabilitySemanticToolRuntimeSnapshot,
+ ): void {
+ this.#run(runId);
+ if (!isSemanticToolRuntimeSnapshot(snapshot)) {
+ throw new CapabilityMockControlPlaneError(
+ "fixture_state_invalid",
+ "semantic tool runtime snapshot is invalid",
+ );
+ }
+ const durableSnapshot = clone(snapshot);
+ this.#semanticToolRuntimeStore?.save(runId, durableSnapshot);
+ this.#state.semanticToolRuntimes![runId] = clone(durableSnapshot);
+ }
+
+ compareAndSwapSemanticToolRuntime(
+ runId: string,
+ expected: CapabilitySemanticToolRuntimeSnapshot | null,
+ snapshot: CapabilitySemanticToolRuntimeSnapshot,
+ ): boolean {
+ this.#run(runId);
+ if (
+ (expected !== null && !isSemanticToolRuntimeSnapshot(expected)) ||
+ !isSemanticToolRuntimeSnapshot(snapshot)
+ ) {
+ throw new CapabilityMockControlPlaneError(
+ "fixture_state_invalid",
+ "semantic tool runtime compare-and-swap snapshot is invalid",
+ );
+ }
+ const replacement = clone(snapshot);
+ const swapped = this.#semanticToolRuntimeStore === undefined
+ ? canonicalJson(this.#state.semanticToolRuntimes![runId] ?? null) ===
+ canonicalJson(expected)
+ : this.#semanticToolRuntimeStore.compareAndSwap(
+ runId,
+ expected === null ? null : clone(expected),
+ replacement,
+ );
+ if (swapped) {
+ this.#state.semanticToolRuntimes![runId] = clone(replacement);
+ }
+ return swapped;
+ }
+
decisionRecords(): readonly CapabilityDecisionRecord[] {
return deepFreeze(clone(this.#state.decisions));
}
@@ -1708,9 +1811,208 @@ export class CapabilityMockControlPlaneAdapter implements CapabilityMockControlP
);
}
}
+ for (const [runId, snapshot] of Object.entries(this.#state.semanticToolRuntimes ?? {})) {
+ if (
+ !this.#state.runs.some((run) => run.id === runId) ||
+ !isSemanticToolRuntimeSnapshot(snapshot)
+ ) {
+ throw new CapabilityMockControlPlaneError(
+ "fixture_state_invalid",
+ `semantic tool runtime for ${runId} is invalid`,
+ );
+ }
+ }
}
}
+function isSemanticToolRuntimeSnapshot(
+ value: unknown,
+): value is CapabilitySemanticToolRuntimeSnapshot {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ return false;
+ }
+ const snapshot = value as Record<string, unknown>;
+ if (
+ snapshot.schema !== "paperclip.capability.semantic-tool-runtime.v1" ||
+ !Number.isSafeInteger(snapshot.resultSequence) ||
+ Number(snapshot.resultSequence) < 0 ||
+ typeof snapshot.operationResults !== "object" ||
+ snapshot.operationResults === null ||
+ Array.isArray(snapshot.operationResults) ||
+ !Array.isArray(snapshot.extensions)
+ ) {
+ return false;
+ }
+ const operationResults = snapshot.operationResults as Record<
+ string,
+ unknown
+ >;
+ if (!Object.values(operationResults).every(isCapabilityJsonValue)) {
+ return false;
+ }
+ const keys = new Set<string>();
+ const validExtensions = snapshot.extensions.every((candidate) => {
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
+ return false;
+ }
+ const extension = candidate as Record<string, unknown>;
+ if (
+ typeof extension.key !== "string" ||
+ extension.key.length === 0 ||
+ keys.has(extension.key) ||
+ typeof extension.input !== "string"
+ ) {
+ return false;
+ }
+ if (extension.status === "pending") {
+ if ("resultId" in extension || "execution" in extension) return false;
+ if (
+ (extension.ownerId !== undefined &&
+ (typeof extension.ownerId !== "string" || extension.ownerId.length === 0)) ||
+ (extension.leaseExpiresAtMs !== undefined &&
+ (!Number.isSafeInteger(extension.leaseExpiresAtMs) ||
+ Number(extension.leaseExpiresAtMs) < 0)) ||
+ (extension.phase !== undefined &&
+ extension.phase !== "reserved" &&
+ extension.phase !== "executing")
+ ) {
+ return false;
+ }
+ if (extension.preparedExecution !== undefined) {
+ if (
+ extension.phase !== "executing" ||
+ typeof extension.preparedExecution !== "object" ||
+ extension.preparedExecution === null ||
+ Array.isArray(extension.preparedExecution)
+ ) {
+ return false;
+ }
+ const prepared = extension.preparedExecution as Record<string, unknown>;
+ if (
+ !isCapabilityJsonValue(prepared.value) ||
+ (prepared.commandResult !== null &&
+ !isCapabilityCommandResult(prepared.commandResult)) ||
+ !Array.isArray(prepared.entityRefs) ||
+ prepared.entityRefs.some((ref) => typeof ref !== "string")
+ ) {
+ return false;
+ }
+ }
+ keys.add(extension.key);
+ return true;
+ }
+ if (extension.status === "indeterminate") {
+ if (
+ extension.reason !== "idempotency_receipt_unavailable" ||
+ "resultId" in extension ||
+ "execution" in extension ||
+ "ownerId" in extension ||
+ "leaseExpiresAtMs" in extension ||
+ "phase" in extension ||
+ "preparedExecution" in extension
+ ) {
+ return false;
+ }
+ keys.add(extension.key);
+ return true;
+ }
+ if (
+ (extension.status !== undefined && extension.status !== "completed") ||
+ typeof extension.resultId !== "string" ||
+ extension.resultId.length === 0 ||
+ !Object.prototype.hasOwnProperty.call(
+ operationResults,
+ extension.resultId,
+ ) ||
+ typeof extension.execution !== "object" ||
+ extension.execution === null ||
+ Array.isArray(extension.execution)
+ ) {
+ return false;
+ }
+ const execution = extension.execution as Record<string, unknown>;
+ if (
+ !("value" in execution) ||
+ !isCapabilityJsonValue(execution.value) ||
+ !("commandResult" in execution) ||
+ (execution.commandResult !== null &&
+ !isCapabilityCommandResult(execution.commandResult)) ||
+ !Array.isArray(execution.entityRefs) ||
+ execution.entityRefs.some((ref) => typeof ref !== "string")
+ ) {
+ return false;
+ }
+ if (
+ canonicalJson(operationResults[extension.resultId]) !==
+ canonicalJson(execution.value)
+ ) {
+ return false;
+ }
+ keys.add(extension.key);
+ return true;
+ });
+ if (!validExtensions) return false;
+ const generatedResultIds = [
+ ...Object.keys(operationResults),
+ ...snapshot.extensions.flatMap((candidate) =>
+ candidate.status === "pending" || candidate.status === "indeterminate"
+ ? []
+ : [candidate.resultId],
+ ),
+ ];
+ return generatedResultIds.every((resultId) => {
+ const match = /^tool-result-(\d+)$/.exec(resultId);
+ if (match === null) return true;
+ const sequence = Number(match[1]);
+ return (
+ Number.isSafeInteger(sequence) &&
+ sequence > 0 &&
+ sequence <= Number(snapshot.resultSequence)
+ );
+ });
+}
+
+function isCapabilityJsonValue(value: unknown): value is CapabilityJsonValue {
+ if (
+ value === null ||
+ typeof value === "string" ||
+ typeof value === "boolean"
+ ) {
+ return true;
+ }
+ if (typeof value === "number") return Number.isFinite(value);
+ if (Array.isArray(value)) return value.every(isCapabilityJsonValue);
+ if (typeof value !== "object") return false;
+ return Object.values(value as Record<string, unknown>).every(
+ isCapabilityJsonValue,
+ );
+}
+
+function isCapabilityCommandResult(
+ value: unknown,
+): value is CapabilityCommandResult {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ return false;
+ }
+ const result = value as Record<string, unknown>;
+ return (
+ typeof result.commandId === "string" &&
+ result.commandId.length > 0 &&
+ typeof result.commandKind === "string" &&
+ Object.prototype.hasOwnProperty.call(
+ CAPABILITY_COMMAND_REQUIRED_CLAIMS,
+ result.commandKind,
+ ) &&
+ (result.disposition === "applied" || result.disposition === "duplicate") &&
+ Number.isSafeInteger(result.stateRevision) &&
+ Number(result.stateRevision) >= 0 &&
+ Array.isArray(result.entityRefs) &&
+ result.entityRefs.every((ref) => typeof ref === "string") &&
+ Array.isArray(result.scheduledWakeIds) &&
+ result.scheduledWakeIds.every((id) => typeof id === "string")
+ );
+}
+
function isFixtureState(value: unknown): value is CapabilityFixtureState {
return (
typeof value === "object" &&
diff --git a/packages/paperclip-runner/src/tools/capability-semantic-tool-catalog.ts b/packages/paperclip-runner/src/tools/capability-semantic-tool-catalog.ts
new file mode 100644
index 0000000000..f4113ebc09
--- /dev/null
+++ b/packages/paperclip-runner/src/tools/capability-semantic-tool-catalog.ts
@@ -0,0 +1,12 @@
+/** Scenario/eval projection of the per-action protocol definitions. */
+import { PAPERCLIP_PROTOCOL_ACTIONS } from "../protocol-actions/index.js";
+import type { CapabilityOptionalCatalogGroup, CapabilitySemanticToolDescriptor } from "./capability-semantic-tool-types.js";
+const descriptors = PAPERCLIP_PROTOCOL_ACTIONS.filter((action) => action.scenario !== null)
+ .sort((left, right) => left.scenario!.order - right.scenario!.order)
+ .map((action) => action.scenario!.descriptor as unknown as CapabilitySemanticToolDescriptor);
+export const CAPABILITY_SEMANTIC_TOOL_CATALOG: readonly CapabilitySemanticToolDescriptor[] = Object.freeze(descriptors);
+export const CAPABILITY_OPTIONAL_TOOL_CATALOGS: Readonly<Record<CapabilityOptionalCatalogGroup, readonly CapabilitySemanticToolDescriptor[]>> = Object.freeze({
+ discovery: toolsInGroup("discovery"), delegation_dependencies: toolsInGroup("delegation_dependencies"), governance: toolsInGroup("governance"), cases: toolsInGroup("cases"), workspace_runtime: toolsInGroup("workspace_runtime"), routines: toolsInGroup("routines"), company_skills: toolsInGroup("company_skills"), secrets: toolsInGroup("secrets"), portability_admin: toolsInGroup("portability_admin"), test_escape_hatch: toolsInGroup("test_escape_hatch"),
+});
+export function capabilitySemanticTool(operationId: string): CapabilitySemanticToolDescriptor | undefined { return CAPABILITY_SEMANTIC_TOOL_CATALOG.find((tool) => tool.operationId === operationId); }
+function toolsInGroup(group: CapabilityOptionalCatalogGroup): readonly CapabilitySemanticToolDescriptor[] { return Object.freeze(CAPABILITY_SEMANTIC_TOOL_CATALOG.filter((tool) => tool.optionalGroup === group)); }
diff --git a/packages/paperclip-runner/src/tools/capability-semantic-tool-runtime.ts b/packages/paperclip-runner/src/tools/capability-semantic-tool-runtime.ts
new file mode 100644
index 0000000000..e282fffb99
--- /dev/null
+++ b/packages/paperclip-runner/src/tools/capability-semantic-tool-runtime.ts
@@ -0,0 +1,1752 @@
+import { randomUUID } from "node:crypto";
+
+import type {
+ CapabilityCommandEnvelope,
+ CapabilityJsonValue,
+ CapabilityMockControlPlanePort,
+ CapabilitySemanticToolRuntimeSnapshot,
+ CapabilitySemanticCommand,
+} from "../mock-core/capability-control-plane-types.js";
+import { capabilitySemanticTool } from "./capability-semantic-tool-catalog.js";
+import { CapabilityToolAuthorizationEngine } from "./capability-tool-authorization.js";
+import type {
+ CapabilityAuthorizationRecord,
+ CapabilityJsonSchema,
+ CapabilityModelToolDelivery,
+ CapabilityModelToolInvocationResult,
+ CapabilityModelToolSuccess,
+ CapabilityPolicyDenial,
+ CapabilityScenarioToolPolicy,
+ CapabilitySemanticToolDescriptor,
+ CapabilityToolAuthorizationContext,
+ CapabilityToolInvocation,
+ CapabilityToolInvocationResult,
+ CapabilityToolSuccess,
+ CapabilityVisibleToolSet,
+} from "./capability-semantic-tool-types.js";
+
+export interface CapabilitySemanticToolRuntimeOptions {
+ adapter: CapabilityMockControlPlanePort;
+ runId: string;
+ scenarioGrants?: string[];
+ policy?: CapabilityScenarioToolPolicy;
+ resolveSecretValue?: (name: string) => Promise<string | null> | string | null;
+ /**
+ * Optional trusted backend receipt lookup for an expired extension. The
+ * package-local mock runtime falls back to the exact prepared receipt stored
+ * before execution. Legacy records without a prepared receipt are recoverable
+ * only for fixture computations whose output is independent of mutable
+ * adapter state. State-derived exports require an exact prepared receipt or
+ * a trusted backend lookup so a retry cannot substitute a newer projection
+ * for the value observed by the original execution.
+ */
+ resolveExpiredExtensionReceipt?: (input: {
+ operationId: string;
+ input: Record<string, CapabilityJsonValue>;
+ idempotencyKey: string;
+ }) => Promise<Pick<CapabilityExpiredExtensionReceipt, "value" | "entityRefs"> | null> |
+ Pick<CapabilityExpiredExtensionReceipt, "value" | "entityRefs"> | null;
+ now?: () => number;
+}
+
+export interface CapabilityExpiredExtensionReceipt {
+ operationId: string;
+ input: Record<string, CapabilityJsonValue>;
+ idempotencyKey: string;
+ value: CapabilityJsonValue;
+ entityRefs?: string[];
+}
+
+interface ExtensionExecution {
+ value: CapabilityJsonValue;
+ commandResult: CapabilityToolSuccess["commandResult"];
+ entityRefs: string[];
+}
+
+interface ExtensionIdempotencyRecord {
+ input: string;
+ execution: Promise<{ resultId: string; value: ExtensionExecution }> | null;
+ ownerId: string | null;
+ leaseExpiresAtMs: number;
+ leaseHeartbeat: ReturnType<typeof setInterval> | null;
+ cleanupRetry: ReturnType<typeof setTimeout> | null;
+ completed?: { resultId: string; value: ExtensionExecution };
+ recoveryFailure?: "idempotency_receipt_unavailable";
+}
+
+interface CapabilitySemanticRuntimeState {
+ extensionIdempotency: Map<string, ExtensionIdempotencyRecord>;
+ operationResults: Map<string, CapabilityJsonValue>;
+ resultSequence: number;
+}
+
+const RUNTIME_STATE_BY_ADAPTER = new WeakMap<
+ CapabilityMockControlPlanePort,
+ Map<string, CapabilitySemanticRuntimeState>
+>();
+const EXTENSION_EXECUTION_LEASE_MS = 30_000;
+const EXTENSION_EXECUTION_HEARTBEAT_MS = Math.floor(
+ EXTENSION_EXECUTION_LEASE_MS / 3,
+);
+const RUNTIME_PERSIST_CAS_ATTEMPTS = 8;
+const RUNTIME_COMPLETION_CAS_ATTEMPTS = 64;
+const REPLAY_SAFE_LEGACY_MOCK_EXTENSIONS = new Set([
+ "discovery.projects",
+ "discovery.goals",
+ "cases.list",
+ "routines.list",
+ "company_skills.list",
+ "secrets.metadata",
+ "company_skills.sync",
+ "routines.manage",
+ "cases.upsert",
+ "company.admin",
+ "test.generic_api",
+]);
+
+export class CapabilitySemanticToolRuntime {
+ readonly #adapter: CapabilityMockControlPlanePort;
+ readonly #runId: string;
+ readonly #scenarioGrants: string[];
+ readonly #policy: CapabilityScenarioToolPolicy | undefined;
+ readonly #resolveSecretValue: CapabilitySemanticToolRuntimeOptions["resolveSecretValue"];
+ readonly #resolveExpiredExtensionReceipt: CapabilitySemanticToolRuntimeOptions["resolveExpiredExtensionReceipt"];
+ readonly #now: () => number;
+ readonly #authorization = new CapabilityToolAuthorizationEngine();
+ readonly #state: CapabilitySemanticRuntimeState;
+
+ constructor(options: CapabilitySemanticToolRuntimeOptions) {
+ this.#adapter = options.adapter;
+ this.#runId = options.runId;
+ this.#scenarioGrants = [...new Set(options.scenarioGrants ?? [])].sort();
+ this.#policy = options.policy === undefined ? undefined : structuredClone(options.policy);
+ this.#resolveSecretValue = options.resolveSecretValue;
+ this.#resolveExpiredExtensionReceipt = options.resolveExpiredExtensionReceipt;
+ this.#now = options.now ?? Date.now;
+ let adapterState = RUNTIME_STATE_BY_ADAPTER.get(options.adapter);
+ if (adapterState === undefined) {
+ adapterState = new Map();
+ RUNTIME_STATE_BY_ADAPTER.set(options.adapter, adapterState);
+ }
+ const existingState = adapterState.get(options.runId);
+ if (existingState !== undefined) this.#state = existingState;
+ else {
+ this.#state = this.#restoreState(
+ options.adapter.loadSemanticToolRuntime(options.runId),
+ );
+ adapterState.set(options.runId, this.#state);
+ }
+ }
+
+ visibleTools(): CapabilityVisibleToolSet {
+ return this.#authorization.computeVisibleTools(this.#context());
+ }
+
+ authorizationRecords(): readonly CapabilityAuthorizationRecord[] {
+ return this.#authorization.records();
+ }
+
+ /**
+ * Publishes the exact observed result of an expired extension that entered
+ * execution. This is a trusted recovery boundary: normal tool invocations
+ * cannot guess, replay, or replace an ambiguous effect after its executor
+ * exits.
+ */
+ reconcileExpiredExtensionReceipt(
+ receipt: CapabilityExpiredExtensionReceipt,
+ ): { resultId: string } {
+ const descriptor = capabilitySemanticTool(receipt.operationId);
+ if (
+ descriptor?.mockCommandMapping.kind !== "mock_extension" ||
+ descriptor.idempotency !== "required"
+ ) {
+ throw new Error("extension receipt reconciliation is not available");
+ }
+ const idempotencyKey = receipt.idempotencyKey.trim();
+ if (idempotencyKey.length === 0) {
+ throw new Error("extension receipt idempotency key is required");
+ }
+ if (receipt.entityRefs?.some((ref) => typeof ref !== "string")) {
+ throw new Error("extension receipt entity references are invalid");
+ }
+ const key = `${this.#runId}:${receipt.operationId}:${idempotencyKey}`;
+ const input = canonicalJson(receipt.input);
+ const value = structuredClone(receipt.value);
+ const entityRefs = [...new Set(receipt.entityRefs ?? [])].sort();
+
+ for (let attempt = 0; attempt < RUNTIME_COMPLETION_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const extension = durable?.extensions.find(
+ (candidate) => candidate.key === key,
+ );
+ if (durable === null || extension === undefined || extension.input !== input) {
+ throw new Error("expired extension receipt does not match durable execution");
+ }
+ if (
+ extension.status !== "pending" &&
+ extension.status !== "indeterminate"
+ ) {
+ const durableResult = durable.operationResults[extension.resultId];
+ if (durableResult === undefined) {
+ throw new Error("completed extension receipt omitted its operation result");
+ }
+ // The original authorized executor may publish while trusted recovery
+ // is resolving the expired lease. Its durable completion is already
+ // authoritative for this exact key and canonical input; adopt it
+ // instead of letting a stale recovery observation replace or reject
+ // successfully completed work.
+ this.#state.operationResults.set(
+ extension.resultId,
+ structuredClone(durableResult),
+ );
+ this.#state.resultSequence = Math.max(
+ this.#state.resultSequence,
+ durable.resultSequence,
+ );
+ this.#adoptReconciledExtension(
+ key,
+ input,
+ extension.resultId,
+ structuredClone(extension.execution),
+ );
+ return { resultId: extension.resultId };
+ }
+ if (
+ extension.status === "pending" &&
+ (extension.phase !== "executing" ||
+ (extension.leaseExpiresAtMs ?? 0) > this.#now())
+ ) {
+ throw new Error("extension execution lease is still live or unproved");
+ }
+ const replacement = structuredClone(durable);
+ let resultSequence = Math.max(
+ replacement.resultSequence,
+ this.#state.resultSequence,
+ );
+ let resultId: string;
+ do {
+ resultId = `tool-result-${++resultSequence}`;
+ } while (Object.prototype.hasOwnProperty.call(
+ replacement.operationResults,
+ resultId,
+ ));
+ const execution: ExtensionExecution = {
+ value,
+ commandResult: null,
+ entityRefs,
+ };
+ replacement.resultSequence = resultSequence;
+ replacement.operationResults[resultId] = structuredClone(value);
+ replacement.extensions = replacement.extensions.map((candidate) =>
+ candidate.key === key
+ ? {
+ key,
+ input,
+ status: "completed" as const,
+ resultId,
+ execution: structuredClone(execution),
+ }
+ : candidate,
+ );
+ if (!this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) continue;
+ this.#state.resultSequence = resultSequence;
+ this.#adoptReconciledExtension(key, input, resultId, execution);
+ return { resultId };
+ }
+ throw new Error("durable extension changed during receipt reconciliation");
+ }
+
+ /** Returns only the result shape allowed to cross observable boundaries. */
+ async invoke(invocation: CapabilityToolInvocation): Promise<CapabilityToolInvocationResult> {
+ return (await this.#invoke(invocation, false)).observableResult;
+ }
+
+ /**
+ * Invokes a tool for provider delivery. The raw result remains in a capsule
+ * that serializes and clones as the redacted observable result.
+ */
+ async invokeForModel(invocation: CapabilityToolInvocation): Promise<CapabilityModelToolDelivery> {
+ const result = await this.#invoke(invocation, true);
+ const modelResult = result.modelResult !== undefined
+ ? result.modelResult
+ : !result.observableResult.ok
+ ? result.observableResult
+ : undefined;
+ if (modelResult === undefined) throw new Error("model delivery result was not produced");
+ return new CapabilityModelToolDeliveryImpl(
+ result.observableResult,
+ modelResult,
+ );
+ }
+
+ async #invoke(
+ invocation: CapabilityToolInvocation,
+ includeModelResult: boolean,
+ ): Promise<{
+ observableResult: CapabilityToolInvocationResult;
+ modelResult?: CapabilityModelToolInvocationResult;
+ }> {
+ const context = this.#context();
+ const authorization = this.#authorization.authorizeInvocation(
+ invocation.operationId,
+ invocation.input,
+ context,
+ );
+ if (authorization.outcome !== "allowed") {
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ authorization,
+ authorization.outcome === "absent" ? "operation_absent" : "policy_denied",
+ ),
+ };
+ }
+
+ const descriptor = capabilitySemanticTool(invocation.operationId)!;
+ const validationIssues = validateJsonSchema(descriptor.inputSchema, invocation.input);
+ if (validationIssues.length > 0) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "input_schema_invalid",
+ );
+ return { observableResult: this.#denial(invocation.operationId, denied, "input_invalid") };
+ }
+ if (descriptor.idempotency === "required" && !invocation.idempotencyKey?.trim()) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "idempotency_key_required",
+ );
+ return { observableResult: this.#denial(invocation.operationId, denied, "input_invalid") };
+ }
+ if (invocation.operationId === "decide_approval" && this.#isSelfApproval(invocation.input)) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "self_approval_conflict",
+ );
+ return { observableResult: this.#denial(invocation.operationId, denied, "policy_denied") };
+ }
+
+ const beforeRevision = this.#adapter.snapshot().revision;
+ try {
+ const extensionIdempotencyKey = descriptor.mockCommandMapping.kind === "mock_extension" &&
+ descriptor.idempotency === "required"
+ ? `${this.#runId}:${invocation.operationId}:${invocation.idempotencyKey!.trim()}`
+ : null;
+ const canonicalInput = extensionIdempotencyKey === null
+ ? null
+ : canonicalJson(invocation.input);
+ const cachedExtension = extensionIdempotencyKey === null
+ ? undefined
+ : this.#state.extensionIdempotency.get(extensionIdempotencyKey);
+ if (cachedExtension !== undefined && cachedExtension.input !== canonicalInput) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "idempotency_key_conflict",
+ );
+ return { observableResult: this.#denial(invocation.operationId, denied, "input_invalid") };
+ }
+ let execution: ExtensionExecution;
+ let resultId: string | null;
+ let extensionRecord: ExtensionIdempotencyRecord | null = null;
+ if (extensionIdempotencyKey !== null) {
+ let idempotencyRecord = cachedExtension;
+ if (idempotencyRecord === undefined) {
+ idempotencyRecord = {
+ input: canonicalInput!,
+ execution: null,
+ ownerId: null,
+ leaseExpiresAtMs: 0,
+ leaseHeartbeat: null,
+ cleanupRetry: null,
+ };
+ this.#state.extensionIdempotency.set(
+ extensionIdempotencyKey,
+ idempotencyRecord,
+ );
+ let executionStarted = false;
+ try {
+ executionStarted = this.#startExtensionExecution(
+ extensionIdempotencyKey,
+ idempotencyRecord,
+ descriptor,
+ invocation,
+ );
+ } catch (error) {
+ // Acquisition has not handed an execution promise to this record.
+ // Do not let a transient store failure strand the local key; any
+ // durable lease that committed before the failure still gates the
+ // next attempt through the normal recovery path.
+ this.#state.extensionIdempotency.delete(extensionIdempotencyKey);
+ throw error;
+ }
+ if (!executionStarted) {
+ this.#state.extensionIdempotency.delete(extensionIdempotencyKey);
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "idempotency_recovery_in_flight",
+ );
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ denied,
+ "operation_unsupported",
+ ),
+ };
+ }
+ }
+ if (idempotencyRecord.execution === null) {
+ let durableState = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ let durableExtension = durableState?.extensions.find(
+ (extension) => extension.key === extensionIdempotencyKey,
+ );
+ if (durableState === null || durableExtension === undefined) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "idempotency_recovery_in_flight",
+ );
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ denied,
+ "operation_unsupported",
+ ),
+ };
+ }
+ if (durableExtension.status === "indeterminate") {
+ const recovered = await this.#resolveExpiredExtension(invocation);
+ if (!recovered) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ durableExtension.reason,
+ );
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ denied,
+ "operation_unsupported",
+ ),
+ };
+ }
+ durableState = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ durableExtension = durableState?.extensions.find(
+ (extension) => extension.key === extensionIdempotencyKey,
+ );
+ if (durableState === null || durableExtension?.status !== "completed") {
+ throw new Error("indeterminate extension recovery did not publish a durable receipt");
+ }
+ }
+ if (durableExtension.status === "pending") {
+ if ((durableExtension.leaseExpiresAtMs ?? 0) > this.#now()) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "idempotency_recovery_in_flight",
+ );
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ denied,
+ "operation_unsupported",
+ ),
+ };
+ }
+ if (
+ durableExtension.phase === "executing"
+ ) {
+ const recovered = await this.#resolveExpiredExtension(
+ invocation,
+ );
+ if (!recovered) {
+ this.#markExpiredExtensionIndeterminate(
+ extensionIdempotencyKey,
+ idempotencyRecord,
+ );
+ }
+ durableState = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ durableExtension = durableState?.extensions.find(
+ (extension) => extension.key === extensionIdempotencyKey,
+ );
+ if (durableExtension?.status === "indeterminate") {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ durableExtension.reason,
+ );
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ denied,
+ "operation_unsupported",
+ ),
+ };
+ }
+ if (durableState === null || durableExtension?.status !== "completed") {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "idempotency_recovery_in_flight",
+ );
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ denied,
+ "operation_unsupported",
+ ),
+ };
+ }
+ }
+ }
+ if (durableExtension.status === "pending") {
+ if (!this.#startExtensionExecution(
+ extensionIdempotencyKey,
+ idempotencyRecord,
+ descriptor,
+ invocation,
+ )) {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "idempotency_recovery_in_flight",
+ );
+ return {
+ observableResult: this.#denial(
+ invocation.operationId,
+ denied,
+ "operation_unsupported",
+ ),
+ };
+ }
+ } else {
+ if (durableExtension.input !== idempotencyRecord.input) {
+ throw new Error("durable extension input changed during recovery");
+ }
+ const completed = {
+ resultId: durableExtension.resultId,
+ value: structuredClone(durableExtension.execution),
+ };
+ const durableResult = durableState.operationResults[completed.resultId];
+ if (durableResult === undefined) {
+ throw new Error("durable extension receipt omitted its operation result");
+ }
+ idempotencyRecord.completed = structuredClone(completed);
+ idempotencyRecord.execution = Promise.resolve(structuredClone(completed));
+ idempotencyRecord.ownerId = null;
+ idempotencyRecord.leaseExpiresAtMs = 0;
+ this.#state.operationResults.set(
+ completed.resultId,
+ structuredClone(durableResult),
+ );
+ this.#state.resultSequence = Math.max(
+ this.#state.resultSequence,
+ durableState.resultSequence,
+ );
+ }
+ }
+ if (idempotencyRecord.execution === null) {
+ throw new Error("durable extension execution was not acquired");
+ }
+ const completed = await idempotencyRecord.execution;
+ execution = structuredClone(completed.value);
+ resultId = completed.resultId;
+ extensionRecord = idempotencyRecord;
+ } else {
+ execution = await this.#execute(descriptor, invocation);
+ resultId = execution.commandResult?.commandId ?? null;
+ }
+ let observableValue = redactForBoundary(descriptor, execution.value, "output");
+ let observableCommandResult = execution.commandResult === null
+ ? null
+ : redactForBoundary(descriptor, toJsonValue(execution.commandResult), "output") as CapabilityToolSuccess["commandResult"];
+ if (
+ extensionIdempotencyKey !== null &&
+ extensionRecord !== null &&
+ extensionRecord.completed === undefined
+ ) {
+ if (resultId === null) {
+ throw new Error("durable extension execution omitted its result id");
+ }
+ const completed = {
+ resultId,
+ value: structuredClone(execution),
+ };
+ const published = await this.#completeExtensionExecution(
+ extensionIdempotencyKey,
+ extensionRecord,
+ completed,
+ observableValue,
+ );
+ if (published === null) {
+ // The extension already ran. Retain and renew its durable ownership
+ // so another runtime cannot execute it again while this runtime can
+ // still publish the exact completed receipt on an identical retry.
+ try {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const extension = durable?.extensions.find(
+ (candidate) => candidate.key === extensionIdempotencyKey,
+ );
+ if (
+ durable === null ||
+ extension?.status !== "pending" ||
+ extension.ownerId !== extensionRecord.ownerId
+ ) {
+ this.#stopExtensionExecutionLease(extensionRecord);
+ }
+ } catch {
+ // A read failure cannot prove ownership was lost. Keep renewing it.
+ }
+ throw new Error("durable extension execution lease was superseded");
+ }
+ // A trusted recovery may publish the durable receipt while this
+ // executor is still completing after heartbeat-store failures. Adopt
+ // that receipt instead of turning already-completed work into a
+ // denial; the durable key and canonical input were verified below.
+ resultId = published.resultId;
+ execution = structuredClone(published.value);
+ observableValue = structuredClone(published.observableValue);
+ observableCommandResult = execution.commandResult === null
+ ? null
+ : redactForBoundary(
+ descriptor,
+ toJsonValue(execution.commandResult),
+ "output",
+ ) as CapabilityToolSuccess["commandResult"];
+ completed.resultId = published.resultId;
+ completed.value = structuredClone(published.value);
+ this.#stopExtensionExecutionLease(extensionRecord);
+ extensionRecord.completed = completed;
+ extensionRecord.execution = Promise.resolve(
+ structuredClone(extensionRecord.completed),
+ );
+ extensionRecord.ownerId = null;
+ extensionRecord.leaseExpiresAtMs = 0;
+ }
+ const finalAuthorization = this.#authorization.attachStateChange(
+ authorization.sequence,
+ beforeRevision,
+ this.#adapter.snapshot().revision,
+ execution.entityRefs,
+ );
+ let sequencedResultPersisted = false;
+ if (extensionIdempotencyKey === null && resultId === null) {
+ resultId = this.#persistSequencedOperationResult(observableValue);
+ sequencedResultPersisted = true;
+ }
+ if (resultId === null) throw new Error("semantic tool result id was not allocated");
+ this.#state.operationResults.set(resultId, structuredClone(observableValue));
+ if (extensionIdempotencyKey === null && !sequencedResultPersisted) {
+ this.#persistState();
+ }
+ const success: CapabilityToolSuccess = {
+ schema: "paperclip.capability.tool-result.v1",
+ ok: true,
+ operationId: invocation.operationId,
+ operationResultId: resultId,
+ value: observableValue,
+ commandResult: observableCommandResult,
+ authorization: finalAuthorization,
+ };
+ const observableResult = deepFreeze(success);
+ if (!includeModelResult) return { observableResult };
+ const modelResult: CapabilityModelToolSuccess = deepFreeze({
+ schema: "paperclip.capability.model-tool-result.v1",
+ ok: true,
+ operationId: invocation.operationId,
+ operationResultId: resultId,
+ value: structuredClone(execution.value),
+ commandResult: execution.commandResult === null ? null : structuredClone(execution.commandResult),
+ authorization: finalAuthorization,
+ });
+ return { observableResult, modelResult };
+ } catch {
+ const denied = this.#authorization.denyInvocation(
+ invocation.operationId,
+ context,
+ "mock_operation_rejected",
+ );
+ return { observableResult: this.#denial(invocation.operationId, denied, "operation_unsupported") };
+ }
+ }
+
+ #nextResultId(): string {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ this.#state.resultSequence = Math.max(
+ this.#state.resultSequence,
+ durable?.resultSequence ?? 0,
+ );
+ return `tool-result-${++this.#state.resultSequence}`;
+ }
+
+ #adoptReconciledExtension(
+ key: string,
+ input: string,
+ resultId: string,
+ value: ExtensionExecution,
+ ): void {
+ const completed = { resultId, value: structuredClone(value) };
+ const existing = this.#state.extensionIdempotency.get(key);
+ if (existing) this.#stopExtensionExecutionLease(existing);
+ this.#state.extensionIdempotency.set(key, {
+ input,
+ execution: Promise.resolve(structuredClone(completed)),
+ ownerId: null,
+ leaseExpiresAtMs: 0,
+ leaseHeartbeat: null,
+ cleanupRetry: null,
+ completed,
+ });
+ this.#state.operationResults.set(resultId, structuredClone(value.value));
+ }
+
+ async #resolveExpiredExtension(
+ invocation: CapabilityToolInvocation,
+ ): Promise<boolean> {
+ const idempotencyKey = invocation.idempotencyKey?.trim();
+ if (!idempotencyKey) return false;
+ const recoveryInput = {
+ operationId: invocation.operationId,
+ input: structuredClone(invocation.input) as Record<string, CapabilityJsonValue>,
+ idempotencyKey,
+ };
+ const key = `${this.#runId}:${invocation.operationId}:${idempotencyKey}`;
+ const extension = this.#adapter
+ .loadSemanticToolRuntime(this.#runId)
+ ?.extensions.find((candidate) => candidate.key === key);
+ let observed: Pick<
+ CapabilityExpiredExtensionReceipt,
+ "value" | "entityRefs"
+ > | null =
+ extension?.status === "pending" &&
+ extension.phase === "executing" &&
+ extension.input === canonicalJson(invocation.input) &&
+ extension.preparedExecution !== undefined
+ ? {
+ value: structuredClone(extension.preparedExecution.value),
+ entityRefs: [...extension.preparedExecution.entityRefs],
+ }
+ : null;
+ if (observed === null && this.#resolveExpiredExtensionReceipt !== undefined) {
+ observed = await this.#resolveExpiredExtensionReceipt(recoveryInput);
+ }
+ if (observed === null) {
+ const descriptor = capabilitySemanticTool(invocation.operationId);
+ if (
+ descriptor?.mockCommandMapping.kind === "mock_extension" &&
+ descriptor.idempotency === "required" &&
+ REPLAY_SAFE_LEGACY_MOCK_EXTENSIONS.has(
+ descriptor.mockCommandMapping.extension,
+ )
+ ) {
+ // Snapshots written before preparedExecution existed can still be
+ // recovered without replaying an external mutation. Every idempotent
+ // extension in this explicit allowlist is a pure fixture computation.
+ // Secret reads and mutable state-derived exports are deliberately
+ // excluded: neither can recover the exact value observed by the lost
+ // executor without a prepared or authoritative receipt.
+ const reconstructed = this.#prepareBuiltInExtensionExecution(
+ descriptor,
+ asObject(invocation.input),
+ );
+ observed = {
+ value: structuredClone(reconstructed.value),
+ entityRefs: [...reconstructed.entityRefs],
+ };
+ }
+ }
+ if (observed === null) return false;
+ this.reconcileExpiredExtensionReceipt({
+ ...recoveryInput,
+ value: structuredClone(observed.value),
+ ...(observed.entityRefs === undefined
+ ? {}
+ : { entityRefs: [...observed.entityRefs] }),
+ });
+ return true;
+ }
+
+ #markExpiredExtensionIndeterminate(
+ key: string,
+ record: ExtensionIdempotencyRecord,
+ ): void {
+ for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const extension = durable?.extensions.find((candidate) => candidate.key === key);
+ if (
+ durable === null ||
+ extension === undefined ||
+ extension.status !== "pending" ||
+ extension.input !== record.input ||
+ extension.phase !== "executing" ||
+ (extension.leaseExpiresAtMs ?? 0) > this.#now()
+ ) {
+ return;
+ }
+ const replacement = structuredClone(durable);
+ replacement.extensions = replacement.extensions.map((candidate) =>
+ candidate.key === key
+ ? {
+ key,
+ input: record.input,
+ status: "indeterminate" as const,
+ reason: "idempotency_receipt_unavailable" as const,
+ }
+ : candidate,
+ );
+ if (!this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) continue;
+ this.#stopExtensionExecutionLease(record);
+ record.ownerId = null;
+ record.leaseExpiresAtMs = 0;
+ record.recoveryFailure = "idempotency_receipt_unavailable";
+ return;
+ }
+ }
+
+ #startExtensionExecution(
+ key: string,
+ record: ExtensionIdempotencyRecord,
+ descriptor: CapabilitySemanticToolDescriptor,
+ invocation: CapabilityToolInvocation,
+ ): boolean {
+ const ownerId = randomUUID();
+ let leaseExpiresAtMs = 0;
+ let acquired = false;
+ for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const existing = durable?.extensions.find((candidate) => candidate.key === key);
+ if (
+ existing !== undefined &&
+ (existing.status !== "pending" ||
+ existing.input !== record.input ||
+ existing.phase === "executing" ||
+ (existing.leaseExpiresAtMs ?? 0) > this.#now())
+ ) {
+ return false;
+ }
+ leaseExpiresAtMs = this.#now() + EXTENSION_EXECUTION_LEASE_MS;
+ const replacement: CapabilitySemanticToolRuntimeSnapshot = durable === null
+ ? {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: this.#state.resultSequence,
+ operationResults: Object.fromEntries(this.#state.operationResults),
+ extensions: [],
+ }
+ : structuredClone(durable);
+ const pending = {
+ key,
+ input: record.input,
+ status: "pending" as const,
+ ownerId,
+ leaseExpiresAtMs,
+ phase: "reserved" as const,
+ };
+ const existingIndex = replacement.extensions.findIndex(
+ (candidate) => candidate.key === key,
+ );
+ if (existingIndex === -1) replacement.extensions.push(pending);
+ else replacement.extensions[existingIndex] = pending;
+ if (this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) {
+ this.#state.resultSequence = Math.max(
+ this.#state.resultSequence,
+ replacement.resultSequence,
+ );
+ acquired = true;
+ break;
+ }
+ }
+ if (!acquired) return false;
+ if (record.cleanupRetry !== null) clearTimeout(record.cleanupRetry);
+ record.cleanupRetry = null;
+ record.ownerId = ownerId;
+ record.leaseExpiresAtMs = leaseExpiresAtMs;
+ // Deterministic package-local mock extensions can persist their exact
+ // result before crossing the executing boundary. Async/custom effects do
+ // not guess a receipt and retain the external reconciliation boundary.
+ const preparedExecution = this.#prepareBuiltInExtensionExecution(
+ descriptor,
+ asObject(invocation.input),
+ );
+ let executionStarted = false;
+ try {
+ executionStarted = this.#markExtensionExecutionStarted(
+ key,
+ record,
+ preparedExecution,
+ );
+ } catch {
+ executionStarted = false;
+ }
+ if (!executionStarted) {
+ this.#scheduleFailedExtensionCleanup(key, record);
+ return false;
+ }
+ const execution = Promise.resolve(structuredClone(preparedExecution)).then((value) => ({
+ resultId: value.commandResult?.commandId ?? this.#nextResultId(),
+ value,
+ }));
+ record.execution = execution;
+ record.leaseHeartbeat = setInterval(() => {
+ try {
+ this.#renewExtensionExecutionLease(key, record);
+ } catch {
+ // A transient durable-store failure does not prove that ownership was
+ // lost. Keep the execution alive and retry at the next heartbeat; the
+ // completion CAS still validates the exact owner before publishing.
+ }
+ }, EXTENSION_EXECUTION_HEARTBEAT_MS);
+ record.leaseHeartbeat.unref();
+ void execution.catch(() => {
+ record.execution = null;
+ this.#scheduleFailedExtensionCleanup(key, record);
+ });
+ return true;
+ }
+
+ #scheduleFailedExtensionCleanup(
+ key: string,
+ record: ExtensionIdempotencyRecord,
+ ): void {
+ if (record.cleanupRetry !== null) return;
+ const failedOwnerId = record.ownerId;
+ if (failedOwnerId === null) return;
+ const cleanup = () => {
+ record.cleanupRetry = null;
+ if (this.#removeFailedExtensionLease(key, failedOwnerId)) {
+ if (record.ownerId === failedOwnerId) {
+ this.#stopExtensionExecutionLease(record);
+ if (this.#state.extensionIdempotency.get(key) === record) {
+ this.#state.extensionIdempotency.delete(key);
+ }
+ }
+ return;
+ }
+ if (record.ownerId !== failedOwnerId) return;
+ record.cleanupRetry = setTimeout(cleanup, 1_000);
+ record.cleanupRetry.unref();
+ };
+ cleanup();
+ }
+
+ #removeFailedExtensionLease(
+ key: string,
+ failedOwnerId: string,
+ ): boolean {
+ try {
+ for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
+ const current = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const currentExtension = current?.extensions.find(
+ (candidate) => candidate.key === key,
+ );
+ if (
+ current === null ||
+ currentExtension?.status !== "pending" ||
+ currentExtension.ownerId !== failedOwnerId
+ ) {
+ return true;
+ }
+ const withoutFailedLease = structuredClone(current);
+ withoutFailedLease.extensions = withoutFailedLease.extensions.filter(
+ (candidate) => candidate.key !== key,
+ );
+ if (this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ current,
+ withoutFailedLease,
+ )) return true;
+ }
+ } catch {
+ return false;
+ }
+ return false;
+ }
+
+ #markExtensionExecutionStarted(
+ key: string,
+ record: ExtensionIdempotencyRecord,
+ preparedExecution: ExtensionExecution | undefined,
+ ): boolean {
+ for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const extension = durable?.extensions.find((candidate) => candidate.key === key);
+ if (
+ durable === null ||
+ extension?.status !== "pending" ||
+ extension.ownerId !== record.ownerId ||
+ extension.phase === "executing"
+ ) {
+ return false;
+ }
+ const replacement = structuredClone(durable);
+ const leaseExpiresAtMs = this.#now() + EXTENSION_EXECUTION_LEASE_MS;
+ replacement.extensions = replacement.extensions.map((candidate) =>
+ candidate.key === key
+ ? {
+ ...candidate,
+ phase: "executing" as const,
+ leaseExpiresAtMs,
+ ...(preparedExecution === undefined
+ ? {}
+ : { preparedExecution: structuredClone(preparedExecution) }),
+ }
+ : candidate,
+ );
+ if (!this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) continue;
+ record.leaseExpiresAtMs = leaseExpiresAtMs;
+ return true;
+ }
+ return false;
+ }
+
+ #renewExtensionExecutionLease(
+ key: string,
+ record: ExtensionIdempotencyRecord,
+ ): boolean {
+ if (record.ownerId === null) return false;
+ for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const extension = durable?.extensions.find((candidate) => candidate.key === key);
+ if (durable === null || extension?.status !== "pending" ||
+ extension.ownerId !== record.ownerId) return false;
+ const replacement = structuredClone(durable);
+ const leaseExpiresAtMs = this.#now() + EXTENSION_EXECUTION_LEASE_MS;
+ replacement.extensions = replacement.extensions.map((candidate) =>
+ candidate.key === key
+ ? { ...candidate, leaseExpiresAtMs }
+ : candidate,
+ );
+ if (!this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) continue;
+ record.leaseExpiresAtMs = leaseExpiresAtMs;
+ return true;
+ }
+ return false;
+ }
+
+ async #completeExtensionExecution(
+ key: string,
+ record: ExtensionIdempotencyRecord,
+ completed: { resultId: string; value: ExtensionExecution },
+ observableValue: CapabilityJsonValue,
+ ): Promise<{
+ resultId: string;
+ value: ExtensionExecution;
+ observableValue: CapabilityJsonValue;
+ } | null> {
+ // Execution already happened. Retry only the durable completion merge so
+ // a lease heartbeat or unrelated snapshot update cannot discard its
+ // receipt or cause the operation to execute again.
+ for (let attempt = 0; attempt < RUNTIME_COMPLETION_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const extension = durable?.extensions.find((candidate) => candidate.key === key);
+ if (durable === null || extension === undefined) return null;
+ if (extension.status === "completed") {
+ const durableResult = durable.operationResults[extension.resultId];
+ return extension.input === record.input && durableResult !== undefined
+ ? {
+ resultId: extension.resultId,
+ value: structuredClone(extension.execution),
+ observableValue: structuredClone(durableResult),
+ }
+ : null;
+ }
+ if (extension.status !== "pending" || record.ownerId === null ||
+ extension.ownerId !== record.ownerId) {
+ return null;
+ }
+ const replacement = structuredClone(durable);
+ const existingResult = replacement.operationResults[completed.resultId];
+ if (
+ existingResult !== undefined &&
+ canonicalJson(existingResult) !== canonicalJson(observableValue)
+ ) {
+ replacement.resultSequence = Math.max(
+ replacement.resultSequence,
+ this.#state.resultSequence,
+ ) + 1;
+ completed.resultId = `tool-result-${replacement.resultSequence}`;
+ this.#state.resultSequence = replacement.resultSequence;
+ }
+ replacement.resultSequence = Math.max(
+ replacement.resultSequence,
+ this.#state.resultSequence,
+ );
+ replacement.operationResults[completed.resultId] = structuredClone(observableValue);
+ replacement.extensions = replacement.extensions.map((candidate) =>
+ candidate.key === key
+ ? {
+ key,
+ input: record.input,
+ status: "completed" as const,
+ resultId: completed.resultId,
+ execution: structuredClone(completed.value),
+ }
+ : candidate,
+ );
+ if (this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) {
+ return {
+ resultId: completed.resultId,
+ value: structuredClone(completed.value),
+ observableValue: structuredClone(observableValue),
+ };
+ }
+ if ((attempt + 1) % RUNTIME_PERSIST_CAS_ATTEMPTS === 0) {
+ // Yield so lease heartbeats and other runtimes can make progress. The
+ // bounded outer loop prevents a broken store from pinning invocation
+ // completion forever; the fulfilled local execution remains available
+ // for an exact publication retry without re-executing the extension.
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ }
+ }
+ return null;
+ }
+
+ #stopExtensionExecutionLease(record: ExtensionIdempotencyRecord): void {
+ if (record.leaseHeartbeat !== null) clearInterval(record.leaseHeartbeat);
+ record.leaseHeartbeat = null;
+ if (record.cleanupRetry !== null) clearTimeout(record.cleanupRetry);
+ record.cleanupRetry = null;
+ }
+
+ #restoreState(
+ snapshot: CapabilitySemanticToolRuntimeSnapshot | null,
+ ): CapabilitySemanticRuntimeState {
+ if (snapshot === null) {
+ return {
+ extensionIdempotency: new Map(),
+ operationResults: new Map(),
+ resultSequence: 0,
+ };
+ }
+ const extensionIdempotency = new Map<string, ExtensionIdempotencyRecord>();
+ for (const extension of snapshot.extensions) {
+ if (extension.status === "pending") {
+ extensionIdempotency.set(extension.key, {
+ input: extension.input,
+ execution: null,
+ ownerId: extension.ownerId ?? null,
+ leaseExpiresAtMs: extension.leaseExpiresAtMs ?? 0,
+ leaseHeartbeat: null,
+ cleanupRetry: null,
+ });
+ continue;
+ }
+ if (extension.status === "indeterminate") {
+ extensionIdempotency.set(extension.key, {
+ input: extension.input,
+ execution: null,
+ ownerId: null,
+ leaseExpiresAtMs: 0,
+ leaseHeartbeat: null,
+ cleanupRetry: null,
+ recoveryFailure: extension.reason,
+ });
+ continue;
+ }
+ const completed = {
+ resultId: extension.resultId,
+ value: structuredClone(extension.execution),
+ };
+ extensionIdempotency.set(extension.key, {
+ input: extension.input,
+ execution: Promise.resolve(structuredClone(completed)),
+ ownerId: null,
+ leaseExpiresAtMs: 0,
+ leaseHeartbeat: null,
+ cleanupRetry: null,
+ completed,
+ });
+ }
+ return {
+ extensionIdempotency,
+ operationResults: new Map(
+ Object.entries(snapshot.operationResults).map(([key, value]) => [
+ key,
+ structuredClone(value),
+ ]),
+ ),
+ resultSequence: snapshot.resultSequence,
+ };
+ }
+
+ #localSnapshot(): CapabilitySemanticToolRuntimeSnapshot {
+ return {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: this.#state.resultSequence,
+ operationResults: Object.fromEntries(
+ [...this.#state.operationResults].map(([key, value]) => [
+ key,
+ structuredClone(value),
+ ]),
+ ),
+ extensions: [...this.#state.extensionIdempotency]
+ .map(([key, record]) =>
+ record.completed === undefined
+ ? record.recoveryFailure === undefined
+ ? {
+ key,
+ input: record.input,
+ status: "pending" as const,
+ ...(record.ownerId === null ? {} : { ownerId: record.ownerId }),
+ leaseExpiresAtMs: record.leaseExpiresAtMs,
+ }
+ : {
+ key,
+ input: record.input,
+ status: "indeterminate" as const,
+ reason: record.recoveryFailure,
+ }
+ : {
+ key,
+ input: record.input,
+ status: "completed" as const,
+ resultId: record.completed.resultId,
+ execution: structuredClone(record.completed.value),
+ },
+ ),
+ };
+ }
+
+ #persistSequencedOperationResult(value: CapabilityJsonValue): string {
+ for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const replacement = durable === null
+ ? this.#localSnapshot()
+ : structuredClone(durable);
+ const sequence = Math.max(
+ replacement.resultSequence,
+ this.#state.resultSequence,
+ ) + 1;
+ const resultId = `tool-result-${sequence}`;
+ replacement.resultSequence = sequence;
+ replacement.operationResults[resultId] = structuredClone(value);
+ if (!this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) continue;
+ this.#state.resultSequence = sequence;
+ this.#state.operationResults.set(resultId, structuredClone(value));
+ return resultId;
+ }
+ throw new Error("durable semantic tool runtime changed during result allocation");
+ }
+
+ #persistState(): void {
+ const localSnapshot = this.#localSnapshot();
+ for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
+ const durable = this.#adapter.loadSemanticToolRuntime(this.#runId);
+ const replacement = durable === null
+ ? structuredClone(localSnapshot)
+ : structuredClone(durable);
+ replacement.resultSequence = Math.max(
+ replacement.resultSequence,
+ localSnapshot.resultSequence,
+ );
+ for (const [resultId, value] of Object.entries(localSnapshot.operationResults)) {
+ const existing = replacement.operationResults[resultId];
+ if (existing !== undefined && canonicalJson(existing) !== canonicalJson(value)) {
+ throw new Error("durable semantic tool result id was reused");
+ }
+ replacement.operationResults[resultId] = structuredClone(value);
+ }
+ // Extension leases and completed receipts use their own CAS path. A
+ // general invocation must preserve the latest durable copy instead of
+ // replacing it with a stale restored adapter snapshot.
+ if (this.#adapter.compareAndSwapSemanticToolRuntime(
+ this.#runId,
+ durable,
+ replacement,
+ )) {
+ this.#state.resultSequence = replacement.resultSequence;
+ return;
+ }
+ }
+ throw new Error("durable semantic tool runtime changed during persistence");
+ }
+
+ async #execute(
+ descriptor: CapabilitySemanticToolDescriptor,
+ invocation: CapabilityToolInvocation,
+ ): Promise<{ value: CapabilityJsonValue; commandResult: CapabilityToolSuccess["commandResult"]; entityRefs: string[] }> {
+ const input = asObject(invocation.input);
+ switch (descriptor.mockCommandMapping.kind) {
+ case "context_read":
+ return { value: toJsonValue(this.#adapter.context(this.#runId)), commandResult: null, entityRefs: [] };
+ case "snapshot_read":
+ return {
+ value: this.#snapshotProjection(descriptor.mockCommandMapping.projection, input),
+ commandResult: null,
+ entityRefs: [],
+ };
+ case "operation_result": {
+ const id = requireString(input.operationResultId);
+ const result = this.#state.operationResults.get(id);
+ if (result === undefined) throw new Error("operation result is not available");
+ return { value: structuredClone(result), commandResult: null, entityRefs: [] };
+ }
+ case "semantic_command": {
+ const command = commandForOperation(descriptor.operationId, input);
+ const envelope: CapabilityCommandEnvelope = {
+ runId: this.#runId,
+ idempotencyKey: invocation.idempotencyKey!,
+ command,
+ };
+ const commandResult = await this.#adapter.applyCommand(envelope);
+ return {
+ value: toJsonValue(commandResult),
+ commandResult,
+ entityRefs: commandResult.entityRefs,
+ };
+ }
+ case "mock_extension":
+ return this.#executeExtension(descriptor, input);
+ }
+ }
+
+ async #executeExtension(
+ descriptor: CapabilitySemanticToolDescriptor,
+ input: Record<string, CapabilityJsonValue>,
+ ): Promise<ExtensionExecution> {
+ const extension = descriptor.mockCommandMapping.kind === "mock_extension"
+ ? descriptor.mockCommandMapping.extension
+ : "";
+ if (extension === "secrets.value") {
+ // Secret reads are explicitly non-idempotent and never enter the durable
+ // extension lease path, which also keeps secret values out of receipts.
+ const name = requireString(input.name);
+ const value = await this.#resolveSecretValue?.(name);
+ if (value === null || value === undefined) throw new Error("secret is not available");
+ return { value: { name, value }, commandResult: null, entityRefs: [] };
+ }
+ return this.#prepareBuiltInExtensionExecution(descriptor, input);
+ }
+
+ #prepareBuiltInExtensionExecution(
+ descriptor: CapabilitySemanticToolDescriptor,
+ input: Record<string, CapabilityJsonValue>,
+ ): ExtensionExecution {
+ switch (descriptor.mockCommandMapping.kind === "mock_extension"
+ ? descriptor.mockCommandMapping.extension
+ : "") {
+ case "discovery.projects":
+ case "discovery.goals":
+ case "cases.list":
+ case "routines.list":
+ case "company_skills.list":
+ case "secrets.metadata":
+ return { value: [], commandResult: null, entityRefs: [] };
+ case "portability.export": {
+ const snapshot = this.#adapter.snapshot();
+ return {
+ value: {
+ schema: "paperclip.capability.mock-export.v1",
+ company: { id: snapshot.company.id, name: snapshot.company.name },
+ taskCount: snapshot.tasks.length,
+ actorCount: snapshot.actors.length,
+ },
+ commandResult: null,
+ entityRefs: [],
+ };
+ }
+ case "company_skills.sync":
+ return {
+ value: { synced: true },
+ commandResult: null,
+ entityRefs: [],
+ };
+ case "routines.manage":
+ return {
+ value: { managed: true },
+ commandResult: null,
+ entityRefs: [],
+ };
+ case "cases.upsert":
+ return {
+ value: {
+ key: requireString(input.key),
+ body: requireString(input.body),
+ upserted: true,
+ },
+ commandResult: null,
+ entityRefs: [],
+ };
+ case "company.admin":
+ return {
+ value: {
+ action: requireString(input.action),
+ applied: true,
+ },
+ commandResult: null,
+ entityRefs: [],
+ };
+ case "test.generic_api":
+ return {
+ value: {
+ status: 200,
+ body: null,
+ warning: "TEST-ONLY mock request; no control plane or network was contacted.",
+ },
+ commandResult: null,
+ entityRefs: [],
+ };
+ case "secrets.value":
+ throw new Error("non-idempotent secret reads cannot enter durable extension execution");
+ default:
+ throw new Error("mock extension is not implemented");
+ }
+ }
+
+ #snapshotProjection(
+ projection: string,
+ input: Record<string, CapabilityJsonValue>,
+ ): CapabilityJsonValue {
+ const snapshot = this.#adapter.snapshot();
+ const context = this.#adapter.context(this.#runId);
+ switch (projection) {
+ case "active_task_history":
+ return toJsonValue(snapshot.comments.filter((comment) => comment.taskId === context.activeTask.id));
+ case "active_task_documents":
+ return toJsonValue(snapshot.documents
+ .filter((document) => document.taskId === context.activeTask.id)
+ .map(({ id, key, title, format, latestRevisionId, revisions }) => ({
+ id, key, title, format, latestRevisionId, revisionCount: revisions.length,
+ })));
+ case "active_task_document": {
+ const key = requireString(input.key);
+ const document = snapshot.documents.find(
+ (candidate) => candidate.taskId === context.activeTask.id && candidate.key === key,
+ );
+ if (document === undefined) throw new Error("document is not available");
+ return toJsonValue(document);
+ }
+ case "active_task_document_revisions": {
+ const key = requireString(input.key);
+ const document = snapshot.documents.find(
+ (candidate) => candidate.taskId === context.activeTask.id && candidate.key === key,
+ );
+ if (document === undefined) throw new Error("document is not available");
+ return toJsonValue(document.revisions);
+ }
+ case "company_tasks": {
+ const query = typeof input.query === "string" ? input.query.toLowerCase() : "";
+ const status = typeof input.status === "string" ? input.status : null;
+ return toJsonValue(snapshot.tasks.filter(
+ (task) =>
+ (query === "" || `${task.identifier} ${task.title} ${task.description ?? ""}`.toLowerCase().includes(query)) &&
+ (status === null || task.status === status),
+ ));
+ }
+ case "company_actors":
+ return toJsonValue(snapshot.actors.map(({ id, companyId, name, role, status }) => ({ id, companyId, name, role, status })));
+ case "company_approvals":
+ return toJsonValue(snapshot.approvals);
+ case "active_task_workspace":
+ return toJsonValue(snapshot.workspaceServices.filter((service) => service.taskId === context.activeTask.id));
+ default:
+ throw new Error("snapshot projection is not implemented");
+ }
+ }
+
+ #context(): CapabilityToolAuthorizationContext {
+ const runContext = this.#adapter.context(this.#runId);
+ return {
+ runId: this.#runId,
+ actor: {
+ id: runContext.actor.id,
+ role: runContext.actor.role,
+ capabilityGrants: [...runContext.actor.capabilityGrants],
+ },
+ task: {
+ id: runContext.activeTask.id,
+ assigneeActorId: runContext.activeTask.assigneeActorId,
+ workMode: runContext.activeTask.workMode,
+ },
+ scenarioGrants: [...this.#scenarioGrants],
+ policy: this.#policy,
+ };
+ }
+
+ #isSelfApproval(input: CapabilityJsonValue): boolean {
+ const approvalId = asObject(input).approvalId;
+ if (typeof approvalId !== "string") return false;
+ const actorId = this.#adapter.context(this.#runId).actor.id;
+ const approval = this.#adapter.snapshot().approvals.find((candidate) => candidate.id === approvalId);
+ return approval?.requestedByActorId === actorId;
+ }
+
+ #denial(
+ operationId: string,
+ authorization: CapabilityAuthorizationRecord,
+ code: CapabilityPolicyDenial["error"]["code"],
+ ): CapabilityPolicyDenial {
+ return deepFreeze({
+ schema: "paperclip.capability.tool-result.v1",
+ ok: false,
+ error: {
+ code,
+ message: code === "operation_absent"
+ ? "The requested semantic operation is not available."
+ : "The requested semantic operation was not executed.",
+ operationId,
+ reason: authorization.reason,
+ },
+ authorization,
+ });
+ }
+}
+
+function commandForOperation(
+ operationId: string,
+ input: Record<string, CapabilityJsonValue>,
+): CapabilitySemanticCommand {
+ switch (operationId) {
+ case "report_progress":
+ case "answer_status_question":
+ return { kind: "report_progress", body: requireString(input.body) };
+ case "finish_task":
+ return { kind: "finish_task", summary: requireString(input.summary) };
+ case "block_task":
+ return {
+ kind: "block_task",
+ reason: requireString(input.reason),
+ blockedByTaskIds: optionalStringArray(input.blockedByTaskIds),
+ };
+ case "request_review":
+ return { kind: "request_review", summary: requireString(input.summary) };
+ case "write_document":
+ return {
+ kind: "write_document",
+ key: requireString(input.key),
+ title: requireString(input.title),
+ body: requireString(input.body, true),
+ baseRevisionId: input.baseRevisionId === null ? null : requireString(input.baseRevisionId),
+ changeSummary: typeof input.changeSummary === "string" ? input.changeSummary : undefined,
+ };
+ case "request_human_input":
+ return {
+ kind: "request_human_input",
+ interactionKind: requireString(input.interactionKind) as never,
+ title: requireString(input.title),
+ prompt: requireString(input.prompt),
+ payload: input.payload,
+ targetRevisionId: input.targetRevisionId === null || input.targetRevisionId === undefined
+ ? input.targetRevisionId
+ : requireString(input.targetRevisionId),
+ continuationPolicy: requireString(input.continuationPolicy) as never,
+ };
+ case "register_deliverable":
+ return {
+ kind: "register_deliverable",
+ filename: requireString(input.filename),
+ contentType: requireString(input.contentType),
+ byteSize: input.byteSize as number,
+ sha256: requireString(input.sha256),
+ contentRef: requireString(input.contentRef),
+ title: requireString(input.title),
+ };
+ case "create_task":
+ return {
+ kind: "create_task",
+ title: requireString(input.title),
+ description: typeof input.description === "string" ? input.description : undefined,
+ assigneeActorId: typeof input.assigneeActorId === "string" ? input.assigneeActorId : undefined,
+ priority: typeof input.priority === "string" ? input.priority as never : undefined,
+ blockedByTaskIds: optionalStringArray(input.blockedByTaskIds),
+ };
+ case "set_dependencies":
+ return { kind: "set_dependencies", blockedByTaskIds: optionalStringArray(input.blockedByTaskIds) ?? [] };
+ case "request_approval":
+ return { kind: "request_approval", approvalType: requireString(input.approvalType), payload: input.payload ?? {} };
+ case "decide_approval":
+ return {
+ kind: "decide_approval",
+ approvalId: requireString(input.approvalId),
+ decision: requireString(input.decision) as never,
+ note: requireString(input.note),
+ };
+ case "comment_on_approval":
+ return { kind: "comment_on_approval", approvalId: requireString(input.approvalId), body: requireString(input.body) };
+ case "control_workspace_service":
+ return {
+ kind: "control_workspace_service",
+ serviceId: requireString(input.serviceId),
+ action: requireString(input.action) as never,
+ url: typeof input.url === "string" ? input.url : undefined,
+ };
+ default:
+ throw new Error("semantic command mapping is not implemented");
+ }
+}
+
+export function validateJsonSchema(schema: CapabilityJsonSchema, value: CapabilityJsonValue, path = "$" ): string[] {
+ if (schema.oneOf !== undefined) {
+ return schema.oneOf.some((candidate) => validateJsonSchema(candidate, value, path).length === 0)
+ ? []
+ : [`${path} does not match any allowed shape`];
+ }
+ if (schema.type !== undefined && !matchesType(schema.type, value)) return [`${path} must be ${schema.type}`];
+ if (schema.enum !== undefined && !schema.enum.some((candidate) => JSON.stringify(candidate) === JSON.stringify(value))) {
+ return [`${path} must be an allowed value`];
+ }
+ if (typeof value === "string" && schema.minLength !== undefined && value.length < schema.minLength) {
+ return [`${path} is too short`];
+ }
+ if (typeof value === "number" && schema.minimum !== undefined && value < schema.minimum) {
+ return [`${path} is below the minimum`];
+ }
+ if (Array.isArray(value) && schema.items !== undefined) {
+ return value.flatMap((item, index) => validateJsonSchema(schema.items!, item, `${path}[${index}]`));
+ }
+ if (schema.type === "object" && typeof value === "object" && value !== null && !Array.isArray(value)) {
+ const object = value as Record<string, CapabilityJsonValue>;
+ const issues = (schema.required ?? [])
+ .filter((key) => !(key in object))
+ .map((key) => `${path}.${key} is required`);
+ for (const [key, child] of Object.entries(object)) {
+ const childSchema = schema.properties?.[key];
+ if (childSchema !== undefined) issues.push(...validateJsonSchema(childSchema, child, `${path}.${key}`));
+ else if (schema.additionalProperties === false) issues.push(`${path}.${key} is not allowed`);
+ else if (typeof schema.additionalProperties === "object") {
+ issues.push(...validateJsonSchema(schema.additionalProperties, child, `${path}.${key}`));
+ }
+ }
+ return issues;
+ }
+ return [];
+}
+
+function matchesType(type: NonNullable<CapabilityJsonSchema["type"]>, value: CapabilityJsonValue): boolean {
+ if (Array.isArray(type)) return type.some((candidate) => matchesType(candidate, value));
+ switch (type) {
+ case "null": return value === null;
+ case "array": return Array.isArray(value);
+ case "object": return typeof value === "object" && value !== null && !Array.isArray(value);
+ case "integer": return typeof value === "number" && Number.isSafeInteger(value);
+ default: return typeof value === type;
+ }
+}
+
+function redactForBoundary(
+ descriptor: CapabilitySemanticToolDescriptor,
+ value: CapabilityJsonValue,
+ boundary: CapabilitySemanticToolDescriptor["redaction"][number]["appliesTo"][number],
+): CapabilityJsonValue {
+ let redacted = structuredClone(value);
+ for (const rule of descriptor.redaction) {
+ if (!rule.appliesTo.includes(boundary)) continue;
+ redacted = replaceJsonPath(redacted, rule.path, rule.replacement);
+ }
+ return redacted;
+}
+
+function replaceJsonPath(
+ value: CapabilityJsonValue,
+ path: string,
+ replacement: CapabilityJsonValue,
+): CapabilityJsonValue {
+ if (path === "$") return replacement;
+ if (!path.startsWith("$.")) return value;
+ const segments = path.slice(2).split(".");
+ if (segments.some((segment) => segment.length === 0)) return value;
+
+ const root = structuredClone(value);
+ let cursor: CapabilityJsonValue = root;
+ for (const segment of segments.slice(0, -1)) {
+ if (typeof cursor !== "object" || cursor === null || Array.isArray(cursor)) return root;
+ const next: CapabilityJsonValue | undefined = cursor[segment];
+ if (next === undefined) return root;
+ cursor = next;
+ }
+ if (typeof cursor !== "object" || cursor === null || Array.isArray(cursor)) return root;
+ const leaf = segments.at(-1)!;
+ if (!(leaf in cursor)) return root;
+ cursor[leaf] = replacement;
+ return root;
+}
+
+function optionalStringArray(value: CapabilityJsonValue | undefined): string[] | undefined {
+ if (value === undefined) return undefined;
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) throw new Error("expected string array");
+ return value as string[];
+}
+
+function requireString(value: CapabilityJsonValue | undefined, allowEmpty = false): string {
+ if (typeof value !== "string" || (!allowEmpty && value.length === 0)) throw new Error("expected string");
+ return value;
+}
+
+function asObject(value: CapabilityJsonValue): Record<string, CapabilityJsonValue> {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("expected object input");
+ return value;
+}
+
+function toJsonValue(value: unknown): CapabilityJsonValue {
+ return structuredClone(value) as CapabilityJsonValue;
+}
+
+function canonicalJson(value: CapabilityJsonValue): string {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
+ if (typeof value === "object" && value !== null) {
+ return `{${Object.keys(value).sort().map((key) =>
+ `${JSON.stringify(key)}:${canonicalJson(value[key]!)}`
+ ).join(",")}}`;
+ }
+ return JSON.stringify(value);
+}
+
+function deepFreeze<T>(value: T): T {
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
+ Object.freeze(value);
+ for (const child of Object.values(value)) deepFreeze(child);
+ return value;
+}
+
+class CapabilityModelToolDeliveryImpl implements CapabilityModelToolDelivery {
+ readonly observableResult: CapabilityToolInvocationResult;
+ readonly #modelResult: CapabilityModelToolInvocationResult;
+
+ constructor(
+ observableResult: CapabilityToolInvocationResult,
+ modelResult: CapabilityModelToolInvocationResult,
+ ) {
+ this.observableResult = observableResult;
+ this.#modelResult = modelResult;
+ Object.freeze(this);
+ }
+
+ readModelResult(): CapabilityModelToolInvocationResult {
+ return deepFreeze(structuredClone(this.#modelResult));
+ }
+
+ toJSON(): CapabilityToolInvocationResult {
+ return this.observableResult;
+ }
+}
diff --git a/packages/paperclip-runner/src/tools/capability-semantic-tools.test.ts b/packages/paperclip-runner/src/tools/capability-semantic-tools.test.ts
new file mode 100644
index 0000000000..5a4685a670
--- /dev/null
+++ b/packages/paperclip-runner/src/tools/capability-semantic-tools.test.ts
@@ -0,0 +1,1996 @@
+import { describe, expect, expectTypeOf, it, vi } from "vitest";
+
+import type {
+ CapabilityFixtureApproval,
+ CapabilityFixtureSeed,
+ CapabilityJsonValue,
+ CapabilitySemanticToolRuntimeSnapshot,
+} from "../mock-core/capability-control-plane-types.js";
+import {
+ CapabilityMockControlPlaneAdapter,
+ type CapabilitySemanticToolRuntimeStore,
+} from "../mock-core/capability-mock-control-plane-adapter.js";
+import {
+ CAPABILITY_OPTIONAL_TOOL_CATALOGS,
+ CAPABILITY_SEMANTIC_TOOL_CATALOG,
+ capabilitySemanticTool,
+} from "./capability-semantic-tool-catalog.js";
+import { CapabilitySemanticToolRuntime, validateJsonSchema } from "./capability-semantic-tool-runtime.js";
+import { CapabilityCodexToolBinding, CapabilityFakeAgentToolBinding } from "./capability-tool-bindings.js";
+import {
+ CAPABILITY_CONTROL_PLANE_OWNED_OPERATION_IDS,
+ type CapabilityModelToolSuccess,
+ type CapabilityToolSuccess,
+} from "./capability-semantic-tool-types.js";
+
+const OPEN = {
+ identity: {
+ runId: "run-tools",
+ sessionId: "session-tools",
+ companyId: "company-1",
+ issueId: "task-1",
+ agentId: "actor-1",
+ },
+ backendKind: "mock" as const,
+ sourceInstanceId: "capability-tools-test",
+};
+
+async function runtimeFor(options: {
+ workMode?: "standard" | "ask" | "planning" | "skill_test";
+ role?: string;
+ actorGrants?: string[];
+ scenarioGrants?: string[];
+ policy?: ConstructorParameters<typeof CapabilitySemanticToolRuntime>[0]["policy"];
+ seed?: CapabilityFixtureSeed;
+ resolveSecretValue?: (name: string) => string | null;
+ semanticToolRuntimeStore?: CapabilitySemanticToolRuntimeStore;
+ now?: () => number;
+} = {}) {
+ const actor = {
+ id: "actor-1",
+ companyId: "company-1",
+ name: "Fixture Actor",
+ role: options.role ?? "engineer",
+ status: "active" as const,
+ budgetId: "budget-actor-1",
+ capabilityGrants: options.actorGrants ?? [],
+ };
+ const adapter = new CapabilityMockControlPlaneAdapter(
+ {
+ ...options.seed,
+ actors: [actor],
+ tasks: options.seed?.tasks ?? [{
+ id: "task-1",
+ companyId: "company-1",
+ identifier: "MCK-1",
+ title: "Tool boundary fixture",
+ description: "Protected task details",
+ status: "todo",
+ priority: "high",
+ workMode: options.workMode ?? "standard",
+ parentId: null,
+ assigneeActorId: "actor-1",
+ checkoutRunId: null,
+ executionRunId: null,
+ startedAt: null,
+ completedAt: null,
+ }],
+ },
+ { semanticToolRuntimeStore: options.semanticToolRuntimeStore },
+ );
+ await adapter.start();
+ await adapter.openFixtureRun(OPEN);
+ return {
+ adapter,
+ runtime: new CapabilitySemanticToolRuntime({
+ adapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: options.scenarioGrants,
+ policy: options.policy,
+ resolveSecretValue: options.resolveSecretValue,
+ now: options.now,
+ }),
+ };
+}
+
+describe("Capability semantic tool catalog", () => {
+ it("defines a unique versioned provider-neutral catalog and every optional group", () => {
+ const operationIds = CAPABILITY_SEMANTIC_TOOL_CATALOG.map((tool) => tool.operationId);
+ expect(new Set(operationIds).size).toBe(operationIds.length);
+ expect(CAPABILITY_SEMANTIC_TOOL_CATALOG.every((tool) => tool.version === 1)).toBe(true);
+ expect(CAPABILITY_SEMANTIC_TOOL_CATALOG.every((tool) => tool.inputSchema.type === "object")).toBe(true);
+ expect(CAPABILITY_SEMANTIC_TOOL_CATALOG.every((tool) => tool.outputSchema.type === "object")).toBe(true);
+ expect(CAPABILITY_SEMANTIC_TOOL_CATALOG.every((tool) => tool.mockCommandMapping !== undefined)).toBe(true);
+
+ expect(Object.keys(CAPABILITY_OPTIONAL_TOOL_CATALOGS).sort()).toEqual([
+ "cases",
+ "company_skills",
+ "delegation_dependencies",
+ "discovery",
+ "governance",
+ "portability_admin",
+ "routines",
+ "secrets",
+ "test_escape_hatch",
+ "workspace_runtime",
+ ]);
+ expect(Object.values(CAPABILITY_OPTIONAL_TOOL_CATALOGS).every((tools) => tools.length > 0)).toBe(true);
+ expect([
+ "get_task_context",
+ "get_task_history",
+ "list_documents",
+ "read_document",
+ "list_document_revisions",
+ "report_progress",
+ "answer_status_question",
+ "finish_task",
+ "block_task",
+ "request_review",
+ "write_document",
+ "request_human_input",
+ "register_deliverable",
+ "inspect_operation_result",
+ ].every((id) => capabilitySemanticTool(id)?.disposition === "always_agent_tool")).toBe(true);
+ });
+
+ it("keeps control-plane operations absent and binds identical fake-agent and Codex surfaces", async () => {
+ const { runtime } = await runtimeFor();
+ const visible = runtime.visibleTools();
+ const fake = new CapabilityFakeAgentToolBinding().bind(visible);
+ const codex = new CapabilityCodexToolBinding().bind(visible);
+ expect(fake.map((tool) => tool.operationId)).toEqual(codex.map((tool) => tool.name));
+ expect(codex.every((tool) => tool.type === "function" && tool.strict)).toBe(true);
+ for (const operationId of CAPABILITY_CONTROL_PLANE_OWNED_OPERATION_IDS) {
+ expect(visible.tools.some((tool) => tool.operationId === operationId)).toBe(false);
+ }
+ expect(JSON.stringify({ fake, codex })).not.toContain("Bearer ");
+ });
+});
+
+describe("Capability exposure and authorization", () => {
+ it("computes exposure before invocation from task mode, claims, role, and policy", async () => {
+ const baseline = await runtimeFor();
+ const baselineIds = baseline.runtime.visibleTools().tools.map((tool) => tool.operationId);
+ expect(baselineIds).toContain("finish_task");
+ expect(baselineIds).not.toContain("search_tasks");
+
+ const ask = await runtimeFor({ workMode: "ask" });
+ const askIds = ask.runtime.visibleTools().tools.map((tool) => tool.operationId);
+ expect(askIds).toContain("answer_status_question");
+ expect(askIds).not.toContain("finish_task");
+ expect(askIds).not.toContain("write_document");
+
+ const granted = await runtimeFor({
+ scenarioGrants: ["discovery:tasks:read", "governance:approvals:decide"],
+ role: "approver",
+ policy: { deniedOperationIds: ["search_tasks"] },
+ });
+ const grantedIds = granted.runtime.visibleTools().tools.map((tool) => tool.operationId);
+ expect(grantedIds).not.toContain("search_tasks");
+ expect(grantedIds).toContain("decide_approval");
+ expect(granted.runtime.authorizationRecords().some(
+ (record) => record.operationId === "search_tasks" && record.reason === "operation_denied_by_policy",
+ )).toBe(true);
+ });
+
+ it("keeps always tools active-task scoped and returns typed denials without protected state", async () => {
+ const protectedValue = "protected-approval-payload";
+ const approval: CapabilityFixtureApproval = {
+ id: "approval-protected",
+ companyId: "company-1",
+ taskIds: ["task-1"],
+ type: "request_board_approval",
+ status: "pending",
+ requestedByActorId: null,
+ payload: { private: protectedValue },
+ decisionNote: null,
+ comments: [],
+ createdAt: "2026-08-09T00:00:00.000Z",
+ decidedAt: null,
+ };
+ const { adapter, runtime } = await runtimeFor({ seed: { approvals: [approval] } });
+ const revision = adapter.snapshot().revision;
+ const scoped = await runtime.invoke({
+ operationId: "get_task_context",
+ input: { taskId: "task-other" },
+ });
+ expect(scoped).toMatchObject({ ok: false, error: { code: "input_invalid" } });
+ expect(adapter.snapshot().revision).toBe(revision);
+
+ const denied = await runtime.invoke({
+ operationId: "decide_approval",
+ input: { approvalId: "approval-protected", decision: "approved", note: "approve" },
+ idempotencyKey: "decision-1",
+ });
+ expect(denied).toMatchObject({ ok: false, error: { code: "policy_denied" } });
+ expect(JSON.stringify(denied)).not.toContain(protectedValue);
+
+ const absent = await runtime.invoke({ operationId: "checkout_task", input: {} });
+ expect(absent).toMatchObject({
+ ok: false,
+ error: { code: "operation_absent", reason: "control_plane_owned_operation" },
+ });
+ expect(JSON.stringify(absent)).not.toContain("Protected task details");
+ });
+
+ it("emits authorization records with decision reasons and resulting state changes", async () => {
+ const { adapter, runtime } = await runtimeFor();
+ const beforeRevision = adapter.snapshot().revision;
+ const result = await runtime.invoke({
+ operationId: "report_progress",
+ input: { body: "Semantic progress." },
+ idempotencyKey: "progress-1",
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) throw new Error("expected success");
+ expect(result.authorization).toMatchObject({
+ outcome: "allowed",
+ reason: "task_scoped_always_tool",
+ resultingStateChange: {
+ beforeRevision,
+ afterRevision: adapter.snapshot().revision,
+ },
+ });
+ expect(result.authorization.resultingStateChange?.entityRefs).toEqual(
+ expect.arrayContaining(["task:task-1"]),
+ );
+ expect(adapter.snapshot().comments.at(-1)?.body).toBe("Semantic progress.");
+ expect(validateJsonSchema(
+ capabilitySemanticTool("report_progress")!.outputSchema,
+ structuredClone(result) as unknown as CapabilityJsonValue,
+ )).toEqual([]);
+ });
+
+ it("executes the minimum always-tool workflow through the mock command contract", async () => {
+ const { adapter, runtime } = await runtimeFor();
+ const written = await runtime.invoke({
+ operationId: "write_document",
+ input: {
+ key: "plan",
+ title: "Plan",
+ body: "# Semantic plan",
+ baseRevisionId: null,
+ },
+ idempotencyKey: "write-plan-1",
+ });
+ expect(written.ok).toBe(true);
+ const revisionId = written.ok
+ ? written.commandResult?.entityRefs.find((ref) => ref.startsWith("revision:"))?.slice(9)
+ : undefined;
+ expect(revisionId).toBeTruthy();
+
+ const read = await runtime.invoke({ operationId: "read_document", input: { key: "plan" } });
+ expect(read).toMatchObject({ ok: true, value: { key: "plan", latestRevisionId: revisionId } });
+ const revisions = await runtime.invoke({
+ operationId: "list_document_revisions",
+ input: { key: "plan" },
+ });
+ expect(revisions).toMatchObject({ ok: true, value: [{ id: revisionId, revision: 1 }] });
+
+ expect(await runtime.invoke({
+ operationId: "register_deliverable",
+ input: {
+ filename: "report.json",
+ contentType: "application/json",
+ byteSize: 42,
+ sha256: "fixture-sha256",
+ contentRef: "fixture://report.json",
+ title: "Semantic report",
+ },
+ idempotencyKey: "deliverable-1",
+ })).toMatchObject({ ok: true });
+ expect(await runtime.invoke({
+ operationId: "request_review",
+ input: { summary: "Ready for semantic review." },
+ idempotencyKey: "review-1",
+ })).toMatchObject({ ok: true });
+ expect(await runtime.invoke({
+ operationId: "request_human_input",
+ input: {
+ interactionKind: "confirmation",
+ title: "Confirm plan",
+ prompt: "Accept this plan?",
+ targetRevisionId: revisionId!,
+ continuationPolicy: "wake_assignee",
+ },
+ idempotencyKey: "confirm-plan-1",
+ })).toMatchObject({ ok: true });
+
+ expect(adapter.snapshot()).toMatchObject({
+ tasks: [{ status: "in_review" }],
+ documents: [{ key: "plan", revisions: [{ body: "# Semantic plan" }] }],
+ interactions: [{ kind: "confirmation", status: "pending" }],
+ artifacts: [{ filename: "report.json" }],
+ workProducts: [{ type: "artifact" }],
+ });
+ });
+
+ it("keeps a pending human-input handoff in review instead of weakening the lifecycle", async () => {
+ const { adapter, runtime } = await runtimeFor();
+ expect(await runtime.invoke({
+ operationId: "request_human_input",
+ input: {
+ interactionKind: "confirmation",
+ title: "Confirm plan",
+ prompt: "Accept this plan?",
+ continuationPolicy: "wake_assignee",
+ },
+ idempotencyKey: "confirm-plan-first",
+ })).toMatchObject({ ok: true });
+
+ expect(await runtime.invoke({
+ operationId: "request_review",
+ input: { summary: "A duplicate review transition must fail closed." },
+ idempotencyKey: "duplicate-review",
+ })).toMatchObject({
+ ok: false,
+ error: { code: "operation_unsupported", reason: "mock_operation_rejected" },
+ });
+ expect(adapter.snapshot()).toMatchObject({
+ tasks: [{ status: "in_review" }],
+ interactions: [{ status: "pending" }],
+ comments: [],
+ });
+ });
+
+ it.each([
+ ["sync_company_skills", "company_skills:write", {}, { synced: true }, "engineer"],
+ ["manage_routine", "routines:write", {}, { managed: true }, "engineer"],
+ ["upsert_case", "cases:write", { key: "case-1", body: "Case body" }, {
+ key: "case-1",
+ body: "Case body",
+ upserted: true,
+ }, "engineer"],
+ ["administer_company", "company:admin", { action: "refresh" }, {
+ action: "refresh",
+ applied: true,
+ }, "admin"],
+ ] as const)(
+ "executes the advertised %s scenario extension",
+ async (operationId, grant, input, value, role) => {
+ const { runtime } = await runtimeFor({ scenarioGrants: [grant], role });
+ await expect(runtime.invoke({
+ operationId,
+ input,
+ idempotencyKey: `extension-${operationId}`,
+ })).resolves.toMatchObject({ ok: true, operationId, value });
+ },
+ );
+
+ it("replays required-idempotency extensions without executing a second result", async () => {
+ const { adapter, runtime } = await runtimeFor({ scenarioGrants: ["cases:write"] });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-1", body: "Case body" },
+ idempotencyKey: "upsert-case-1",
+ } as const;
+
+ const first = await runtime.invoke(invocation);
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ adapter.serialize(),
+ );
+ const recreated = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ });
+ const replay = await recreated.invoke(invocation);
+ expect(first).toMatchObject({ ok: true, value: { upserted: true } });
+ expect(replay).toMatchObject({ ok: true, value: { upserted: true } });
+ if (!first.ok || !replay.ok) throw new Error("expected extension success");
+ expect(replay.operationResultId).toBe(first.operationResultId);
+
+ await expect(recreated.invoke({
+ operationId: "inspect_operation_result",
+ input: { operationResultId: first.operationResultId },
+ })).resolves.toMatchObject({
+ ok: true,
+ value: { key: "case-1", body: "Case body", upserted: true },
+ });
+
+ const next = await recreated.invoke({
+ ...invocation,
+ idempotencyKey: "upsert-case-2",
+ });
+ expect(next).toMatchObject({ ok: true });
+ if (!next.ok) throw new Error("expected extension success");
+ expect(next.operationResultId).not.toBe(first.operationResultId);
+
+ await expect(recreated.invoke({
+ ...invocation,
+ input: { key: "case-1", body: "Different body" },
+ })).resolves.toMatchObject({
+ ok: false,
+ error: { code: "input_invalid", reason: "idempotency_key_conflict" },
+ });
+ });
+
+ it("persists extension completion with its inspectable result atomically", async () => {
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ });
+ const compareAndSwapRuntime = vi.spyOn(
+ adapter,
+ "compareAndSwapSemanticToolRuntime",
+ );
+
+ const result = await runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-atomic", body: "Case body" },
+ idempotencyKey: "upsert-case-atomic",
+ });
+
+ expect(result).toMatchObject({ ok: true });
+ expect(compareAndSwapRuntime).toHaveBeenCalledTimes(3);
+ expect(compareAndSwapRuntime.mock.calls[0]![2].extensions).toEqual([
+ expect.objectContaining({ status: "pending", phase: "reserved" }),
+ ]);
+ expect(compareAndSwapRuntime.mock.calls[1]![2].extensions).toEqual([
+ expect.objectContaining({ status: "pending", phase: "executing" }),
+ ]);
+ const snapshot = compareAndSwapRuntime.mock.calls[2]![2];
+ expect(snapshot.extensions).toHaveLength(1);
+ const [extension] = snapshot.extensions;
+ expect(extension).toMatchObject({ status: "completed" });
+ if (extension?.status !== "completed") {
+ throw new Error("expected completed extension receipt");
+ }
+ expect(snapshot.operationResults[extension.resultId]).toEqual(
+ extension.execution.value,
+ );
+ });
+
+ it("retries the completion merge after a concurrent lease heartbeat", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let injectedHeartbeats = 0;
+ let completionAttempts = 0;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ const completing = snapshot.extensions.some((extension) => extension.status === "completed");
+ if (completing) completionAttempts += 1;
+ if (completing && injectedHeartbeats < 12 && durableSnapshot !== null) {
+ injectedHeartbeats += 1;
+ const heartbeat = structuredClone(durableSnapshot) as CapabilitySemanticToolRuntimeSnapshot;
+ heartbeat.extensions = heartbeat.extensions.map((extension) =>
+ extension.status === "pending"
+ ? { ...extension, leaseExpiresAtMs: (extension.leaseExpiresAtMs ?? 0) + 1_000 }
+ : extension,
+ );
+ durableSnapshot = heartbeat;
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+
+ await expect(runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-raced", body: "Case body" },
+ idempotencyKey: "upsert-case-raced",
+ })).resolves.toMatchObject({ ok: true, value: { upserted: true } });
+
+ expect(injectedHeartbeats).toBe(12);
+ expect(completionAttempts).toBe(13);
+ expect(durableSnapshot?.extensions).toEqual([
+ expect.objectContaining({ status: "completed", resultId: "tool-result-1" }),
+ ]);
+ expect(durableSnapshot?.operationResults["tool-result-1"]).toEqual({
+ key: "case-raced",
+ body: "Case body",
+ upserted: true,
+ });
+ });
+
+ it("bounds completion contention and retries the fulfilled execution without rerunning it", async () => {
+ vi.useFakeTimers({ now: 0 });
+ try {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let rejectCompletion = true;
+ let completionAttempts = 0;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ const completing = snapshot.extensions.some(
+ (extension) => extension.status === "completed",
+ );
+ if (completing) completionAttempts += 1;
+ if (completing && rejectCompletion) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ now: Date.now,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-bounded-contention", body: "Case body" },
+ idempotencyKey: "upsert-case-bounded-contention",
+ } as const;
+
+ const contended = runtime.invoke(invocation);
+ for (let yieldIndex = 0; yieldIndex < 8; yieldIndex += 1) {
+ await vi.advanceTimersToNextTimerAsync();
+ }
+ await expect(contended).resolves.toMatchObject({
+ ok: false,
+ error: { code: "operation_unsupported" },
+ });
+ expect(completionAttempts).toBe(64);
+ expect(durableSnapshot?.extensions).toEqual([
+ expect.objectContaining({ status: "pending" }),
+ ]);
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ const pending = durableSnapshot?.extensions[0];
+ expect(pending?.status).toBe("pending");
+ if (pending?.status !== "pending") throw new Error("expected a pending extension");
+ expect(pending.leaseExpiresAtMs).toBeGreaterThan(Date.now());
+
+ const followerAdapter = CapabilityMockControlPlaneAdapter.restore(
+ adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const follower = new CapabilitySemanticToolRuntime({
+ adapter: followerAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ now: Date.now,
+ });
+ await expect(follower.invoke(invocation)).resolves.toMatchObject({
+ ok: false,
+ error: { reason: "idempotency_recovery_in_flight" },
+ });
+
+ rejectCompletion = false;
+ await expect(runtime.invoke(invocation)).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-1",
+ value: { key: "case-bounded-contention", upserted: true },
+ });
+ expect(completionAttempts).toBe(65);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("reclaims an expired executing marker after its owner terminates", async () => {
+ vi.useFakeTimers({ now: 0 });
+ try {
+ let now = 0;
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let rejectCompletion = true;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ if (rejectCompletion &&
+ snapshot.extensions.some((extension) => extension.status === "completed")) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const first = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ now: () => now,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-ambiguous-effect", body: "Case body" },
+ idempotencyKey: "upsert-case-ambiguous-effect",
+ } as const;
+
+ const contended = first.runtime.invoke(invocation);
+ for (let yieldIndex = 0; yieldIndex < 8; yieldIndex += 1) {
+ await vi.advanceTimersToNextTimerAsync();
+ }
+ await expect(contended).resolves.toMatchObject({
+ ok: false,
+ error: { code: "operation_unsupported" },
+ });
+ expect(durableSnapshot?.extensions).toEqual([
+ expect.objectContaining({ status: "pending", phase: "executing" }),
+ ]);
+
+ // Model termination of the first process: its heartbeat no longer owns
+ // the lease, and the durable store is available to the replacement.
+ vi.clearAllTimers();
+ rejectCompletion = false;
+ now = 60_000;
+ const followerAdapter = CapabilityMockControlPlaneAdapter.restore(
+ first.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const follower = new CapabilitySemanticToolRuntime({
+ adapter: followerAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ now: () => now,
+ resolveExpiredExtensionReceipt: async () => ({
+ value: {
+ key: "case-ambiguous-effect",
+ body: "Case body",
+ upserted: true,
+ },
+ }),
+ });
+ await expect(follower.invoke(invocation)).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-1",
+ value: { key: "case-ambiguous-effect", upserted: true },
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("retries rejected-execution cleanup through snapshot contention", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let rejectExecutionAllocation = true;
+ let injectedCleanupContention = false;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => {
+ if (
+ rejectExecutionAllocation &&
+ durableSnapshot?.extensions.some((extension) => extension.status === "pending")
+ ) {
+ rejectExecutionAllocation = false;
+ throw new Error("injected extension result allocation failure");
+ }
+ return durableSnapshot === null ? null : structuredClone(durableSnapshot);
+ },
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ const removingFailedLease =
+ durableSnapshot?.extensions.some((extension) => extension.status === "pending") &&
+ snapshot.extensions.length === 0;
+ if (removingFailedLease && !injectedCleanupContention && durableSnapshot !== null) {
+ injectedCleanupContention = true;
+ durableSnapshot = {
+ ...structuredClone(durableSnapshot),
+ resultSequence: durableSnapshot.resultSequence + 1,
+ };
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-cleanup-raced", body: "Case body" },
+ idempotencyKey: "upsert-case-cleanup-raced",
+ } as const;
+
+ await expect(runtime.invoke(invocation)).resolves.toMatchObject({ ok: false });
+ await vi.waitFor(() => expect(durableSnapshot?.extensions).toEqual([]));
+ expect(injectedCleanupContention).toBe(true);
+ await expect(runtime.invoke(invocation)).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-2",
+ value: { key: "case-cleanup-raced", upserted: true },
+ });
+ });
+
+ it("retains a failed lease until cleanup contention clears", async () => {
+ vi.useFakeTimers({ now: 0 });
+ try {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let failExecutionAllocation = true;
+ let cleanupAttempts = 0;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => {
+ if (
+ failExecutionAllocation &&
+ durableSnapshot?.extensions.some((extension) => extension.status === "pending")
+ ) {
+ failExecutionAllocation = false;
+ throw new Error("injected result allocation failure");
+ }
+ return durableSnapshot === null ? null : structuredClone(durableSnapshot);
+ },
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ const removingFailedLease =
+ durableSnapshot?.extensions.some((extension) => extension.status === "pending") &&
+ snapshot.extensions.length === 0;
+ if (removingFailedLease) {
+ cleanupAttempts += 1;
+ if (cleanupAttempts <= 8) return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ now: Date.now,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-cleanup-exhausted", body: "Case body" },
+ idempotencyKey: "upsert-case-cleanup-exhausted",
+ } as const;
+
+ await expect(runtime.invoke(invocation)).resolves.toMatchObject({ ok: false });
+ expect(cleanupAttempts).toBe(8);
+ expect(durableSnapshot?.extensions).toEqual([
+ expect.objectContaining({ status: "pending" }),
+ ]);
+
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(cleanupAttempts).toBe(9);
+ expect(durableSnapshot?.extensions).toEqual([]);
+ await expect(runtime.invoke(invocation)).resolves.toMatchObject({
+ ok: true,
+ value: { key: "case-cleanup-exhausted", upserted: true },
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("allocates read result ids from the latest shared durable sequence", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const first = await runtimeFor({ semanticToolRuntimeStore: durableStore });
+ await expect(first.runtime.invoke({ operationId: "get_task_context", input: {} }))
+ .resolves.toMatchObject({ ok: true, operationResultId: "tool-result-1" });
+ const followerAdapter = CapabilityMockControlPlaneAdapter.restore(
+ first.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const follower = new CapabilitySemanticToolRuntime({
+ adapter: followerAdapter,
+ runId: OPEN.identity.runId,
+ });
+
+ await expect(follower.invoke({ operationId: "get_task_context", input: {} }))
+ .resolves.toMatchObject({ ok: true, operationResultId: "tool-result-2" });
+ await expect(first.runtime.invoke({ operationId: "get_task_context", input: {} }))
+ .resolves.toMatchObject({ ok: true, operationResultId: "tool-result-3" });
+ expect(Object.keys(durableSnapshot?.operationResults ?? {})).toEqual([
+ "tool-result-1",
+ "tool-result-2",
+ "tool-result-3",
+ ]);
+ });
+
+ it("retries extension acquisition after an unrelated snapshot update", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let injectedContention = false;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ const acquiring = snapshot.extensions.some((extension) => extension.status === "pending");
+ if (acquiring && !injectedContention) {
+ injectedContention = true;
+ durableSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 1,
+ operationResults: {},
+ extensions: [],
+ };
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+
+ await expect(runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-acquire-raced", body: "Case body" },
+ idempotencyKey: "upsert-case-acquire-raced",
+ })).resolves.toMatchObject({ ok: true, value: { upserted: true } });
+ expect(injectedContention).toBe(true);
+ expect(durableSnapshot?.resultSequence).toBe(2);
+ expect(durableSnapshot?.extensions).toEqual([
+ expect.objectContaining({ status: "completed" }),
+ ]);
+ });
+
+ it("fails closed while a restored extension is in flight and reconciles its durable receipt", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () =>
+ durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-pending", body: "Case body" },
+ idempotencyKey: "upsert-case-pending",
+ } as const;
+
+ const inFlight = runtime.invoke(invocation);
+ const serializedWhileInFlight = adapter.serialize();
+ expect(() =>
+ CapabilityMockControlPlaneAdapter.restore(serializedWhileInFlight),
+ ).toThrow(
+ "restoring pending semantic extensions requires a process-independent runtime store",
+ );
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ serializedWhileInFlight,
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ });
+
+ await expect(restored.invoke(invocation)).resolves.toMatchObject({
+ ok: false,
+ error: {
+ code: "operation_unsupported",
+ reason: "idempotency_recovery_in_flight",
+ },
+ });
+ const completed = await inFlight;
+ expect(completed).toMatchObject({ ok: true });
+
+ const recovered = await restored.invoke(invocation);
+ expect(recovered).toMatchObject({
+ ok: true,
+ operationResultId: completed.ok ? completed.operationResultId : undefined,
+ value: { key: "case-pending", body: "Case body", upserted: true },
+ });
+ });
+
+ it("does not revive a serialized pending extension when the durable store is empty", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const first = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-empty-store-pending", body: "Case body" },
+ idempotencyKey: "empty-store-pending",
+ } as const;
+
+ const inFlight = first.runtime.invoke(invocation);
+ const serializedWhilePending = first.adapter.serialize();
+ await expect(inFlight).resolves.toMatchObject({ ok: true });
+ durableSnapshot = null;
+
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ serializedWhilePending,
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ });
+ await expect(restored.invoke(invocation)).resolves.toMatchObject({
+ ok: true,
+ value: { key: "case-empty-store-pending", upserted: true },
+ });
+ expect(durableSnapshot?.extensions).toEqual([
+ expect.objectContaining({
+ key: "run-tools:upsert_case:empty-store-pending",
+ status: "completed",
+ }),
+ ]);
+ });
+
+ it("does not revive serialized completed extensions when the durable store is empty", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const first = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+ await expect(first.runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-stale-completed", body: "Stale body" },
+ idempotencyKey: "stale-completed",
+ })).resolves.toMatchObject({ ok: true });
+ const serializedWithCompleted = first.adapter.serialize();
+ durableSnapshot = null;
+
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ serializedWithCompleted,
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ });
+ await expect(restored.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-after-empty-store", body: "Fresh body" },
+ idempotencyKey: "fresh-after-empty-store",
+ })).resolves.toMatchObject({
+ ok: true,
+ value: { key: "case-after-empty-store", upserted: true },
+ });
+ expect(durableSnapshot?.extensions).toEqual([
+ expect.objectContaining({
+ key: "run-tools:upsert_case:fresh-after-empty-store",
+ status: "completed",
+ }),
+ ]);
+ });
+
+ it("renews a live extension lease before another runtime can reclaim it", async () => {
+ vi.useFakeTimers({ now: 0 });
+ try {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () =>
+ durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-live", body: "Case body" },
+ idempotencyKey: "live-case",
+ } as const;
+
+ const inFlight = runtime.invoke(invocation);
+ expect(durableSnapshot?.extensions[0]).toMatchObject({
+ status: "pending",
+ leaseExpiresAtMs: 30_000,
+ });
+ vi.advanceTimersByTime(10_000);
+ expect(durableSnapshot?.extensions[0]).toMatchObject({
+ status: "pending",
+ leaseExpiresAtMs: 40_000,
+ });
+
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ now: () => 30_001,
+ });
+ await expect(restored.invoke(invocation)).resolves.toMatchObject({
+ ok: false,
+ error: {
+ code: "operation_unsupported",
+ reason: "idempotency_recovery_in_flight",
+ },
+ });
+ await expect(inFlight).resolves.toMatchObject({ ok: true });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("retries a lease heartbeat after a transient durable-store failure", async () => {
+ vi.useFakeTimers({ now: 0 });
+ try {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let failNextLoad = false;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => {
+ if (failNextLoad) {
+ failNextLoad = false;
+ throw new Error("transient store read failure");
+ }
+ return durableSnapshot === null ? null : structuredClone(durableSnapshot);
+ },
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+ const inFlight = runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-heartbeat-retry", body: "Case body" },
+ idempotencyKey: "heartbeat-retry",
+ });
+
+ failNextLoad = true;
+ expect(() => vi.advanceTimersByTime(10_000)).not.toThrow();
+ expect(durableSnapshot?.extensions[0]?.leaseExpiresAtMs).toBe(30_000);
+ vi.advanceTimersByTime(10_000);
+ expect(durableSnapshot?.extensions[0]?.leaseExpiresAtMs).toBe(50_000);
+ await expect(inFlight).resolves.toMatchObject({ ok: true });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("recovers a prepared extension after repeated heartbeat failures", async () => {
+ vi.useFakeTimers({ now: 0 });
+ try {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let failHeartbeatLoads = false;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => {
+ if (failHeartbeatLoads) throw new Error("persistent store read failure");
+ return durableSnapshot === null ? null : structuredClone(durableSnapshot);
+ },
+ save: (_runId, snapshot) => { durableSnapshot = structuredClone(snapshot); },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ now: () => Date.now(),
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-heartbeat-loss", body: "Case body" },
+ idempotencyKey: "heartbeat-loss",
+ } as const;
+
+ const inFlight = runtime.invoke(invocation);
+ failHeartbeatLoads = true;
+ vi.advanceTimersByTime(40_000);
+ failHeartbeatLoads = false;
+ expect(durableSnapshot?.extensions[0]).toMatchObject({
+ status: "pending",
+ phase: "executing",
+ leaseExpiresAtMs: 30_000,
+ });
+
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const resolveExpiredExtensionReceipt = vi.fn(() => ({
+ value: {
+ key: "case-heartbeat-loss",
+ body: "Conflicting recovered body",
+ upserted: true,
+ },
+ }));
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ now: () => Date.now(),
+ resolveExpiredExtensionReceipt,
+ });
+ const recovered = await restored.invoke(invocation);
+ const original = await inFlight;
+ expect(recovered).toMatchObject({ ok: true });
+ expect(original).toMatchObject({ ok: true });
+ if (!recovered.ok || !original.ok) throw new Error("expected recovered execution");
+ expect(recovered.operationResultId).toBe(original.operationResultId);
+ expect(recovered.value).toEqual({
+ key: "case-heartbeat-loss",
+ body: "Case body",
+ upserted: true,
+ });
+ expect(original.value).toEqual(recovered.value);
+ expect(resolveExpiredExtensionReceipt).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("retries initial acquisition after a transient durable-store failure", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ let failNextLoad = false;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => {
+ if (failNextLoad) {
+ failNextLoad = false;
+ throw new Error("transient store read failure");
+ }
+ return durableSnapshot === null ? null : structuredClone(durableSnapshot);
+ },
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const { runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ semanticToolRuntimeStore: durableStore,
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-acquisition-retry", body: "Case body" },
+ idempotencyKey: "acquisition-retry",
+ };
+
+ failNextLoad = true;
+ await expect(runtime.invoke(invocation)).resolves.toMatchObject({
+ ok: false,
+ error: { reason: "mock_operation_rejected" },
+ });
+ await expect(runtime.invoke(invocation)).resolves.toMatchObject({
+ ok: true,
+ value: { key: "case-acquisition-retry", upserted: true },
+ });
+ });
+
+ it("reconstructs a legacy expired built-in receipt after executor loss", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 0,
+ operationResults: {},
+ extensions: [{
+ key: `${OPEN.identity.runId}:upsert_case:expired-case`,
+ input: '{"body":"Case body","key":"case-expired"}',
+ status: "pending",
+ ownerId: "terminated-executor",
+ leaseExpiresAtMs: 1_000,
+ phase: "executing",
+ }],
+ };
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const base = await runtimeFor({ scenarioGrants: ["cases:write"] });
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ now: () => 1_001,
+ });
+
+ await expect(restored.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-expired", body: "Case body" },
+ idempotencyKey: "expired-case",
+ })).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-1",
+ value: { key: "case-expired", body: "Case body", upserted: true },
+ });
+ expect(durableSnapshot.extensions[0]).toMatchObject({
+ status: "completed",
+ resultId: "tool-result-1",
+ execution: {
+ value: { key: "case-expired", body: "Case body", upserted: true },
+ },
+ });
+ expect(durableSnapshot.operationResults).toEqual({
+ "tool-result-1": { key: "case-expired", body: "Case body", upserted: true },
+ });
+ });
+
+ it("recovers an expired built-in extension from its prepared receipt", async () => {
+ const observedExport = {
+ schema: "paperclip.capability.mock-export.v1",
+ company: { id: "company-1", name: "Previously Exported Company" },
+ taskCount: 1,
+ actorCount: 1,
+ };
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 0,
+ operationResults: {},
+ extensions: [{
+ key: `${OPEN.identity.runId}:export_company:prepared-export`,
+ input: "{}",
+ status: "pending",
+ ownerId: "terminated-exporter",
+ leaseExpiresAtMs: 1_000,
+ phase: "executing",
+ preparedExecution: {
+ value: observedExport,
+ commandResult: null,
+ entityRefs: [],
+ },
+ }],
+ };
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => { durableSnapshot = structuredClone(snapshot); },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const base = await runtimeFor({ scenarioGrants: ["portability:export"] });
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const resolveExpiredExtensionReceipt = vi.fn(async () => ({
+ value: {
+ ...observedExport,
+ company: { id: "company-1", name: "Conflicting Resolver Company" },
+ },
+ }));
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["portability:export"],
+ resolveExpiredExtensionReceipt,
+ now: () => 1_001,
+ });
+
+ await expect(restored.invoke({
+ operationId: "export_company",
+ input: {},
+ idempotencyKey: "prepared-export",
+ })).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-1",
+ value: observedExport,
+ });
+ expect(durableSnapshot.extensions[0]).toMatchObject({
+ status: "completed",
+ resultId: "tool-result-1",
+ execution: { value: observedExport },
+ });
+ expect(resolveExpiredExtensionReceipt).not.toHaveBeenCalled();
+ });
+
+ it("terminally marks a legacy export without an exact receipt", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 0,
+ operationResults: {},
+ extensions: [{
+ key: `${OPEN.identity.runId}:export_company:expired-export`,
+ input: "{}",
+ status: "pending",
+ ownerId: "terminated-exporter",
+ leaseExpiresAtMs: 1_000,
+ phase: "executing",
+ }],
+ };
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const base = await runtimeFor({
+ scenarioGrants: ["portability:export"],
+ seed: { company: { name: "Company State Changed After Execution" } },
+ });
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["portability:export"],
+ now: () => 1_001,
+ });
+
+ await expect(restored.invoke({
+ operationId: "export_company",
+ input: {},
+ idempotencyKey: "expired-export",
+ })).resolves.toMatchObject({
+ ok: false,
+ error: {
+ code: "operation_unsupported",
+ reason: "idempotency_receipt_unavailable",
+ },
+ });
+ expect(durableSnapshot.extensions).toEqual([{
+ key: `${OPEN.identity.runId}:export_company:expired-export`,
+ input: "{}",
+ status: "indeterminate",
+ reason: "idempotency_receipt_unavailable",
+ }]);
+ expect(durableSnapshot.operationResults).toEqual({});
+
+ const retriedAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const retried = new CapabilitySemanticToolRuntime({
+ adapter: retriedAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["portability:export"],
+ now: () => 2_001,
+ });
+ await expect(retried.invoke({
+ operationId: "export_company",
+ input: {},
+ idempotencyKey: "expired-export",
+ })).resolves.toMatchObject({
+ ok: false,
+ error: {
+ code: "operation_unsupported",
+ reason: "idempotency_receipt_unavailable",
+ },
+ });
+ expect(durableSnapshot.operationResults).toEqual({});
+
+ const authoritativeExport = {
+ schema: "paperclip.capability.mock-export.v1",
+ company: { id: "company-1", name: "Originally Exported Company" },
+ taskCount: 1,
+ actorCount: 1,
+ };
+ const resolvingAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const resolving = new CapabilitySemanticToolRuntime({
+ adapter: resolvingAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["portability:export"],
+ resolveExpiredExtensionReceipt: async () => ({ value: authoritativeExport }),
+ now: () => 3_001,
+ });
+ await expect(resolving.invoke({
+ operationId: "export_company",
+ input: {},
+ idempotencyKey: "expired-export",
+ })).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-1",
+ value: authoritativeExport,
+ });
+ expect(durableSnapshot.extensions[0]).toMatchObject({
+ status: "completed",
+ resultId: "tool-result-1",
+ });
+ });
+
+ it("adopts an authoritative completion that wins the recovery publication race", async () => {
+ const authoritative = {
+ key: "case-publication-race",
+ body: "Original executor body",
+ upserted: true,
+ };
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 1,
+ operationResults: { "tool-result-1": authoritative },
+ extensions: [{
+ key: `${OPEN.identity.runId}:upsert_case:publication-race`,
+ input: '{"body":"Case body","key":"case-publication-race"}',
+ status: "completed",
+ resultId: "tool-result-1",
+ execution: {
+ value: authoritative,
+ commandResult: null,
+ entityRefs: ["case:case-publication-race"],
+ },
+ }],
+ };
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => { durableSnapshot = structuredClone(snapshot); },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const base = await runtimeFor({ scenarioGrants: ["cases:write"] });
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ });
+
+ expect(restored.reconcileExpiredExtensionReceipt({
+ operationId: "upsert_case",
+ input: { key: "case-publication-race", body: "Case body" },
+ idempotencyKey: "publication-race",
+ value: {
+ key: "case-publication-race",
+ body: "Stale recovery observation",
+ upserted: true,
+ },
+ entityRefs: ["case:stale-observation"],
+ })).toEqual({ resultId: "tool-result-1" });
+ await expect(restored.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-publication-race", body: "Case body" },
+ idempotencyKey: "publication-race",
+ })).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-1",
+ value: authoritative,
+ });
+ expect(durableSnapshot.operationResults).toEqual({
+ "tool-result-1": authoritative,
+ });
+ });
+
+ it("resolves an expired mutable export receipt during a restored retry", async () => {
+ const observedExport = {
+ schema: "paperclip.capability.mock-export.v1",
+ company: { id: "company-1", name: "Previously Exported Company" },
+ taskCount: 1,
+ actorCount: 1,
+ };
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 0,
+ operationResults: {},
+ extensions: [{
+ key: `${OPEN.identity.runId}:export_company:recovered-export`,
+ input: "{}",
+ status: "pending",
+ ownerId: "terminated-exporter",
+ leaseExpiresAtMs: 1_000,
+ phase: "executing",
+ }],
+ };
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => { durableSnapshot = structuredClone(snapshot); },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) return false;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const base = await runtimeFor({ scenarioGrants: ["portability:export"] });
+ const restoredAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const resolveExpiredExtensionReceipt = vi.fn(async () => ({ value: observedExport }));
+ const restored = new CapabilitySemanticToolRuntime({
+ adapter: restoredAdapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["portability:export"],
+ now: () => 1_001,
+ resolveExpiredExtensionReceipt,
+ });
+
+ await expect(restored.invoke({
+ operationId: "export_company",
+ input: {},
+ idempotencyKey: "recovered-export",
+ })).resolves.toMatchObject({
+ ok: true,
+ operationResultId: "tool-result-1",
+ value: observedExport,
+ });
+ expect(resolveExpiredExtensionReceipt).toHaveBeenCalledOnce();
+ expect(durableSnapshot.extensions[0]).toMatchObject({
+ status: "completed",
+ resultId: "tool-result-1",
+ });
+
+ await restored.invoke({
+ operationId: "export_company",
+ input: {},
+ idempotencyKey: "recovered-export",
+ });
+ expect(resolveExpiredExtensionReceipt).toHaveBeenCalledOnce();
+ });
+
+ it("allows only one restored runtime to reclaim an expired extension lease", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 0,
+ operationResults: {},
+ extensions: [{
+ key: `${OPEN.identity.runId}:upsert_case:contended-case`,
+ input: '{"body":"Case body","key":"case-contended"}',
+ status: "pending",
+ ownerId: "terminated-executor",
+ leaseExpiresAtMs: 1_000,
+ }],
+ };
+ let successfulClaims = 0;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () => structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ if (snapshot.extensions.some((extension) =>
+ extension.status === "pending" &&
+ extension.ownerId !== "terminated-executor" &&
+ extension.phase === "reserved"
+ )) successfulClaims += 1;
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const base = await runtimeFor({ scenarioGrants: ["cases:write"] });
+ const serialized = base.adapter.serialize();
+ const runtimes = [0, 1].map(() => {
+ const adapter = CapabilityMockControlPlaneAdapter.restore(serialized, {
+ semanticToolRuntimeStore: durableStore,
+ });
+ return new CapabilitySemanticToolRuntime({
+ adapter,
+ runId: OPEN.identity.runId,
+ scenarioGrants: ["cases:write"],
+ now: () => 1_001,
+ });
+ });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-contended", body: "Case body" },
+ idempotencyKey: "contended-case",
+ } as const;
+
+ const results = await Promise.all(
+ runtimes.map((runtime) => runtime.invoke(invocation)),
+ );
+
+ expect(results.filter((result) => result.ok)).toHaveLength(1);
+ expect(results.filter((result) => !result.ok)).toEqual([
+ expect.objectContaining({
+ error: expect.objectContaining({
+ code: "operation_unsupported",
+ reason: "idempotency_recovery_in_flight",
+ }),
+ }),
+ ]);
+ expect(successfulClaims).toBe(1);
+ });
+
+ it("preserves a durable extension lease when a stale runtime saves another result", async () => {
+ let durableSnapshot: CapabilitySemanticToolRuntimeSnapshot | null = null;
+ const durableStore: CapabilitySemanticToolRuntimeStore = {
+ load: () =>
+ durableSnapshot === null ? null : structuredClone(durableSnapshot),
+ save: (_runId, snapshot) => {
+ durableSnapshot = structuredClone(snapshot);
+ },
+ compareAndSwap: (_runId, expected, snapshot) => {
+ if (JSON.stringify(durableSnapshot) !== JSON.stringify(expected)) {
+ return false;
+ }
+ durableSnapshot = structuredClone(snapshot);
+ return true;
+ },
+ };
+ const base = await runtimeFor({ semanticToolRuntimeStore: durableStore });
+ const staleAdapter = CapabilityMockControlPlaneAdapter.restore(
+ base.adapter.serialize(),
+ { semanticToolRuntimeStore: durableStore },
+ );
+ const staleRuntime = new CapabilitySemanticToolRuntime({
+ adapter: staleAdapter,
+ runId: OPEN.identity.runId,
+ });
+ const pendingKey = `${OPEN.identity.runId}:upsert_case:owned-elsewhere`;
+ durableSnapshot = {
+ schema: "paperclip.capability.semantic-tool-runtime.v1",
+ resultSequence: 0,
+ operationResults: {},
+ extensions: [{
+ key: pendingKey,
+ input: '{"body":"Case body","key":"case-owned"}',
+ status: "pending",
+ ownerId: "other-runtime",
+ leaseExpiresAtMs: 30_000,
+ }],
+ };
+
+ await expect(staleRuntime.invoke({
+ operationId: "get_task_context",
+ input: {},
+ })).resolves.toMatchObject({ ok: true });
+
+ expect(durableSnapshot.extensions).toEqual([
+ expect.objectContaining({
+ key: pendingKey,
+ status: "pending",
+ ownerId: "other-runtime",
+ }),
+ ]);
+ });
+
+ it("rejects incomplete or malformed restored extension executions", async () => {
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ });
+ await runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-1", body: "Case body" },
+ idempotencyKey: "upsert-case-1",
+ });
+
+ for (const mutate of [
+ (execution: Record<string, unknown>) => delete execution.value,
+ (execution: Record<string, unknown>) => {
+ execution.commandResult = { disposition: "applied" };
+ },
+ ]) {
+ const snapshot = JSON.parse(adapter.serialize()) as {
+ semanticToolRuntimes: Record<
+ string,
+ { extensions: Array<{ execution: Record<string, unknown> }> }
+ >;
+ };
+ const execution =
+ snapshot.semanticToolRuntimes[OPEN.identity.runId]!.extensions[0]!
+ .execution;
+ mutate(execution);
+ expect(() =>
+ CapabilityMockControlPlaneAdapter.restore(JSON.stringify(snapshot)),
+ ).toThrow("semantic tool runtime for run-tools is invalid");
+ }
+ });
+
+ it("rejects restored extension receipts that disagree with inspection", async () => {
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ });
+ const result = await runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-1", body: "Case body" },
+ idempotencyKey: "upsert-case-1",
+ });
+ if (!result.ok) throw new Error("expected extension success");
+
+ const snapshot = JSON.parse(adapter.serialize()) as {
+ semanticToolRuntimes: Record<
+ string,
+ { operationResults: Record<string, unknown> }
+ >;
+ };
+ snapshot.semanticToolRuntimes[OPEN.identity.runId]!
+ .operationResults[result.operationResultId] = { upserted: false };
+
+ expect(() =>
+ CapabilityMockControlPlaneAdapter.restore(JSON.stringify(snapshot)),
+ ).toThrow("semantic tool runtime for run-tools is invalid");
+ });
+
+ it("rejects a restored result sequence that can reuse a prior result id", async () => {
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["cases:write"],
+ });
+ const result = await runtime.invoke({
+ operationId: "upsert_case",
+ input: { key: "case-1", body: "Case body" },
+ idempotencyKey: "upsert-case-1",
+ });
+ expect(result).toMatchObject({ operationResultId: "tool-result-1" });
+
+ const snapshot = JSON.parse(adapter.serialize()) as {
+ semanticToolRuntimes: Record<string, { resultSequence: number }>;
+ };
+ snapshot.semanticToolRuntimes[OPEN.identity.runId]!.resultSequence = 0;
+ expect(() =>
+ CapabilityMockControlPlaneAdapter.restore(JSON.stringify(snapshot)),
+ ).toThrow("semantic tool runtime for run-tools is invalid");
+ });
+
+ it("serializes concurrent retries for required-idempotency extensions", async () => {
+ const { runtime } = await runtimeFor({ scenarioGrants: ["cases:write"] });
+ const invocation = {
+ operationId: "upsert_case",
+ input: { key: "case-concurrent", body: "Case body" },
+ idempotencyKey: "upsert-case-concurrent",
+ } as const;
+
+ const [first, replay] = await Promise.all([
+ runtime.invoke(invocation),
+ runtime.invoke(invocation),
+ ]);
+ expect(first).toMatchObject({ ok: true });
+ expect(replay).toMatchObject({ ok: true });
+ if (!first.ok || !replay.ok) throw new Error("expected extension success");
+ expect(replay.operationResultId).toBe(first.operationResultId);
+
+ const [accepted, conflicting] = await Promise.all([
+ runtime.invoke({ ...invocation, idempotencyKey: "shared-key" }),
+ runtime.invoke({
+ ...invocation,
+ input: { key: "case-concurrent", body: "Different body" },
+ idempotencyKey: "shared-key",
+ }),
+ ]);
+ expect(accepted).toMatchObject({ ok: true });
+ expect(conflicting).toMatchObject({
+ ok: false,
+ error: { code: "input_invalid", reason: "idempotency_key_conflict" },
+ });
+ });
+});
+
+describe("Capability security policy", () => {
+ it("separates model-only secret delivery from every observable result boundary", async () => {
+ expectTypeOf<CapabilityModelToolSuccess>().not.toMatchTypeOf<CapabilityToolSuccess>();
+
+ const secret = "CAPABILITY_SECRET_SENTINEL_f42d4fbc";
+ const { adapter, runtime } = await runtimeFor({
+ scenarioGrants: ["secrets:values:read"],
+ policy: { allowSecretValueAccess: true },
+ resolveSecretValue: (name) => name === "DEPLOY_TOKEN" ? secret : null,
+ });
+ expect(runtime.visibleTools().tools.map((tool) => tool.operationId)).toContain("read_secret_value");
+ const result = await runtime.invoke({
+ operationId: "read_secret_value",
+ input: { name: "DEPLOY_TOKEN" },
+ });
+ expect(result).toMatchObject({
+ ok: true,
+ value: { name: "DEPLOY_TOKEN", value: "[SECRET_VALUE]" },
+ });
+ if (!result.ok) throw new Error("expected secret read success");
+ expect(result.authorization.redactions).toEqual([
+ { path: "$.value", replacement: "[SECRET_VALUE]" },
+ ]);
+ expect(adapter.loadSemanticToolRuntime(OPEN.identity.runId)?.extensions)
+ .toEqual([]);
+
+ const inspected = await runtime.invoke({
+ operationId: "inspect_operation_result",
+ input: { operationResultId: result.operationResultId },
+ });
+ expect(inspected).toMatchObject({ ok: true, value: { value: "[SECRET_VALUE]" } });
+
+ const modelDelivery = await runtime.invokeForModel({
+ operationId: "read_secret_value",
+ input: { name: "DEPLOY_TOKEN" },
+ });
+ expect(modelDelivery.readModelResult()).toMatchObject({
+ schema: "paperclip.capability.model-tool-result.v1",
+ ok: true,
+ value: { name: "DEPLOY_TOKEN", value: secret },
+ });
+ expect(modelDelivery.observableResult).toMatchObject({
+ schema: "paperclip.capability.tool-result.v1",
+ ok: true,
+ value: { name: "DEPLOY_TOKEN", value: "[SECRET_VALUE]" },
+ });
+
+ const observablePayloads = {
+ publicInvocation: result,
+ trace: { toolResult: modelDelivery },
+ snapshot: structuredClone(modelDelivery),
+ browser: { toolResult: modelDelivery.observableResult },
+ authorization: runtime.authorizationRecords(),
+ };
+ expect(JSON.stringify(observablePayloads)).not.toContain(secret);
+
+ const failing = await runtimeFor({
+ scenarioGrants: ["secrets:values:read"],
+ policy: { allowSecretValueAccess: true },
+ resolveSecretValue: () => {
+ throw new Error(`resolver rejected ${secret}`);
+ },
+ });
+ const failedDelivery = await failing.runtime.invokeForModel({
+ operationId: "read_secret_value",
+ input: { name: "DEPLOY_TOKEN" },
+ });
+ expect(failedDelivery.observableResult).toMatchObject({
+ ok: false,
+ error: { code: "operation_unsupported", reason: "mock_operation_rejected" },
+ });
+ expect(JSON.stringify({
+ error: failedDelivery,
+ authorization: failing.runtime.authorizationRecords(),
+ })).not.toContain(secret);
+
+ let unclaimedResolverCalls = 0;
+ const ungranted = await runtimeFor({
+ scenarioGrants: ["secrets:values:read"],
+ resolveSecretValue: () => {
+ unclaimedResolverCalls += 1;
+ return secret;
+ },
+ });
+ expect(ungranted.runtime.visibleTools().tools.map((tool) => tool.operationId)).not.toContain("read_secret_value");
+ const unclaimedDelivery = await ungranted.runtime.invokeForModel({
+ operationId: "read_secret_value",
+ input: { name: "DEPLOY_TOKEN" },
+ });
+ expect(unclaimedDelivery.readModelResult()).toMatchObject({
+ ok: false,
+ error: { code: "policy_denied", reason: "secret_value_access_disabled" },
+ });
+ expect(unclaimedResolverCalls).toBe(0);
+ expect(JSON.stringify(unclaimedDelivery)).not.toContain(secret);
+ });
+
+ it("prohibits self approval even with the role and explicit decision claim", async () => {
+ const approval: CapabilityFixtureApproval = {
+ id: "approval-self",
+ companyId: "company-1",
+ taskIds: ["task-1"],
+ type: "request_board_approval",
+ status: "pending",
+ requestedByActorId: "actor-1",
+ payload: { summary: "self requested" },
+ decisionNote: null,
+ comments: [],
+ createdAt: "2026-08-09T00:00:00.000Z",
+ decidedAt: null,
+ };
+ const { adapter, runtime } = await runtimeFor({
+ role: "approver",
+ scenarioGrants: ["governance:approvals:decide"],
+ seed: { approvals: [approval] },
+ });
+ const result = await runtime.invoke({
+ operationId: "decide_approval",
+ input: { approvalId: "approval-self", decision: "approved", note: "self approve" },
+ idempotencyKey: "self-decision",
+ });
+ expect(result).toMatchObject({
+ ok: false,
+ error: { code: "policy_denied", reason: "self_approval_conflict" },
+ });
+ expect(adapter.snapshot().approvals[0]?.status).toBe("pending");
+ });
+
+ it("keeps the generic escape hatch test-only, explicitly granted, and allowlisted", async () => {
+ const denied = await runtimeFor({ workMode: "skill_test", scenarioGrants: ["test:generic_api_request"] });
+ expect(denied.runtime.visibleTools().tools.map((tool) => tool.operationId)).not.toContain("generic_api_request");
+
+ const { runtime } = await runtimeFor({
+ workMode: "skill_test",
+ scenarioGrants: ["test:generic_api_request"],
+ policy: {
+ allowGenericEscapeHatch: true,
+ genericEscapeHatchAllowlist: [{ method: "GET", path: "/mock/health" }],
+ },
+ });
+ expect(runtime.visibleTools().tools.map((tool) => tool.operationId)).toContain("generic_api_request");
+ const allowed = await runtime.invoke({
+ operationId: "generic_api_request",
+ input: { method: "GET", path: "/mock/health", headers: { authorization: "Bearer not-forwarded" } },
+ idempotencyKey: "escape-1",
+ });
+ expect(allowed).toMatchObject({ ok: true, value: { status: 200, body: null } });
+ expect(JSON.stringify(allowed)).not.toContain("not-forwarded");
+
+ const blocked = await runtime.invoke({
+ operationId: "generic_api_request",
+ input: { method: "POST", path: "/api/companies" },
+ idempotencyKey: "escape-2",
+ });
+ expect(blocked).toMatchObject({
+ ok: false,
+ error: { code: "policy_denied", reason: "generic_escape_hatch_target_denied" },
+ });
+ });
+});
diff --git a/packages/paperclip-runner/src/tools/capability-tool-authorization.ts b/packages/paperclip-runner/src/tools/capability-tool-authorization.ts
new file mode 100644
index 0000000000..d2d8a10350
--- /dev/null
+++ b/packages/paperclip-runner/src/tools/capability-tool-authorization.ts
@@ -0,0 +1,233 @@
+import { capabilitySemanticTool, CAPABILITY_SEMANTIC_TOOL_CATALOG } from "./capability-semantic-tool-catalog.js";
+import {
+ CAPABILITY_CONTROL_PLANE_OWNED_OPERATION_IDS,
+ type CapabilityAuthorizationRecord,
+ type CapabilityJsonValue,
+ type CapabilitySemanticToolDescriptor,
+ type CapabilityToolAuthorizationContext,
+ type CapabilityVisibleToolSet,
+} from "./capability-semantic-tool-types.js";
+
+export class CapabilityToolAuthorizationEngine {
+ #sequence = 0;
+ readonly #records: CapabilityAuthorizationRecord[] = [];
+
+ computeVisibleTools(context: CapabilityToolAuthorizationContext): CapabilityVisibleToolSet {
+ const tools: CapabilitySemanticToolDescriptor[] = [];
+ const authorizationRecords = CAPABILITY_SEMANTIC_TOOL_CATALOG.map((tool) => {
+ const decision = this.#evaluate(tool, context, undefined);
+ const record = this.#record(context, tool, "exposure", decision.allowed ? "exposed" : "absent", decision.reason);
+ if (decision.allowed) tools.push(tool);
+ return record;
+ });
+ return deepFreeze({
+ schema: "paperclip.capability.visible-tools.v1",
+ tools: clone(tools),
+ authorizationRecords,
+ });
+ }
+
+ authorizeInvocation(
+ operationId: string,
+ input: CapabilityJsonValue,
+ context: CapabilityToolAuthorizationContext,
+ ): CapabilityAuthorizationRecord {
+ if ((CAPABILITY_CONTROL_PLANE_OWNED_OPERATION_IDS as readonly string[]).includes(operationId)) {
+ return this.#recordUnknown(context, operationId, "absent", "control_plane_owned_operation");
+ }
+ const tool = capabilitySemanticTool(operationId);
+ if (tool === undefined) {
+ return this.#recordUnknown(context, operationId, "absent", "unknown_operation");
+ }
+ const decision = this.#evaluate(tool, context, input);
+ return this.#record(
+ context,
+ tool,
+ "invocation",
+ decision.allowed ? "allowed" : "denied",
+ decision.reason,
+ );
+ }
+
+ denyInvocation(
+ operationId: string,
+ context: CapabilityToolAuthorizationContext,
+ reason: string,
+ ): CapabilityAuthorizationRecord {
+ const tool = capabilitySemanticTool(operationId);
+ return tool === undefined
+ ? this.#recordUnknown(context, operationId, "absent", reason)
+ : this.#record(context, tool, "invocation", "denied", reason);
+ }
+
+ attachStateChange(
+ sequence: number,
+ beforeRevision: number,
+ afterRevision: number,
+ entityRefs: string[],
+ ): CapabilityAuthorizationRecord {
+ const record = this.#records.find((candidate) => candidate.sequence === sequence);
+ if (record === undefined || record.outcome !== "allowed") {
+ throw new Error(`cannot attach state change to authorization record ${sequence}`);
+ }
+ record.resultingStateChange = {
+ beforeRevision,
+ afterRevision,
+ entityRefs: [...entityRefs].sort(),
+ };
+ return deepFreeze(clone(record));
+ }
+
+ records(): readonly CapabilityAuthorizationRecord[] {
+ return deepFreeze(clone(this.#records));
+ }
+
+ #evaluate(
+ tool: CapabilitySemanticToolDescriptor,
+ context: CapabilityToolAuthorizationContext,
+ input: CapabilityJsonValue | undefined,
+ ): { allowed: boolean; reason: string } {
+ const policy = context.policy ?? {};
+ if (policy.deniedOperationIds?.includes(tool.operationId)) {
+ return { allowed: false, reason: "operation_denied_by_policy" };
+ }
+ if (!tool.taskModes.includes(context.task.workMode)) {
+ return { allowed: false, reason: "operation_not_available_in_task_mode" };
+ }
+ if (
+ tool.allowedRoles !== undefined &&
+ !tool.allowedRoles.map(normalize).includes(normalize(context.actor.role))
+ ) {
+ return { allowed: false, reason: "actor_role_not_authorized" };
+ }
+ const deniedClaims = new Set(policy.deniedClaims ?? []);
+ if (tool.requiredClaims.some((claim) => deniedClaims.has(claim))) {
+ return { allowed: false, reason: "required_claim_denied_by_policy" };
+ }
+ const grants = new Set([...context.actor.capabilityGrants, ...context.scenarioGrants]);
+ if (tool.requiredClaims.some((claim) => !grants.has(claim))) {
+ return { allowed: false, reason: "required_claim_missing" };
+ }
+ if (tool.operationId === "read_secret_value" && policy.allowSecretValueAccess !== true) {
+ return { allowed: false, reason: "secret_value_access_disabled" };
+ }
+ if (tool.operationId === "generic_api_request") {
+ if (policy.allowGenericEscapeHatch !== true) {
+ return { allowed: false, reason: "generic_escape_hatch_disabled" };
+ }
+ if (input !== undefined && !genericRequestAllowed(input, policy.genericEscapeHatchAllowlist ?? [])) {
+ return { allowed: false, reason: "generic_escape_hatch_target_denied" };
+ }
+ }
+ if (tool.operationId === "request_human_input" && input !== undefined) {
+ const interactionKind = objectValue(input)?.interactionKind;
+ if (
+ typeof interactionKind === "string" &&
+ policy.allowedInteractionKinds !== undefined &&
+ !policy.allowedInteractionKinds.includes(interactionKind as never)
+ ) {
+ return { allowed: false, reason: "interaction_kind_denied_by_policy" };
+ }
+ }
+ return {
+ allowed: true,
+ reason: tool.disposition === "always_agent_tool" ? "task_scoped_always_tool" : "required_claims_granted",
+ };
+ }
+
+ #record(
+ context: CapabilityToolAuthorizationContext,
+ tool: CapabilitySemanticToolDescriptor,
+ phase: CapabilityAuthorizationRecord["phase"],
+ outcome: CapabilityAuthorizationRecord["outcome"],
+ reason: string,
+ ): CapabilityAuthorizationRecord {
+ const grants = [...new Set([...context.actor.capabilityGrants, ...context.scenarioGrants])].sort();
+ const consideredClaims = [...tool.requiredClaims].sort();
+ return this.#store({
+ schema: "paperclip.capability.authorization-record.v1",
+ sequence: ++this.#sequence,
+ runId: context.runId,
+ actorId: context.actor.id,
+ taskId: context.task.id,
+ operationId: tool.operationId,
+ phase,
+ outcome,
+ consideredClaims,
+ grantedClaims: consideredClaims.filter((claim) => grants.includes(claim)),
+ missingClaims: consideredClaims.filter((claim) => !grants.includes(claim)),
+ reason,
+ redactions: tool.redaction.map(({ path, replacement }) => ({ path, replacement })),
+ resultingStateChange: null,
+ });
+ }
+
+ #recordUnknown(
+ context: CapabilityToolAuthorizationContext,
+ operationId: string,
+ outcome: "absent" | "denied",
+ reason: string,
+ ): CapabilityAuthorizationRecord {
+ return this.#store({
+ schema: "paperclip.capability.authorization-record.v1",
+ sequence: ++this.#sequence,
+ runId: context.runId,
+ actorId: context.actor.id,
+ taskId: context.task.id,
+ operationId,
+ phase: "invocation",
+ outcome,
+ consideredClaims: [],
+ grantedClaims: [],
+ missingClaims: [],
+ reason,
+ redactions: [],
+ resultingStateChange: null,
+ });
+ }
+
+ #store(record: CapabilityAuthorizationRecord): CapabilityAuthorizationRecord {
+ this.#records.push(record);
+ return deepFreeze(clone(record));
+ }
+}
+
+function genericRequestAllowed(
+ input: CapabilityJsonValue,
+ allowlist: Array<{ method: string; path: string }>,
+): boolean {
+ const object = objectValue(input);
+ if (object === undefined || typeof object.method !== "string" || typeof object.path !== "string") {
+ return false;
+ }
+ const method = object.method.toUpperCase();
+ return allowlist.some(
+ (entry) => entry.method.toUpperCase() === method && pathMatches(entry.path, object.path as string),
+ );
+}
+
+function pathMatches(pattern: string, path: string): boolean {
+ if (!pattern.endsWith("*")) return pattern === path;
+ return path.startsWith(pattern.slice(0, -1));
+}
+
+function objectValue(value: CapabilityJsonValue): Record<string, CapabilityJsonValue> | undefined {
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+ ? value
+ : undefined;
+}
+
+function normalize(value: string): string {
+ return value.trim().toLowerCase();
+}
+
+function clone<T>(value: T): T {
+ return structuredClone(value);
+}
+
+function deepFreeze<T>(value: T): T {
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
+ Object.freeze(value);
+ for (const child of Object.values(value)) deepFreeze(child);
+ return value;
+}
diff --git a/packages/paperclip-runner/src/tools/capability-tool-bindings.ts b/packages/paperclip-runner/src/tools/capability-tool-bindings.ts
new file mode 100644
index 0000000000..f2c69db2fa
--- /dev/null
+++ b/packages/paperclip-runner/src/tools/capability-tool-bindings.ts
@@ -0,0 +1,77 @@
+import type {
+ CapabilityJsonSchema,
+ CapabilitySemanticToolDescriptor,
+ CapabilityVisibleToolSet,
+} from "./capability-semantic-tool-types.js";
+
+export interface CapabilityToolBinding<TDefinition> {
+ readonly kind: "fake_agent" | "codex";
+ bind(visibleTools: CapabilityVisibleToolSet): readonly TDefinition[];
+ operationId(definition: TDefinition): string;
+}
+
+export interface CapabilityFakeAgentToolDefinition {
+ operationId: string;
+ description: string;
+ inputSchema: CapabilityJsonSchema;
+ outputSchema: CapabilityJsonSchema;
+}
+
+export interface CapabilityCodexToolDefinition {
+ type: "function";
+ name: string;
+ description: string;
+ strict: true;
+ parameters: CapabilityJsonSchema;
+}
+
+export class CapabilityFakeAgentToolBinding implements CapabilityToolBinding<CapabilityFakeAgentToolDefinition> {
+ readonly kind = "fake_agent" as const;
+
+ bind(visibleTools: CapabilityVisibleToolSet): readonly CapabilityFakeAgentToolDefinition[] {
+ return freezeDefinitions(visibleTools.tools.map((tool) => ({
+ operationId: tool.operationId,
+ description: tool.description,
+ inputSchema: structuredClone(tool.inputSchema),
+ outputSchema: structuredClone(tool.outputSchema),
+ })));
+ }
+
+ operationId(definition: CapabilityFakeAgentToolDefinition): string {
+ return definition.operationId;
+ }
+}
+
+export class CapabilityCodexToolBinding implements CapabilityToolBinding<CapabilityCodexToolDefinition> {
+ readonly kind = "codex" as const;
+
+ bind(visibleTools: CapabilityVisibleToolSet): readonly CapabilityCodexToolDefinition[] {
+ return freezeDefinitions(visibleTools.tools.map(toCodexDefinition));
+ }
+
+ operationId(definition: CapabilityCodexToolDefinition): string {
+ return definition.name;
+ }
+}
+
+function toCodexDefinition(tool: CapabilitySemanticToolDescriptor): CapabilityCodexToolDefinition {
+ return {
+ type: "function",
+ name: tool.operationId,
+ description: tool.description,
+ strict: true,
+ parameters: structuredClone(tool.inputSchema),
+ };
+}
+
+function freezeDefinitions<T>(definitions: T[]): readonly T[] {
+ for (const definition of definitions) deepFreeze(definition);
+ return Object.freeze(definitions);
+}
+
+function deepFreeze<T>(value: T): T {
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
+ Object.freeze(value);
+ for (const child of Object.values(value)) deepFreeze(child);
+ return value;
+}
diff --git a/packages/paperclip-runner/src/tools/index.ts b/packages/paperclip-runner/src/tools/index.ts
new file mode 100644
index 0000000000..d14ec59dfb
--- /dev/null
+++ b/packages/paperclip-runner/src/tools/index.ts
@@ -0,0 +1,5 @@
+export * from "./capability-semantic-tool-types.js";
+export * from "./capability-semantic-tool-catalog.js";
+export * from "./capability-tool-authorization.js";
+export * from "./capability-semantic-tool-runtime.js";
+export * from "./capability-tool-bindings.js";